package com.codvision.workflow.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.codvision.workflow.entity.WorkFlowRecord;
import com.codvision.workflow.service.WorkFlowRecordService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import static com.codvision.workflow.constant.WorkFlowConstant.WORK_FLOW_TIME_OUT_CLAIM_TASK_ID;
import static com.codvision.workflow.constant.enums.WorkFlowOperationTypeEnum.CLAIM;


/**
 * 用户任务完成超时检查
 * @author hxl
 */
@RequiredArgsConstructor
public class WorkFlowTaskCompleteTimeOutJob implements Job {

    private final TaskService taskService;
    private final WorkFlowRecordService workFlowRecordService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String taskId = (String) jobDataMap.get("taskId");
        if (StringUtils.isBlank(taskId)) {
            return;
        }

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return;
        }

        // 若此时未签收并且存在签收超时配置，则直接返回
        WorkFlowRecord claimRecord = workFlowRecordService.getByTaskIdAndAction(taskId, CLAIM.getType());
        if (claimRecord == null) {
            String value = (String) taskService.getVariableLocal(taskId, WORK_FLOW_TIME_OUT_CLAIM_TASK_ID + taskId);
            if (StringUtils.isNotBlank(value)) {
                return;
            }
        }

        WorkFlowRecord workFlowRecord = workFlowRecordService.getByTodoTaskId(taskId);
        if (workFlowRecord == null || StringUtils.isBlank(workFlowRecord.getDeadlineTime())) {
            return;
        }

        boolean isExpired = StringUtils.isBlank(workFlowRecord.getCompleteTime())
                || DateUtil.compare(DateUtil.parse(workFlowRecord.getCompleteTime(), DatePattern.NORM_DATETIME_PATTERN), DateUtil.parse(workFlowRecord.getDeadlineTime(), DatePattern.NORM_DATETIME_PATTERN)) > 0;
        workFlowRecord.setIsExpired(isExpired);
        workFlowRecordService.updateById(workFlowRecord);
    }
}
