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

import cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum;
import cn.axzo.workflow.core.common.exception.WorkflowEngineException;
import cn.axzo.workflow.core.engine.event.ExtTaskInstUpdateEvent;
import cn.axzo.workflow.core.repository.entity.ExtAxHiTaskInst;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.variable.api.delegate.VariableScope;

import java.util.Objects;

import static cn.axzo.workflow.core.common.code.AsyncJobRespCode.DATA_NOT_EXISTS;

/**
 * 异步操作扩展任务表的处理器
 *
 * @author wangli
 * @since 2024/4/29 20:22
 */
@Slf4j
public class AsyncExtTaskInstJobHandler implements JobHandler {
    public static final String TYPE = "async-update-ext-task-inst";
    private final ExtAxHiTaskInstService extAxHiTaskInstService;

    public AsyncExtTaskInstJobHandler(ExtAxHiTaskInstService extAxHiTaskInstService) {
        this.extAxHiTaskInstService = extAxHiTaskInstService;
    }

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        ExtTaskInstUpdateEvent event = JSONObject.parseObject(job.getCustomValues(), ExtTaskInstUpdateEvent.class);
        String taskId = event.getTaskId();
        String processInstanceId = event.getProcessInstanceId();
        String assignee = event.getAssignee();
        BpmnProcessInstanceResultEnum resultEnum = event.getResultEnum();

        ExtAxHiTaskInst existence = extAxHiTaskInstService.getByTaskId(taskId, processInstanceId);
        if (Objects.nonNull(existence)) {
            log.info("更新扩展任务实例表数据: taskId:{}, instanceId:{}, currentStatus:{}, anticipateStatus: {}",
                    taskId, processInstanceId, existence.getStatus(), resultEnum.getStatus());
        } else {
            log.warn("无法正确更新扩展任务表数据: taskId:{}, instanceId:{}, anticipateStatus: {}",
                    taskId, processInstanceId, resultEnum.getStatus());
            throw new WorkflowEngineException(DATA_NOT_EXISTS, processInstanceId, taskId);
        }
        extAxHiTaskInstService.updateByTaskIdAndInstanceId(taskId, processInstanceId, assignee, resultEnum);
    }
}
