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.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

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


/**
 * 用户任务签收超时检查
 * @author hxl
 */
@RequiredArgsConstructor
public class WorkFlowTaskClaimTimeOutJob implements Job {

    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;
        }

        // 判断是否已签收，若已签收则比较完成时间和截止时间大小以此确认是否超时
        WorkFlowRecord workFlowRecord = workFlowRecordService.getByTaskIdAndAction(taskId, CLAIM.getType());
        if (workFlowRecord != null) {
            if (StringUtils.isBlank(workFlowRecord.getDeadlineTime())) {
                return;
            }

            // 若完成时间大于截止时间则设置超时状态
            int compare = DateUtil.compare(DateUtil.parse(workFlowRecord.getCompleteTime(), DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.parse(workFlowRecord.getDeadlineTime(), DatePattern.NORM_DATETIME_PATTERN));
            if (compare > 0) {
                workFlowRecord.setIsExpired(true);
                workFlowRecordService.updateById(workFlowRecord);
                return;
            }
        }

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

        workFlowRecord.setIsExpired(true);
        workFlowRecordService.updateById(workFlowRecord);
    }
}
