package com.xvji.aspect;

import com.xvji.quartz.domain.SysJob;
import com.xvji.quartz.service.ISysJobService;
import com.xvji.domain.PredictTask;
import com.xvji.domain.TrainTask;
import com.xvji.service.PredictTaskService;
import com.xvji.service.TrainTaskService;
import com.xvji.utils.InvokeTargetUtils;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 定时任务同步切面：当若依定时任务页面修改后，同步回业务任务表
 */
@Aspect
@Component
public class SysJobSyncAspect {

    private static final Logger log = LoggerFactory.getLogger(SysJobSyncAspect.class);

    @Autowired
    private PredictTaskService predictTaskService;

    @Autowired(required = false)
    private TrainTaskService trainTaskService;

    /**
     * 拦截若依定时任务更新方法，同步到业务任务
     * 当定时任务页面修改后，自动更新业务任务表对应字段
     */
    @AfterReturning(
            // 关键点：切到ServiceImpl实现类，而非ISysJobService接口
            pointcut = "execution(* com.xvji.quartz.service.impl.SysJobServiceImpl.updateSysJob(..)) && args(sysJob)",
            returning = "result"
    )
    public void afterUpdateSysJob(SysJob sysJob, boolean result) {
        if (!result) {
            log.info("定时任务更新失败，无需同步");
            return;
        }

        // 1. 从invokeTarget解析业务任务ID
        Long taskId = InvokeTargetUtils.parseTaskIdFromInvokeTarget(sysJob.getInvokeTarget());
        if (taskId == null) {
            log.info("定时任务调用目标格式错误，无法解析业务ID");
            return;
        }

        // 2. 状态转换：定时任务String → 业务任务Integer
        Integer taskStatus = "1".equals(sysJob.getStatus()) ? 1 : 0;

        // 3. 同步到预测任务（训练任务同理）
        if ("PREDICT_TASK".equals(sysJob.getJobGroup())) {
            PredictTask predictTask = new PredictTask();
            predictTask.setPTaskId(taskId);
            predictTask.setPTaskName(sysJob.getJobName());
            predictTask.setPCronExpression(sysJob.getCronExpression());
            //predictTask.setPTaskStatus(taskStatus);
            predictTaskService.updateById(predictTask);
            log.info("同步预测任务[ID:{}]成功", taskId);
        }else if ("TRAIN_TASK".equals(sysJob.getJobGroup()) && trainTaskService != null) {
            TrainTask trainTask = new TrainTask();
            trainTask.setTTaskId(taskId);
            trainTask.setTTaskName(sysJob.getJobName());
            trainTask.setTCronExpression(sysJob.getCronExpression());
            //trainTask.setTTaskStatus(taskStatus);
            trainTaskService.updateById(trainTask);
            log.info("定时任务[ID:{}]同步训练任务[ID:{}]成功", sysJob.getJobId(), taskId);
        } else {
            log.warn("定时任务[ID:{}]任务组[{}]不支持同步，跳过", sysJob.getJobId(), sysJob.getJobGroup());
        }
    }
}