package com.yanzhu.flowable.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yanzhu.common.core.domain.AjaxResult;
import com.yanzhu.common.core.domain.entity.SysUser;
import com.yanzhu.common.core.text.Convert;
import com.yanzhu.common.utils.SecurityUtils;
import com.yanzhu.common.utils.StringUtils;
import com.yanzhu.flowable.common.constant.ProcessConstants;
import com.yanzhu.flowable.common.enums.FlowComment;
import com.yanzhu.flowable.factory.FlowServiceFactory;
import com.yanzhu.flowable.service.IFlowDefinitionService;
import com.yanzhu.flowable.service.ISysDeployFormService;
import com.yanzhu.project.domain.ProProjectApply;
import com.yanzhu.project.service.IProProjectApplyService;
import com.yanzhu.system.domain.FlowProcDefDto;
import com.yanzhu.system.domain.flowable.FlowDeptVo;
import com.yanzhu.system.domain.flowable.FlowQueryVo;
import com.yanzhu.system.mapper.FlowDeployMapper;
import com.yanzhu.system.service.ISysDeptService;
import com.yanzhu.system.service.ISysPostService;
import com.yanzhu.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程定义
 *
 * @author Tony
 * @date 2021-04-03
 */
@Service
@Slf4j
public class FlowDefinitionServiceImpl extends FlowServiceFactory implements IFlowDefinitionService {

    @Resource
    private ISysDeployFormService sysDeployFormService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysPostService postService;

    @Resource
    private FlowDeployMapper flowDeployMapper;

    @Autowired
    private IProProjectApplyService proProjectApplyService;

    private static final String BPMN_FILE_SUFFIX = ".bpmn";

    @Override
    public boolean exist(String processDefinitionKey) {
        ProcessDefinitionQuery processDefinitionQuery
                = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
        long count = processDefinitionQuery.count();
        return count > 0 ? true : false;
    }


    /**
     * 流程定义列表
     *
     * @param flowQueryVo  流程查询
     * @return 流程定义分页列表数据
     */
    @Override
    public Page<FlowProcDefDto> list(FlowQueryVo flowQueryVo) {
        Page<FlowProcDefDto> page = new Page<>();
        PageHelper.startPage(flowQueryVo.getPageNum(), flowQueryVo.getPageSize());
        List<FlowProcDefDto> dataList = flowDeployMapper.selectDeployList(flowQueryVo);
        // 加载挂表单
        /**for (FlowProcDefDto procDef : dataList) {
            SysForm sysForm = sysDeployFormService.selectSysDeployFormByDeployId(procDef.getDeploymentId());
            if (Objects.nonNull(sysForm)) {
                procDef.setFormName(sysForm.getFormName());
                procDef.setFormId(sysForm.getFormId());
            }
        }*/
        if(flowQueryVo.getDeptId()!=null){
            // 单位查询时::查询缺省工作流
            List<String> categoryList = dataList.stream().map(FlowProcDefDto::getCategory).collect(Collectors.toList());
            List<FlowProcDefDto> defaultList = flowDeployMapper.selectDefaultDeployList(categoryList);
            if(CollectionUtils.isNotEmpty(defaultList)){
                dataList.addAll(defaultList);
            }
        }
        page.setTotal(new PageInfo(dataList).getTotal());
        page.setRecords(dataList);
        return page;
    }


    /**
     * 导入流程文件
     *
     * 当每个key的流程第一次部署时，指定版本为1。对其后所有使用相同key的流程定义，
     * 部署时版本会在该key当前已部署的最高版本号基础上加1。key参数用于区分流程定义
     * @param name 流程名称
     * @param category 流程类型
     * @param OwnerDeptId 流程单位
     * @param in 流程文件流
     */
    @Override
    public void importFile(String name, String category, String OwnerDeptId, InputStream in) {
        Deployment deploy = repositoryService.createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in).name(name).category(category).deploy();
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        repositoryService.setProcessDefinitionCategory(definition.getId(), category);
        /**新增流程单位关系**/
        FlowDeptVo flowDeptVo = new FlowDeptVo();
        flowDeptVo.setProcdefId(definition.getId());
        //超管能为
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            if(StringUtils.isNotEmpty(OwnerDeptId)){
                // OwnerDeptId转换Long失败...默认返回null
                flowDeptVo.setDeptId(Convert.toLong(OwnerDeptId));
            }
        }else{
            // 从部门祖籍列表中获取项目单位信息...
            Long projectDeptId = Convert.toLong(SecurityUtils.getLoginUser().getUser().getDept().getAncestors().split(",")[2]);
            flowDeptVo.setDeptId(projectDeptId);
        }
        if(flowDeptVo.getDeptId()!=null){
            flowDeployMapper.insertActReProcdefDept(flowDeptVo);
        }
    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Override
    public AjaxResult readXml(String deployId) throws IOException {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(definition.getDeploymentId(), definition.getResourceName());
        String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
        return AjaxResult.success("", result);
    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Override
    public InputStream readImage(String deployId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        //获得图片流
        DefaultProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //输出为图片
        return diagramGenerator.generateDiagram(
                bpmnModel,
                "png",
                Collections.emptyList(),
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体",
                null,
                1.0,
                false);

    }

    /**
     * 根据流程定义ID启动流程实例
     *
     * @param procDefId 流程模板ID
     * @param proProjectApply 流程表单
     * @return
     */
    @Override
    public AjaxResult startProcessInstanceById(String procDefId, ProProjectApply proProjectApply) {
        try {
            /**保存流程表单**/
            int res = proProjectApplyService.insertProProjectApply(proProjectApply);
            if(res>0){
                Map<String, Object> variables = new HashMap<>();
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId)
                        .latestVersion().singleResult();
                if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
                    return AjaxResult.error("流程已被挂起,请联系管理员激活流程");
                }
                SysUser sysUser = SecurityUtils.getLoginUser().getUser();
                String userId = Convert.toStr(sysUser.getUserId());
                // 设置流程发起人Id到流程中
                identityService.setAuthenticatedUserId(userId);
                variables.put(ProcessConstants.PROCESS_INITIATOR, userId);
                variables.put("businessKey", proProjectApply.getId());
                ProcessInstance processInstance;
                if(variables.get("businessKey")!=null){
                    processInstance = runtimeService.startProcessInstanceById(procDefId, Convert.toStr(variables.get("businessKey")),variables);
                }else{
                    processInstance = runtimeService.startProcessInstanceById(procDefId, variables);
                }
                // 给第一步申请人节点设置任务执行人和意见
                Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
                if (Objects.nonNull(task)) {
                    taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), sysUser.getNickName() + "发起流程申请");
                    taskService.setAssignee(task.getId(), Convert.toStr(userId));
                    taskService.complete(task.getId(), variables);
                }
                return AjaxResult.success("流程启动成功");
            }else{
                return AjaxResult.error("流程表单保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("流程启动错误");
        }
    }

    /**
     * 激活或挂起流程定义
     *
     * @param state    状态
     * @param deployId 流程部署ID
     */
    @Override
    public void updateState(Integer state, String deployId) {
        ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        // 激活
        if (state == 1) {
            repositoryService.activateProcessDefinitionById(procDef.getId(), true, null);
        }
        // 挂起
        if (state == 2) {
            repositoryService.suspendProcessDefinitionById(procDef.getId(), true, null);
        }
    }


    /**
     * 删除流程定义
     *
     * @param deployId 流程部署ID act_ge_bytearray 表中 deployment_id值
     */
    @Override
    public void delete(String deployId) {
        // true 允许级联删除 ,不设置会导致数据库外键关联异常
        repositoryService.deleteDeployment(deployId, true);
    }

}
