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

import cn.axzo.workflow.common.model.response.bpmn.task.BpmnHistoricTaskInstanceVO;
import org.flowable.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 历史任务实例的 MapStruts 转换器
 *
 * @author wangli
 * @since 2023/7/29 17:50
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)
public interface BpmnHistoricTaskInstanceConverter extends EntityConverter<BpmnHistoricTaskInstanceVO,
        HistoricTaskInstance> {
    /**
     * @see MultiInstanceActivityBehavior#DELETE_REASON_END
     */
    String DELETE_REASON_END = "MI_END";

    @Override
    @Mapping(target = "taskId", source = "id")
    @Mapping(target = "taskDefinitionKey", source = "taskDefinitionKey")
    @Mapping(target = "name", source = "name")
    @Mapping(target = "processInstanceId", source = "processInstanceId")
    @Mapping(target = "processDefinitionId", source = "processDefinitionId")
    @Mapping(target = "assignee", source = "assignee")
    @Mapping(target = "createTime", source = "createTime")
    @Mapping(target = "endTime", source = "endTime")
    @Mapping(target = "durationInMillis", source = "durationInMillis")
    @Mapping(target = "tenantId", source = "tenantId")
    @Mapping(target = "deleteReason", source = "deleteReason")
    BpmnHistoricTaskInstanceVO toVo(HistoricTaskInstance entity);


    default List<BpmnHistoricTaskInstanceVO> toVosSkipMiEnd(List<HistoricTaskInstance> entities) {
        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }
        List<BpmnHistoricTaskInstanceVO> vos = new ArrayList<>();
        entities.stream()
                .filter(i -> !Objects.equals(DELETE_REASON_END, i.getDeleteReason()))
                .forEach(i -> vos.add(toVo(i)));
        return vos;
    }

}
