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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.tcm.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.DispatchPaperFormDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.RepairConsultDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.RescueProcessDto;
import com.yeejoin.amos.boot.module.tcm.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.tcm.api.entity.DispatchPaper;
import com.yeejoin.amos.boot.module.tcm.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.tcm.api.entity.RepairConsult;
import com.yeejoin.amos.boot.module.tcm.api.entity.Template;
import com.yeejoin.amos.boot.module.tcm.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.tcm.api.enums.DispatchPaperEnums;
import com.yeejoin.amos.boot.module.tcm.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.tcm.api.mapper.RepairConsultMapper;
import com.yeejoin.amos.boot.module.tcm.api.service.IRepairConsultService;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 警情填报业务数据项服务实现类
 *
 * @author system_generator
 * @date 2021-08-03
 */
@Service
public class RepairConsultServiceImpl extends BaseService<RepairConsultDto,RepairConsult,RepairConsultMapper> implements IRepairConsultService {

    private final Logger logger = LoggerFactory.getLogger(RepairConsultServiceImpl.class);
    @Autowired
    TemplateServiceImpl templateServiceImpl;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    private AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    DispatchPaperServiceImpl dispatchPaperServiceImpl;

    @Autowired
    DispatchTaskServiceImpl dispatchTaskServiceImpl;

    @Autowired
    RescueProcessServiceImpl rescueProcessServiceImpl;


    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    private EmqKeeper emqKeeper;

    @Value("${mqtt.topic.alertHeart.push}")
    private String alertHeartpushTopic;

    @Value("${mqtt.topic.alertMatrix.push}")
    private String alertMatrixpushTopic;

    @Autowired
    ISourceFileService sourceFileService;


    /**
     * 记录处置日志同时修改案件的状态
     * @param alertId
     * @param type
     * @param taskId
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Boolean saveRepairConsultByAlertIdType(Long alertId, String type, Long taskId,AgencyUserModel user) {
        Boolean flag = false;
        RepairConsult repairConsult = new RepairConsult();
        repairConsult.setParentId(alertId);
        AlertCalledFormDto alertCallFrom = alertCalledServiceImpl.selectAlertCalledByIdNoCache(alertId);
        if(alertCallFrom == null || alertCallFrom.getAlertCalledDto() == null) {
            throw new BadRequest("未找到警情信息");
        }
        AlertCalledDto alertCalledVo  = alertCallFrom.getAlertCalledDto();
        // 获取模板 拼接json
        LambdaQueryWrapper<Template> templateQueryWrapper = new LambdaQueryWrapper<>();
        if(TzsCommonParam.WXFK_TS.equals(type)) {
            templateQueryWrapper.eq(Template::getTypeCode,"RECORD-" + TzsCommonParam.WXFK);
        } else {
            templateQueryWrapper.eq(Template::getTypeCode,"RECORD-" + type);
        }
        Template template = templateServiceImpl.getOne(templateQueryWrapper);
        String content = template.getContent();
        String createTime = DateUtils.getDateNowString();
        DispatchPaperEnums CZHJ = null;
        StringBuffer attach = new StringBuffer();
        // 公众号生成接警记录
        if(AlertStageEnums.JJ.getCode().equals(type)) {
            // 接警的处置环节为已接警
            CZHJ = DispatchPaperEnums.receivedAlert;
            String createUser = user.getRealName();
            String emergency_call = alertCalledVo.getEmergencyCall();
            String area = alertCalledVo.getAddress();
            String alertType = alertCalledVo.getAlarmType();
            if(createUser == null)
                throw new BadRequest("坐席人缺失");
            if(emergency_call == null)
                throw new BadRequest("求援人电话缺失");
            if(area == null)
                throw new BadRequest("区域缺失");
            if(alertType == null)
                throw new BadRequest("警情类型缺失");
            content = content.replace("$createTime",createTime).replace("$createUser",createUser).replace("$call",emergency_call);
            content = content.replace("$area",area).replace("$alertType",alertType);
        } else if(TzsCommonParam.APPJJ.equals(type)) {
            // 接警的处置环节为已接警   公众号上报
            CZHJ = DispatchPaperEnums.receivedAlert;
            String emergency_call = alertCalledVo.getEmergencyCall();
            String area = alertCalledVo.getAddress();
            String alertType = alertCalledVo.getAlarmType();

            if(emergency_call == null)
                throw new BadRequest("求援人电话缺失");
            if(area == null)
                throw new BadRequest("区域缺失");
            if(alertType == null)
                throw new BadRequest("警情类型缺失");
            content = content.replace("$createTime",createTime).replace("$call",emergency_call);
            content = content.replace("$area",area).replace("$alertType",alertType);
            // 小程序接警 记录添加图片附件  bykongfm 2021-11-02  task-4217
            Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(alertId);
            List<AttachmentDto> mapList = imgMap.get("imgs");
            if(mapList != null && mapList.size() > 0) {
                mapList.stream().forEach(m -> {
                    attach.append(",");
                    attach.append(m.getUrl());
                });
            }
        } else if(TzsCommonParam.PQ.equals(type)) {
            // 派遣的处置环节为已派遣
            CZHJ = DispatchPaperEnums.dispatched;
            String createUser =  user.getRealName();
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String unit = dispatchTask.getResponseOrgName();
            if(unit == null)
                throw new BadRequest("派遣单位缺失");
            String person = dispatchTask.getResponseUserName();
            String phone = dispatchTask.getResponseUserTel();
            if("119".equals(unit)) {
                person = "";
                phone = "";
            }
            String taskType = "";
            if(AlertStageEnums.KRJY.getId().equals( alertCalledVo.getAlarmTypeCode())) {
                taskType = "救援任务单";
            } else if(AlertStageEnums.GZWX.getId().equals( alertCalledVo.getAlarmTypeCode())) {
                taskType = "故障维修单";
            } else if(AlertStageEnums.TSZX.getId().equals( alertCalledVo.getAlarmTypeCode())) {
                taskType = "投诉处理单";
            }
            content = content.replace("$createTime",createTime).replace("$createUser",createUser).replace("$unit",unit);
            content = content.replace("$person",person).replace("$phone",phone).replace("$taskType",taskType);
        } else if(TzsCommonParam.DD.equals(type)) {

            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            content = content.replace("$createTime",createTime).replace("$person",person);
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
            String FKFS = dispatchPaper.getArriveFeedbackType();
            content = content.replace("$FKFS",FKFS);
            if(dispatchTask.getIsSaveTask() != null && dispatchTask.getIsSaveTask()) {
                // 到达的处置环节为维保已到达或者 已到达
                CZHJ = DispatchPaperEnums.rescueArrived;
            } else {
                CZHJ = DispatchPaperEnums.repaireArrived;
            }
        } else if(TzsCommonParam.JC.equals(type)) {
            //救出为救援完成
            CZHJ = DispatchPaperEnums.rescued;
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            content = content.replace("$createTime",createTime).replace("$person",person);
            RescueProcessDto rescueProcessDto = rescueProcessServiceImpl.getProcessByAlertId(alertId);
            String FKFS = rescueProcessDto.getArriveFeedbackType();
            content = content.replace("$FKFS",FKFS);
        } else if(TzsCommonParam.JYHF.equals(type)) {
            //救援回访
            CZHJ = DispatchPaperEnums.rescueBack;
            String createUser =  user.getRealName();
            String create = alertCalledVo.getEmergencyPerson();
            content = content.replace("$createTime",createTime).replace("$createUser",createUser).replace("$create",create);
        } else if(TzsCommonParam.WXFK.equals(type)) { //从派遣单获取数据
            //维修反馈修改到维修完成
            CZHJ = DispatchPaperEnums.repaired;
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            content = content.replace("$createTime",createTime).replace("$person",person);
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                 if(TzsCommonParam.FIX_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                }
                if(TzsCommonParam.FIX_FEEDBACK_TYPE.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("FKFS",alertFormValue.getFieldValue());
                }
            });
            // 反馈方式从动态表单中取得
            String FKFS = tempMap.get("FKFS") == null ? "" :  tempMap.get("FKFS");
            content = content.replace("$FKFS",FKFS).replace("$fixResult",tempMap.get("fixResult"));
            // 小程序维修反馈 记录添加图片附件  bykongfm 2021-11-02  task-4217
            Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(dispatchTask.getPaperId());
            List<AttachmentDto> mapList = imgMap.get("imgs");
            if(mapList != null && mapList.size() > 0) {
                mapList.stream().forEach(m -> {
                    attach.append(",");
                    attach.append(m.getUrl());
                });
            }
        } else if(TzsCommonParam.WXFK_TS.equals(type)) { //从派遣单获取数据
            //投诉的维修反馈修改成维保已处置
            CZHJ = DispatchPaperEnums.disposed;
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            content = content.replace("$createTime",createTime).replace("$person",person);
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                if(TzsCommonParam.ACTION_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                } else if(TzsCommonParam.CONSULT_FEEDBACK_TYPE.equals(alertFormValue.getFieldCode())) {
                    tempMap.put(TzsCommonParam.FKFS,alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get(TzsCommonParam.FKFS)).replace("$fixResult",tempMap.get("fixResult"));
            type = TzsCommonParam.WXFK;
            // 小程序维修反馈 记录添加图片附件  bykongfm 2021-11-02  task-4217
            Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(dispatchTask.getPaperId());
            List<AttachmentDto> mapList = imgMap.get("imgs");
            if(mapList != null && mapList.size() > 0) {
                mapList.stream().forEach(m -> {
                    attach.append(",");
                    attach.append(m.getUrl());
                });
            }
        } else if(TzsCommonParam.BXFK.equals(type)) {
            //报修反馈
            CZHJ = DispatchPaperEnums.reportorBack;
            String person = alertCalledVo.getEmergencyPerson() + "(" + alertCalledVo.getEmergencyCall() + ")";
            content = content.replace("$createTime",createTime).replace("$person",person);
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                if(TzsCommonParam.FEEDBACK_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("feedbackResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",dispatchPaperFormDto.getDispatchPaper().getFeedbackType()).replace("$feedbackResult",tempMap.get("feedbackResult"));
            // 小程序报修人反馈 记录添加图片附件  bykongfm 2021-11-02  task-4217
            Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(alertId);
            List<AttachmentDto> mapList = imgMap.get("feedbacks");
            if(mapList != null && mapList.size() > 0) {
                mapList.stream().forEach(m -> {
                    attach.append(",");
                    attach.append(m.getUrl());
                });
            }
        } else if(TzsCommonParam.TSRFK.equals(type)) {
            //投诉人已反馈
            CZHJ = DispatchPaperEnums.complainantBack;
            String person = alertCalledVo.getEmergencyPerson() + "(" + alertCalledVo.getEmergencyCall() + ")";
            content = content.replace("$createTime",createTime).replace("$person",person);
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                if(TzsCommonParam.FEEDBACK_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("feedbackResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",dispatchPaperFormDto.getDispatchPaper().getFeedbackType()).replace("$feedbackResult",tempMap.get("feedbackResult"));
            // 小程序投诉人反馈记录添加图片附件  bykongfm 2021-11-02  task-4217
            Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(alertId);
            List<AttachmentDto> mapList = imgMap.get("feedbacks");
            if(mapList != null && mapList.size() > 0) {
                mapList.stream().forEach(m -> {
                    attach.append(",");
                    attach.append(m.getUrl());
                });
            }
        }
        AlertStageEnums RZHJ = AlertStageEnums.getEnumByCode(type);
        repairConsult.setType(RZHJ.getCode());
        repairConsult.setAlertStageCode(RZHJ.getId());
        repairConsult.setAlertStatus(RZHJ.getValue());
        repairConsult.setDescription(content);
        if(attach.length() > 0) {
            String attachment = attach.toString().substring(1);
            repairConsult.setAttachment(attachment);
        }
        flag = this.save(repairConsult);
        if(flag) {
            // 记录处置记录后修改 案件状态
            alertCalledServiceImpl.updateAlertStage(alertCalledVo,CZHJ);
                // 警情伤亡消息 矩阵 消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("alertId",String.valueOf(alertCalledVo.getSequenceNbr()));
            // KRJY 的 repaired   complainantBack  和 reportorBack 警情完成
            if(CZHJ == DispatchPaperEnums.reportorBack || CZHJ == DispatchPaperEnums.complainantBack) {
                jsonObject.put("finished",true);
            } else if(CZHJ == DispatchPaperEnums.repaired  && alertCalledVo.getAlarmTypeCode().equals(AlertStageEnums.KRJY.getId())) {
                jsonObject.put("finished",true);
            }
            try {
                emqKeeper.getMqttClient().publish(alertHeartpushTopic, jsonObject.toString().getBytes("UTF-8"), 1, false);
                emqKeeper.getMqttClient().publish(alertMatrixpushTopic, jsonObject.toString().getBytes("UTF-8"), 1, false);

            } catch (MqttException e) {
                logger.error("mqtt发送失败" +jsonObject );
            } catch (UnsupportedEncodingException e) {
                logger.error("mqtt发送失败" +jsonObject );
            }

        }
        return flag;
    }

}