package com.fdkankan.platform.order.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.platform.order.entity.Order;
import com.fdkankan.platform.user.request.RequestOrder;
import com.fdkankan.platform.user.vo.ResponseOrder;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 订单表 Mapper 接口
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Mapper
public interface IOrderMapper extends BaseMapper<Order> {

    @Select(" SELECT count(id) FROM t_order WHERE (DATEDIFF(order_time, NOW())=0) AND REC_STATUS = 'A' AND payment_status = 'paid' ")
    Integer queryOrderCountByToday();

    @Select(" SELECT count(id) FROM t_order WHERE (DATE_FORMAT( order_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )) AND REC_STATUS = 'A' AND payment_status = 'paid' ")
    int queryOrderCountByMonth();

    @Select(" SELECT IFNULL(SUM(total_amount),0) FROM t_order WHERE (DATEDIFF(order_time,NOW())=0) AND REC_STATUS = 'A' AND payment_status = 'paid' ")
    BigDecimal queryTurnoverByToday();

    @Select(" SELECT IFNULL(SUM(total_amount),0) FROM t_order WHERE (DATE_FORMAT( order_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )) AND REC_STATUS = 'A' AND payment_status = 'paid' ")
    BigDecimal queryTurnoverByMonth();

    @Select(" SELECT IFNULL(SUM(total_amount),0) FROM t_order WHERE (PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( order_time, '%Y%m' ) ) =1) AND REC_STATUS = 'A' AND payment_status = 'paid' ")
    BigDecimal queryTurnoverByLastMonth();

    @Select(" SELECT count(id) FROM t_order WHERE REC_STATUS = 'A' AND payment_status = 'paid' ")
    int queryAllPayOrdersCount();

    @Select(" SELECT IFNULL(SUM(total_amount),0) FROM t_order WHERE REC_STATUS = 'A' AND payment_status = 'paid' ")
    BigDecimal queryAllTurnoverByOrder();

    @Select(" SELECT count(id) FROM t_order WHERE REC_STATUS = 'A' AND payment_status = 'paid' AND shipping_status = #{status} ")
    int queryOrderCountByShippingStatus(@Param("status")String status);

    @Select(" SELECT order_time as orderTime, count(id) as orderCount, finish_time FROM t_order WHERE (DATE_SUB(CURDATE(), INTERVAL 12 DAY) <=date(order_time)) AND REC_STATUS = 'A' AND payment_status = 'paid' group by day(order_time) ")
    List<ResponseOrder> queryTrendOrder();


    Page<ResponseOrder> getListByParam(Page<ResponseOrder> page, @Param("param") RequestOrder param);

    @Update(" UPDATE t_order Left JOIN t_trade_log on t_order.order_sn = t_trade_log.order_sn set t_order.shipping_status = 'received', t_order.finish_time = NOW() WHERE (DATE_SUB(CURDATE(), INTERVAL 15 DAY) < date(t_trade_log.trade_time)) and (t_order.shipping_status = 'shipped') ")
    void autoUpdateOrderStatus();
}
