package com.jeequan.jeepay.pay.service;

import cn.hutool.core.date.DateUtil;
import com.jeequan.jeepay.db.entity.StatsTaskRecord;
import com.jeequan.jeepay.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/***
* 退款处理通用逻辑
*
* @author jmdhappy
*
* @date 2021/9/25 23:50
*/
@Service
@Slf4j
public class StatisticsService {

    @Autowired private StatsTradeService statsTradeService;
    @Autowired private StatsChannelService statsChannelService;
    @Autowired private StatsPayWayService statsPayWayService;
    @Autowired private StatsDeviceService statsDeviceService;
    @Autowired private StatsTaskRecordService statsTaskRecordService;


    /** 处理数据统计任务 **/
    @Async
    public void doStats(Date beginDate, Date endDate) {
        String beginDateStr = DateUtil.formatDate(beginDate);
        log.info("开始处理统计数据，日期：{}", beginDateStr);

        // 数据修复任务记录 初始化
        Long taskId = statsTaskRecordService.initTask(StatsTaskRecord.TASK_TYPE_CRON, beginDate, endDate);

        try {
//            //交易数据统计
            statsTradeService.handleStats(beginDate, endDate);

            //通道数据统计
            statsChannelService.handleStats(beginDate, endDate);

            //支付方式统计
            statsPayWayService.handleStats(beginDate, endDate);

            //设备统计
            statsDeviceService.handleStats(beginDate, endDate);

            statsTaskRecordService.updateSuccess(taskId, null);

            log.info("完成处理统计数据，日期：{}", beginDateStr);
        }catch (Exception e) {

            statsTaskRecordService.updateFail(taskId, "数据统计定时任务异常：" + e.getMessage());
            log.info("统计数据处理失败，日期：{}", beginDateStr);
        }
    }

}
