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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskBackAuditDTO;
import cn.axzo.workflow.core.engine.cmd.CustomBackTaskCmd;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.task.api.Task;
import org.flowable.variable.api.delegate.VariableScope;

import java.util.Collections;
import java.util.Objects;

@Slf4j
public class AsyncBackTaskJobHandler extends AbstractExecuteWithLockJobHandler implements JobHandler {

    public static final String TYPE = "async-back-task";

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

    @Override
    public void executeInternal(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        log.info("AsyncBackTaskJobHandler executing...");
        log(job);
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        BpmnTaskBackAuditDTO dto = JSONUtil.toBean(job.getCustomValues(), BpmnTaskBackAuditDTO.class);
        Task task = processEngineConfiguration.getTaskService().createTaskQuery().taskId(dto.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            return;
        }
        processEngineConfiguration.getCommandExecutor().execute(new CustomBackTaskCmd(
                CustomBackTaskCmd.CustomBackParamsDto.builder()
                        .targetTaskIds(Collections.singletonList(dto.getTaskId()))
                        .advice(dto.getAdvice())
                        .operationDesc(dto.getOperationDesc())
                        .attachmentList(dto.getAttachmentList())
                        .operator(dto.getApprover())
                        .processInstanceId(task.getProcessInstanceId())
                        .currentActivityId(task.getTaskDefinitionKey())
                        .toActivityId(dto.getToActivityId())
                        .validateApprover(true)
                        .build()));
    }
}
