package com.gree.mall.manager.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.enums.OrderShareStatusEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
import com.gree.mall.manager.enums.WXShareStatusEnum;
import com.gree.mall.manager.logic.order.OrderLogic;
import com.gree.mall.manager.logic.order.OrderShareLogic;
import com.gree.mall.manager.plus.entity.OrderInfo;
import com.gree.mall.manager.plus.entity.OrderRefund;
import com.gree.mall.manager.plus.entity.OrderShare;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.plus.service.OrderInfoService;
import com.gree.mall.manager.plus.service.OrderRefundService;
import com.gree.mall.manager.plus.service.OrderShareService;
import com.gree.mall.manager.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自动签收订单
 */
@ConditionalOnProperty(name = "schedule.enable", havingValue = "true", matchIfMissing = true)
@Slf4j
@Component
public class OverOrderSchedule {


    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    private OrderShareLogic orderShareLogic;
    @Autowired
    OrderShareService orderShareService;
    @Autowired
    OrderRefundService orderRefundService;
    @Autowired
    OrderLogic orderLogic;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;

//
    @Transactional
    @Scheduled(fixedDelay = 5 * 60 * 1000)
    public void task() throws Exception {
        Date timeByDay = DateUtils.getTimeByDay(new Date(), -7);

        List<OrderInfo> list = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.YFH.toString())
                .lt(OrderInfo::getDeliverTime, timeByDay).list();
        if (list.size() == 0) {
            return;
        }
        List<String> orderIds = list.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
        //1.将订单已完成
        orderInfoService.lambdaUpdate()
                .set(OrderInfo::getOverTime, new Date())
                .set(OrderInfo::getOrderStatus, OrderStatusEnum.OVER.toString())
                .in(OrderInfo::getOrderId, orderIds).update();

        //3.将结算数据记录订单完成时间
        orderShareService.lambdaUpdate()
                .set(OrderShare::getOrderStatus,OrderStatusEnum.OVER.toString())
                .set(OrderShare::getOrderFinishTime,new Date())
                .in(OrderShare::getOrderId,orderIds).update();
    }

    



    //8点到22点，每5分钟执行1次
    @Scheduled(cron = "0 */5 8-22 * * ?")
    public void orderShareTask() {
        Date timeByDay = DateUtil.offsetDay(new Date(),-3);
        List<OrderInfo> list = orderInfoService.lambdaQuery().eq(OrderInfo::getIsShare, false)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.OVER.toString())
                .lt(OrderInfo::getOverTime, timeByDay)
                .page(new Page<>(1,500)).getRecords();
        if(list.size() == 0){
            return;
        }
        for(OrderInfo orderInfo : list){
            String orderId = orderInfo.getOrderId();
            List<OrderShare> orderShares = orderShareService.lambdaQuery()
                    .eq(OrderShare::getOrderId, orderId)
                    .eq(OrderShare::getStatus, OrderShareStatusEnum.ING.toString())
                    .list();
            if(CollectionUtils.isEmpty(orderShares)){
                orderInfo.setIsShare(true);
                continue;
            }
            //查询是否存在未处理完成的售后单
            Integer count = orderRefundService.lambdaQuery()
                    .eq(OrderRefund::getOrderId,orderId)
                    .in(OrderRefund::getOrderStatus, "DSJCL", "DSJSH", "DMJCL").count();
            if(count > 0){
                log.error("订单{}存在未完结的维权订单",orderInfo.getOrderId());
                continue;
            }
            Boolean result = orderShareLogic.confirmAuto(orderShares, orderInfo);
            orderInfo.setIsShare(result);
        }
        orderInfoService.updateBatchById(list);

        //判断是否异常结算
        Date day30 = DateUtils.getTimeByDay(-30);
        orderShareService.lambdaUpdate()
                .set(OrderShare::getStatus,OrderShareStatusEnum.EXCEPTION.toString())
                .set(OrderShare::getRemark,"异常结算：超30天未结算")
                .le(OrderShare::getPayTime,day30)
                .eq(OrderShare::getStatus,OrderShareStatusEnum.ING.toString())
                .update();
    }

    @Scheduled(cron = "0 */5 8-22 * * ?")
    public void orderShareQueryTask() {

        List<OrderShare> orderShares = orderShareService.lambdaQuery()
                .eq(OrderShare::getStatus, OrderShareStatusEnum.OVER.toString())
                .eq(OrderShare::getShareStatus, WXShareStatusEnum.PROCESSING.toString())
                .list();

        if (CollectionUtil.isEmpty(orderShares)) {
            return;
        }

        log.info("开始分账结果查询");

        for (OrderShare share : orderShares) {
            try {
                orderShareLogic.queryShareResult(share);

            } catch (Exception e) {
                log.error("分账结果查询异常: ", e);
            }
        }
        log.info("结束分账结果查询");
    }

}
