package com.th.demo.controller.process;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.th.demo.model.system.SysUser;
import com.th.demo.model.system.Type;
import com.th.demo.service.process.BussinessService;
import com.th.demo.service.system.SysUserService;
import com.th.demo.tools.DateTools;
import com.th.demo.tools.Tools;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by dell on 2018-11-13.
 */
@RestController
@RequestMapping(value = "/ProcessTask")
public class TaskController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;
    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Autowired
    private BussinessService bussinessService;

    @Autowired
    private SysUserService sysUserService;

    String result = Type.FAIL;



    @RequestMapping(value = "/queryBussinessData.do")
    public String query(  String processInstanceId ) throws IOException {

        System.out.println("----------------"+processInstanceId);
         Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        System.out.println("----------------"+task.getProcessDefinitionId());
        ProcessDefinition pdef = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()) .singleResult();
        System.out.println("----------------"+pdef.getKey());

      result =   bussinessService.queryBussiness(processInstanceId,pdef.getKey());

        return result;
    }




    @RequestMapping(value = "/query.do")
    public String query(int page,
                        int rows,
                        String key,
                        String userId,
                        HttpServletResponse response) throws IOException {

        PageHelper.startPage(page, rows);
        List<Task> list = taskService.createTaskQuery().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (Task t : list) {
            HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(t.getProcessInstanceId()).singleResult();
            map = new HashMap<String, Object>();
            map.put("id", t.getId());
            map.put("name", t.getName());
            map.put("processDefinitionId", t.getProcessDefinitionId());
            map.put("processInstanceId", t.getProcessInstanceId());
            map.put("assignee", t.getAssignee());
            map.put("isSuspended", t.isSuspended());
            map.put("startTime", DateTools.DateToStr(hpi.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            if(hpi.getStartUserId()!=null) {
                String userName = sysUserService.queryByUserId(hpi.getStartUserId());
                map.put("startUserId", userName);
            }
            map.put("duration", DateTools.getDayHourMinSec(new Date(), hpi.getStartTime()));

            listmap.add(map);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(listmap);
        //PageInfo<Task> pageInfo = new PageInfo<>(list);
        result = JSON.toJSONString(pageInfo);
        return result;
    }


    @RequestMapping(value = "/find.do")
    public String find(int page,
                       int rows,
                       String assignee,
                       String userId,
                       HttpServletResponse response) throws IOException {

        PageHelper.startPage(page, rows);
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).orderByTaskCreateTime().desc().list();

        List<Map<String, Object>> listmap = new ArrayList<>();
        Map<String, Object> map;
        for (Task t : list) {
            HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(t.getProcessInstanceId()).singleResult();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(t.getProcessDefinitionId()).singleResult();
            map = new HashMap<String, Object>();
            map.put("id", t.getId());
            map.put("name", processDefinition.getName());
            map.put("key", processDefinition.getKey());
            map.put("processDefinitionId", t.getProcessDefinitionId());
            map.put("processInstanceId", t.getProcessInstanceId());
            map.put("assignee", t.getAssignee());
            map.put("isSuspended", t.isSuspended());
            map.put("startTime",  DateTools.DateToStr(hpi.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            if(hpi.getStartUserId()!=null) {
                String userName = sysUserService.queryByUserId(hpi.getStartUserId());
                map.put("startUserId", userName);
            }
            map.put("duration",DateTools.getDayHourMinSec(new Date(), hpi.getStartTime()));

            listmap.add(map);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(listmap);
        //PageInfo<Task> pageInfo = new PageInfo<>(list);
        result = JSON.toJSONString(pageInfo);
        return result;
    }

    @RequestMapping(value = "/complete.do")
    public String complete(String taskId,
                           String comment,
                           String userId,
                           String flag) throws IOException {


        try {

            Authentication.setAuthenticatedUserId("admin");

            taskService.addComment(taskId, null, comment);

            Map<String, Object> variables = new HashMap<>();
            variables.put("flag", flag);
            taskService.complete(taskId, variables);
            result = Type.SUCCESS;
        } catch (Exception ex) {
            ex.printStackTrace();
            result = Type.FAIL + ex.getMessage();
        } finally {
            return result;
        }
    }

    @RequestMapping(value = "/showImg.do")
    public void showImg(String processInstanceId
            , HttpServletResponse response) throws IOException {
        try {
            //获取历史流程实例
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取流程图
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());

            processEngineConfiguration = processEngine.getProcessEngineConfiguration();
            Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

            ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();

            ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

            List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
            //高亮环节id集合
            List<String> highLightedActivitis = new ArrayList<String>();
            //高亮线路id集合
            List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

            for (HistoricActivityInstance tempActivity : highLightedActivitList) {
                String activityId = tempActivity.getActivityId();
                highLightedActivitis.add(activityId);
            }
            //当前流程实例执行到哪个节点
            ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();// 执行实例
            highLightedActivitis.add(execution.getActivityId());
            //中文显示的是口口口，设置字体就好了
            InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(), 1.0);
            //单独返回流程图，不高亮显示
//        InputStream imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
            // 输出资源内容到相应对象
            byte[] b = new byte[1024];
            int len;
            OutputStream out = response.getOutputStream();
            while ((len = in.read(b, 0, 1024)) != -1) {
                out.write(b, 0, len);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/showHistoryImg.do")
    public void showHistoryImg(String processInstanceId
            , HttpServletResponse response) throws IOException {
        try {
            //获取历史流程实例
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //获取流程图
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());

            processEngineConfiguration = processEngine.getProcessEngineConfiguration();
            Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

            ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();

            ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

            List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
            //高亮环节id集合
            List<String> highLightedActivitis = new ArrayList<String>();
            //高亮线路id集合
            List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

            for (HistoricActivityInstance tempActivity : highLightedActivitList) {
                String activityId = tempActivity.getActivityId();
                highLightedActivitis.add(activityId);
            }

            //中文显示的是口口口，设置字体就好了
            InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(), 1.0);
            //单独返回流程图，不高亮显示
//        InputStream imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
            // 输出资源内容到相应对象
            byte[] b = new byte[1024];
            int len;
            OutputStream out = response.getOutputStream();
            while ((len = in.read(b, 0, 1024)) != -1) {
                out.write(b, 0, len);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取需要高亮的线
     *
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }


}
