package com.ho.flow.service.impl;

import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.flow.service.FlowWorkOrderService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fancl
 * @desc: 流程实现类
 * @date 2023/1/25
 */
@Service
@Slf4j
public class FlowWorkOrderServiceImpl implements FlowWorkOrderService {

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Override
    public ProcessInstance startProcess(String processDefinitionKey, String businessKey, Map<String, Object> variables, String tenantId) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId(processDefinitionKey, businessKey, variables, tenantId);
        return processInstance;
    }

    //查询待分配或待审核的任务列表
    //因为待分配和待审核都是按照流程发起时 stationId 来赋值,所以需要根据所对应的工单状态来确定是哪个
    @Override
    public Map<String, String> queryToBeDoneMap(String category, String assignType, List<String> candidateUsers, List<String> stationIds, String tenantId) {
        Map<String, String> businessKeyMap = new HashMap<>();
        //查询代办,没有代办返回空
        List<Task> taskList = taskService.createTaskQuery()
                .taskTenantId(tenantId)
                //目前创建工作流时没有找到category的赋值方法,后续再研究
                //.taskCategory(category)
                .taskCandidateUser(assignType,candidateUsers)
                .taskCandidateGroupIn(stationIds).list();
        if (taskList == null || taskList.isEmpty()) {
            return businessKeyMap;
        }
        for (Task task : taskList) {
            String processInstanceId = task.getProcessInstanceId();
            //从流程实例查询到对应的业务key
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            businessKeyMap.put(businessKey, task.getId());
        }
        return businessKeyMap;
    }

    //个人任务列表
    //返回对应businessKeyList
    @Override
    public Map<String, String> queryPersonalTask(String category, String assignee, String tenantId) {
        Map<String, String> businessKeyMap = new HashMap<>();
        List<Task> taskList = taskService.createTaskQuery()
                .taskTenantId(tenantId)
                .taskCategory(category)
                .taskAssignee(assignee)
                .list();
        if (taskList == null || taskList.isEmpty()) {
            return businessKeyMap;
        }
        for (Task task : taskList) {
            String processInstanceId = task.getProcessInstanceId();
            //从流程实例查询到对应的业务key
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            businessKeyMap.put(businessKey, task.getId());
        }
        return businessKeyMap;

    }


    //得到业务id 集合
    @Override
    public List<String> getOrderIdList(Map<String, String> toDistributeMap, Map<String, String> toDoMap, Map<String, String> toCheckMap) {
        List<String> orderList = new ArrayList<>();
        toDistributeMap.forEach((k ,v)->{
            orderList.add(k);
        });

        toDoMap.forEach((k ,v)->{
            orderList.add(k);
        });
        toCheckMap.forEach((k ,v)->{
            orderList.add(k);
        });
        return orderList;
    }

    @Override
    public void completeTask(String taskId, Map<String, Object> variables) {
        //先查询任务,如果任务不存在,提示错误
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if(task ==null){
            throw  new BusinessException(BaseResponseCode.TASK_NOT_EXISTS);
        }
        try{
            taskService.complete(taskId, variables);
        }catch (Exception e){
            log.error("completeTask Error :" +e.getMessage());
        }
        log.info("completeTask, taskId:{} ,variables:{}", taskId, variables);
    }

    @Override
    public boolean matchPermit(List<String> positions, String[] postConfig) {
        //两个集合中有一个匹配到就有权限
        for (String post : postConfig) {
            for (String position : positions) {
                if(position.equals(post)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<String> intToString(List<Integer> intList) {
        List<String> strList = new ArrayList<>();
        if(intList==null || intList.isEmpty()){
            return strList;
        }
        for (Integer integerObj : intList) {
            strList.add(integerObj.toString());
        }
        return strList;
    }
}
