package com.qqchen.deploy.backend.workflow.converter;

import com.qqchen.deploy.backend.framework.converter.BaseConverter;
import com.qqchen.deploy.backend.workflow.dto.WorkflowDefinitionDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowHistoricalInstancesDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowInstanceDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowInstanceStartRequest;
import com.qqchen.deploy.backend.workflow.entity.WorkflowDefinition;
import com.qqchen.deploy.backend.workflow.entity.WorkflowInstance;
import com.qqchen.deploy.backend.workflow.enums.WorkflowInstanceStatusEnums;
import org.flowable.engine.runtime.ProcessInstance;
import org.mapstruct.*;

import java.time.LocalDateTime;

/**
 * 工作流实例转换器
 */
@Mapper(config = BaseConverter.class)
public interface WorkflowInstanceConverter extends BaseConverter<WorkflowInstance, WorkflowInstanceDTO> {

    @Override
    @Named("toDto")
    WorkflowInstanceDTO toDto(WorkflowInstance entity);

    @Named("toHistoricalDto")
    WorkflowHistoricalInstancesDTO toWorkflowHistoricalInstancesDTO(WorkflowInstance workflowInstance);

    /**
     * 从多个源对象创建 WorkflowInstance
     * 
     * @param request 工作流启动请求
     * @param processInstance Flowable 流程实例
     * @param definition 工作流定义
     * @return 工作流实例
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "processInstanceId", source = "processInstance.id")
    @Mapping(target = "processDefinitionId", source = "processInstance.processDefinitionId")
    @Mapping(target = "workflowDefinitionId", source = "definition.id")
    @Mapping(target = "businessKey", source = "request.businessKey")
    @Mapping(target = "graphSnapshot", source = "definition.graph")
    @Mapping(target = "variables", source = "request.variables")
    @Mapping(target = "status", constant = "NOT_STARTED")
    @Mapping(target = "startTime", expression = "java(java.time.LocalDateTime.now())")
    @Mapping(target = "endTime", ignore = true)
    @Mapping(target = "createTime", ignore = true)
    @Mapping(target = "updateTime", ignore = true)
    @Mapping(target = "createBy", ignore = true)
    @Mapping(target = "updateBy", ignore = true)
    @Mapping(target = "version", ignore = true)
    @Mapping(target = "deleted", ignore = true)
    WorkflowInstance toEntity(
        WorkflowInstanceStartRequest request,
        ProcessInstance processInstance,
        WorkflowDefinition definition
    );

}
