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

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.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.DispatchPaperEnums;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 派遣单服务实现类
 *
 * @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;


    /**
     * 分页查询
     */
    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.getEnum(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);
        QueryWrapper<AlertFormValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("alert_called_id", dispatchPaper.getSequenceNbr()).eq("alert_type_code",        DispatchPaperEnums.getEnum(dispatchPaper.getAlertCode()).getDynamicCode());
        // 派遣单动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        dispatchPaperFormDto.setDynamicFormAlert(list);
        return dispatchPaperFormDto;


    }

    @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.getEnum("notFinish");
        dispatchPaper.setPaperStatus(finishStatus.getValue());
        dispatchPaper.setPaperStatusCode(finishStatus.getCode());

        DispatchPaperEnums dispatchStatus = DispatchPaperEnums.getEnum("receivedAlert");
        dispatchPaper.setProcessStatus(dispatchStatus.getValue());
        dispatchPaper.setProcessStatusCode(dispatchStatus.getCode());

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

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

        this.save(dispatchPaper);

        // 根据类型创建动态表单信息
        String dynamicCode = DispatchPaperEnums.getEnum(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(DispatchPaperEnums.getEnum(dispatchPaper.getAlertCode()).getDynamicCode());
            initDto.getFormItemDescr().setFieldValue(null);
            paperFormValuelist.add(initDto.getFormItemDescr());
        });
        // 保存动态表单数据
        iAlertFormValueService.saveBatch(paperFormValuelist);
        dispatchPaperFormDto.setDispatchPaper(dispatchPaper);
        dispatchPaperFormDto.setDynamicFormAlert(paperFormValuelist);

        if("KRJY".equals(alertCode)) {
            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());
        dispatchSaveFeedbackDto.setRemark(dispatchPaper.getRemark());
        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();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case "save_feedback_time":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackTime(null);
                    } else {
                        try {
                            dispatchSaveFeedbackDto.setSaveFeedbackTime(sdf.parse(value));
                        } catch (ParseException e) {
                            throw new BadRequest("救援时间格式错误");
                        }
                    }
                    break;
                case "save_feedback_user":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackUser(null);
                    } else {
                        dispatchSaveFeedbackDto.setSaveFeedbackUser(value);
                    }
                    break;
                case "save_feedback_uid":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchSaveFeedbackDto.setSaveFeedbackUid(null);
                    } else {
                        dispatchSaveFeedbackDto.setSaveFeedbackUid(value);
                    }
                    break;
                case "save_feedback_result":
                    value = alertFormValue.getFieldValue();
                    dispatchSaveFeedbackDto.setSaveFeedbackResult(value);
                    break;
                case "fix_result":
                    value = alertFormValue.getFieldValue();
                    dispatchSaveFeedbackDto.setFixResult(value);
                    break;
                case "error_result":
                    value = alertFormValue.getFieldValue();
                    dispatchSaveFeedbackDto.setErrorResult(value);
                    break;
            }

        });

        return dispatchSaveFeedbackDto;
    }

    @Override
    public Boolean saveDispatchSaveFeedback(DispatchSaveFeedbackDto dispatchSaveFeedbackDto) {
        Boolean flag = false;
        // 保存救援回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchSaveFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
                    switch (alertFormValue.getFieldCode()) {
                        case "save_feedback_time":
                            if (dispatchSaveFeedbackDto.getSaveFeedbackTime() != null)
                                alertFormValue.setFieldValue(sdf.format(dispatchSaveFeedbackDto.getSaveFeedbackTime()));
                            break;
                        case "save_feedback_user":
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackUser()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackUser());
                            break;
                        case "save_feedback_uid":
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackUid()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackUid());
                            break;
                        case "save_feedback_result":
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getSaveFeedbackResult()))
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getSaveFeedbackResult());
                            break;
                        case "fix_result":
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getFixResult())) {
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getFixResult());
                                QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("type", "WXJG").eq("name", dispatchSaveFeedbackDto.getFixResult());
                                DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                                alertFormValue.setFieldValueCode(fixResult.getCode());
                            }
                            break;
                        case "error_result":
                            if (StringUtils.isNotBlank(dispatchSaveFeedbackDto.getErrorResult())) {
                                alertFormValue.setFieldValue(dispatchSaveFeedbackDto.getErrorResult());
                                QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("type", "GZYY").eq("name", dispatchSaveFeedbackDto.getErrorResult());
                                DataDictionary errorResult = iDataDictionaryService.getOne(queryWrapper);
                                alertFormValue.setFieldValueCode(errorResult.getCode());
                            }
                            break;
                    }
        });
        dispatchPaper.setFeedbackCode(dispatchSaveFeedbackDto.getFeedbackCode());
        dispatchPaper.setFeedbackType(dispatchSaveFeedbackDto.getFeedbackType());
        dispatchPaper.setFeedbackFinishTime(dispatchSaveFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchSaveFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchSaveFeedbackDto.getFeedbackUname());
        dispatchPaper.setRemark(dispatchSaveFeedbackDto.getRemark());
        dispatchPaper.setFeedbackTime(dispatchSaveFeedbackDto.getFeedbackTime());
        // 保存动态表单数据
        iAlertFormValueService.updateBatchById(dynamicFormAlert);
        // 保存派遣表
        flag = this.updateById(dispatchPaper);
        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();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case "fix_feedback_time": //报修反馈时间
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFixFeedbackTime(null);
                    } else {
                        try {
                            dispatchRepairFeedbackDto.setFixFeedbackTime(sdf.parse(value));
                        } catch (ParseException e) {
                            throw new BadRequest("维修反馈时间格式错误");
                        }
                    }
                    break;
                case "feedback_result"://报修结果
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setFeedbackResult(value);
                    break;
                case "fix_feedback_type":// 保修反馈方式
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setFixFeedbackType(value);
                    break;
                case "fix_feedback_uname":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFixFeedbackUname(null);
                    } else {
                        dispatchRepairFeedbackDto.setFixFeedbackUname(value);
                    }
                    break;
                case "fix_feedback_uid":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchRepairFeedbackDto.setFixFeedbackUid(null);
                    } else {
                        dispatchRepairFeedbackDto.setFixFeedbackUid(value);
                    }
                    break;
                case "fix_result":
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setFixResult(value);
                    break;
                case "error_result":
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setErrorResult(value);
                    break;
                case "fix_remark":
                    value = alertFormValue.getFieldValue();
                    dispatchRepairFeedbackDto.setFixRemark(value);
                    break;
            }

        });

        return dispatchRepairFeedbackDto;
    }

    @Override
    public Boolean saveDispatchRepairFeedback(DispatchRepairFeedbackDto dispatchRepairFeedbackDto) {
        Boolean flag = false;
        // 保存救援回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchRepairFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            switch (alertFormValue.getFieldCode()) {
                case "fix_feedback_time":
                    if (dispatchRepairFeedbackDto.getFixFeedbackTime() != null)
                        alertFormValue.setFieldValue(sdf.format(dispatchRepairFeedbackDto.getFixFeedbackTime()));
                    break;
                case "feedback_result":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFeedbackResult())) {
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFeedbackResult());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "FKJG").eq("name", dispatchRepairFeedbackDto.getFeedbackResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case "fix_feedback_type":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackType())) {
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixFeedbackType());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "FKFS").eq("name", dispatchRepairFeedbackDto.getFixFeedbackType());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case "fix_feedback_uname":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackUname()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixFeedbackUname());
                    break;
                case "fix_feedback_uid":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixFeedbackUid()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixFeedbackUid());
                    break;
                case "fix_result":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixResult())) {
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixResult());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "WXJG").eq("name", dispatchRepairFeedbackDto.getFixResult());
                        DataDictionary fixResult = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(fixResult.getCode());
                    }
                    break;
                case "error_result":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getErrorResult())) {
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getErrorResult());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "GZYY").eq("name", dispatchRepairFeedbackDto.getErrorResult());
                        DataDictionary errorResult = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(errorResult.getCode());
                    }
                    break;
                case "fix_remark":
                    if (StringUtils.isNotBlank(dispatchRepairFeedbackDto.getFixRemark()))
                        alertFormValue.setFieldValue(dispatchRepairFeedbackDto.getFixRemark());
                    break;
            }
        });
        dispatchPaper.setFeedbackCode(dispatchRepairFeedbackDto.getFeedbackCode());
        dispatchPaper.setFeedbackType(dispatchRepairFeedbackDto.getFeedbackType());
        dispatchPaper.setFeedbackFinishTime(dispatchRepairFeedbackDto.getFeedbackFinishTime());
        dispatchPaper.setFeedbackUid(dispatchRepairFeedbackDto.getFeedbackUid());
        dispatchPaper.setFeedbackUname(dispatchRepairFeedbackDto.getFeedbackUname());
        dispatchPaper.setRemark(dispatchRepairFeedbackDto.getRemark());
        dispatchPaper.setFeedbackTime(dispatchRepairFeedbackDto.getFeedbackTime());
        // 保存动态表单数据
        iAlertFormValueService.updateBatchById(dynamicFormAlert);
        // 保存派遣表
        flag = this.updateById(dispatchPaper);
        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();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            String value = null;
            switch (alertFormValue.getFieldCode()) {
                case "consult_feedback_time": //咨询反馈时间
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackTime(null);
                    } else {
                        try {
                            dispatchConsultFeedbackDto.setConsultFeedbackTime(sdf.parse(value));
                        } catch (ParseException e) {
                            throw new BadRequest("咨询反馈时间格式错误");
                        }
                    }
                    break;
                case "action_result"://处置结果
                    value = alertFormValue.getFieldValue();
                    dispatchConsultFeedbackDto.setActionResult(value);
                    break;
                case "feedback_result"://咨询反馈结果
                    value = alertFormValue.getFieldValue();
                    dispatchConsultFeedbackDto.setFeedbackResult(value);
                    break;
                case "consult_feedback_type":// 咨询反馈方式
                    value = alertFormValue.getFieldValue();
                    dispatchConsultFeedbackDto.setConsultFeedbackType(value);
                    break;
                case "consult_feedback_uname":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackUname(null);
                    } else {
                        dispatchConsultFeedbackDto.setConsultFeedbackUname(value);
                    }
                    break;
                case "consult_feedback_uid":
                    value = alertFormValue.getFieldValue();
                    if (StringUtils.isBlank(value)) {
                        dispatchConsultFeedbackDto.setConsultFeedbackUid(null);
                    } else {
                        dispatchConsultFeedbackDto.setConsultFeedbackUid(value);
                    }
                    break;
                case "main_feedback_result":
                    value = alertFormValue.getFieldValue();
                    dispatchConsultFeedbackDto.setMainFeedbackResult(value);
                    break;
            }

        });
        return dispatchConsultFeedbackDto;
    }

    @Override
    public Boolean saveDispatchConsultFeedback(DispatchConsultFeedbackDto dispatchConsultFeedbackDto) {
        Boolean flag = false;
        // 保存救援回访信息
        DispatchPaperFormDto dispatchPaperFormDto = this.selectDispatchPaperDtoByAlertId(dispatchConsultFeedbackDto.getAlertId());
        DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
        // 动态字段
        List<AlertFormValue> dynamicFormAlert = dispatchPaperFormDto.getDynamicFormAlert();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dynamicFormAlert.stream().forEach(alertFormValue -> {
            switch (alertFormValue.getFieldCode()) {
                case "consult_feedback_time":
                    if (dispatchConsultFeedbackDto.getConsultFeedbackTime() != null)
                        alertFormValue.setFieldValue(sdf.format(dispatchConsultFeedbackDto.getConsultFeedbackTime()));
                    break;
                case "action_result":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getActionResult())) {
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getActionResult());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "CZJG").eq("name", dispatchConsultFeedbackDto.getActionResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case "consult_feedback_type":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackType())) {
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getConsultFeedbackType());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "FKFS").eq("name", dispatchConsultFeedbackDto.getConsultFeedbackType());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
                case "consult_feedback_uname":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackUname()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getConsultFeedbackUname());
                    break;
                case "consult_feedback_uid":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getConsultFeedbackUid()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getConsultFeedbackUid());
                    break;
                case "main_feedback_result":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getMainFeedbackResult()))
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getMainFeedbackResult());
                    break;
                case "feedback_result":
                    if (StringUtils.isNotBlank(dispatchConsultFeedbackDto.getFeedbackResult())) {
                        alertFormValue.setFieldValue(dispatchConsultFeedbackDto.getFeedbackResult());
                        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("type", "FKJG").eq("name", dispatchConsultFeedbackDto.getFeedbackResult());
                        DataDictionary feedbackType = iDataDictionaryService.getOne(queryWrapper);
                        alertFormValue.setFieldValueCode(feedbackType.getCode());
                    }
                    break;
            }
        });
        dispatchPaper.setFeedbackCode(dispatchConsultFeedbackDto.getFeedbackCode());
        dispatchPaper.setFeedbackType(dispatchConsultFeedbackDto.getFeedbackType());
        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);
        return flag;
    }

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

}