package com.czg.task;

import cn.hutool.core.collection.CollUtil;
import com.czg.account.service.ShopInfoService;
import com.czg.order.service.ShopOrderStatisticService;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.order.service.ShopTableOrderStatisticService;
import com.czg.service.RedisService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * 统计任务
 *
 * @author Administrator
 */
@Component
@Slf4j
public class StatisticTask {
    @DubboReference
    private ShopInfoService shopInfoService;

    @Resource
    private ShopOrderStatisticService orderStatisticService;
    @Resource
    private RedisService redisService;
    @Resource
    private ShopTableOrderStatisticService shopTableOrderStatisticService;
    @Resource
    private ShopProdStatisticService shopProdStatisticService;


    //每天 00点15分 执行 开始统计数据
    @Scheduled(cron = "0 0 5 * * ? ")
    public void run() {
        log.info("统计数据，定时任务执行");
        long start = System.currentTimeMillis();
        // 获取前一天
        LocalDate yesterday = LocalDate.now().minusDays(1);
        baseStatistic(yesterday);
        log.info("统计数据，定时任务执行完毕，耗时:{}ms", System.currentTimeMillis() - start);
    }


    /**
     * 基础统计
     *
     * @param date 日期yyyy-MM-dd
     */
    private void baseStatistic(LocalDate date) {
        List<Long> shopIdList = shopInfoService.getShopIdList();
        if (CollUtil.isEmpty(shopIdList)) {
            return;
        }
        redisService.set("task:statistic:date:", "");
        for (Long shopId : shopIdList) {
            statisticAndInsertOrder(shopId, date);
            statisticAndInsertProd(shopId, date);
            statisticAndInsertTable(shopId, date);
        }
        redisService.del("task:statistic:date:");
    }

    public void statisticAndInsertOrder(Long shopId, LocalDate date) {
        try {
            orderStatisticService.statisticAndInsert(shopId, date);
        } catch (Exception e) {
            log.error("统计订单数据失败，店铺id:{}，日期:{}", shopId, date, e);
        }
    }

    public void statisticAndInsertProd(Long shopId, LocalDate date) {
        try {
            shopProdStatisticService.statisticAndInsert(shopId, date, 0L);
        } catch (Exception e) {
            log.error("统计商品数据失败，店铺id:{}，日期:{}", shopId, date, e);
        }
    }

    public void statisticAndInsertTable(Long shopId, LocalDate date) {
        try {
            shopTableOrderStatisticService.statisticAndInsert(shopId, date);
        } catch (Exception e) {
            log.error("统计桌台数据失败，店铺id:{}，日期:{}", shopId, date, e);
        }
    }


}
