package com.codvision.workflow.job;


import com.codvision.workflow.entity.WorkFlowData;
import com.codvision.workflow.service.WorkFlowDataService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 完整流程的超时检查
 * @author hxl
 */
@RequiredArgsConstructor
public class WorkFlowGlobalTimeOutJob implements Job {

    private final RuntimeService runtimeService;
    private final WorkFlowDataService workFlowDataService;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String instanceId = (String) jobDataMap.get("instanceId");
        if (StringUtils.isBlank(instanceId)) {
            return;
        }

        // 判断流程是否已结束，若已结束则直接返回
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        if (processInstance == null) {
            return;
        }

        // 获取流程数据，若数据获取为空则直接返回
        WorkFlowData workFlowData = workFlowDataService.getFormDataByInstanceId(instanceId);
        if (workFlowData == null) {
            return;
        }

        // 设置超期状态
        workFlowData.setIsExpired(true);
        workFlowDataService.updateById(workFlowData);
    }
}
