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

import cn.axzo.workflow.common.model.response.bpmn.task.BpmnTaskTodoPageItemVO;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.*;

import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 流程实例待审批任务的 MapStruts 转换器
 *
 * @author wangli
 * @since 2023/7/26 23:00
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)
public interface BpmnTaskTodoPageItemConverter extends EntityConverter<BpmnTaskTodoPageItemVO, HistoricTaskInstance> {

    @Mapping(target = "id", source = "id")
    @Mapping(target = "taskName", source = "name")
    @Mapping(target = "category", source = "category")
    @Mapping(target = "claimTime", source = "createTime")
    @Mapping(target = "owner", source = "owner")
    @Mapping(target = "assignee", source = "assignee")
    @Mapping(target = "formKey", source = "formKey")
    @Override
    BpmnTaskTodoPageItemVO toVo(HistoricTaskInstance entity);

    default List<BpmnTaskTodoPageItemVO> toVos(List<HistoricTaskInstance> tasks,
                                               Map<String, ProcessInstance> processInstanceMap) {
        if (tasks.isEmpty()) {
            return Collections.emptyList();
        }
        List<BpmnTaskTodoPageItemVO> vos = new ArrayList<>();
        tasks.forEach(i -> {
            BpmnTaskTodoPageItemVO vo = toVo(i);
            ProcessInstance instance = processInstanceMap.getOrDefault(i.getProcessInstanceId(), null);
            if (Objects.nonNull(instance)) {
                vo.setProcessInstanceId(instance.getProcessInstanceId());
                vo.setProcessInstanceName(instance.getName());
                vo.setBusinessKey(instance.getBusinessKey());
                vo.setStartUserId(instance.getStartUserId());
                vo.setStartTime(instance.getStartTime());
                vos.add(vo);
            }
        });
        return vos;
    }
}
