package cn.newfeifan.mall.module.trade.dal.mysql.order;

import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.mybatis.core.mapper.BaseMapperX;
import cn.newfeifan.mall.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.newfeifan.mall.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.newfeifan.mall.module.trade.controller.admin.order.vo.TradeOrderPageReqVO;
import cn.newfeifan.mall.module.trade.controller.app.order.vo.AppTradeOrderPageReqVO;
import cn.newfeifan.mall.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.newfeifan.mall.module.trade.enums.order.TradeOrderRefundStatusEnum;
import cn.newfeifan.mall.module.trade.enums.order.TradeOrderStatusEnum;
import cn.newfeifan.mall.module.trade.service.order.TradeOrderCountWithMoney;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Mapper
public interface TradeOrderMapper extends BaseMapperX<TradeOrderDO> {
    //add by Ben 20240604
    @Select("SELECT ancestor FROM `distri_share_path` where descendant = #{userId} and depth=1 and deleted = 0")
    Long selectAncesterByMemberUserId(@Param("userId") Long userId);

    default int updateByIdAndStatus(Long id, Integer status, TradeOrderDO update) {
        return update(update, new LambdaUpdateWrapper<TradeOrderDO>()
                .eq(TradeOrderDO::getId, id).eq(TradeOrderDO::getStatus, status));
    }

    default TradeOrderDO selectByIdAndUserId(Long id, Long userId) {
        return selectOne(TradeOrderDO::getId, id, TradeOrderDO::getUserId, userId);
    }

    default PageResult<TradeOrderDO> selectPage(TradeOrderPageReqVO reqVO, Set<Long> userIds, List<Long> orderIds) {
        LambdaQueryWrapperX<TradeOrderDO> queryWrapper = new LambdaQueryWrapperX<TradeOrderDO>()
                .likeIfPresent(TradeOrderDO::getNo, reqVO.getNo())
                .eqIfPresent(TradeOrderDO::getUserId, reqVO.getUserId())
                .eqIfPresent(TradeOrderDO::getDeliveryType, reqVO.getDeliveryType())
                .inIfPresent(TradeOrderDO::getUserId, userIds)
                .eqIfPresent(TradeOrderDO::getType, reqVO.getType())
                .eqIfPresent(TradeOrderDO::getTerminal, reqVO.getTerminal())
                .eqIfPresent(TradeOrderDO::getLogisticsId, reqVO.getLogisticsId())
                .eqIfPresent(TradeOrderDO::getMerchantId, reqVO.getMerchantId())
                .eqIfPresent(TradeOrderDO::getShopId, reqVO.getShopId())
                .eqIfPresent(TradeOrderDO::getPayStatus, reqVO.getPayStatus())
                .inIfPresent(TradeOrderDO::getId, orderIds)
                .betweenIfPresent(TradeOrderDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(TradeOrderDO::getId);
        if(reqVO.getStatus() != null && reqVO.getStatus().equals(TradeOrderStatusEnum.AFTER_SALE.getStatus())){
            queryWrapper.eq(TradeOrderDO::getRefundStatus, TradeOrderRefundStatusEnum.ALL.getStatus());
        }else if(reqVO.getStatus() != null){
            queryWrapper.eqIfPresent(TradeOrderDO::getStatus, reqVO.getStatus());
            queryWrapper.ne(TradeOrderDO::getRefundStatus, TradeOrderRefundStatusEnum.ALL.getStatus());
        }

        if(reqVO.getOrderCalcTime() != null){
            queryWrapper.apply("date(create_time) = {0}", reqVO.getOrderCalcTime());
        }
        return selectPage(reqVO, queryWrapper);
    }

    // TODO @疯狂：如果用 map 返回，要不这里直接用 TradeOrderSummaryRespVO 返回？也算合理，就当  sql 查询出这么个玩意~~
    default List<Map<String, Object>> selectOrderSummaryGroupByRefundStatus(TradeOrderPageReqVO reqVO, Set<Long> userIds) {
        return selectMaps(new MPJLambdaWrapperX<TradeOrderDO>()
                .selectAs(TradeOrderDO::getRefundStatus, TradeOrderDO::getRefundStatus)  // 售后状态
                .selectCount(TradeOrderDO::getId, "count") // 售后状态对应的数量
                .likeIfPresent(TradeOrderDO::getNo, reqVO.getNo())
                .eqIfPresent(TradeOrderDO::getUserId, reqVO.getUserId())
                .eqIfPresent(TradeOrderDO::getDeliveryType, reqVO.getDeliveryType())
                .inIfPresent(TradeOrderDO::getUserId, userIds)
                .eqIfPresent(TradeOrderDO::getType, reqVO.getType())
                .eqIfPresent(TradeOrderDO::getStatus, reqVO.getStatus())
                .eqIfPresent(TradeOrderDO::getTerminal, reqVO.getTerminal())
                .eqIfPresent(TradeOrderDO::getLogisticsId, reqVO.getLogisticsId())
                .betweenIfPresent(TradeOrderDO::getCreateTime, reqVO.getCreateTime())
                .groupBy(TradeOrderDO::getRefundStatus)); // 按售后状态分组
    }

    default PageResult<TradeOrderDO> selectPage(AppTradeOrderPageReqVO reqVO, Long userId) {
        return selectPage(reqVO, new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getUserId, userId)
                .eqIfPresent(TradeOrderDO::getStatus, reqVO.getStatus())
                .eqIfPresent(TradeOrderDO::getCommentStatus, reqVO.getCommentStatus())
                .orderByDesc(TradeOrderDO::getId)); // TODO 非繁人：未来不同的 status，不同的排序
    }

    default Long selectCountByUserIdAndStatus(Long userId, Integer status, Boolean commentStatus) {
        return selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getUserId, userId)
                .eqIfPresent(TradeOrderDO::getStatus, status)
                .eqIfPresent(TradeOrderDO::getCommentStatus, commentStatus));
    }

    default Long selectCountByStatus(Integer status) {
        return selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eqIfPresent(TradeOrderDO::getStatus, status));
    }

    default Long selectCountByStatus(Integer status, Long shopId, Long merId, TradeOrderPageReqVO reqVO) {
        return selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eqIfPresent(TradeOrderDO::getStatus, status)
                .likeIfPresent(TradeOrderDO::getNo, reqVO.getNo())
                .eqIfPresent(TradeOrderDO::getUserId, reqVO.getUserId())
                .eqIfPresent(TradeOrderDO::getDeliveryType, reqVO.getDeliveryType())
                .eqIfPresent(TradeOrderDO::getType, reqVO.getType())
                .eqIfPresent(TradeOrderDO::getTerminal, reqVO.getTerminal())
                .eqIfPresent(TradeOrderDO::getLogisticsId, reqVO.getLogisticsId())
                .betweenIfPresent(TradeOrderDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(TradeOrderDO::getShopId, shopId)
                .eqIfPresent(TradeOrderDO::getMerchantId, merId)
                .ne(TradeOrderDO::getRefundStatus, TradeOrderRefundStatusEnum.ALL.getStatus())
        );
    }


    default TradeOrderDO selectOrderByIdAndUserId(Long orderId, Long loginUserId) {
        return selectOne(new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getId, orderId)
                .eq(TradeOrderDO::getUserId, loginUserId));
    }

    default List<TradeOrderDO> selectListByStatusAndCreateTimeLt(Integer status, LocalDateTime createTime) {
        return selectList(new LambdaUpdateWrapper<TradeOrderDO>()
                .eq(TradeOrderDO::getStatus, status)
                .lt(TradeOrderDO::getCreateTime, createTime));
    }

    default List<TradeOrderDO> selectListByStatusAndDeliveryTimeLt(Integer status, LocalDateTime deliveryTime) {
        return selectList(new LambdaUpdateWrapper<TradeOrderDO>()
                .eq(TradeOrderDO::getStatus, status)
                .lt(TradeOrderDO::getDeliveryTime, deliveryTime));
    }

    default List<TradeOrderDO> selectListByStatusAndReceiveTimeLt(Integer status, LocalDateTime receive,
                                                                  Boolean commentStatus) {
        return selectList(new LambdaUpdateWrapper<TradeOrderDO>()
                .eq(TradeOrderDO::getStatus, status)
                .lt(TradeOrderDO::getReceiveTime, receive)
                .eq(TradeOrderDO::getCommentStatus, commentStatus));
    }

    default TradeOrderDO selectByUserIdAndCombinationActivityIdAndStatus(Long userId, Long combinationActivityId, Integer status) {
        return selectOne(new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getUserId, userId)
                .eq(TradeOrderDO::getStatus, status)
        );
    }


    default Integer selectByMerId(Long key) {
        return Integer.parseInt(String.valueOf(selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eqIfPresent(TradeOrderDO::getMerchantId, key))));
    }

    default List<TradeOrderDO> selectOrderListByMerId(Long id, Long merId, Long shopId) {
        return selectList(new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getMerchantId, merId)
                .eq(TradeOrderDO::getShopId, shopId)
                .eq(TradeOrderDO::getId, id)
        );
    }

    default Long selectCountByStatus(Integer status, Long shopId, Long merId) {
        return selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eq(TradeOrderDO::getStatus, status)
                .eq(TradeOrderDO::getShopId, shopId)
                .eq(TradeOrderDO::getMerchantId, merId)
        );
    }

    default Long selectCountByRefundStatus(Integer refundStatus, TradeOrderPageReqVO reqVO){
        return selectCount(new LambdaQueryWrapperX<TradeOrderDO>()
                .eqIfPresent(TradeOrderDO::getRefundStatus, refundStatus)
                .likeIfPresent(TradeOrderDO::getNo, reqVO.getNo())
                .eqIfPresent(TradeOrderDO::getDeliveryType, reqVO.getDeliveryType())
                .eqIfPresent(TradeOrderDO::getType, reqVO.getType())
                .eqIfPresent(TradeOrderDO::getTerminal, reqVO.getTerminal())
                .eqIfPresent(TradeOrderDO::getMerchantId, reqVO.getMerchantId())
                .eqIfPresent(TradeOrderDO::getShopId,reqVO.getShopId())
                .betweenIfPresent(TradeOrderDO::getCreateTime, reqVO.getCreateTime())
        );
    }

    /**
     * 获取订单统计
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param merId 商户id
     * @param shopId 店铺id
     * @return 订单统计
     */
    List<TradeOrderCountWithMoney> selectOrderCountWithTime(@Param("start") LocalDate startTime, @Param("end") LocalDate endTime, @Param("merId") Long merId, @Param("shopId") Long shopId);
}
