package com.njcn.bpm.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.bpm.pojo.dto.BpmInstanceInfo;
import com.njcn.bpm.pojo.dto.PageResult;
import com.njcn.bpm.pojo.po.BpmForm;
import com.njcn.bpm.pojo.vo.instance.BpmProcessInstanceVO;
import com.njcn.bpm.pojo.vo.task.BpmTaskVO;
import com.njcn.supervision.api.BusinessCommonFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.vo.UserVO;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.njcn.bpm.utils.CollectionUtils.*;
import static com.njcn.bpm.utils.MapUtils.findAndThen;


/**
 * Bpm 任务 Convert
 *
 * @author hongawen
 */
@Mapper
public interface BpmTaskConvert {

    BpmTaskConvert INSTANCE = Mappers.getMapper(BpmTaskConvert.class);



    default PageResult<BpmTaskVO> buildTodoTaskPage(PageResult<Task> pageResult,
                                                    Map<String, ProcessInstance> processInstanceMap,
                                                    Map<String, UserVO> userMap,
                                                    BusinessCommonFeignClient businessCommonFeignClient) {

        return BeanUtils.toBean(pageResult, BpmTaskVO.class, taskVO -> {
            ProcessInstance processInstance = processInstanceMap.get(taskVO.getProcessInstanceId());
            if (processInstance == null) {
                return;
            }
            taskVO.setProcessInstance(BeanUtils.toBean(processInstance, BpmTaskVO.ProcessInstance.class));
            UserVO startUserVO = userMap.get(processInstance.getStartUserId());
            taskVO.getProcessInstance().setStartUser(BeanUtils.toBean(startUserVO, BpmProcessInstanceVO.User.class));
            String processDefinitionId = taskVO.getProcessInstance().getProcessDefinitionId();
            String key = processDefinitionId.substring(0,processDefinitionId.lastIndexOf(":"));
            key = key.substring(0,key.lastIndexOf(":"));
            BpmInstanceInfo instanceInfo = businessCommonFeignClient.getInstanceInfo(key, processInstance.getBusinessKey()).getData();
            if(Objects.nonNull(instanceInfo)){
                taskVO.setHistoryInstanceId(instanceInfo.getHistoryInstanceId());
                taskVO.setInstanceSign(instanceInfo.getInstanceSign());
            }
        });

    }

    default List<BpmTaskVO> buildTodoTaskList(List<Task> taskList,
                                                    Map<String, ProcessInstance> processInstanceMap,
                                                    Map<String, UserVO> userMap,
                                                    BusinessCommonFeignClient businessCommonFeignClient) {

        return BeanUtils.toBean(taskList, BpmTaskVO.class, taskVO -> {
            ProcessInstance processInstance = processInstanceMap.get(taskVO.getProcessInstanceId());
            if (processInstance == null) {
                return;
            }
            taskVO.setProcessInstance(BeanUtils.toBean(processInstance, BpmTaskVO.ProcessInstance.class));
            UserVO startUserVO = userMap.get(processInstance.getStartUserId());
            taskVO.getProcessInstance().setStartUser(BeanUtils.toBean(startUserVO, BpmProcessInstanceVO.User.class));
            String processDefinitionId = taskVO.getProcessInstance().getProcessDefinitionId();
            String key = processDefinitionId.substring(0,processDefinitionId.lastIndexOf(":"));
            key = key.substring(0,key.lastIndexOf(":"));
            BpmInstanceInfo instanceInfo = businessCommonFeignClient.getInstanceInfo(key, processInstance.getBusinessKey()).getData();
            if(Objects.nonNull(instanceInfo)){
                taskVO.setHistoryInstanceId(instanceInfo.getHistoryInstanceId());
                taskVO.setInstanceSign(instanceInfo.getInstanceSign());
            }
        });

    }




    default PageResult<BpmTaskVO> buildTaskPage(PageResult<HistoricTaskInstance> pageResult,
                                                Map<String, HistoricProcessInstance> processInstanceMap,
                                                Map<String, UserVO> userMap,
                                                Map<String, Dept> deptMap,
                                                BusinessCommonFeignClient businessCommonFeignClient) {
        List<BpmTaskVO> taskVOList = convertList(pageResult.getList(), task -> {
            BpmTaskVO taskVO = BeanUtils.toBean(task, BpmTaskVO.class);
            taskVO.setStatus(FlowableUtils.getTaskStatus(task));
            taskVO.setReason(FlowableUtils.getTaskReason(task));
            // 用户信息
            UserVO assignUser = userMap.get(task.getAssignee());
            if (assignUser != null) {
                taskVO.setAssigneeUser(BeanUtils.toBean(assignUser, BpmProcessInstanceVO.User.class));
                findAndThen(deptMap, assignUser.getDeptId(), dept -> taskVO.getAssigneeUser().setDeptName(dept.getName()));
            }
            // 流程实例
            HistoricProcessInstance processInstance = processInstanceMap.get(taskVO.getProcessInstanceId());
            if (processInstance != null) {
                UserVO startUser = userMap.get(processInstance.getStartUserId());
                taskVO.setProcessInstance(BeanUtils.toBean(processInstance, BpmTaskVO.ProcessInstance.class));
                taskVO.getProcessInstance().setStartUser(BeanUtils.toBean(startUser, BpmProcessInstanceVO.User.class));
            }
            //处理额外信息
            String processDefinitionId = taskVO.getProcessInstance().getProcessDefinitionId();
            String key = processDefinitionId.substring(0,processDefinitionId.lastIndexOf(":"));
            key = key.substring(0,key.lastIndexOf(":"));
            BpmInstanceInfo instanceInfo = businessCommonFeignClient.getInstanceInfo(key, processInstance.getBusinessKey()).getData();
            if(Objects.nonNull(instanceInfo)){
                taskVO.setHistoryInstanceId(instanceInfo.getHistoryInstanceId());
                taskVO.setInstanceSign(instanceInfo.getInstanceSign());
            }
            return taskVO;
        });
        return new PageResult<>(taskVOList, pageResult.getTotal());
    }

    default List<BpmTaskVO> buildTaskListByProcessInstanceId(List<HistoricTaskInstance> taskList,
                                                             HistoricProcessInstance processInstance,
                                                             Map<String, BpmForm> formMap,
                                                             Map<String, UserVO> userMap,
                                                             Map<String, Dept> deptMap) {
        List<BpmTaskVO> taskVOList = convertList(taskList, task -> {
            BpmTaskVO taskVO = BeanUtils.toBean(task, BpmTaskVO.class);
            taskVO.setStatus(FlowableUtils.getTaskStatus(task));
            taskVO.setReason(FlowableUtils.getTaskReason(task));
            // 流程实例
            UserVO startUser = userMap.get(processInstance.getStartUserId());
            taskVO.setProcessInstance(BeanUtils.toBean(processInstance, BpmTaskVO.ProcessInstance.class));
            taskVO.getProcessInstance().setStartUser(BeanUtils.toBean(startUser, BpmProcessInstanceVO.User.class));
            // 表单信息
            BpmForm form = MapUtil.get(formMap, task.getFormKey(), BpmForm.class);
            if (form != null) {
                taskVO.setFormId(form.getId());
                taskVO.setFormName(form.getName());
                taskVO.setFormConf(form.getConf());
                taskVO.setFormFields(form.getFields());
                taskVO.setFormVariables(FlowableUtils.getTaskFormVariable(task));
            }
            // 用户信息
            UserVO assignUser = userMap.get(task.getAssignee());
            if (assignUser != null) {
                taskVO.setAssigneeUser(BeanUtils.toBean(assignUser, BpmProcessInstanceVO.User.class));
                findAndThen(deptMap, assignUser.getDeptId(), dept -> taskVO.getAssigneeUser().setDeptName(dept.getName()));
            }
            UserVO ownerUser = userMap.get(task.getOwner());
            if (ownerUser != null) {
                taskVO.setOwnerUser(BeanUtils.toBean(ownerUser, BpmProcessInstanceVO.User.class));
                findAndThen(deptMap, ownerUser.getDeptId(), dept -> taskVO.getOwnerUser().setDeptName(dept.getName()));
            }
            return taskVO;
        });

        // 拼接父子关系
        Map<String, List<BpmTaskVO>> childrenTaskMap = convertMultiMap(
                filterList(taskVOList, r -> StrUtil.isNotEmpty(r.getParentTaskId())),
                BpmTaskVO::getParentTaskId);
        for (BpmTaskVO taskVO : taskVOList) {
            taskVO.setChildren(childrenTaskMap.get(taskVO.getId()));
        }
        return filterList(taskVOList, r -> StrUtil.isEmpty(r.getParentTaskId()));
    }

    default List<BpmTaskVO> buildTaskListByParentTaskId(List<Task> taskList,
                                                            Map<String, UserVO> userMap,
                                                            Map<String, Dept> deptMap) {
        return convertList(taskList, task -> BeanUtils.toBean(task, BpmTaskVO.class, taskVO -> {
            UserVO assignUser = userMap.get(task.getAssignee());
            if (assignUser != null) {
                taskVO.setAssigneeUser(BeanUtils.toBean(assignUser, BpmProcessInstanceVO.User.class));
                Dept dept = deptMap.get(assignUser.getDeptId());
                if (dept != null) {
                    taskVO.getAssigneeUser().setDeptName(dept.getName());
                }
            }
            UserVO ownerUser = userMap.get(task.getOwner());
            if (ownerUser != null) {
                taskVO.setOwnerUser(BeanUtils.toBean(ownerUser, BpmProcessInstanceVO.User.class));
                findAndThen(deptMap, ownerUser.getDeptId(), dept -> taskVO.getOwnerUser().setDeptName(dept.getName()));
            }
        }));
    }

//    default BpmMessageSendWhenTaskCreatedReqDTO convert(ProcessInstance processInstance, AdminUserRespDTO startUser,
//                                                        Task task) {
//        BpmMessageSendWhenTaskCreatedReqDTO reqDTO = new BpmMessageSendWhenTaskCreatedReqDTO();
//        reqDTO.setProcessInstanceId(processInstance.getProcessInstanceId())
//                .setProcessInstanceName(processInstance.getName()).setStartUserId(startUser.getId())
//                .setStartUserNickname(startUser.getNickname()).setTaskId(task.getId()).setTaskName(task.getName())
//                .setAssigneeUserId(NumberUtils.parseLong(task.getAssignee()));
//        return reqDTO;
//    }

    /**
     * 将父任务的属性，拷贝到子任务（加签任务）
     * <p>
     * 为什么不使用 mapstruct 映射？因为 TaskEntityImpl 还有很多其他属性，这里我们只设置我们需要的。
     * 使用 mapstruct 会将里面嵌套的各个属性值都设置进去，会出现意想不到的问题。
     *
     * @param parentTask 父任务
     * @param childTask  加签任务
     */
    default void copyTo(TaskEntityImpl parentTask, TaskEntityImpl childTask) {
        childTask.setName(parentTask.getName());
        childTask.setDescription(parentTask.getDescription());
        childTask.setCategory(parentTask.getCategory());
        childTask.setParentTaskId(parentTask.getId());
        childTask.setProcessDefinitionId(parentTask.getProcessDefinitionId());
        childTask.setProcessInstanceId(parentTask.getProcessInstanceId());
//        childTask.setExecutionId(parentTask.getExecutionId()); // TODO 芋艿：新加的，不太确定；尴尬，不加时，子任务不通过会失败（报错）；加了，子任务审批通过会失败（报错）
        childTask.setTaskDefinitionKey(parentTask.getTaskDefinitionKey());
        childTask.setTaskDefinitionId(parentTask.getTaskDefinitionId());
        childTask.setPriority(parentTask.getPriority());
        childTask.setCreateTime(new Date());
        childTask.setTenantId(parentTask.getTenantId());
    }

}
