package com.ho.flow.order1;


import com.fasterxml.jackson.databind.JsonNode;
import com.ho.flow.constant.WorkOrderConstant;
import com.ho.flow.service.ProcessFlowService;
import com.ho.flow.vo.req.workorder.OrderReq;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

/**
 * @author fancl
 * @desc: 工单
 * @date 2023/1/22
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TaskOrder1Demo {
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;

    @Autowired
    ProcessFlowService processFlowService;

    @Autowired
    HistoryService historyService;

    @Value("${flow.workOrder.procDefKey}")
    String procDefKey;

    @Test
    public void getNext(){
        String taskId="567539";
        String next = processFlowService.getNextTaskName(taskId);
        System.out.println();
    }

    /**
     * 测试使用251这个station
     */
    //查询并领取
    @Test
    public void claimTask() {
        List<String> stationIds = new ArrayList<>();
        stationIds.add("251");
        stationIds.add("20");
        String tenantId = "1";
        //任务执行人
        String assignee = "fan";
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey("workOrder")
                .processVariableValueEquals("assignType", "workOrder")
                .taskTenantId(tenantId)
                .taskAssignee(assignee)
                .list();
        Task task = taskList.get(0);
        taskService.setVariableLocal(task.getId(), "complete", 0);
        taskService.setVariableLocal(task.getId(), "beizhu", "王老吉");
        taskService.complete(task.getId());
        System.out.println();
        //完成任务时的流程变量,设置 orderReq.workId
        /*Map<String, Object> map = new HashMap<>();
        List<String> toUsers = Arrays.asList("node2", "node3");
        map.put("toUsers", toUsers);
        map.put("stationId","25");
        for (Task task : taskList) {
            //领取任务
            taskService.claim(task.getId(), assignee);
            taskService.setVariable(task.getId(), "stationId", "25");
            //执行任务,并指定下一个节点的候选人
            //taskService.setVariables(task.getId(), map);
            taskService.complete(task.getId());
        }*/

        System.out.println();

    }


    //查询任务的历史流程变量
    @Test
    public void queryHist(){
        String procInstId = "620281";
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(procInstId).list();
        for (HistoricTaskInstance taskInstance : list) {
            HistoricVariableInstance variableInstance = historyService.createHistoricVariableInstanceQuery()
                    .taskId(taskInstance.getId()).processInstanceId(procInstId).variableName("nodeOneUsers").singleResult();
           JsonNode value = (JsonNode) variableInstance.getValue();
            String s = value.toString();
            String[] userIds = s.split(",");

            System.out.println(variableInstance.getValue().toString());
        }

        System.out.println();
    }

    //接受或驳回
    @Test
    public void getUserTask2() {
        List<String> stationIds = new ArrayList<>();
        String tenantId = "1";
        String assignee = "老范";
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(procDefKey)
                //.processVariableValueEquals("assignType","workOrder")
                //.processVariableValueEquals("role","canDistributeOrder")
                .taskTenantId(tenantId)
                .taskAssignee(assignee)
                //.taskCandidateUser("canDistributeOrder")
                //.processVariableValueEquals()
                //.taskAssignee(assignType)
                .list();
        //完成任务时的流程变量,设置 orderReq.workId
        Map<String, Object> map = new HashMap<>();
        OrderReq orderReq = new OrderReq();
        //下一个处理人还是自己
        orderReq.setWorkerId("老范");
        orderReq.setReject(0);
        map.put("orderReq", orderReq);
        //接受
        //先处理一个
        if(taskList!=null ){
            taskService.complete(taskList.get(0).getId(), map);
        }
        for (Task task : taskList) {
            //
            //taskService.complete(task.getId(), map);
        }

        System.out.println();

    }

    //处理工单
    @Test
    public void getUserTask3() {
        List<String> stationIds = new ArrayList<>();
        stationIds.add("251");
        stationIds.add("45");
        String tenantId = "1";
        String assignee = "老范";
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(procDefKey)
                //.processVariableValueEquals("assignType","workOrder")
                //.processVariableValueEquals("currentNode", WorkOrderConstant.canCheckOrder)
                .taskTenantId(tenantId)
                .taskAssignee(assignee)
                //.taskCandidateUser("canCheckOrder")
                //.taskAssignee(assignType)
                //.taskCandidateUser("canCheckOrder",candiusers)
                //.taskCandidateGroupIn(stationIds)

                .list();
        //处理工单
        Map<String, Object> map = new HashMap<>();
        //将下一节点改为验收节点
        map.put("currentNode", WorkOrderConstant.canCheckOrder);
        //先处理一个
        if(taskList!=null){
            Task task =taskList.get(0);
            taskService.setVariables(task.getId(), map);
            taskService.complete(task.getId(), map);
        }
        //增加local变量
        for (Task task : taskList) {
            //taskService.setVariables(task.getId(), map);
            //taskService.complete(task.getId(), map);
        }

        System.out.println();

    }

    //验收工单
    @Test
    public void getUserTask4() {
        List<String> stationIds = new ArrayList<>();
        stationIds.add("251");
        //注意45是没有值的, 46才有值
        stationIds.add("20");
        String tenantId = "1";
        String assignee = "老范";
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(procDefKey)
                .processVariableValueEquals("assignType", "workOrder")
                .processVariableValueEquals("currentNode", WorkOrderConstant.canCheckOrder)
                .taskTenantId(tenantId)
                //.taskAssignee(assignee)
                //.taskCandidateUser("canCheckOrder")
                //.taskAssignee(assignType)
                //.taskCandidateUser("canCheckOrder",candiusers)
                .taskCandidateGroupIn(stationIds)
                .list();
        //处理工单
        Map<String, Object> map = new HashMap<>();
        OrderReq orderReq = new OrderReq();
        //orderReq.setWorkerId("老范");
        orderReq.setComplete(1);
        map.put("orderReq", orderReq);
        for (Task task : taskList) {
            //taskService.setVariables(task.getId(), map);
            //taskService.complete(task.getId(), map);
        }

        System.out.println();

    }

    //分配流程,指定下一节点处理人是自己
    @Test
    public void distributeTask() {
        //要完成的taskId
        String taskId = "22509";
        //责任人
        String assign = "ceo";
        //集团id
        String tenantId = "1973";
        //设置变量
        Map<String, Object> variables = new HashMap<>();
        //variables.put("age", 30);
        //variables.put("dizhi", "dizhi2");
        List<Task> list = taskService.createTaskQuery().taskTenantId(tenantId).taskAssignee(assign).list();
        for (Task task : list) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            Map<String, Object> processVariables1 = processInstance.getProcessVariables();
            //分配给谁,谁就能查询到这个任务,有worker角色的人才去查 ,没这个角色就不用查,使用assignee来查询自己的任务
            //task.setAssignee("fanfan1");
            OrderReq orderReq = new OrderReq();
            orderReq.setWorkerId("fanfan1");
            //指定下一个接收人 d2
            variables.put("orderReq", orderReq);
            //if(task.getId().equals(taskId)){
            //taskService.setVariables(task.getId(), variables);
            //此时可以增加工单处理记录
            taskService.complete(task.getId(), variables);
            //}
        }


    }

    //接收流程,指定下一节点处理人是自己
    @Test
    public void acceptTask() {
        //要完成的taskId
        String taskId = "22509";
        //责任人
        String assign = "fanfan1";
        //集团id
        String tenantId = "1973";
        //设置变量
        Map<String, Object> variables = new HashMap<>();
        List<Task> list = taskService.createTaskQuery().taskTenantId(tenantId).taskAssignee(assign).list();
        for (Task task : list) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            Map<String, Object> processVariables1 = processInstance.getProcessVariables();
            //流程变量
            //接收后,下一个节点还是自己
            OrderReq orderReq = new OrderReq();
            //reject 设置为0
            orderReq.setReject(0);
            orderReq.setWorkerId("fanfan1");
            variables.put("orderReq", orderReq);
            taskService.setVariables(task.getId(), variables);
            taskService.complete(task.getId(), variables);
        }


    }

    //拒绝流程,将流程返回给上个节点(ceo)
    @Test
    public void rejectTask() {
        //要完成的taskId
        String taskId = "22509";
        //责任人
        String assign = "fanfan1";
        //集团id
        String tenantId = "1973";
        //设置变量
        Map<String, Object> variables = new HashMap<>();
        List<Task> list = taskService.createTaskQuery().taskTenantId(tenantId).taskAssignee(assign).list();
        for (Task task : list) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            Map<String, Object> processVariables1 = processInstance.getProcessVariables();
            //流程变量
            OrderReq orderReq = new OrderReq();
            //设置为拒绝
            orderReq.setReject(1);
            //还要把归属人设置为ceo
            variables.put("orderReq", orderReq);
            task.setAssignee("ceo");
            //if(task.getId().equals(taskId)){
            taskService.setVariables(task.getId(), variables);
            taskService.complete(task.getId(), variables);
            //}
        }


    }

    //完成工单
    @Test
    public void completeTask() {
        //要完成的taskId
        String taskId = "22509";
        //责任人
        String assign = "fanfan1";
        //集团id
        String tenantId = "1973";
        //设置变量
        Map<String, Object> variables = new HashMap<>();

        List<Task> list = taskService.createTaskQuery().taskTenantId(tenantId).taskAssignee(assign).list();
        for (Task task : list) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            Map<String, Object> processVariables1 = processInstance.getProcessVariables();
            //流程变量
            taskService.setVariables(task.getId(), variables);
            taskService.complete(task.getId(), variables);
            //}
        }


    }

}
