package com.yeejoin.amos.boot.module.elevator.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.DispatchPaperFormDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.DispatchTaskDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.MainPersonDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.RescueProcessDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatDispatchFeedbackDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMessageDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMyBussinessDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMyTaskDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMyTaskListDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatUserFeedbackDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.elevator.api.entity.DispatchPaper;
import com.yeejoin.amos.boot.module.elevator.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.elevator.api.entity.RescueProcess;
import com.yeejoin.amos.boot.module.elevator.api.entity.RescueStation;
import com.yeejoin.amos.boot.module.elevator.api.entity.Template;
import com.yeejoin.amos.boot.module.elevator.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.elevator.api.entity.WechatRelation;
import com.yeejoin.amos.boot.module.elevator.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.elevator.api.enums.DispatchPaperEnums;
import com.yeejoin.amos.boot.module.elevator.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.elevator.api.mapper.DispatchTaskMapper;
import com.yeejoin.amos.boot.module.elevator.api.mapper.ElevatorMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IDispatchTaskService;
import com.yeejoin.amos.boot.module.elevator.api.service.IRescueStationService;
import com.yeejoin.amos.boot.module.elevator.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.elevator.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 派遣任务服务实现类
 *
 * @author system_generator
 * @date 2021-08-03
 */
@Service
public class DispatchTaskServiceImpl extends BaseService<DispatchTaskDto,DispatchTask,DispatchTaskMapper> implements IDispatchTaskService {

    private final Logger logger = LoggerFactory.getLogger(DispatchTaskServiceImpl.class);
    @Autowired
    DispatchPaperServiceImpl dispatchPaperServiceImpl;

    @Autowired
    AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;

    @Autowired
    TemplateServiceImpl templateServiceImpl;

    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    ITzBaseEnterpriseInfoService enterpriseInfoService;

    @Autowired
    IRescueStationService iRescueStationService;

    @Autowired
    RepairConsultServiceImpl repairConsultServiceImpl;

    @Autowired
    RescueProcessServiceImpl rescueProcessServiceImpl;

    @Autowired
    private DataDictionaryServiceImpl iDataDictionaryService;

    @Autowired
    ISourceFileService ISourceFileService;

    @Autowired
    WechatRelationServiceImpl wechatRelationServiceImpl;

    @Autowired
    WechatServiceImpl wechatService;

    @Autowired
    private EmqKeeper emqKeeper;

    @Autowired
    CtiServiceImpl ctiService;

    @Autowired
    private ElevatorMapper elevatorMapper;

    @Autowired
    ISourceFileService sourceFileService;

    @Value("${tzs.wechat.tempId.kr}")
    private String KRJY_TEMPID;

    @Value("${tzs.wechat.tempId.wx}")
    private String WX_TEMPID;

    @Value("${tzs.wechat.tempId.ts}")
    private String TS_TEMPID;

    @Value("${tzs.wechat.url.kr}")
    private String KRJY_URL;

    @Value("${tzs.wechat.url.wx}")
    private String WX_URL;

    @Value("${tzs.wechat.url.ts}")
    private String TS_URL;

    @Value("${mqtt.topic.task.newtask}")
    private String newTaskTopic;


    /**
     * 分页查询
     */
    public Page<DispatchTaskDto> queryForDispatchTaskPage(Page<DispatchTaskDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<DispatchTaskDto> queryForDispatchTaskList()   {
        return this.queryForList("" , false);
    }

    @Override
    public DispatchTaskDto getTaskInfo(String orgTypeCode, Long alertId) {
        DispatchTaskDto dispatchTaskDto = new DispatchTaskDto();
        // 获取警情信息 填充模板返回
        AlertCalledDto alertCalledDto = alertCalledServiceImpl.queryBySeq(alertId);
        dispatchTaskDto.setOrgType(DispatchPaperEnums.getEnumByCode(orgTypeCode).getValue());
        dispatchTaskDto.setOrgTypeCode(DispatchPaperEnums.getEnumByCode(orgTypeCode).getId());
        dispatchTaskDto.setAlertId(alertId);
        dispatchTaskDto.setAlertCode(alertCalledDto.getAlarmTypeCode());
        // 获取模板 拼接json
        LambdaQueryWrapper<Template> templateQueryWrapper = new LambdaQueryWrapper<>();
        String alertTypeCode =   AlertStageEnums.getEnumById(alertCalledDto.getAlarmTypeCode()).getCode()  ;
        templateQueryWrapper.eq(Template::getTypeCode,"TASK-" + alertTypeCode);
        Template template = templateServiceImpl.getOne(templateQueryWrapper);
        String content = template.getContent();
        // 替换模板内容
        // 通用替换字段 报修时间 地址 电梯识别码 使用单位分类
        String createTime = DateUtils.date2LongStr(alertCalledDto.getCallTime());
        String rescueCode = alertCalledDto.getDeviceId();

        String emergencyCall = alertCalledDto.getEmergencyCall()  == null ? "" : alertCalledDto.getEmergencyCall();
        String contactPhone = alertCalledDto.getContactPhone()  == null ? "" : alertCalledDto.getContactPhone();

        // 电梯数据
//        Elevator elevator = elevatorServiceImpl.selectByAlertId(alertId);
        Map<String,Object> map  = elevatorServiceImpl.selectByAlertId(alertId);
        String address = map.get("address")  == null ? "" : String.valueOf(map.get("address"));
        String useSiteCategory = map.get("useSiteCategory")  == null ? "" : String.valueOf(map.get("useSiteCategory"));
        String useUnit = String.valueOf(map.get("useUnit"));
        content = content.replace("$call_time",createTime).replace("$address",address).replace("$rescue_code",rescueCode).replace("$use_site_category",useSiteCategory);
        String typeCode = "";
        if(AlertStageEnums.KRJY.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.KRJY.getId();
        } else if(AlertStageEnums.GZWX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.GZWX.getId();
        } else if(AlertStageEnums.TSZX.toString().equals(alertTypeCode)) {
            typeCode  = AlertStageEnums.TSZX.getId();
        }
        // 警情信息动态数据
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, alertId).eq(AlertFormValue::getAlertTypeCode,typeCode);
        // 派遣单动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        // map 存取数据
        Map<String,String> dynamicParms = new HashMap<String,String> ();
        list.stream().forEach(paperFormValue -> {
            dynamicParms.put(paperFormValue.getFieldCode(),paperFormValue.getFieldValue());
        });
        String desc = "";
        switch(alertTypeCode) {
            case "KRJY" : // 困人救援
                dispatchTaskDto.setIsSaveTask(true);
                String trappedNum = dynamicParms.get("trapped_num") == null ? "" : dynamicParms.get("trapped_num");
                String trappedFloorNum = dynamicParms.get("trapped_floor_num") == null ? "" : dynamicParms.get("trapped_floor_num");
                String isLight = dynamicParms.get("is_light") == null ? "" : dynamicParms.get("is_light");
                String trappedTime = dynamicParms.get("trapped_time") == null ? "" : dynamicParms.get("trapped_time");
                String injuredNum = dynamicParms.get("injured_num") == null ? "" : dynamicParms.get("injured_num");
                String dieNum = dynamicParms.get("die_num") == null ? "" : dynamicParms.get("die_num");
                String hasInjury = Integer.parseInt(injuredNum) + Integer.parseInt(dieNum) > 0 ? "有" : "无";
                content = content.replace("$trapped_num",trappedNum).replace("$trapped_floor_num", trappedFloorNum);
                content = content.replace("$emergency_call",emergencyCall).replace("$contact_phone", contactPhone);
                content = content.replace("$is_light", isLight).replace("$trapped_time", trappedTime);
                content = content.replace("$hasInjury", hasInjury);
                break;
            case "GZWX" : // 故障维修
                dispatchTaskDto.setIsSaveTask(false);
                desc = dynamicParms.get("fault_report") == null ? "" : dynamicParms.get("fault_report");
                content = content.replace("$use_unit", useUnit).replace("$desc", desc);
                break;
            case "TSZX" : // 投诉咨询
                dispatchTaskDto.setIsSaveTask(false);
                desc = dynamicParms.get("complaint_consulttation") == null ? "" : dynamicParms.get("complaint_consulttation");
                content = content.replace("$emergency_call",emergencyCall).replace("$contact_phone", contactPhone);
                content = content.replace("$use_unit", useUnit).replace("$desc", desc);
                break;
        }
        dispatchTaskDto.setDispatchContext(content);
        return dispatchTaskDto;
    }

    @Override
    public String returnDistanceByTaskId(Long taskId, String longitude, String latitude) {
        return baseMapper.returnDistanceByTaskId(taskId, longitude, latitude);
    }

    @Override
    public WechatMyTaskDto getTaskInfoByTaskId(Long taskId) {
        return baseMapper.getTaskInfoByTaskId(taskId);
    }

    @Transactional
    @Override
    public Boolean taskArrive(Long taskId) {
        Boolean flag = false;
        Date now = new Date();
        // 首先更新任务到达时间
        DispatchTask task = this.getById(taskId);
        this.update(new LambdaUpdateWrapper<DispatchTask>().set(DispatchTask::getArriveTime,now).eq(DispatchTask::getSequenceNbr,taskId));
        // 其次更新派遣单中相关信息
        dispatchPaperServiceImpl.update(new LambdaUpdateWrapper<DispatchPaper>().
                set(DispatchPaper::getArriveTime,now).
                set(DispatchPaper::getSaveOrgName,task.getResponseOrgName()).
                set(DispatchPaper::getArriveFeedbackCode,"856").
                set(DispatchPaper::getArriveFeedbackType,"主动反馈").
                eq(DispatchPaper::getSequenceNbr,task.getPaperId()));
        // 如果存在救援过程表更新救援过程表中信息
        if(task.getIsSaveTask() != null && task.getIsSaveTask()) {
            rescueProcessServiceImpl.update(new LambdaUpdateWrapper<RescueProcess>().
                    set(RescueProcess::getArriveTime,now).
                    set(RescueProcess::getArriveStatus,true).
                    set(RescueProcess::getArriveFeedbackType,"主动反馈").
                    set(RescueProcess::getArriveFeedbackCode,"856").
                    eq(RescueProcess::getAlertId,task.getAlertId()));
        }
        // 更新到达日志
        repairConsultServiceImpl.saveRepairConsultByAlertIdType( task.getAlertId(),"DD",taskId,null);
        flag = true;

        return flag;
    }

    @Transactional
    @Override
    public Boolean saveFinish(Long taskId) {
        Boolean flag = false;
        Date now = new Date();
        DispatchTask task = this.getById(taskId);
        // 更新派遣单中相关信息 -- 动态字段
        iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                set(AlertFormValue::getFieldValue,DateUtils.date2LongStr(now)).
                eq(AlertFormValue::getFieldCode,"save_time").
                eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
        // 更新救出冗余字段
        dispatchPaperServiceImpl.update(new LambdaUpdateWrapper<DispatchPaper>().eq(DispatchPaper::getSequenceNbr,task.getPaperId())
                .set(DispatchPaper::getSaveTime,now)
        );
        // 如果存在救援过程表更新救援过程表中信息
        if(task.getIsSaveTask()) {
            rescueProcessServiceImpl.update(new LambdaUpdateWrapper<RescueProcess>().
                    set(RescueProcess::getRescueTime,now).
                    set(RescueProcess::getRescueStatus,true).
                    set(RescueProcess::getRescueFeedbackType,"主动反馈").
                    set(RescueProcess::getRescueFeedbackCode,"856").
                    eq(RescueProcess::getAlertId,task.getAlertId()));
            task.setSaveTime(now);
            this.updateById(task);
        }
        // 更新到达日志
        repairConsultServiceImpl.saveRepairConsultByAlertIdType( task.getAlertId(),"JC",taskId,null);
        flag = true;

        return flag;
    }

    @Override
    public List<WechatMyTaskListDto> getTaskListByPhonePager(String phone, String typeCode, Long current) {

        return baseMapper.getTaskListByPhonePager(phone, typeCode, current*5);
    }

    @Override
    @Transactional
    public WechatMyTaskDto saveWechatFeedBack(WechatDispatchFeedbackDto wechatDispatchFeedbackDto) {
        // 更新反馈信息
        DispatchTask task = this.getById(wechatDispatchFeedbackDto.getTaskId());
        DispatchPaper dispatchPaper = dispatchPaperServiceImpl.getById(task.getPaperId());
        Date now = new Date();
        AlertCalled alertCalled = alertCalledServiceImpl.getById(task.getAlertId());
        //  反馈方式  -- 根据类型保存到动态表中
        if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.KRJY.getId())) { // 困人救援
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,"主动反馈").
                    set(AlertFormValue::getFieldValueCode,"856").
                    eq(AlertFormValue::getFieldCode,"fix_feedback_type").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserName()).
                    eq(AlertFormValue::getFieldCode,"fix_feedback_uname").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserId() + "").
                    eq(AlertFormValue::getFieldCode,"fix_feedback_uid").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,wechatDispatchFeedbackDto.getRemark()).
                    eq(AlertFormValue::getFieldCode,"fix_remark").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            dispatchPaper.setRepairOrgName(task.getResponseOrgName());
            dispatchPaper.setRepairUser(task.getResponseUserName());
        } else if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.GZWX.getId())) { // 故障维修
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,"主动反馈").
                    set(AlertFormValue::getFieldValueCode,"856").
                    eq(AlertFormValue::getFieldCode,"fix_feedback_type").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserName()).
                    eq(AlertFormValue::getFieldCode,"fix_feedback_uname").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserId() + "").
                    eq(AlertFormValue::getFieldCode,"fix_feedback_uid").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,wechatDispatchFeedbackDto.getRemark()).
                    eq(AlertFormValue::getFieldCode,"fix_remark").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            dispatchPaper.setRepairOrgName(task.getResponseOrgName());
            dispatchPaper.setRepairUser(task.getResponseUserName());
        } else if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.TSZX.getId())) {// 投诉建议
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,"主动反馈").
                    set(AlertFormValue::getFieldValueCode,"856").
                    eq(AlertFormValue::getFieldCode,"consult_feedback_type").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserName()).
                    eq(AlertFormValue::getFieldCode,"consult_feedback_uname").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,task.getResponseUserId() + "").
                    eq(AlertFormValue::getFieldCode,"consult_feedback_uid").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,wechatDispatchFeedbackDto.getRemark()).
                    eq(AlertFormValue::getFieldCode,"main_feedback_result").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            dispatchPaper.setDealUser(task.getResponseUserName());
            dispatchPaper.setDealOrgName(task.getResponseOrgName());
        }

        // 反馈时间
        dispatchPaper.setFeedbackFinishTime(now);
        dispatchPaper.setRepairUser(task.getResponseUserName());

        // 保存照片
        Map<String, List<AttachmentDto>> attachmentMap = new HashMap<>();
        attachmentMap.put("imgs",wechatDispatchFeedbackDto.getImgs());
        ISourceFileService.saveAttachments(task.getPaperId(),attachmentMap);

        dispatchPaperServiceImpl.updateById(dispatchPaper);


        if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.TSZX.getId())) {// 投诉建议
            //  动态字段
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,wechatDispatchFeedbackDto.getRemark()).
                    eq(AlertFormValue::getFieldCode,"main_feedback_result").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));

            if (StringUtils.isNotBlank(wechatDispatchFeedbackDto.getDealResult())) {
                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.CZJG).eq(DataDictionary::getCode, wechatDispatchFeedbackDto.getDealResult());
                DataDictionary actionResult = iDataDictionaryService.getOne(queryWrapper);
                iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                        set(AlertFormValue::getFieldValue,actionResult.getName()).
                        set(AlertFormValue::getFieldValueCode,actionResult.getCode()).
                        eq(AlertFormValue::getFieldCode,"action_result").
                        eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(task.getAlertId(),TzsCommonParam.WXFK_TS,task.getSequenceNbr(),null);



        } else { // 困人救援 或者 投诉建议
            //  动态字段
            iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                    set(AlertFormValue::getFieldValue,wechatDispatchFeedbackDto.getRemark()).
                    eq(AlertFormValue::getFieldCode,"fix_remark").
                    eq(AlertFormValue::getAlertCalledId,task.getPaperId()));

            if (StringUtils.isNotBlank(wechatDispatchFeedbackDto.getFixResult())) {
                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.WXJG).eq(DataDictionary::getCode, wechatDispatchFeedbackDto.getFixResult());
                DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                        set(AlertFormValue::getFieldValue,fixResult.getName()).
                        set(AlertFormValue::getFieldValueCode,fixResult.getCode()).
                        eq(AlertFormValue::getFieldCode,"fix_result").
                        eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            }
            if (StringUtils.isNotBlank(wechatDispatchFeedbackDto.getErrorResult())) {
                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.GZYY).eq(DataDictionary::getCode, wechatDispatchFeedbackDto.getErrorResult());
                DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                        set(AlertFormValue::getFieldValue,fixResult.getName()).
                        set(AlertFormValue::getFieldValueCode,fixResult.getCode()).
                        eq(AlertFormValue::getFieldCode,"error_result").
                        eq(AlertFormValue::getAlertCalledId,task.getPaperId()));
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(task.getAlertId(),TzsCommonParam.WXFK,task.getSequenceNbr(),null);
        }






        WechatMyTaskDto temp = this.getTaskInfoByTaskId(wechatDispatchFeedbackDto.getTaskId());
        List<AlertFormValue> paperList = null;
        Map<String, List<AttachmentDto>> imgMap = null;
        List<AttachmentDto> imgDtos = null;
        Map<String, List<AttachmentDto>> errorImgMap = null;
        List<AttachmentDto> errorImgDtos = null;
        List<AttachmentDto> feedbackDtos = null;
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        switch (temp.getTaskTypeCode()) {
            case "960" : // 困人救援
                temp.setHasDeadHurt("无");
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getAlertId());
                // 警情动态表单数据
                List<AlertFormValue> alertList = iAlertFormValueService.list(queryWrapper);
                alertList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("trapped_floor_num".equals(t.getFieldCode())) {
                        // 被困楼层
                        temp.setTrappedFloorNum(value);
                    } else if("trapped_num".equals(t.getFieldCode())) {
                        // 被困人数
                        temp.setTrappedNum(value);
                    } else if("injured_num".equals(t.getFieldCode())) {
                        // 受伤人数
                        if(StringUtils.isNotEmpty(value)) {
                            temp.setHasDeadHurt("有");
                        }
                    } else if("die_num".equals(t.getFieldCode())) {
                        // 死亡人数
                        if(StringUtils.isNotEmpty(value)) {
                            temp.setHasDeadHurt("有");
                        }
                    }
                });
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("error_result".equals(t.getFieldCode())) {
                        // 故障原因
                        temp.setErrorResult(value);
                    } else if("fix_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFixResult(value);
                    } else if("fix_remark".equals(t.getFieldCode())) {
                        // 维修备注
                        temp.setRemark(value);
                    }
                });


                imgMap = sourceFileService.getAttachments(temp.getPaperId());
                imgDtos = imgMap.get("imgs");
                temp.setFixImgs(imgDtos);

                break;
            case "961" : // 故障维修
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("error_result".equals(t.getFieldCode())) {
                        // 故障原因
                        temp.setErrorResult(value);
                    } else if("fix_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFixResult(value);
                    } else if("fix_remark".equals(t.getFieldCode())) {
                        // 维修备注
                        temp.setRemark(value);
                    } else if("feedback_result".equals(t.getFieldCode())) {
                        // 反馈结果
                        temp.setFeedbackResult(value);
                    }
                });

                imgMap = sourceFileService.getAttachments(temp.getPaperId());
                imgDtos = imgMap.get("imgs");
                temp.setFixImgs(imgDtos);
                errorImgMap = sourceFileService.getAttachments(temp.getAlertId());
                errorImgDtos = errorImgMap.get("imgs");
                temp.setErrorImgs(errorImgDtos);
                feedbackDtos = errorImgMap.get("feedbacks");
                temp.setFeedBackImgs(feedbackDtos);
                break;
            case "962" : // 投诉建议
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("action_result".equals(t.getFieldCode())) {
                        //	处置结果
                        temp.setActionResult(value);
                    } else if("main_feedback_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setRemark(value);
                    } else if("feedback_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFeedbackResult(value);
                    }
                });
                imgMap = sourceFileService.getAttachments(temp.getPaperId());
                imgDtos = imgMap.get("imgs");
                temp.setFixImgs(imgDtos);
                errorImgMap = sourceFileService.getAttachments(temp.getAlertId());
                errorImgDtos = errorImgMap.get("imgs");
                temp.setErrorImgs(errorImgDtos);
                feedbackDtos = errorImgMap.get("feedbacks");
                temp.setFeedBackImgs(feedbackDtos);
                break;
        }

        return temp;
    }

    @Override
    public WechatMessageDto getWechatMessageDtoByDispatchTaskDto(DispatchTaskDto dispatchTaskDto) {
        WechatMessageDto temp = new WechatMessageDto();
        // 根据警情分类 封装MessageDto
        AlertCalled alertCalled = alertCalledServiceImpl.getById(dispatchTaskDto.getAlertId());
        Map<String,String> data = new HashMap<>();

        if(AlertStageEnums.KRJY.getId().equals(dispatchTaskDto.getAlertCode())) {
            temp.setTemplateId(KRJY_TEMPID);
            temp.setUrl(KRJY_URL+ "?id=" + dispatchTaskDto.getSequenceNbr());
            data.put("first","电梯困人任务已派遣，请尽快前往救援!");
            data.put("keyword1",alertCalled.getAddress());
            data.put("keyword2", DateUtils.date2LongStr(dispatchTaskDto.getDispatchTime()));
            data.put("remark", "请在收到任务后30分钟内到达人员被困位置进行救援！");
            temp.setData(data);
        } else if(AlertStageEnums.GZWX.getId().equals(dispatchTaskDto.getAlertCode())) {
            temp.setTemplateId(WX_TEMPID);
            temp.setUrl(WX_URL + "?id=" + dispatchTaskDto.getSequenceNbr());
            data.put("first","故障维修任务已派遣，请尽快前往救援!");
            data.put("keyword1","故障维修");
            data.put("keyword2", "电梯故障");
            data.put("keyword3", alertCalled.getEmergencyPerson());
            data.put("keyword4", alertCalled.getEmergencyCall());
            data.put("keyword5", DateUtils.date2LongStr(dispatchTaskDto.getDispatchTime()));
            data.put("remark", "任务已派遣，请尽快前往处置！");
            temp.setData(data);
        } else if(AlertStageEnums.TSZX.getId().equals(dispatchTaskDto.getAlertCode())) {
            temp.setTemplateId(TS_TEMPID);
            temp.setUrl(TS_URL+ "?id=" + dispatchTaskDto.getSequenceNbr());
            data.put("first","投诉建议任务已派遣，请尽快前往救援!");
            //data.put("keyword1","投诉建议");
            //data.put("keyword2", "投诉建议");
            data.put("keyword1", alertCalled.getEmergencyPerson());
            //data.put("keyword4", alertCalled.getEmergencyCall());
            data.put("keyword2", DateUtils.date2LongStr(dispatchTaskDto.getDispatchTime()));
            data.put("remark", "任务已派遣，请尽快前往处置！");
            temp.setData(data);
        }
        return temp;
    }

    @Override
    public List<MainPersonDto> todayTaskPerson() {
        return baseMapper.todayTaskPerson();
    }

    @Transactional
    @Override
    public WechatMyBussinessDto saveUserFeed(WechatUserFeedbackDto wechatUserFeedbackDto) {
        AlertCalled alertCalled = alertCalledServiceImpl.getById(wechatUserFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperServiceImpl.getOne(new LambdaQueryWrapper<DispatchPaper>().eq(DispatchPaper::getIsDelete,0).eq(DispatchPaper::getAlertId,wechatUserFeedbackDto.getAlertId()));
        Date now = new Date();

        dispatchPaper.setFeedbackCode("856");
        dispatchPaper.setFeedbackType("主动反馈");
        // 反馈时间
        dispatchPaper.setFeedbackFinishTime(now);
        dispatchPaper.setFeedbackTime(now);
        // 反馈人信息
        dispatchPaper.setFeedbackUid(alertCalled.getEmergencyCall());
        dispatchPaper.setFeedbackUname(alertCalled.getEmergencyCall() + alertCalled.getEmergencyPerson());

        // 保存照片
        Map<String, List<AttachmentDto>> attachmentMap = new HashMap<>();
        attachmentMap.put("feedbacks",wechatUserFeedbackDto.getImgs());
        ISourceFileService.saveAttachments(alertCalled.getSequenceNbr(),attachmentMap);
        // 备注
        dispatchPaper.setRemark(wechatUserFeedbackDto.getRemark());
        dispatchPaperServiceImpl.updateById(dispatchPaper);

        if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.KRJY.getId())) { // 困人救援

        } else if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.GZWX.getId())) { // 故障维修
            if (StringUtils.isNotBlank(wechatUserFeedbackDto.getFeedBackResult())) {
                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKJG).eq(DataDictionary::getCode, wechatUserFeedbackDto.getFeedBackResult());
                DataDictionary feedbackResult = iDataDictionaryService.getOne(queryWrapper);
                iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                        set(AlertFormValue::getFieldValue,feedbackResult.getName()).
                        set(AlertFormValue::getFieldValueCode,feedbackResult.getCode()).
                        eq(AlertFormValue::getFieldCode,"feedback_result").
                        eq(AlertFormValue::getAlertCalledId,dispatchPaper.getSequenceNbr()));
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(alertCalled.getSequenceNbr(),TzsCommonParam.BXFK,null,null);
        } else if(alertCalled.getAlarmTypeCode().equals(AlertStageEnums.TSZX.getId())) {// 投诉建议
            if (StringUtils.isNotBlank(wechatUserFeedbackDto.getFeedBackResult())) {
                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKJG).eq(DataDictionary::getCode, wechatUserFeedbackDto.getFeedBackResult());
                DataDictionary feedbackResult = iDataDictionaryService.getOne(queryWrapper);
                iAlertFormValueService.update(new LambdaUpdateWrapper<AlertFormValue>().
                        set(AlertFormValue::getFieldValue,feedbackResult.getName()).
                        set(AlertFormValue::getFieldValueCode,feedbackResult.getCode()).
                        eq(AlertFormValue::getFieldCode,"feedback_result").
                        eq(AlertFormValue::getAlertCalledId,dispatchPaper.getSequenceNbr()));
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(alertCalled.getSequenceNbr(),TzsCommonParam.TSRFK,null,null);
        }


        WechatMyBussinessDto temp = alertCalledServiceImpl.getBussinessInfoById(alertCalled.getSequenceNbr());

        List<AlertFormValue> paperList = null;
        Map<String, List<AttachmentDto>> imgMap = null;
        List<AttachmentDto> imgDtos = null;
        Map<String, List<AttachmentDto>> errorImgMap = null;
        List<AttachmentDto> errorImgDtos = null;
        List<AttachmentDto> feedbackDtos = null;
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        switch (temp.getTaskTypeCode()) {
            case "960" : // 困人救援
                temp.setHasDeadHurt("无");
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getSequenceNbr());
                // 警情动态表单数据
                List<AlertFormValue> alertList = iAlertFormValueService.list(queryWrapper);
                alertList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("trapped_floor_num".equals(t.getFieldCode())) {
                        // 被困楼层
                        temp.setTrappedFloorNum(value);
                    } else if("trapped_num".equals(t.getFieldCode())) {
                        // 被困人数
                        temp.setTrappedNum(value);
                    } else if("injured_num".equals(t.getFieldCode())) {
                        // 受伤人数
                        if(StringUtils.isNotEmpty(value)) {
                            temp.setHasDeadHurt("有");
                        }
                    } else if("die_num".equals(t.getFieldCode())) {
                        // 死亡人数
                        if(StringUtils.isNotEmpty(value)) {
                            temp.setHasDeadHurt("有");
                        }
                    }
                });
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("error_result".equals(t.getFieldCode())) {
                        // 故障原因
                        temp.setErrorResult(value);
                    } else if("fix_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFixResult(value);
                    } else if("fix_remark".equals(t.getFieldCode())) {
                        // 维修备注
                        temp.setRemark(value);
                    }
                });


                imgMap = sourceFileService.getAttachments(temp.getPaperId());
                imgDtos = imgMap.get("imgs");
                temp.setFixImgs(imgDtos);

                break;
            case "961" : // 故障维修
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("error_result".equals(t.getFieldCode())) {
                        // 故障原因
                        temp.setErrorResult(value);
                    } else if("fix_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFixResult(value);
                    } else if("fix_remark".equals(t.getFieldCode())) {
                        // 维修备注
                        temp.setRemark(value);
                    } else if("feedback_result".equals(t.getFieldCode())) {
                        // 反馈结果
                        temp.setFeedbackResult(value);
                    }
                });


                imgMap = sourceFileService.getAttachments(temp.getPaperId());
                imgDtos = imgMap.get("imgs");
                temp.setFixImgs(imgDtos);
                errorImgMap = sourceFileService.getAttachments(temp.getSequenceNbr());
                errorImgDtos = errorImgMap.get("imgs");
                temp.setErrorImgs(errorImgDtos);
                feedbackDtos = errorImgMap.get("feedbacks");
                temp.setFeedBackImgs(feedbackDtos);
                break;
            case "962" : // 投诉建议
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
                // 派遣动态表单
                paperList = iAlertFormValueService.list(queryWrapper);
                paperList.stream().forEach(t -> {
                    String value = t.getFieldValue();
                    if("action_result".equals(t.getFieldCode())) {
                        //	处置结果
                        temp.setActionResult(value);
                    } else if("main_feedback_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setRemark(value);
                    } else if("feedback_result".equals(t.getFieldCode())) {
                        // 维修结果
                        temp.setFeedbackResult(value);
                    }
                });
                errorImgMap = sourceFileService.getAttachments(temp.getSequenceNbr());
                errorImgDtos = errorImgMap.get("imgs");
                temp.setErrorImgs(errorImgDtos);
                feedbackDtos = errorImgMap.get("feedbacks");
                temp.setFeedBackImgs(feedbackDtos);
                break;
        }
        return temp;
    }

    @Transactional
    @Override
    public Boolean createDispatchTask(DispatchTaskDto dispatchTaskDto, AgencyUserModel sendUser) {
        if(sendUser == null) {
            throw  new BadRequest("派遣任务创建人不能为空");
        }
        boolean flag = false;
        // 判断派遣单是否存在 如果不存在先创建派遣单
        DispatchPaperFormDto dispatchPaperDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(dispatchTaskDto.getAlertId());
        if(dispatchPaperDto == null || dispatchPaperDto.getDispatchPaper() == null) {
            dispatchPaperDto = dispatchPaperServiceImpl.createDispatchPaper(dispatchTaskDto.getAlertId(), dispatchTaskDto.getAlertCode(), sendUser);
        }
        DispatchPaper dispatchPaper = dispatchPaperDto.getDispatchPaper();
        List<AlertFormValue> dynamicFormAlert = dispatchPaperDto.getDynamicFormAlert();
        // 创建派遣单
        dispatchTaskDto.setDispatchTime(new Date());
        DispatchTask dispatchTask = BeanDtoVoUtils.convert(dispatchTaskDto, DispatchTask.class);

        String groupCode = ctiService.getSkillGroup(sendUser.getUserId());
        dispatchTask.setSkillGroup(groupCode);
        dispatchPaper.setSkillGroup(groupCode);

        if(AlertStageEnums.KRJY.getId().equals(dispatchTaskDto.getAlertCode())) {
            dispatchTask.setIsSaveTask(true);
        }
        dispatchTask.setPaperId(dispatchPaperDto.getDispatchPaper().getSequenceNbr());
        if(dispatchPaper.getRepairOrgTaskId() != null && (dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.levelOneUnit.getCode()) || dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.levelTwoUnit.getCode()))) {
            throw new BadRequest("已经派遣过其他力量调派");
        }
        if(dispatchPaper.getUseOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.useUnit.getCode())) {
            throw new BadRequest("已经派遣过使用单位");
        }
        if(dispatchPaper.getRepairOrgTaskId() != null && dispatchTask.getOrgTypeCode().equals(DispatchPaperEnums.repairUnit.getCode()) ) {
            throw new BadRequest("已经派遣过维修单位调派");
        }

        flag = this.save(dispatchTask);
        if(flag) { // 创建好派遣任务单以后根据任务单类型修改派遣单信息
            // 社会信用代码 根据类型查找放入
	        TzBaseEnterpriseInfo maintenanceUnit;
            switch (dispatchTask.getOrgTypeCode()) {
                case "useUnit": // 使用单位
	                TzBaseEnterpriseInfo useUnit =
			                enterpriseInfoService.getById(dispatchTask.getResponseOrgId());
                    dispatchPaper.setUseOrgId(useUnit.getSequenceNbr());
                    dispatchPaper.setUseOrgTaskId(dispatchTask.getSequenceNbr());
                    if(AlertStageEnums.getEnumById(dispatchPaper.getAlertCode()).getCode().equals(AlertStageEnums.KRJY.getCode())) {
                        dynamicFormAlert.stream().forEach(alertFormValue -> {
                            if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                                alertFormValue.setFieldValue(DispatchPaperEnums.hasDispatched.getValue());
                                alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                            }else if(alertFormValue.getFieldCode().equals("response_level")) {
                                alertFormValue.setFieldValue(DispatchPaperEnums.useUnit.getValue());
                                alertFormValue.setFieldValueCode(DispatchPaperEnums.useUnit.getId());
                                // 响应级别反馈给警情
                                LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
                                updateWrapper.eq(AlertCalled::getSequenceNbr,dispatchTask.getAlertId());
                                updateWrapper.set(AlertCalled::getResponseLevel,DispatchPaperEnums.useUnit.getValue());
                                alertCalledServiceImpl.update(updateWrapper);
                            }
                        });
                    }
                    break;
                case "repairUnit":
                    Map<String, Object> unitMessage = elevatorMapper.selectMainUnitMessage(dispatchTask.getResponseOrgId());
                    dispatchPaper.setRepairOrgId(String.valueOf(unitMessage.get("sequenceNbr")));
//                    maintenanceUnit = enterpriseInfoService.getById(dispatchTask.getResponseOrgId());
//                    dispatchPaper.setRepairOrgId(maintenanceUnit.getSequenceNbr());
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    break;
                case "levelOneUnit":
                    Map<String, Object> unitMessageOne = elevatorMapper.selectMainUnitMessage(dispatchTask.getResponseOrgId());
                    dispatchPaper.setRepairOrgId(String.valueOf(unitMessageOne.get("sequenceNbr")));
//	                maintenanceUnit = enterpriseInfoService.getById(dispatchTask.getResponseOrgId());
//	                String socialCreditCode = maintenanceUnit.getUseCode();useCode
	                String socialCreditCode = String.valueOf(unitMessageOne.get("useCode"));
//                    dispatchPaper.setRepairOrgId(maintenanceUnit.getSequenceNbr());
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    // 修改动态字段
                    dynamicFormAlert.stream().forEach(alertFormValue -> {
                        if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.hasDispatched.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.levelOneUnit.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.levelOneUnit.getId());
                            // 响应级别反馈给警情
                            LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.eq(AlertCalled::getSequenceNbr,dispatchTask.getAlertId());
                            updateWrapper.set(AlertCalled::getResponseLevel,DispatchPaperEnums.levelOneUnit.getValue());
                            alertCalledServiceImpl.update(updateWrapper);
                        } else if(alertFormValue.getFieldCode().equals("save_credit_code")) {
                            alertFormValue.setFieldValue(socialCreditCode);
                        }
                    });
                    break;
                case "levelTwoUnit":
                    RescueStation rescueStation = iRescueStationService.getById(dispatchTask.getResponseOrgId());
                    dispatchPaper.setRepairOrgId(String.valueOf(rescueStation.getSequenceNbr()));
                    dispatchPaper.setRepairOrgTaskId(dispatchTask.getSequenceNbr());
                    // 修改动态字段
                    dynamicFormAlert.stream().forEach(alertFormValue -> {
                        if(alertFormValue.getFieldCode().equals("dispatch_status")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.hasDispatched.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.hasDispatched.getId());
                        } else if(alertFormValue.getFieldCode().equals("response_level")) {
                            alertFormValue.setFieldValue(DispatchPaperEnums.levelTwoUnit.getValue());
                            alertFormValue.setFieldValueCode(DispatchPaperEnums.levelTwoUnit.getId());
                            // 响应级别反馈给警情
                            LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.eq(AlertCalled::getSequenceNbr,dispatchTask.getAlertId());
                            updateWrapper.set(AlertCalled::getResponseLevel,DispatchPaperEnums.levelTwoUnit.getValue());
                            alertCalledServiceImpl.update(updateWrapper);
                        }
                    });
                    break;
            }
            //  保存派遣单
            dispatchPaperServiceImpl.updateById(dispatchPaper);
            // 保存动态表单数据
            iAlertFormValueService.updateBatchById(dynamicFormAlert);
            // 记录日志
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchTask.getAlertId(), TzsCommonParam.PQ, dispatchTask.getSequenceNbr(),sendUser);
            // 派遣后如果困人救援更新派遣过程表
            if(AlertStageEnums.KRJY.getId().equals(dispatchPaper.getAlertCode())) {
                RescueProcessDto rescueProcessDto = rescueProcessServiceImpl.getProcessByAlertId(dispatchTaskDto.getAlertId());
                if(rescueProcessDto.getDispatchStatus() == null && rescueProcessDto.getDispatchTime() == null) {
                    rescueProcessDto.setDispatchStatus(true);
                    rescueProcessDto.setDispatchTime(dispatchTask.getDispatchTime());
                    rescueProcessDto.setDispatchUserName(sendUser.getRealName());
                    rescueProcessDto.setDispatchUserId(dispatchTask.getRecUserId());
                    rescueProcessServiceImpl.updateByAlertId(rescueProcessDto);
                }
            }
            String infoCode = dispatchTaskDto.getDispatchInfoCode();
            if(infoCode.indexOf("0") != -1 && StringUtils.isNotBlank(dispatchTaskDto.getResponseUserTel())) { // 下发了小程序
                // 发送任务单
                WechatRelation temp = wechatRelationServiceImpl.getOne(new LambdaQueryWrapper<WechatRelation>().eq(WechatRelation::getPhone,dispatchTaskDto.getResponseUserTel()));
                if(temp != null && temp.getOpenId() != null) {
                    dispatchTaskDto.setSequenceNbr(dispatchTask.getSequenceNbr());
                    WechatMessageDto dto = this.getWechatMessageDtoByDispatchTaskDto(dispatchTaskDto);
                    wechatService.sendWechatModelMessage(temp.getOpenId() ,  dto);
                }
            }
            if(infoCode.indexOf("1") != -1 && StringUtils.isNotBlank(dispatchTaskDto.getResponseUserTel())) { // 下发了短信
                HashMap<String, String>  params = new HashMap<>();
                params.put("smsCode","SMS_TZS_0006");
                params.put("mobile",dispatchTaskDto.getResponseUserTel());
                params.put("content",dispatchTaskDto.getDispatchContext());
                FeignClientResult<SmsRecordModel> result = Systemctl.smsClient.sendCommonSms(params);
            }
            // mqtt 通知新派遣
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("taskId",dispatchTaskDto.getSequenceNbr());
            try {
                emqKeeper.getMqttClient().publish(newTaskTopic, jsonObject.toString().getBytes("UTF-8"), 1, false);
            } catch (MqttException e) {
                logger.error("mqtt发送失败" +jsonObject );
            } catch (UnsupportedEncodingException e) {
                logger.error("mqtt发送失败" +jsonObject );
            }

        }
        return flag;
    }
}