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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.tzs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertFormInitDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchConsultFeedbackDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchPaperDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchPaperFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchRepairFeedbackDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DispatchSaveFeedbackDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.RescueProcessDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchPaper;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.tzs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.tzs.api.entity.MaintenanceUnit;
import com.yeejoin.amos.boot.module.tzs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.tzs.api.enums.DispatchPaperEnums;
import com.yeejoin.amos.boot.module.tzs.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.tzs.api.mapper.DispatchPaperMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IDispatchPaperService;
import com.yeejoin.amos.boot.module.tzs.api.service.IMaintenanceUnitService;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
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.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
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 DispatchPaperServiceImpl extends BaseService<DispatchPaperDto,DispatchPaper,DispatchPaperMapper> implements IDispatchPaperService {

    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    private AlertFormServiceImpl alertFormServiceImpl;

    @Autowired
    private ElevatorServiceImpl elevatorServiceImpl;

    @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());

        // 电梯维保单位统一信用代码
        Elevator elevator = elevatorServiceImpl.selectByAlertId(alertId);
        MaintenanceUnit maintenanceUnit = iMaintenanceUnitService.getById(elevator.getMaintainUnitId());
        dispatchPaper.setRepairOrgCreditCode(maintenanceUnit.getSocialCreditCode());

        this.save(dispatchPaper);

        // 根据类型创建动态表单信息
        String dynamicCode = DispatchPaperEnums.getEnumById(alertCode).getDynamicCode();
        List<AlertFormInitDto>  alertFormInitDtoList = alertFormServiceImpl.getFormlist(dynamicCode);
        List<AlertFormValue> paperFormValuelist = new ArrayList<AlertFormValue>(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;
            }

        });

        return dispatchSaveFeedbackDto;
    }

    @Transactional
    @Override
    public Boolean saveDispatchSaveFeedback(DispatchSaveFeedbackDto dispatchSaveFeedbackDto, AgencyUserModel user) {
        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;
                    }
        });
        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.setFeedbackCode(dispatchPaper.getFeedbackCode());// 维修反馈code
        dispatchRepairFeedbackDto.setFeedbackType(dispatchPaper.getFeedbackType());// 维修反馈类型
        dispatchRepairFeedbackDto.setFeedbackFinishTime(dispatchPaper.getFeedbackFinishTime()); //维修完成时间
        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.setFixFeedbackTime(null);
                    } else {
                        try {
                            dispatchRepairFeedbackDto.setFixFeedbackTime(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.setFixFeedbackType(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());
        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.getFixFeedbackTime() != null) {
                        if(alertFormValue.getFieldValue() == null) {
                            tempMap.put(TzsCommonParam.BXFK,true);
                        }
                        alertFormValue.setFieldValue(DateUtils.date2LongStr(dispatchRepairFeedbackDto.getFixFeedbackTime()));
                    }
                    break;
                case TzsCommonParam.FEEDBACK_RESULT:
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFeedbackResult())) {
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", TzsCommonParam.WXJG).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.getFixFeedbackType())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKFS).eq(DataDictionary::getCode, dispatchRepairFeedbackDto.getFixFeedbackType());
                        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.getFeedbackCode())) {
            dispatchPaper.setFeedbackCode(dispatchRepairFeedbackDto.getFeedbackCode());
            dispatchPaper.setFeedbackType(DispatchPaperEnums.getEnumById(dispatchRepairFeedbackDto.getFeedbackCode()).getValue());
        }
        dispatchPaper.setFeedbackFinishTime(dispatchRepairFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchRepairFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchRepairFeedbackDto.getFeedbackUname());
        dispatchPaper.setRemark(dispatchRepairFeedbackDto.getRemark());
        if(dispatchPaper.getFeedbackTime() == null && dispatchRepairFeedbackDto.getFeedbackTime() != null) {
            tempMap.put("FEEDBACK",true);
        }
        dispatchPaper.setFeedbackTime(dispatchRepairFeedbackDto.getFeedbackTime());
        // 保存动态表单数据
        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(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.setConsultFeedbackType(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(TzsCommonParam.TSRFK,true);
                        }
                        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.getConsultFeedbackType())) {
                        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DataDictionary::getType, TzsCommonParam.FKFS).eq(DataDictionary::getCode, dispatchConsultFeedbackDto.getConsultFeedbackType());
                        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("FEEDBACK",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;
    }

}