package cn.axzo.workflow.core.engine.cmd;

import cn.axzo.workflow.common.model.dto.TermNodeAddTimerJobDTO;
import cn.axzo.workflow.core.engine.job.AsyncTermNodeAlterJobHandler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.ManagementService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.TimerJobService;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntity;

import java.io.Serializable;
import java.util.Date;

/**
 * 自定义添加定时任务的逻辑
 *
 * @author wangli
 * @since 2025-03-19 18:24
 */
@Slf4j
public class CustomAddTimerJobCmd extends AbstractCommand<Void> implements Serializable {
    private final TermNodeAddTimerJobDTO dto;

    public CustomAddTimerJobCmd(TermNodeAddTimerJobDTO dto) {
        this.dto = dto;
    }

    @Override
    public String paramToJsonString() {
        return JSON.toJSONString(dto);
    }

    @Override
    public Void executeInternal(CommandContext commandContext) {
        log.info("CustomAddTimerJobCmd start. instanceId: {}, activityId: {}, delayTime: {}, timeUnit: {}", dto.getProcessInstanceId(), dto.getActivityId(), dto.getDelayTime(), dto.getTimeUnit());
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);

        ManagementService managementService = processEngineConfiguration.getManagementService();
        Date alterTime;
        switch (dto.getTimeUnit()) {
            case "M":
                alterTime = DateUtil.offsetDay(new Date(), dto.getDelayTime());
                break;
            case "H":
                alterTime = DateUtil.offsetHour(new Date(), dto.getDelayTime());
                break;
            default:
                alterTime = DateUtil.offsetSecond(new Date(), dto.getDelayTime());
                break;
        }

        managementService.executeCommand(context -> {
            TimerJobService timerJobService = CommandContextUtil.getTimerJobService();
            TimerJobEntity timerJobEntity = timerJobService.createTimerJob();
            timerJobEntity.setJobType("timer");
            timerJobEntity.setJobHandlerType(AsyncTermNodeAlterJobHandler.TYPE); // 这里填写你自定义的 JobHandler 类型
            timerJobEntity.setProcessInstanceId(dto.getProcessInstanceId());
            timerJobEntity.setExecutionId(null);
            timerJobEntity.setDuedate(alterTime); // 立即执行
            timerJobEntity.setRepeat(null); // 不重复
            timerJobEntity.setRetries(1);
            timerJobEntity.setJobHandlerConfiguration(dto.getActivityId()); // 可选，传递参数
            timerJobService.scheduleTimerJob(timerJobEntity);
            return null;
        });

        return null;
    }
}
