package cn.axzo.workflow.core.service.converter;

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.common.model.response.bpmn.process.BpmnProcessDefinitionVO;
import cn.axzo.workflow.common.model.response.bpmn.process.BpmnProcessInstanceVO;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.Arrays;

import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 历史流程实例的 MapStruts 转换器
 *
 * @author wangli
 * @since 2023/7/26 16:01
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)
public interface BpmnProcessInstanceConverter extends EntityConverter<BpmnProcessInstanceVO,
        HistoricProcessInstance> {

    @Mapping(target = "id", source = "id")
    @Mapping(target = "name", source = "name")
    @Mapping(target = "result", source = "businessStatus")
    @Mapping(target = "createAt", source = "startTime")
    @Mapping(target = "endTime", source = "endTime")
    @Mapping(target = "businessKey", source = "businessKey")
    @Mapping(target = "variables", source = "processVariables")
    @Mapping(target = "startUserId", source = "startUserId")
    @Override
    BpmnProcessInstanceVO toVo(HistoricProcessInstance entity);

    default BpmnProcessInstanceVO toVo(HistoricProcessInstance processInstance,
                                       BpmnProcessDefinitionVO processDefinition,
                                       HistoricVariableInstance initiatorVariableInstance) {
        BpmnProcessInstanceVO vo = toVo(processInstance);
        vo.setCategory(processDefinition.getCategory());
        vo.setProcessDefinitionId(processDefinition.getId());
        vo.setProcessDefinitionKey(processInstance.getProcessDefinitionKey());
        vo.setInitiator((BpmnTaskDelegateAssigner) initiatorVariableInstance.getValue());
        return vo;
    }
}
