package com.qmth.sop.business.activiti.listener;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.sop.business.bean.dto.FlowRejectSequenceDto;
import com.qmth.sop.business.bean.result.*;
import com.qmth.sop.business.entity.*;
import com.qmth.sop.business.service.*;
import com.qmth.sop.business.util.SmsSendUtil;
import com.qmth.sop.common.contant.SpringContextHolder;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.*;
import com.qmth.sop.common.util.JacksonUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.ResourceEntity;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description: 全局监听
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2022/2/8
 */
@Component
public class ProcessEventListener implements ActivitiEventListener, Serializable {
    private final static Logger log = LoggerFactory.getLogger(ProcessEventListener.class);

    @Override
    public void onEvent(ActivitiEvent event) {
        switch (event.getType()) {
            case PROCESS_STARTED:
                // 流程启动
                log.info("流程启动_PROCESS_STARTED:ProcessInstanceId:{},ExecutionId:{},ProcessDefinitionId:{}", event.getProcessInstanceId(), event.getExecutionId(), event.getProcessDefinitionId());
                break;
            case PROCESS_COMPLETED:
                // 流程结束
                log.info("流程结束_PROCESS_COMPLETED:ProcessInstanceId:{},ExecutionId:{},ProcessDefinitionId:{}", event.getProcessInstanceId(), event.getExecutionId(), event.getProcessDefinitionId());
                HistoryService historyService = SpringContextHolder.getBean(HistoryService.class);

                List<HistoricVariableInstance> historicVariableInstanceList = historyService.createHistoricVariableInstanceQuery().processInstanceId(event.getProcessInstanceId()).list();
                if (!CollectionUtils.isEmpty(historicVariableInstanceList)) {
                    TFCustomFlow tfCustomFlow = null;
                    TFCustomFlowEntity tfCustomFlowEntity = null;
                    TFFlowApprove tfFlowApprove = null;
                    TFFlowLog tfFlowLog = null;
                    for (HistoricVariableInstance h : historicVariableInstanceList) {
                        if (Objects.equals(h.getVariableName(), SystemConstant.FLOW_CUSTOM)) {
                            tfCustomFlow = (TFCustomFlow) h.getValue();
                            Optional.ofNullable(tfCustomFlow).orElseThrow(() -> ExceptionResultEnum.FLOW_CUSTOM_NO_DATA.exception());
                        }
                        if (Objects.equals(h.getVariableName(), SystemConstant.FLOW_ENTITY)) {
                            tfCustomFlowEntity = (TFCustomFlowEntity) h.getValue();
                            Optional.ofNullable(tfCustomFlowEntity).orElseThrow(() -> ExceptionResultEnum.FLOW_ENTITY_NO_DATA.exception());
                        }
                        if (Objects.equals(h.getVariableName(), SystemConstant.FLOW_APPROVE)) {
                            tfFlowApprove = (TFFlowApprove) h.getValue();
                            Optional.ofNullable(tfFlowApprove).orElseThrow(() -> ExceptionResultEnum.FLOW_APPROVE_NO_DATA.exception());
                        }
                        if (Objects.equals(h.getVariableName(), SystemConstant.FLOW_APPROVE_LOG)) {
                            tfFlowLog = (TFFlowLog) h.getValue();
                            Optional.ofNullable(tfFlowLog).orElseThrow(() -> ExceptionResultEnum.FLOW_APPROVE_LOG_NO_DATA.exception());
                        }
                    }
                    this.sendFlowFinishSms(tfCustomFlow.getType(), tfCustomFlowEntity, tfFlowApprove.getStatus(), tfFlowLog);
                }
                break;
            case TASK_CREATED:
                log.info("流程任务创建_TASK_CREATED:ProcessInstanceId:{},ExecutionId:{},ProcessDefinitionId:{}", event.getProcessInstanceId(), event.getExecutionId(), event.getProcessDefinitionId());
                TaskService taskService = SpringContextHolder.getBean(TaskService.class);
                ActivitiEntityEvent activitiEntityEvent = (ActivitiEntityEvent) event;
                if (activitiEntityEvent.getEntity() instanceof Task) {
                    Task task = (Task) activitiEntityEvent.getEntity();
                    if (Objects.nonNull(task)) {
                        TFCustomFlow tfCustomFlow = (TFCustomFlow) taskService.getVariable(task.getId(), SystemConstant.FLOW_CUSTOM);
                        Optional.ofNullable(tfCustomFlow).orElseThrow(() -> ExceptionResultEnum.FLOW_CUSTOM_NO_DATA.exception());

                        TFCustomFlowEntity tfCustomFlowEntity = (TFCustomFlowEntity) taskService.getVariable(task.getId(), SystemConstant.FLOW_ENTITY);
                        Optional.ofNullable(tfCustomFlowEntity).orElseThrow(() -> ExceptionResultEnum.FLOW_ENTITY_NO_DATA.exception());

                        TFFlowApprove tfFlowApprove = (TFFlowApprove) taskService.getVariable(task.getId(), SystemConstant.FLOW_APPROVE);
                        Optional.ofNullable(tfFlowApprove).orElseThrow(() -> ExceptionResultEnum.FLOW_APPROVE_NO_DATA.exception());

                        TFFlowLog tfFlowLog = (TFFlowLog) taskService.getVariable(task.getId(), SystemConstant.FLOW_APPROVE_LOG);
                        Optional.ofNullable(tfFlowLog).orElseThrow(() -> ExceptionResultEnum.FLOW_APPROVE_LOG_NO_DATA.exception());

                        //此处统一流程节点保存延期预警任务
                        if ((tfCustomFlow.getType() == TFCustomTypeEnum.OFFICE_SOP_FLOW || tfCustomFlow.getType() == TFCustomTypeEnum.CLOUD_MARK_SOP_FLOW)
                                && tfFlowLog.getApproveOperation() != FlowApproveOperationEnum.DRAFT
                                && tfFlowLog.getApproveOperation() != FlowApproveOperationEnum.END
                                && tfFlowLog.getApproveOperation() != FlowApproveOperationEnum.FINISH) {
                            if (Objects.nonNull(task.getAssignee())) {
                                this.sendSopFlowDoneSms(tfCustomFlow.getType(), tfCustomFlowEntity, task.getName(), Long.parseLong(task.getAssignee()));
                            } else {
                                List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(task.getId());
                                if (!CollectionUtils.isEmpty(identityLinkList)) {
                                    for (IdentityLink i : identityLinkList) {
                                        this.sendSopFlowDoneSms(tfCustomFlow.getType(), tfCustomFlowEntity, task.getName(), Long.parseLong(i.getUserId()));
                                    }
                                }
                            }
                        }
                    }
                }
                break;
            case TASK_COMPLETED:
                // 任务被完成了。它会在ENTITY_DELETE事件之前触发。当任务是流程一部分时，事件会在流程继续运行之前， 后续事件将是ACTIVITY_COMPLETE，对应着完成任务的节点。
                log.info("流程任务完成_TASK_COMPLETED:ProcessInstanceId:{},ExecutionId:{},ProcessDefinitionId:{}", event.getProcessInstanceId(), event.getExecutionId(), event.getProcessDefinitionId());
                taskService = SpringContextHolder.getBean(TaskService.class);
                TSJobRemindService jobRemindService = SpringContextHolder.getBean(TSJobRemindService.class);
                activitiEntityEvent = (ActivitiEntityEvent) event;
                if (activitiEntityEvent.getEntity() instanceof Task) {
                    Task task = (Task) activitiEntityEvent.getEntity();
                    if (Objects.nonNull(task)) {
                        TFCustomFlow tfCustomFlow = (TFCustomFlow) taskService.getVariable(task.getId(), SystemConstant.FLOW_CUSTOM);
                        Optional.ofNullable(tfCustomFlow).orElseThrow(() -> ExceptionResultEnum.FLOW_CUSTOM_NO_DATA.exception());

                        TFFlowLog tfFlowLog = (TFFlowLog) taskService.getVariable(task.getId(), SystemConstant.FLOW_APPROVE_LOG);
                        Optional.ofNullable(tfFlowLog).orElseThrow(() -> ExceptionResultEnum.FLOW_APPROVE_LOG_NO_DATA.exception());

                        if ((tfCustomFlow.getType() == TFCustomTypeEnum.OFFICE_SOP_FLOW || tfCustomFlow.getType() == TFCustomTypeEnum.CLOUD_MARK_SOP_FLOW) && tfFlowLog.getApproveSetup().intValue() > 1) {//流程提交不需要提醒
                            //任务完成后统一设置延期预警任务enable为false
                            jobRemindService.updateJobRemind(Long.parseLong(task.getId()));
                        }
                    }
                }
                break;
            case ENTITY_CREATED:
                activitiEntityEvent = (ActivitiEntityEvent) event;
                if (activitiEntityEvent.getEntity() instanceof ResourceEntity) {
                    ResourceEntity resourceEntity = (ResourceEntity) activitiEntityEvent.getEntity();
                    log.info("ENTITY_CREATED,id:{},name:{},deploymentId:{},persistentState:{}", resourceEntity.getId(), resourceEntity.getName(), resourceEntity.getDeploymentId(), resourceEntity.getPersistentState());
                    String xml = new String(resourceEntity.getBytes(), StandardCharsets.UTF_8);
                    if (resourceEntity.getName().endsWith(SystemConstant.BPMN_PREFIX)) {
                        parseXml(xml, resourceEntity);
                    } else {
//                        log.info("ENTITY_CREATED,data:{}", data);
                        SystemConstant.FLOW_MAP.add(resourceEntity.getDeploymentId() + SystemConstant.FLOW_FORM_ID_SPACE + resourceEntity.getName(), xml);
                        if (SystemConstant.FLOW_MAP.containsKey(resourceEntity.getDeploymentId() + SystemConstant.BPMN_PREFIX)) {
                            parseXml(SystemConstant.FLOW_MAP.get(resourceEntity.getDeploymentId() + SystemConstant.BPMN_PREFIX).get(0), resourceEntity);
                        }
                    }
                }
                break;
            default:
//                log.info("default->type:{},ProcessInstanceId:{},ExecutionId:{},ProcessDefinitionId:{}", event.getType(), event.getProcessInstanceId(), event.getExecutionId(), event.getProcessDefinitionId());
                break;
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    /**
     * 解析xml
     *
     * @param xml
     * @param resourceEntity
     */
    protected void parseXml(String xml, ResourceEntity resourceEntity) {
//        log.info("ENTITY_CREATED,xml:{}", xml);
        try {
//            TDFormWidgetService tdFormWidgetService = SpringContextHolder.getBean(TDFormWidgetService.class);
            Document doc = DocumentHelper.parseText(xml);
            Element rootElement = doc.getRootElement();
            // 通过element对象的elementIterator方法获取迭代器
            Iterator iterator = rootElement.elementIterator();
            LinkedHashMap<String, FlowTaskResult> setupMap = new LinkedHashMap<>();//流程审批步骤map
            TFCustomTypeEnum customTypeEnum = null;
            Map<String, List<FlowRejectSequenceDto>> approveRejectMap = null;
            while (iterator.hasNext()) {
                Element element = (Element) iterator.next();
                List<Attribute> attributes = element.attributes();
                for (Attribute attr : attributes) {
//                    log.info("属性：{},---值：{}", attr.getName(), attr.getValue());
                    if (Objects.equals(attr.getName(), SystemConstant.ID) &&
                            (Objects.equals(attr.getValue(), TFCustomTypeEnum.OFFICE_SOP_FLOW.name())
                                    || Objects.equals(attr.getValue(), TFCustomTypeEnum.CLOUD_MARK_SOP_FLOW.name())
                                    || Objects.equals(attr.getValue(), TFCustomTypeEnum.DING_EXCEPTION_FLOW.name())
                                    || Objects.equals(attr.getValue(), TFCustomTypeEnum.PROJECT_EXCHANGE_FLOW.name())
                                    || Objects.equals(attr.getValue(), TFCustomTypeEnum.QUALITY_PROBLEM_FLOW.name()))) {
                        customTypeEnum = TFCustomTypeEnum.valueOf(attr.getValue());
                        break;
                    }
                }
                Iterator itt = element.elementIterator();
                while (itt.hasNext()) {
                    FlowTaskResult flowTaskResult = new FlowTaskResult();
                    Element node = (Element) itt.next();
                    attributes = node.attributes();
//                    log.info("节点：{},---值：{}", node.getName(), node.getStringValue());
                    if (Objects.equals(node.getName(), SystemConstant.USER_TASK) || Objects.equals(node.getName(), SystemConstant.START_EVENT) || Objects.equals(node.getName(), SystemConstant.END_EVENT)) {
                        for (Attribute attr : attributes) {
//                            log.info("节点属性：{},---节点值：{}", attr.getName(), attr.getValue());
                            if (Objects.equals(node.getName(), SystemConstant.USER_TASK) || Objects.equals(node.getName(), SystemConstant.END_EVENT)) {
                                if (Objects.equals(attr.getName(), SystemConstant.ID)) {
                                    flowTaskResult.setTaskKey(attr.getValue());
                                    String[] strs = attr.getValue().split("_");
                                    flowTaskResult.setSetup(Integer.parseInt(strs[strs.length - 1]));
                                    setupMap.put(attr.getValue(), flowTaskResult);
                                } else if (Objects.equals(attr.getName(), SystemConstant.NAME)) {
                                    flowTaskResult.setTaskName(attr.getValue());
                                } else if (Objects.equals(attr.getName(), SystemConstant.FORM_KEY) && SystemConstant.FLOW_MAP.containsKey(resourceEntity.getDeploymentId() + SystemConstant.FLOW_FORM_ID_SPACE + attr.getValue())) {
                                    if (Objects.equals(node.getName(), SystemConstant.USER_TASK) || Objects.equals(node.getName(), SystemConstant.END_EVENT)) {
                                        flowTaskResult.setFormKey(attr.getValue());
                                        //从数据库取
//                                        List<FlowFormWidgetResult> listData = tdFormWidgetService.flowWidgetQuery(customTypeEnum, flowTaskResult.getSetup());
                                        List<String> list = SystemConstant.FLOW_MAP.get(resourceEntity.getDeploymentId() + SystemConstant.FLOW_FORM_ID_SPACE + attr.getValue());
                                        String data = list.get(list.size() - 1);
                                        List<FlowFormWidgetResult> listData = JSONArray.parseArray(data, FlowFormWidgetResult.class);
                                        for (FlowFormWidgetResult f : listData) {
                                            String[] strs = flowTaskResult.getTaskKey().split("_");
                                            f.setFormId(f.getFormId() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]));
                                            f.setFormName(f.getFormName() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]));
                                            if (!CollectionUtils.isEmpty(f.getTablePropList())) {
                                                for (FlowTablePropResult t : f.getTablePropList()) {
                                                    t.setTdId(t.getWidgetId() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]) + SystemConstant.FLOW_FORM_ID_UNDERLINE + t.getTdId() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]));
                                                    t.setTdName(t.getWidgetId() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]) + SystemConstant.FLOW_FORM_ID_UNDERLINE + t.getTdName() + SystemConstant.FLOW_FORM_ID_UNDERLINE + Integer.parseInt(strs[strs.length - 1]));
                                                }
                                            }
                                        }
                                        flowTaskResult.setFormProperty(listData);
                                    }
                                }
                            } else {
                                List<String> list = SystemConstant.FLOW_MAP.get(resourceEntity.getDeploymentId() + SystemConstant.FLOW_FORM_ID_SPACE + attr.getValue());
                                if (!CollectionUtils.isEmpty(list)) {
                                    String data = list.get(list.size() - 1);
                                    if (Objects.nonNull(data)) {
                                        JSONObject jsonObject = JSONObject.parseObject(data);
                                        if (Objects.nonNull(jsonObject.getJSONObject(SystemConstant.ARRROVE_REJECT_MAP))) {
                                            JSONObject object = jsonObject.getJSONObject(SystemConstant.ARRROVE_REJECT_MAP);
                                            approveRejectMap = new LinkedHashMap<>(object.size());
                                            for (Map.Entry<String, Object> entry : object.entrySet()) {
                                                approveRejectMap.put(entry.getKey(), (List<FlowRejectSequenceDto>) entry.getValue());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            List<Map.Entry<String, FlowTaskResult>> entryList = new ArrayList<Map.Entry<String, FlowTaskResult>>(setupMap.entrySet());
            //比较器
            Collections.sort(entryList, new Comparator<Map.Entry<String, FlowTaskResult>>() {
                @Override
                public int compare(Map.Entry<String, FlowTaskResult> o1, Map.Entry<String, FlowTaskResult> o2) {
                    if (o2.getValue().getSetup() < o1.getValue().getSetup()) {
                        return 1;
                    } else if (o2.getValue().getSetup() > o1.getValue().getSetup()) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            setupMap.clear();
            Iterator<Map.Entry<String, FlowTaskResult>> iter = entryList.iterator();
            Map.Entry<String, FlowTaskResult> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                FlowTaskResult flowTaskResult = tmpEntry.getValue();
                if (!CollectionUtils.isEmpty(approveRejectMap)) {
                    if (approveRejectMap.containsKey(tmpEntry.getKey())) {
                        flowTaskResult.setApproveRejectList(approveRejectMap.get(tmpEntry.getKey()));
                    }
                }
                setupMap.put(tmpEntry.getKey(), flowTaskResult);
            }
            FlowResult flowResult = new FlowResult(resourceEntity.getDeploymentId(), resourceEntity.getName(), setupMap);
//            log.info("flowResult:{}", JacksonUtil.parseJson(flowResult));
            TFCustomFlowService tfCustomFlowService = SpringContextHolder.getBean(TFCustomFlowService.class);
            TFCustomFlow tfCustomFlow = tfCustomFlowService.getOne(new QueryWrapper<TFCustomFlow>().lambda().eq(TFCustomFlow::getFlowDeploymentId, flowResult.getFlowDeploymentId()));
            if (Objects.isNull(tfCustomFlow)) {
                TFCustomFlow maxTfCustomFlow = tfCustomFlowService.findMaxVersion(null, flowResult.getFlowName(), customTypeEnum);
                tfCustomFlow = new TFCustomFlow(null, flowResult.getFlowName(), customTypeEnum, flowResult.getFlowDeploymentId(), TFCustomModelTypeEnum.USER_FIXED);
                flowResult.setId(tfCustomFlow.getId());
                if (Objects.nonNull(maxTfCustomFlow)) {
                    tfCustomFlow.setVersion(maxTfCustomFlow.getVersion() + 1);
                } else {
                    tfCustomFlow.setVersion(1);
                }
                flowResult.setVersion(tfCustomFlow.getVersion());
            } else {
                flowResult.setId(tfCustomFlow.getId());
                flowResult.setVersion(tfCustomFlow.getVersion());
                tfCustomFlow.setUpdateTime(System.currentTimeMillis());
            }
            flowResult.setFlowName(tfCustomFlow.getType().name());
            tfCustomFlow.setFlowProcessVar(JacksonUtil.parseJson(flowResult));
            tfCustomFlowService.saveOrUpdate(tfCustomFlow);
        } catch (DocumentException e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
        SystemConstant.FLOW_MAP.add(resourceEntity.getDeploymentId() + SystemConstant.BPMN_PREFIX, xml);
    }

    /**
     * 发送流程待办短信
     *
     * @param type
     * @param tfCustomFlowEntity
     * @param taskName
     * @param userId
     */
    protected void sendSopFlowDoneSms(TFCustomTypeEnum type, TFCustomFlowEntity tfCustomFlowEntity, String taskName, Long userId) {
        SmsSendUtil smsSendUtil = SpringContextHolder.getBean(SmsSendUtil.class);
        TFCustomFlowEntityService tfCustomFlowEntityService = SpringContextHolder.getBean(TFCustomFlowEntityService.class);
        FlowTaskSmsResult flowTaskSmsResult = tfCustomFlowEntityService.getFlowTaskRemindSmsInfo(tfCustomFlowEntity.getId(), userId);
        if (Objects.isNull(flowTaskSmsResult)) {
            flowTaskSmsResult = tfCustomFlowEntityService.getFlowTaskRemindSmsInfo(tfCustomFlowEntity.getCrmNo(), userId);
        }
        Optional.ofNullable(flowTaskSmsResult).orElseThrow(() -> ExceptionResultEnum.USER_NO_EXISTS.exception());
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("userName", flowTaskSmsResult.getRealName());
        templateParam.put("serviceName", flowTaskSmsResult.getServiceName());
        templateParam.put("customName", flowTaskSmsResult.getCustomName());
        templateParam.put("flowName", type.getTitle() + "【" + taskName + "】");
        smsSendUtil.sendSms(flowTaskSmsResult.getMobileNumber(), SystemConstant.SMS_SOP_DONE_CODE, templateParam);
    }

    /**
     * 发送流程结束短信
     *
     * @param type
     * @param tfCustomFlowEntity
     * @param status
     * @param tfFlowLog
     */
    protected void sendFlowFinishSms(TFCustomTypeEnum type, TFCustomFlowEntity tfCustomFlowEntity, FlowStatusEnum status, TFFlowLog tfFlowLog) {
        SmsSendUtil smsSendUtil = SpringContextHolder.getBean(SmsSendUtil.class);
        SysMessageService sysMessageService = SpringContextHolder.getBean(SysMessageService.class);
        TFCustomFlowEntityService tfCustomFlowEntityService = SpringContextHolder.getBean(TFCustomFlowEntityService.class);

        if ((type == TFCustomTypeEnum.DING_EXCEPTION_FLOW || type == TFCustomTypeEnum.PROJECT_EXCHANGE_FLOW) && status == FlowStatusEnum.FINISH) {//流程结束发送短信
            FlowTaskMsgResult flowTaskMsgResult = tfCustomFlowEntityService.getFlowTaskRemindMsgInfo(tfCustomFlowEntity.getId(), tfCustomFlowEntity.getCreateId());
            Optional.ofNullable(flowTaskMsgResult).orElseThrow(() -> ExceptionResultEnum.USER_NO_EXISTS.exception());

            SysMessage sysMessage = null;
            String configKey = null, content = null;
            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("userName", flowTaskMsgResult.getRealName());
            if (type == TFCustomTypeEnum.DING_EXCEPTION_FLOW) {//考勤异常
                content = MessageEnum.NOTICE_OF_DING_EXCEPTION.getTemplate();
                content = content.replaceAll("\\$\\{userName\\}", flowTaskMsgResult.getRealName());
                content = content.replaceAll("\\$\\{dingDate\\}", DateUtil.format(new Date(flowTaskMsgResult.getApplyTime()), SystemConstant.DEFAULT_DATE_PATTERN));
                content = content.replaceAll("\\$\\{approveRemark\\}", tfFlowLog.getApproveRemark());

                configKey = SystemConstant.SMS_FLOW_DING_EXCEPTION_FINISH_CODE;
                templateParam.put("dingDate", DateUtil.format(new Date(flowTaskMsgResult.getApplyTime()), SystemConstant.DEFAULT_DATE_PATTERN));
                templateParam.put("approveRemark", tfFlowLog.getApproveRemark());

                sysMessage = new SysMessage(tfCustomFlowEntity.getCrmNo(), tfCustomFlowEntity.getCode(),
                        MessageTypeEnum.EXCEPTION_APPROVE, type.name(), flowTaskMsgResult.getServiceId(), tfCustomFlowEntity.getCreateId(), content,tfCustomFlowEntity.getCreateId());
            } else if (type == TFCustomTypeEnum.PROJECT_EXCHANGE_FLOW) {//项目计划变更
                content = MessageEnum.NOTICE_OF_PROJECT_EXCHANGE.getTemplate();
                content = content.replaceAll("\\$\\{userName\\}", flowTaskMsgResult.getRealName());
                content = content.replaceAll("\\$\\{serviceName\\}", flowTaskMsgResult.getServiceName());
                content = content.replaceAll("\\$\\{customName\\}", flowTaskMsgResult.getCustomName());
                content = content.replaceAll("\\$\\{exchangeType\\}", flowTaskMsgResult.getExchangeType().getTitle());

                configKey = SystemConstant.SMS_FLOW_PROJECT_EXCHANGE_FINISH_CODE;
                templateParam.put("serviceName", flowTaskMsgResult.getServiceName());
                templateParam.put("customName", flowTaskMsgResult.getCustomName());
                templateParam.put("exchangeType", flowTaskMsgResult.getExchangeType().getTitle());

                sysMessage = new SysMessage(tfCustomFlowEntity.getCrmNo(), tfCustomFlowEntity.getCode(),
                        MessageTypeEnum.SYSTEM_PLAN_CHANGE, type.name(), flowTaskMsgResult.getServiceId(), tfCustomFlowEntity.getCreateId(), content,tfCustomFlowEntity.getCreateId());
            }
            //发送消息
            sysMessageService.saveSysMessage(Arrays.asList(sysMessage));

            //发送短信
            smsSendUtil.sendSms(flowTaskMsgResult.getMobileNumber(), configKey, templateParam);
        }
    }
}
