package com.awspaas.user.apps.bnbm.datalinkup.job;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.bnbm.datalinkup.entity.DateRange;
import com.awspaas.user.apps.bnbm.datalinkup.service.DataSummaryService;
import com.awspaas.user.apps.bnbm.datalinkup.service.DataSyncService;
import com.awspaas.user.apps.bnbm.datalinkup.service.impl.SaleCountDimensionImpl;
import com.awspaas.user.apps.bnbm.datalinkup.service.impl.SaleDataSummaryServiceImpl;
import com.awspaas.user.apps.bnbm.datalinkup.service.impl.SaleDataSyncServiceImpl;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: SaleDataLinkUpJob
 * @Description: 销售数据同步定时任务
 */
public class SaleDataLinkUpJob implements IJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(SaleDataLinkUpJob.class);

    /**
     * 定时任务执行入口
     * @param context 任务执行上下文
     * @throws JobExecutionException 任务执行异常
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //时间范围数值
        ArrayList<DateRange> list = new ArrayList<>();
        SaleDataSyncServiceImpl syncService = new SaleDataSyncServiceImpl();
        SaleDataSummaryServiceImpl summaryService = new SaleDataSummaryServiceImpl();
        SaleCountDimensionImpl saleCountDimension = new SaleCountDimensionImpl();
        try {
            LOGGER.info("======== 开始执行销售数据同步任务 ========");
            // 查询销售业务的主配置
            List<BO> mainConfigs = SDK.getBOAPI().query("BO_EU_BNBM_DATALINKUP_SJGTPZ")
                    .addQuery("SSYW =", "销售")
                    .list();
            // 使用服务层处理同步逻辑
            ArrayList<DateRange> dateRanges = syncService.syncDataByConfigs(mainConfigs);
            list.addAll(dateRanges);
            LOGGER.info("======== 完成销售数据同步任务 ========");

            // 汇总各板块数据
            LOGGER.info("======== 开始执行销售汇总各板块数据 ========");
            syncService.sumBkTable(mainConfigs);
            LOGGER.info("======== 销售汇总各板块数据执行完成 ========");

            // 数据同步完成后执行汇总计算
            //获取汇总计算时间
            Set<DateRange> collect = list.stream().filter(o -> o.getStartDate() != null || o.getEndDate() != null)
                    .collect(Collectors.toSet());
            DateRange dateRange = new DateRange();
            for (DateRange range : collect) {
                if (range!=null || range.getStartDate()==null || range.getEndDate()==null) {
                    dateRange.setStartDate(range.getStartDate());
                    dateRange.setEndDate(range.getEndDate());
                }
            }
            LOGGER.info("汇总计算开始时间为：{}，结束时间为：{}",dateRange.getStartDate(),dateRange.getEndDate());
            List<RowMap> bkgsMaps = DBSql.getMaps("SELECT BKGS FROM BO_EU_BNBM_DATALINKUP_XS_XSL_HZ GROUP BY BKGS");
            if (bkgsMaps!=null) {
                for (RowMap map : bkgsMaps) {
                    BO bo = new BO();
                    bo.set("BKGS", map.getString("BKGS"));
                    LOGGER.info("========{}- 开始执行一体化-销售数据BI汇总计算 ========",map.getString("BKGS"));
                    summaryService.calculateSummary(dateRange, bo);
                    LOGGER.info("========{}- 一体化-销售数据汇总计算完成 ========",map.getString("BKGS"));
                    LOGGER.info("========{}- 开始执行销售数据汇总计算 ========",map.getString("BKGS"));
                    saleCountDimension.calculateSummary(dateRange, bo);
                    LOGGER.info("========{}- 销售数据汇总计算完成 ========",map.getString("BKGS"));
                }
            }
            LOGGER.info("======== 销售数据同步任务执行完成 ========");

        } catch (Exception e) {
            String errorMsg = "销售数据同步任务执行失败: " + e.getMessage();
            LOGGER.error(errorMsg, e);
            throw new JobExecutionException(errorMsg, e);
        }
    }

}