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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.elevator.api.dto.*;
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.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.DispatchPaperMapper;
import com.yeejoin.amos.boot.module.elevator.api.mapper.ElevatorMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IDispatchPaperService;
import com.yeejoin.amos.boot.module.elevator.api.service.IMaintenanceUnitService;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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.util.*;

/**
 * 派遣单服务实现类
 *
 * @author system_generator
 * @date 2021-08-03
 */
@Service
public class DispatchPaperServiceImpl extends BaseService<DispatchPaperDto,DispatchPaper,DispatchPaperMapper> implements IDispatchPaperService {

    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    private AlertFormServiceImpl alertFormServiceImpl;

    @Autowired
    private ElevatorServiceImpl elevatorServiceImpl;

    @Autowired
    ElevatorMapper elevatorMapper;

    @Autowired
    private IMaintenanceUnitService iMaintenanceUnitService;

    @Autowired
    private AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    private DispatchTaskServiceImpl dispatchTaskServiceImpl;

    @Autowired
    private DataDictionaryServiceImpl iDataDictionaryService;

    @Autowired
    private RescueProcessServiceImpl rescueProcessServiceImpl;

    @Autowired
    RepairConsultServiceImpl repairConsultServiceImpl;

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

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

    /**
     *
     * <pre>
     * 保存派遣单信息
     * </pre>
     *
     * @param dispatchPaperFormDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public DispatchPaperFormDto createDispatchPaper(DispatchPaperFormDto dispatchPaperFormDto) {
        try {
            // 派遣单基本信息
            DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
            dispatchPaper.setDispatchTime(new Date());
            dispatchPaper.setIsDelete(false);

            this.save(dispatchPaper);

            // 动态表单
            List<AlertFormValue> paperFormValuelist = dispatchPaperFormDto.getDynamicFormAlert();
            // 填充警情主键
            paperFormValuelist.stream().forEach(paperFormValue -> {
                paperFormValue.setAlertCalledId(dispatchPaper.getSequenceNbr());
                paperFormValue.setAlertTypeCode(DispatchPaperEnums.getEnumById(dispatchPaper.getAlertCode()).getDynamicCode());
            });
            // 保存动态表单数据
            iAlertFormValueService.saveBatch(paperFormValuelist);
            dispatchPaperFormDto.setDispatchPaper(dispatchPaper);
            dispatchPaperFormDto.setDynamicFormAlert(paperFormValuelist);

            return dispatchPaperFormDto;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("派遣失败，系统异常!");
        }
    }

    @Override
    public DispatchPaperFormDto selectDispatchPaperDtoByAlertId(Long alertId) {
        // 根据警情id 获取 派遣单信息
        DispatchPaper dispatchPaper =selectDispatchPaperByAlertId(alertId);
        // 封装dto
        DispatchPaperFormDto dispatchPaperFormDto = new DispatchPaperFormDto();
        if(dispatchPaper == null) { //如果没有找到paper 返回空Dto
            return dispatchPaperFormDto;
        }
        dispatchPaperFormDto.setDispatchPaper(dispatchPaper);
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, dispatchPaper.getSequenceNbr()).eq(AlertFormValue::getAlertTypeCode,        DispatchPaperEnums.getEnumById(dispatchPaper.getAlertCode()).getDynamicCode());
        // 派遣单动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        dispatchPaperFormDto.setDynamicFormAlert(list);
        return dispatchPaperFormDto;


    }

    @Transactional
    @Override
    public DispatchPaperFormDto createDispatchPaper(Long alertId, String alertCode, AgencyUserModel sendUser) {
        DispatchPaperFormDto dispatchPaperFormDto = new DispatchPaperFormDto();
        // 创建基本信息
        DispatchPaper dispatchPaper = new DispatchPaper();
        dispatchPaper.setAlertCode(alertCode);
        dispatchPaper.setAlertId(alertId);

        dispatchPaper.setDispatchTime(new Date());
        dispatchPaper.setIsDelete(false);
        // 完成状态 派遣状态 派遣人
        DispatchPaperEnums finishStatus =  DispatchPaperEnums.getEnumByCode("notFinish");
        dispatchPaper.setPaperStatus(finishStatus.getValue());
        dispatchPaper.setPaperStatusCode(finishStatus.getId());

        DispatchPaperEnums dispatchStatus = DispatchPaperEnums.getEnumByCode("receivedAlert");
        dispatchPaper.setProcessStatus(dispatchStatus.getValue());
        dispatchPaper.setProcessStatusCode(dispatchStatus.getId());

        dispatchPaper.setSendUserId(sendUser.getUserId());
        dispatchPaper.setSendUserName(sendUser.getRealName());

        // 电梯维保单位统一信用代码
        Map<String,Object> map  = elevatorServiceImpl.selectByAlertId(alertId);
        if(!ObjectUtils.isEmpty(map.get("sequenceNbr"))) {
            List<Map<String,Object>> mapList = elevatorMapper.selectMtByAlertId(String.valueOf(map.get("sequenceNbr")));
            if(!ObjectUtils.isEmpty(mapList) && CollectionUtils.isEmpty(mapList)){
                dispatchPaper.setRepairOrgCreditCode(String.valueOf(mapList.get(0).get("useCode")));
            }
        }
        this.save(dispatchPaper);

        // 根据类型创建动态表单信息
        String dynamicCode = DispatchPaperEnums.getEnumById(alertCode).getDynamicCode();
        List<AlertFormInitDto>  alertFormInitDtoList = alertFormServiceImpl.getFormlist(dynamicCode);
        List<AlertFormValue> paperFormValuelist = new ArrayList<>(alertFormInitDtoList.size());
        // 填充警情主键
        alertFormInitDtoList.stream().forEach(initDto -> {
            initDto.getFormItemDescr().setAlertCalledId(dispatchPaper.getSequenceNbr());
            initDto.getFormItemDescr().setAlertTypeCode(dynamicCode);
            initDto.getFormItemDescr().setFieldValue(null);
            paperFormValuelist.add(initDto.getFormItemDescr());
        });
        // 保存动态表单数据
        iAlertFormValueService.saveBatch(paperFormValuelist);
        dispatchPaperFormDto.setDispatchPaper(dispatchPaper);
        dispatchPaperFormDto.setDynamicFormAlert(paperFormValuelist);

        if("KRJY".equals(AlertStageEnums.getEnumById(alertCode).getCode())) {
            RescueProcessDto rescueProcessDto = new RescueProcessDto();
            rescueProcessDto.setAlertId(alertId);
            rescueProcessDto.setDispatchStatus(true);
            rescueProcessDto.setDispatchTime(dispatchPaper.getDispatchTime());
            rescueProcessServiceImpl.updateByAlertId(rescueProcessDto,null);
        }
        return dispatchPaperFormDto;
    }

    @Override
    public DispatchSaveFeedbackDto getDispatchSaveFeedbackDtoByAlertId(Long alertId) {
        DispatchSaveFeedbackDto dispatchSaveFeedbackDto = new DispatchSaveFeedbackDto();
        dispatchSaveFeedbackDto.setAlertId(alertId);
        AlertCalledFormDto alertCalledFormVo = alertCalledServiceImpl.selectAlertCalledByIdNoCache(alertId);
        // 警情信息
        AlertCalledDto alertCalledDto = alertCalledFormVo.getAlertCalledDto();
        dispatchSaveFeedbackDto.setEmergency(alertCalledDto.getEmergencyPerson());
        dispatchSaveFeedbackDto.setEmergencyCall(alertCalledDto.getEmergencyCall());
        // 派遣单信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(alertId);
        if(dispatchPaperFormDto == null || dispatchPaperFormDto.getDispatchPaper() == null) {
            return new DispatchSaveFeedbackDto(); // 如果没有派遣就没有派遣反馈信息
        }
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
//        dispatchSaveFeedbackDto.setFeedbackCode(dispatchPaper.getFeedbackCode());
//        dispatchSaveFeedbackDto.setFeedbackType(dispatchPaper.getFeedbackType());
        dispatchSaveFeedbackDto.setFeedbackFinishTime(dispatchPaper.getFeedbackFinishTime());
        if(StringUtils.isBlank(dispatchPaper.getFeedbackUid())) {
            dispatchSaveFeedbackDto.setFeedbackUid(null);
        } else {
            dispatchSaveFeedbackDto.setFeedbackUid(dispatchPaper.getFeedbackUid());
        }
        if(StringUtils.isBlank(dispatchPaper.getFeedbackUname())) {
            dispatchSaveFeedbackDto.setFeedbackUname(null);
        } else {
            dispatchSaveFeedbackDto.setFeedbackUname(dispatchPaper.getFeedbackUname());
        }

        //救援响应人和维保响应人
        Long useOrgTaskId = dispatchPaper.getUseOrgTaskId();
        Long repairOrgTaskId = dispatchPaper.getRepairOrgTaskId();

        // 如果维保单位和使用单位都下单了 默认显示维保单位
        DispatchTask dispatchTask = null;
        if(repairOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(repairOrgTaskId);
            dispatchSaveFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchSaveFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        } else if(useOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(useOrgTaskId);
            dispatchSaveFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchSaveFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        }
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case TzsCommonParam.SAVE_FEEDBACK_TIME:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackTime(null);
                    } else {
                        try {
                            dispatchSaveFeedbackDto.setSaveFeedbackTime(DateUtils.longStr2Date(value));
                        } catch (Exception e) {
                            throw new BadRequest("救援时间格式错误");
                        }
                    }
                    break;
                case TzsCommonParam.SAVE_FEEDBACK_USER:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackUser(null);
                    } else {
                        dispatchSaveFeedbackDto.setSaveFeedbackUser(value);
                    }
                    break;
                case TzsCommonParam.SAVE_FEEDBACK_UID:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackUid(null);
                    } else {
                        dispatchSaveFeedbackDto.setSaveFeedbackUid(value);
                    }
                    break;
                case TzsCommonParam.SAVE_FEEDBACK_RESULT:
                    value = alertFormValue.getFieldValue();
                    dispatchSaveFeedbackDto.setSaveFeedbackResult(value);
                    break;
                case TzsCommonParam.FIX_RESULT:
                    value = alertFormValue.getFieldValueCode();
                    dispatchSaveFeedbackDto.setFixResult(value);
                    break;
                case TzsCommonParam.ERROR_RESULT:
                    value = alertFormValue.getFieldValueCode();
                    dispatchSaveFeedbackDto.setErrorResult(value);
                    break;
                case TzsCommonParam.FIX_REMARK:
                    value = alertFormValue.getFieldValue();
                    dispatchSaveFeedbackDto.setFixRemark(value);
                    break;
                case TzsCommonParam.FIX_FEEDBACK_TYPE:// 保修反馈方式
                    value = alertFormValue.getFieldValueCode();
                    dispatchSaveFeedbackDto.setFeedbackCode(value);
                    dispatchSaveFeedbackDto.setFeedbackType(alertFormValue.getFieldValue());
                    break;
            }

        });

        return dispatchSaveFeedbackDto;
    }

    @Transactional
    @Override
    public Boolean saveDispatchSaveFeedback(DispatchSaveFeedbackDto dispatchSaveFeedbackDto, AgencyUserModel user) {
        // 困人救援 需先维护救援过程信息 再保存回访信息
        AlertCalled alertCalled = alertCalledServiceImpl.getById(dispatchSaveFeedbackDto.getAlertId());
        String alarmTypeCode = alertCalled.getAlarmTypeCode();
        String alertStageCode = alertCalled.getAlertStageCode();
        if (DispatchPaperEnums.KRJY.getId().equals(alarmTypeCode)) {
            int rescuedStageCode = Integer.parseInt(DispatchPaperEnums.rescued.getId());
            int currentStageCode = Integer.parseInt(alertStageCode);
            if (currentStageCode < rescuedStageCode) {
                throw new BadRequest("请先完善救援过程信息！");
            }
        }
        boolean flag = false;
        // 保存救援回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchSaveFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        Map<String,Boolean> tempMap = new HashMap<String,Boolean>();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
                    switch (alertFormValue.getFieldCode()) {
                        case TzsCommonParam.SAVE_FEEDBACK_TIME:
                            if (dispatchSaveFeedbackDto.getSaveFeedbackTime() != null) {
                                if(alertFormValue.getFieldValue() == null ) {
                                    tempMap.put(TzsCommonParam.BXFK,true);
                                }
                                alertFormValue.setFieldValue(DateUtils.date2LongStr(dispatchSaveFeedbackDto.getSaveFeedbackTime()));
                            }
                            break;
                        case TzsCommonParam.SAVE_FEEDBACK_USER:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackUser()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackUser());
                            break;
                        case TzsCommonParam.SAVE_FEEDBACK_UID:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackUid()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackUid());
                            break;
                        case TzsCommonParam.SAVE_FEEDBACK_RESULT:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackResult()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackResult());
                            break;
                        case TzsCommonParam.FIX_REMARK:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getFixRemark()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getFixRemark());
                            break;
                        case TzsCommonParam.FIX_RESULT:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getFixResult())) {
                                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.WXJG).eq(DataDictionary::getCode, dispatchSaveFeedbackDto.getFixResult());
                                DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                                alertFormValue.setFieldValue(fixResult.getName());
                                alertFormValue.setFieldValueCode(fixResult.getCode());
                            }
                            break;
                        case TzsCommonParam.ERROR_RESULT:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getErrorResult())) {
                                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.GZYY).eq(DataDictionary::getCode, dispatchSaveFeedbackDto.getErrorResult());
                                DataDictionary errorResult = iDataDictionaryService.getOne(queryWrapper);
                                alertFormValue.setFieldValue(errorResult.getName());
                                alertFormValue.setFieldValueCode(errorResult.getCode());
                            }
                            break;
                        case TzsCommonParam.FIX_FEEDBACK_TYPE:
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getFeedbackCode())) {
                                LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKFS).eq(DataDictionary::getCode, dispatchSaveFeedbackDto.getFeedbackCode());
                                DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                                alertFormValue.setFieldValue(feedbackType.getName());
                                alertFormValue.setFieldValueCode(feedbackType.getCode());
                            }
                            break;
                    }
        });
//        if(StringUtils.isNotBlank(dispatchSaveFeedbackDto.getFeedbackCode())) {
//            dispatchPaper.setFeedbackCode(dispatchSaveFeedbackDto.getFeedbackCode());
//            dispatchPaper.setFeedbackType(DispatchPaperEnums.getEnumById(dispatchSaveFeedbackDto.getFeedbackCode()).getValue());
//        }
        dispatchPaper.setFeedbackFinishTime(dispatchSaveFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchSaveFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchSaveFeedbackDto.getFeedbackUname());
        if(dispatchPaper.getFeedbackTime() == null && dispatchSaveFeedbackDto.getFeedbackFinishTime() != null) {
            tempMap.put("FEEDBACK",true);
        }
        // 保存派遣表
        flag = this.updateById(dispatchPaper);
        // 保存动态表单数据
        iAlertFormValueService.updateBatchById(dynamicFormAlert);
        if(tempMap.get("BXFK") != null) {
            // 救援回访
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchSaveFeedbackDto.getAlertId(),TzsCommonParam.JYHF,null,user);
        }
        if(tempMap.get("FEEDBACK") != null) {
            // 维修反馈
            Long taskId = dispatchPaper.getRepairOrgTaskId() != null ? dispatchPaper.getRepairOrgTaskId() : dispatchPaper.getUseOrgTaskId();
            if(taskId == null) {
                throw new BadRequest("未找到反馈任务单");
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchSaveFeedbackDto.getAlertId(),TzsCommonParam.WXFK,taskId,user);
            dispatchPaper.setFeedbackTime(dispatchSaveFeedbackDto.getFeedbackFinishTime()); // 没有回访时间只有维修完成时间 2021.8.18 演示沟通 维修完成时间即为 反馈时间
        }
        return flag;
    }

    @Override
    public DispatchRepairFeedbackDto getDispatchRepairFeedbackDtoByAlertId(Long alertId) {
        DispatchRepairFeedbackDto dispatchRepairFeedbackDto = new DispatchRepairFeedbackDto();
        dispatchRepairFeedbackDto.setAlertId(alertId);
        AlertCalledFormDto alertCalledFormVo = alertCalledServiceImpl.selectAlertCalledByIdNoCache(alertId);
        // 警情信息
        AlertCalledDto alertCalledDto = alertCalledFormVo.getAlertCalledDto();
        dispatchRepairFeedbackDto.setEmergency(alertCalledDto.getEmergencyPerson());
        dispatchRepairFeedbackDto.setEmergencyCall(alertCalledDto.getEmergencyCall());

        // 派遣单信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(alertId);
        if(dispatchPaperFormDto == null || dispatchPaperFormDto.getDispatchPaper() == null) {
            return new DispatchRepairFeedbackDto(); // 如果没有派遣就没有派遣反馈信息
        }

        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        dispatchRepairFeedbackDto.setFixFeedbackCode(dispatchPaper.getFeedbackCode());// 维修反馈code
        dispatchRepairFeedbackDto.setFixFeedbackTime(dispatchPaper.getFeedbackTime()); //报修人反馈时间
        dispatchRepairFeedbackDto.setRemark(dispatchPaper.getRemark()); // 维修反馈备注
        if(StringUtils.isBlank(dispatchPaper.getFeedbackUid())) { //维修反馈人
            dispatchRepairFeedbackDto.setFeedbackUid(null);
        } else {
            dispatchRepairFeedbackDto.setFeedbackUid(dispatchPaper.getFeedbackUid());
        }

        if(StringUtils.isBlank(dispatchPaper.getFeedbackUname())) { //维修反馈人
            dispatchRepairFeedbackDto.setFeedbackUname(null);
        } else {
            dispatchRepairFeedbackDto.setFeedbackUname(dispatchPaper.getFeedbackUname());
        }


        //维保响应人
        Long useOrgTaskId = dispatchPaper.getUseOrgTaskId();
        Long repairOrgTaskId = dispatchPaper.getRepairOrgTaskId();

        // 如果维保单位和使用单位都下单了 默认显示维保单位
        DispatchTask dispatchTask = null;
        if(repairOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(repairOrgTaskId);
            dispatchRepairFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchRepairFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        } else if(useOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(useOrgTaskId);
            dispatchRepairFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchRepairFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        }

        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case TzsCommonParam.FIX_FEEDBACK_TIME: //报修反馈时间
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFeedbackFinishTime(null);
                    } else {
                        try {
                            dispatchRepairFeedbackDto.setFeedbackFinishTime(DateUtils.longStr2Date(value));
                        } catch (Exception e) {
                            throw new BadRequest("维修反馈时间格式错误");
                        }
                    }
                    break;
                case TzsCommonParam.FEEDBACK_RESULT://报修结果
                    value = alertFormValue.getFieldValueCode();
                    dispatchRepairFeedbackDto.setFeedbackResult(value);
                    break;
                case TzsCommonParam.FIX_FEEDBACK_TYPE:// 保修反馈方式
                    value = alertFormValue.getFieldValueCode();
                    dispatchRepairFeedbackDto.setFeedbackCode(value);
                    break;
                case TzsCommonParam.FIX_FEEDBACK_UNAME:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFixFeedbackUname(null);
                    } else {
                        dispatchRepairFeedbackDto.setFixFeedbackUname(value);
                    }
                    break;
                case TzsCommonParam.FIX_FEEDBACK_UID:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFixFeedbackUid(null);
                    } else {
                        dispatchRepairFeedbackDto.setFixFeedbackUid(value);
                    }
                    break;
                case TzsCommonParam.FIX_RESULT:
                    value = alertFormValue.getFieldValueCode();
                    dispatchRepairFeedbackDto.setFixResult(value);
                    break;
                case TzsCommonParam.ERROR_RESULT:
                    value = alertFormValue.getFieldValueCode();
                    dispatchRepairFeedbackDto.setErrorResult(value);
                    break;
                case TzsCommonParam.FIX_REMARK:
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setFixRemark(value);
                    break;
            }

        });

        return dispatchRepairFeedbackDto;
    }

    @Transactional
    @Override
    public Boolean saveDispatchRepairFeedback(DispatchRepairFeedbackDto dispatchRepairFeedbackDto, AgencyUserModel user) {
        Boolean flag = false;
        // 保存维修回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchRepairFeedbackDto.getAlertId());
        if(ValidationUtil.isEmpty(dispatchPaperFormDto.getDispatchPaper()) || ValidationUtil.isEmpty(dispatchPaperFormDto.getDynamicFormAlert())){
            return flag;
        }
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        Map<String,Boolean> tempMap = new HashMap<String,Boolean>();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            switch (alertFormValue.getFieldCode()) {
                case TzsCommonParam.FIX_FEEDBACK_TIME:
                    if (dispatchRepairFeedbackDto.getFeedbackFinishTime() != null) {
                        if(alertFormValue.getFieldValue() == null) {// 维修人员反馈
                            tempMap.put("WXFK",true);
                            dispatchPaper.setRepairUser(dispatchRepairFeedbackDto.getFeedbackUname());
                            dispatchPaper.setRepairOrgName("坐席");
                        }
                        alertFormValue.setFieldValue(DateUtils.date2LongStr(dispatchRepairFeedbackDto.getFeedbackFinishTime()));
                    }
                    break;
                case TzsCommonParam.FEEDBACK_RESULT:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFeedbackResult())) {
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", TzsCommonParam.FKJG).eq("code", dispatchRepairFeedbackDto.getFeedbackResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(feedbackType.getName());
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case TzsCommonParam.FIX_FEEDBACK_TYPE:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFeedbackCode())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKFS).eq(DataDictionary::getCode, dispatchRepairFeedbackDto.getFeedbackCode());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(feedbackType.getName());
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case TzsCommonParam.FIX_FEEDBACK_UNAME:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackUname()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixFeedbackUname());
                    break;
                case TzsCommonParam.FIX_FEEDBACK_UID:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackUid()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixFeedbackUid());
                    break;
                case TzsCommonParam.FIX_RESULT:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixResult())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.WXJG).eq(DataDictionary::getCode, dispatchRepairFeedbackDto.getFixResult());
                        DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(fixResult.getName());
                        alertFormValue.setFieldValueCode(fixResult.getCode());
                    }
                    break;
                case TzsCommonParam.ERROR_RESULT:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getErrorResult())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.GZYY).eq(DataDictionary::getCode, dispatchRepairFeedbackDto.getErrorResult());
                        DataDictionary errorResult = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(errorResult.getName());
                        alertFormValue.setFieldValueCode(errorResult.getCode());
                    }
                    break;
                case TzsCommonParam.FIX_REMARK:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixRemark()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixRemark());
                    break;
            }
        });
        if(StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackCode())) {
            dispatchPaper.setFeedbackCode(dispatchRepairFeedbackDto.getFixFeedbackCode());
            dispatchPaper.setFeedbackType(DispatchPaperEnums.getEnumById(dispatchRepairFeedbackDto.getFixFeedbackCode()).getValue());
        }
        dispatchPaper.setFeedbackFinishTime(dispatchRepairFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchRepairFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchRepairFeedbackDto.getFeedbackUname());
        dispatchPaper.setRemark(dispatchRepairFeedbackDto.getRemark());
        dispatchPaper.setFeedbackFinishTime(dispatchRepairFeedbackDto.getFixFeedbackTime());
        if(dispatchPaper.getFeedbackTime() == null && dispatchRepairFeedbackDto.getFixFeedbackTime() != null) { // 上报人反馈
            tempMap.put("BXFK",true);
        }
        dispatchPaper.setFeedbackTime(dispatchRepairFeedbackDto.getFixFeedbackTime());
        // 保存动态表单数据
        iAlertFormValueService.updateBatchById(dynamicFormAlert);
        // 保存派遣表
        flag = this.updateById(dispatchPaper);
        if(tempMap.get("WXFK") != null) {
            // 维修反馈
            Long taskId = dispatchPaper.getRepairOrgTaskId() != null ? dispatchPaper.getRepairOrgTaskId() : dispatchPaper.getUseOrgTaskId();
            if(taskId == null) {
                throw new BadRequest("未找到反馈任务单");
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchRepairFeedbackDto.getAlertId(),TzsCommonParam.WXFK,taskId,user);
        }
        if(tempMap.get("BXFK") != null) {
            // 报修反馈
            Long taskId = dispatchPaper.getRepairOrgTaskId() != null ? dispatchPaper.getRepairOrgTaskId() : dispatchPaper.getUseOrgTaskId();
            if(taskId == null) {
                throw new BadRequest("未找到反馈任务单");
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchRepairFeedbackDto.getAlertId(),TzsCommonParam.BXFK,taskId,user);
        }
        return flag;
    }

    @Override
    public DispatchConsultFeedbackDto getDispatchConsultFeedbackDtoByAlertId(Long alertId) {
        DispatchConsultFeedbackDto dispatchConsultFeedbackDto = new DispatchConsultFeedbackDto();
        dispatchConsultFeedbackDto.setAlertId(alertId);
        AlertCalledFormDto alertCalledFormVo =  alertCalledServiceImpl.selectAlertCalledByIdNoCache(alertId);
        // 警情信息
        AlertCalledDto alertCalledDto = alertCalledFormVo.getAlertCalledDto();
        dispatchConsultFeedbackDto.setEmergency(alertCalledDto.getEmergencyPerson());
        dispatchConsultFeedbackDto.setEmergencyCall(alertCalledDto.getEmergencyCall());

        // 派遣单信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(alertId);
        if(dispatchPaperFormDto == null || dispatchPaperFormDto.getDispatchPaper() == null) {
            return new DispatchConsultFeedbackDto(); // 如果没有派遣就没有派遣反馈信息
        }

        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        dispatchConsultFeedbackDto.setFeedbackCode(dispatchPaper.getFeedbackCode());// 维修反馈code
        dispatchConsultFeedbackDto.setFeedbackType(dispatchPaper.getFeedbackType());// 维修反馈类型
        dispatchConsultFeedbackDto.setFeedbackTime(dispatchPaper.getFeedbackTime()); //回访时间
        dispatchConsultFeedbackDto.setRemark(dispatchPaper.getRemark()); // 维修反馈备注
        dispatchConsultFeedbackDto.setFeedbackFinishTime(dispatchPaper.getFeedbackFinishTime()); //维保完成时间
        if(StringUtils.isBlank(dispatchPaper.getFeedbackUid())) { //维修反馈人
            dispatchConsultFeedbackDto.setFeedbackUid(null);
        } else {
            dispatchConsultFeedbackDto.setFeedbackUid(dispatchPaper.getFeedbackUid());
        }

        if(StringUtils.isBlank(dispatchPaper.getFeedbackUname())) { //维修反馈人
            dispatchConsultFeedbackDto.setFeedbackUname(null);
        } else {
            dispatchConsultFeedbackDto.setFeedbackUname(dispatchPaper.getFeedbackUname());
        }


        //维保响应人
        Long useOrgTaskId = dispatchPaper.getUseOrgTaskId();
        Long repairOrgTaskId = dispatchPaper.getRepairOrgTaskId();

        // 如果维保单位和使用单位都下单了 默认显示维保单位
        DispatchTask dispatchTask = null;
        if(repairOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(repairOrgTaskId);
            dispatchConsultFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchConsultFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        } else if(useOrgTaskId != null) {
            dispatchTask = dispatchTaskServiceImpl.getById(useOrgTaskId);
            dispatchConsultFeedbackDto.setResponseUserName(dispatchTask.getResponseUserName());
            dispatchConsultFeedbackDto.setResponseUserTel(dispatchTask.getResponseUserTel());
        }

        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case TzsCommonParam.CONSULT_FEEDBACK_TIME: //咨询反馈时间
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackTime(null);
                    } else {
                        try {
                            dispatchConsultFeedbackDto.setConsultFeedbackTime(DateUtils.longStr2Date(value));
                        } catch (Exception e) {
                            throw new BadRequest("咨询反馈时间格式错误");
                        }
                    }
                    break;
                case TzsCommonParam.ACTION_RESULT://处置结果
                    value = alertFormValue.getFieldValueCode();
                    dispatchConsultFeedbackDto.setActionResult(value);
                    break;
                case TzsCommonParam.FEEDBACK_RESULT://咨询反馈结果
                    value = alertFormValue.getFieldValueCode();
                    dispatchConsultFeedbackDto.setFeedbackResult(value);
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_TYPE:// 咨询反馈方式
                    value = alertFormValue.getFieldValueCode();
                    dispatchConsultFeedbackDto.setConsultFeedbackCode(value);
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_UNAME:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackUname(null);
                    } else {
                        dispatchConsultFeedbackDto.setConsultFeedbackUname(value);
                    }
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_UID:
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackUid(null);
                    } else {
                        dispatchConsultFeedbackDto.setConsultFeedbackUid(value);
                    }
                    break;
                case TzsCommonParam.MAIN_FEEDBACK_RESULT:
                    value = alertFormValue.getFieldValue();
                    dispatchConsultFeedbackDto.setMainFeedbackResult(value);
                    break;
            }

        });
        return dispatchConsultFeedbackDto;
    }

    @Transactional
    @Override
    public Boolean saveDispatchConsultFeedback(DispatchConsultFeedbackDto dispatchConsultFeedbackDto, AgencyUserModel user) {
        Boolean flag = false;
        // 保存救援回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchConsultFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        Map<String,Boolean> tempMap = new HashMap<String,Boolean>();
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            switch (alertFormValue.getFieldCode()) {
                case TzsCommonParam.CONSULT_FEEDBACK_TIME:
                    if (dispatchConsultFeedbackDto.getConsultFeedbackTime() != null) {
                        if(alertFormValue.getFieldValue() == null ) {
                            tempMap.put("FEEDBACK",true);
                            dispatchPaper.setDealUser(dispatchConsultFeedbackDto.getFeedbackUname());
                            dispatchPaper.setDealOrgName("坐席");
                        }
                        alertFormValue.setFieldValue(DateUtils.date2LongStr(dispatchConsultFeedbackDto.getConsultFeedbackTime()));
                    }
                    break;
                case TzsCommonParam.ACTION_RESULT:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getActionResult())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.CZJG).eq(DataDictionary::getCode, dispatchConsultFeedbackDto.getActionResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(feedbackType.getName());
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_TYPE:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackCode())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKFS).eq(DataDictionary::getCode, dispatchConsultFeedbackDto.getConsultFeedbackCode());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(feedbackType.getName());
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_UNAME:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackUname()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getConsultFeedbackUname());
                    break;
                case TzsCommonParam.CONSULT_FEEDBACK_UID:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackUid()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getConsultFeedbackUid());
                    break;
                case TzsCommonParam.MAIN_FEEDBACK_RESULT:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getMainFeedbackResult()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getMainFeedbackResult());
                    break;
                case TzsCommonParam.FEEDBACK_RESULT:
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getFeedbackResult())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKJG).eq(DataDictionary::getCode, dispatchConsultFeedbackDto.getFeedbackResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValue(feedbackType.getName());
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
            }
        });
        if(StringUtils.isNotBlank(dispatchConsultFeedbackDto.getFeedbackCode())) {
            dispatchPaper.setFeedbackCode(dispatchConsultFeedbackDto.getFeedbackCode());
            dispatchPaper.setFeedbackType(DispatchPaperEnums.getEnumById(dispatchConsultFeedbackDto.getFeedbackCode()).getValue());
        }
        if(dispatchPaper.getFeedbackTime() == null && dispatchConsultFeedbackDto.getFeedbackTime() != null) {
            tempMap.put("TSRFK",true);
        }
        dispatchPaper.setFeedbackTime(dispatchConsultFeedbackDto.getFeedbackTime());
        dispatchPaper.setFeedbackFinishTime(dispatchConsultFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchConsultFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchConsultFeedbackDto.getFeedbackUname());
        dispatchPaper.setRemark(dispatchConsultFeedbackDto.getRemark());
        // 保存动态表单数据
        iAlertFormValueService.updateBatchById(dynamicFormAlert);
        // 保存派遣表
        flag = this.updateById(dispatchPaper);
        if(tempMap.get("FEEDBACK") != null) {
            // 维修反馈
            Long taskId = dispatchPaper.getRepairOrgTaskId() != null ? dispatchPaper.getRepairOrgTaskId() : dispatchPaper.getUseOrgTaskId();
            if(taskId == null) {
                throw new BadRequest("未找到反馈任务单");
            }
            // 修改警情到维修反馈
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchConsultFeedbackDto.getAlertId(),TzsCommonParam.WXFK_TS,taskId,user);
        }
        if(tempMap.get("TSRFK") != null) {
            // 修改警情到投诉人反馈
            // 投诉人反馈
            Long taskId = dispatchPaper.getRepairOrgTaskId() != null ? dispatchPaper.getRepairOrgTaskId() : dispatchPaper.getUseOrgTaskId();
            if(taskId == null) {
                throw new BadRequest("未找到反馈任务单");
            }
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(dispatchConsultFeedbackDto.getAlertId(),TzsCommonParam.TSRFK,taskId,user);
        }
        return flag;
    }

    @Override
    public DispatchPaper selectDispatchPaperByAlertId(Long alertId) {
        LambdaQueryWrapper<DispatchPaper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DispatchPaper::getAlertId, alertId);
        // 警情动态表单数据
        DispatchPaper dispatchPaper  = this.getOne(queryWrapper);
        return dispatchPaper;
    }

}