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

import cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum;
import cn.axzo.workflow.common.model.response.bpmn.task.BpmnTaskDonePageItemVO;
import cn.axzo.workflow.common.model.response.bpmn.task.BpmnTaskTodoPageItemVO;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.axzo.workflow.core.common.enums.BpmnProcessTaskResultEnum.MI_END;
import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 流程已完成的审批任务分页的 MapStruts 转换器
 *
 * @author wangli
 * @since 2023/7/26 23:37
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)

public interface BpmnTaskDonePageItemConverter extends EntityConverter<BpmnTaskDonePageItemVO, HistoricTaskInstance> {

    BpmnTaskTodoPageItemConverter todoConverter = Mappers.getMapper(BpmnTaskTodoPageItemConverter.class);

    @Override
    default BpmnTaskDonePageItemVO toVo(HistoricTaskInstance entity) {
        BpmnTaskTodoPageItemVO todo = todoConverter.toVo(entity);
        BpmnTaskDonePageItemVO vo = new BpmnTaskDonePageItemVO();
        BeanUtils.copyProperties(todo, vo);
        vo.setEndTime(entity.getEndTime());
        vo.setDurationInMillis(entity.getDurationInMillis());
        vo.setComment(entity.getDeleteReason());
        return vo;
    }

    default List<BpmnTaskDonePageItemVO> toVos(List<HistoricTaskInstance> tasks,
                                               Map<String, HistoricProcessInstance> historicProcessInstanceMap) {
        if (tasks.isEmpty()) {
            return Collections.emptyList();
        }
        List<BpmnTaskDonePageItemVO> vos = new ArrayList<>();
        tasks.forEach(i -> {
            if (!Objects.equals(MI_END.getStatus(), i.getDeleteReason())) {
                BpmnTaskDonePageItemVO vo = toVo(i);
                HistoricProcessInstance instance = historicProcessInstanceMap.getOrDefault(i.getProcessInstanceId(),
                        null);
                if (Objects.nonNull(instance)) {
                    vo.setProcessInstanceId(instance.getId());
                    vo.setProcessInstanceName(instance.getName());
                    vo.setBusinessKey(instance.getBusinessKey());
                    vo.setStartUserId(instance.getStartUserId());
                    vo.setStartTime(instance.getStartTime());
                    vo.setProcessInstanceEndTime(instance.getEndTime());
                    vo.setResult(BpmnProcessInstanceResultEnum.valueOfStatus(instance.getBusinessStatus()));
                    vos.add(vo);
                }
            }
        });
        return vos;
    }

}

