package com.gree.mall.manager.schedule;

import cn.hutool.core.date.DateUtil;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.gree.mall.manager.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.workorder.OrderBaseLogic;
import com.gree.mall.manager.plus.entity.PgOrderBase;
import com.gree.mall.manager.plus.entity.SettlementOrder;
import com.gree.mall.manager.plus.service.PgOrderBaseService;
import com.gree.mall.manager.plus.service.SettlementOrderService;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.util.CollectionUtils;

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

/**
 * 工单相关定时任务
 * @author ：lijh
 * @description：TODO
 * @date ：2024/4/26 14:12
 */
@ConditionalOnProperty(name = "schedule.enable", havingValue = "true", matchIfMissing = true)
@Component
@Slf4j
public class OrderBaseSchedule {

    @Autowired
    OrderBaseLogic orderBaseLogic;
    @Autowired
    PgOrderBaseService pgOrderBaseService;
    @Autowired
    SettlementOrderService settlementOrderService;

    @Autowired
    WechatLogic wechatLogic;

    /**
     * 生成抢单通知
     */
    @Transactional
    @Scheduled(fixedDelay = 35  * 1000)
    public void task(){
        //抢单的通知，通知给当前网点的所有师傅
        List<PgOrderBase> list = pgOrderBaseService.lambdaQuery()
                .eq(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.DQD.getKey())
                .eq(PgOrderBase::getIsQd, true)
                .eq(PgOrderBase::getIsQdNotice, false)
                .ge(PgOrderBase::getCreateTime, DateUtil.beginOfDay(new Date()))
                .last("limit 1000")
                .list();
        for(PgOrderBase orderBase : list) {
            orderBaseLogic.addQdNotice(orderBase);
        }
        List<String> orderBaseIds = list.stream().map(PgOrderBase::getId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(orderBaseIds)){
            return;
        }
        pgOrderBaseService.lambdaUpdate().set(PgOrderBase::getIsQdNotice,true).in(PgOrderBase::getId,orderBaseIds).update();
    }



    /**
     * 每天五点结算所有结算单
     */
    @Transactional
    @Scheduled(cron = "0 0 17 * * ?")
  //  @Scheduled(fixedDelay = 60  * 1000)
    public void fenzhang() throws WxPayException {
        List<SettlementOrder> settlementOrders = settlementOrderService.lambdaQuery().eq(SettlementOrder::getStatus, "WAIT").list();

        for (SettlementOrder settlementOrder : settlementOrders) {
            wechatLogic.shareSettlementAmountCorn(settlementOrder);
        }

    }

}
