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

import cn.axzo.workflow.common.enums.BpmnCountersignTypeEnum;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskCountersignDTO;
import cn.axzo.workflow.core.engine.cmd.CustomCountersignUserTaskCmd;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
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.variable.api.delegate.VariableScope;

@Slf4j
public class AsyncCountersignUserTaskJobHandler implements JobHandler {

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

    private final ExtAxHiTaskInstService extAxHiTaskInstService;

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

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

    @Override
    public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        log.info("AsyncCountersignUserTaskJobHandler executing...");
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        BpmnTaskCountersignDTO dto = JSONUtil.toBean(job.getCustomValues(), BpmnTaskCountersignDTO.class);
        processEngineConfiguration.getCommandExecutor().execute(new CustomCountersignUserTaskCmd(BpmnCountersignTypeEnum.valueOfType(dto.getCountersignType()),
                dto.getTaskId(),
                dto.getOriginAssigner(),
                dto.getAdvice(),
                dto.getAttachmentList(),
                dto.getTargetAssignerList(),
                extAxHiTaskInstService));
    }
}
