package com.bbd.bpm.serviceImpl;

import com.bbd.bpm.bean.BtnBean;
import com.bbd.bpm.bean.CommonRequest;
import com.bbd.bpm.bean.OaException;
import com.bbd.bpm.dto.request.SpecialRequest;
import com.bbd.bpm.service.ActivitiService;
import org.activiti.bpmn.model.*;
import org.activiti.engine.*;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yanlj on 2017/9/1.
 */
@Component("activitiService")
public class ActivitiServiceImpl implements ActivitiService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    private ProcessEngine processEngine;



    @Override
    public byte[] traceProcessImage(SpecialRequest request) throws IOException {
        Execution execution = null;
        if (StringUtils.isNotBlank(request.getExecutionId())) {
            execution = runtimeService.createExecutionQuery().executionId(request.getExecutionId()).singleResult();//执行实例
        }
        if (execution == null) {
            if (StringUtils.isNotBlank(request.getTaskId())) {
                Task task = taskService.createTaskQuery().taskId(request.getTaskId()).singleResult();
                if (task != null) {
                    execution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();//执行实例
                }
            }
        }
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(execution.getId());

        // 使用spring注入引擎请使用下面的这行代码
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
            InputStream imageStream = diagramGenerator.generateDiagram(
                    bpmnModel,
                    "png",
                    activeActivityIds,
                    new ArrayList<String>(),
                    "宋体",
                    "宋体",
                    null,
                    null,1.0);
        byte[] bytes = IOUtils.toByteArray(imageStream);
        return bytes;
    }



    @Override
    public byte[] getProcessImage(SpecialRequest request) {
        ProcessDefinition processDefinition = null;
        if (StringUtils.isNotBlank(request.getProcdefId())) {
            processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(request.getProcdefId()).singleResult();
        }
        if (processDefinition == null) {
            if (StringUtils.isNotBlank(request.getProcessInstanceId())) {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(request.getProcessInstanceId()).singleResult();
                processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
            }
            if (StringUtils.isNotBlank(request.getTaskId())) {
                Task task = taskService.createTaskQuery().taskId(request.getTaskId()).singleResult();
                processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
            }
        }
        if (processDefinition != null) {
            InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
            try {
                byte[] bytes = IOUtils.toByteArray(inputStream);
                return bytes;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
    @Override
    public byte[] getdeployMent(SpecialRequest request) {
        List<String> names = repositoryService.getDeploymentResourceNames(request.getDeploymentId());
        String imageName = null;
        for (String name : names) {
            if(name.indexOf(".png")>=0){
                imageName = name;
            }
        }
        if(imageName!=null){
            // 通过部署ID和文件名称得到文件的输入流
            InputStream  in = repositoryService.getResourceAsStream(request.getDeploymentId(),imageName);

            try {
                byte[] bytes = IOUtils.toByteArray(in);
                return bytes;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    @Override
    public List<BtnBean> workflowButton(CommonRequest request) throws OaException {
        List<BtnBean> buttons = new ArrayList<>();
       /* if (StringUtils.isNotBlank(request.getContent())) {
            WorkflowBtnBean workflowBtnBean = JSONObject.parseObject(request.getContent(), WorkflowBtnBean.class);
            RepositoryServiceImpl repositoryServiceImpl = (RepositoryServiceImpl) repositoryService;
            Task task = taskService.createTaskQuery().taskId(workflowBtnBean.getTaskId()).singleResult();
            ReadOnlyProcessDefinition definition = repositoryServiceImpl.getDeployedProcessDefinition(task.getProcessDefinitionId());
            ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) definition;
            ActivityImpl activity = processDefinitionEntity.findActivity(task.getTaskDefinitionKey());
            BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
            List<PvmTransition> outgoingTransitions = activity.getOutgoingTransitions();
            if (outgoingTransitions != null && outgoingTransitions.size() > 0) {
                for (PvmTransition transition : outgoingTransitions) {
                    FlowElement flowElement = bpmnModel.getFlowElement(transition.getDestination().getId());
                    if (flowElement instanceof ExclusiveGateway) {
                        System.out.println("ExclusiveGateway");
                        List<SequenceFlow> outgoingFlows = ((ExclusiveGateway) flowElement).getOutgoingFlows();
                        for (SequenceFlow sequenceFlow : outgoingFlows) {
                            if (sequenceFlow.getConditionExpression().contains("chooseWay.checkString")) {
                                if (StringUtils.isNotBlank(sequenceFlow.getName())) {
                                    BtnBean btn = new BtnBean();
                                    btn.setBtnKey(sequenceFlow.getName());
                                    btn.setBtnValue(sequenceFlow.getId());
                                    buttons.add(btn);
                                }
                            }
                        }
                    }
                    if (flowElement instanceof UserTask) {
                        if (StringUtils.isNotBlank(flowElement.getName())) {
                            BtnBean btn = new BtnBean();
                            btn.setBtnValue(flowElement.getName());
                            btn.setBtnKey(flowElement.getName());
                            buttons.add(btn);
                        } else {
                            BtnBean btn = new BtnBean();
                            btn.setBtnValue("提交");
                            btn.setBtnKey("提交");
                            buttons.add(btn);
                        }
                    }
                    if (flowElement instanceof EndEvent) {
                        BtnBean btn = new BtnBean();
                        btn.setBtnValue("结束");
                        btn.setBtnKey("结束");
                        buttons.add(btn);
                    }
                }
            }
        }*/
        return buttons;
    }


}
