package com.centreproject.system.service.job;

import com.centreproject.common.constant.KeyConstants;
import com.centreproject.common.utils.DateUtils;
import com.centreproject.system.service.guestExperience.IKpiDigitalGxService;
import com.centreproject.system.service.guestExperience.IKpiYasIslandCampaignsService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author zhonglei.xu
 */
@Component
@RequiredArgsConstructor
public class YasIslandCampaignsSyncHandler {

    private final IKpiYasIslandCampaignsService iKpiYasIslandCampaignsService;

    /**
     * YasIslandCampaigns同步任务执行器
     * 频率: 暂时配置 每3分钟同步一次
     * 存入数据库中
     */
    @XxlJob("yasIslandCampaignsSyncJobHandler")
    public void execute() {
        // 生成追踪ID
        String traceId = "SYNC-" + KeyConstants.YAS_ISLAND_CAMPAIGNS+"-"+ DateUtils.getRiDate()+"-"+UUID.randomUUID();
        long jobId = XxlJobHelper.getJobId();

        try {
            // 1. 记录任务开始信息
            XxlJobHelper.log("========== 开始执行Yas Island Campaigns同步任务 ==========");
            XxlJobHelper.log("追踪ID: {}", traceId);
            XxlJobHelper.log("开始时间: {}", new java.util.Date());
            // 2. 设置任务参数(会显示在调度日志的"任务参数"列)
            // 可以获取调度中心传入的参数
            XxlJobHelper.getJobParam();
            XxlJobHelper.log("任务参数: " + XxlJobHelper.getJobParam());

            // 3. 执行同步服务
            iKpiYasIslandCampaignsService.startSync(traceId,jobId);

            // 4. 记录成功信息
            XxlJobHelper.log("========== Yas Island Campaigns同步任务执行成功 ==========");
            XxlJobHelper.handleSuccess("Yas Island Campaigns同步完成，追踪ID: " + traceId);

        } catch (Exception e) {
            // 5. 记录错误信息
            XxlJobHelper.log("========== Yas Island Campaigns同步任务执行失败 ==========");
            XxlJobHelper.log("错误信息: {}", e.getMessage());
            XxlJobHelper.log("异常堆栈: ", e);
            // 6. 标记任务失败(会显示在调度日志的"调度备注"列)
            XxlJobHelper.handleFail("同步失败: " + e.getMessage() + "，追踪ID: " + traceId);
            // 抛出异常以便XXL-Job记录失败状态
            throw e;
        }
    }
}
