package me.zhengjie.modules.dm.activiti;

import me.zhengjie.modules.dm.activiti.event.ActivitiEvent;
import me.zhengjie.modules.dm.activiti.status.OperationStatus;
import me.zhengjie.modules.dm.printingRequest.domain.DmPrintingRequest;
import me.zhengjie.modules.dm.printingRequest.repository.DmPrintingRequestRepository;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.util.DmUserUtils;
import me.zhengjie.utils.StringUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 监听自定义事件(触发工作流的操作)
 */
@Component
public class ActivitiPrinterListener implements ApplicationListener<ActivitiEvent> {

    private final String RESERVE_APPROVE_FLOW = "printingApproval";

    @Autowired
    private ProcessEngine engine;
    @Autowired
    private DmUserService dmUserService;
    @Autowired
    private DmPrintingRequestRepository printingRequestRepository;

    @Override
    public void onApplicationEvent(ActivitiEvent event) {
        System.out.println("onApplicationEvent == > "+event.getStatus());
        DmPrintingRequest printingRequest = (DmPrintingRequest) event.getInfo();
        Map<String,Object> variables = new HashMap<>();
        //提交申请
        if(event.getStatus().equals(OperationStatus.PRINTING_SUBMIT) ){
            //申请操作信息
            variables.put("createUser",printingRequest.getRequestUser().getId());
            variables.put("user_id",printingRequest.getRequestUser().getId());
            variables.put("user_table","dm_user");
            variables.put("op_id",printingRequest.getId());
            variables.put("op_table","dm_printing_request");
            variables.put("is_auto",1);//是否自动执行下一节点(0-自动 1-不自动)
            //启动流程
            runFlow(RESERVE_APPROVE_FLOW,variables);
        }
        //提交审批人
        if(event.getStatus().equals(OperationStatus.PRINTING_SUBMIT_APPROVAL_USER)){
            List<Long> approveList = new ArrayList<>();
            //下一节点,审批人信息
            Map<String,Object> approveInfo = printingRequestRepository.selectPrintingApproveUserNames(printingRequest.getId());
            if(approveInfo != null){
                String userIds = (String) approveInfo.get("userIds");
                if(StringUtils.isNotBlank(userIds)){
                    String[] arr = userIds.split(",");
                    for(String s:arr){
                        if(StringUtils.isNotBlank(s)){
                            approveList.add(Long.parseLong(s));
                        }
                    }
                }else{
                 //   approveList = dmUserService.findIdsByIsApprover(true,meeting.getDept().getId());
                }
            }else{
             //   approveList = dmUserService.findIdsByIsApprover(true,meeting.getDept().getId());
            }
            variables.put("approvalUserList",approveList);
            completeTask(printingRequest.getTaskId(),variables);
        }
        //审批
        if(event.getStatus().equals(OperationStatus.PRINTING_APPROVE)){
            variables.put("approve_user_id",DmUserUtils.getCurrDmUser().getId());
            variables.put("approve_user_table","dm_user");
            variables.put("op_id",printingRequest.getId());
            variables.put("op_table","dm_printing_request");
            variables.put("status",printingRequest.getStatus());
            variables.put("reason",printingRequest.getApprovalRemark());
            variables.put("is_auto",1);//不需要自动执行下一节点
            completeTask(printingRequest.getTaskId(),variables);
        }
        //终止流程实例
        if(event.getStatus().equals(OperationStatus.PRINTING_PUZ_INST)){
            puzInstance(printingRequest.getProcInstId(),event.getRemark());
        }
    }

    /**
     * 启动工作流
     */
    private ProcessInstance runFlow(String key, Map<String,Object> variables){
        //根据Key值取最新的流程定义
        RepositoryService repositoryService = engine.getRepositoryService();
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        processDefinitionQuery.processDefinitionKey(key);
        processDefinitionQuery.orderByProcessDefinitionVersion().desc();
        List<ProcessDefinition> list = processDefinitionQuery.list();
        //启动
        RuntimeService runtimeService = engine.getRuntimeService();
        return runtimeService.startProcessInstanceById(list.get(0).getId(),variables);
    }

    /**
     * 完成任务
     * @param taskId 任务id
     * @param variables 参数
     */
    private void completeTask(String taskId, Map<String,Object> variables){
        TaskService taskService = engine.getTaskService();
        taskService.complete(taskId,variables);
    }

    /**
     * 终止流程实例(删除会议时,删除还在进行中的关联流程实例)
     * @param procInstId 实例id
     * @param remark 原因
     */
    public void puzInstance(String procInstId,String remark){
        engine.getRuntimeService().deleteProcessInstance(procInstId,remark);
    }

}
