package com.clx.performance.job;

import com.clx.performance.dao.IntegralTruckDao;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.model.IntegralTruck;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.service.IntegralJobHandlerService;
import com.clx.performance.utils.JobHandlerService;
import com.clx.performance.utils.LocalDateTimeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class IntegralJob {

    private final IntegralTruckDao integralTruckDao;
    private final OrderGoodsDao orderGoodsDao;
    private final JobHandlerService jobHandlerService;

    private final IntegralJobHandlerService integralJobHandlerService;

    /**
     * 下周车辆初始化 (周三)
     * @Scheduled(cron = "0 0 6 ? * 3")
     * 下周车辆初始化 (周日)
     * @Scheduled(cron = "0 0 22 ? * 7")
     */
    @XxlJob("nextWeekTruckInit")
    public void nextWeekTruckInit() {

        jobHandlerService.handler("司机积分-下周车辆初始化", integralJobHandlerService::nextWeekTruckInit);
    }


    /**
     * 车辆周统计(结算上周积分) (周1)
     * @Scheduled(cron = "0 0 1 ? * 1")
     */
    @XxlJob("weekTruckStatistics")
    public void weekTruckStatistics() {
        jobHandlerService.handler("司机积分-车辆周统计", ()->{
            List<IntegralTruck> list = integralTruckDao.listAll();
            log.info("司机积分，车辆数量:{}", list.size());

            list.forEach(integralJobHandlerService::weekTruckStatistics);

        });

        jobHandlerService.handler("司机积分-车辆周统计", integralJobHandlerService::weekTruckStatistics);

    }

    /**
     * 车辆保护期取消 (周一不处理)
     * @Scheduled(cron = "0 0 6,18 ? * 2,3,4,5,6,7")
     */
    @XxlJob("truckProtectionCancel")
    public void truckProtectionCancel() {
        LocalDateTime time = LocalDateTimeUtils.getDayStart().minusDays(7);

        jobHandlerService.handler("司机积分-车辆保护取消", ()->{
            // 查找刚好7天的车辆
            List<IntegralTruck> list = integralTruckDao.selectListByTime(LocalDateTimeUtils.formatTime(time), LocalDateTimeUtils.formatTime(time.plusDays(1)));
            log.info("查找待同步车辆, size:{}", list.size());

            list.forEach(integralJobHandlerService::truckProtectionCancel);

        });
    }

    /**
     * 历史货单同步 (初始化1次)
     */
    @XxlJob("syncHistoryOrderGoods")
    public void syncHistoryOrderGoods() {
        jobHandlerService.handler("司机积分-历史货单同步", ()->{
            List<OrderGoods> list = orderGoodsDao.listIntegralOrderGoodsSync();
            log.info("司机积分，历史货单数量:{}", list.size());

            list.forEach(integralJobHandlerService::syncHistoryOrderGoods);

        });

    }

}
