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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.DispatchPaperFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.RepairConsultDto;
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.RepairConsult;
import com.yeejoin.amos.boot.module.tzs.api.entity.Template;
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.RepairConsultMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IRepairConsultService;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
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.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 {

    @Autowired
    TemplateServiceImpl templateServiceImpl;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    private AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    DispatchPaperServiceImpl dispatchPaperServiceImpl;

    @Autowired
    DispatchTaskServiceImpl dispatchTaskServiceImpl;

    @Autowired
    RescueProcessServiceImpl rescueProcessServiceImpl;

    /**
     * 记录处置日志同时修改案件的状态
     * @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;
        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.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);
            RescueProcessDto rescueProcessDto = rescueProcessServiceImpl.getProcessByAlertId(alertId);
            String FKFS = rescueProcessDto.getArriveFeedbackType();
            content = content.replace("$FKFS",FKFS);
            if(true == 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);
            DispatchPaper dispatchPaper = dispatchPaperFormDto.getDispatchPaper();
            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());
                }
            });
            content = content.replace("$FKFS",dispatchPaper.getFeedbackType()).replace("$fixResult",tempMap.get("fixResult"));
        } 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());
                }
            });
            content = content.replace("$FKFS",dispatchPaper.getFeedbackType()).replace("$fixResult",tempMap.get("fixResult"));
            type = TzsCommonParam.WXFK;
        } else if(TzsCommonParam.BXFK.equals(type)) {
            //报修反馈
            CZHJ = DispatchPaperEnums.reportorBack;
            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_FEEDBACK_TYPE.equals(alertFormValue.getFieldCode())) {
                    tempMap.put(TzsCommonParam.FKFS,alertFormValue.getFieldValue());
                } else if(TzsCommonParam.FIX_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get(TzsCommonParam.FKFS)).replace("$feedbackResult",tempMap.get("fixResult"));
        } else if(TzsCommonParam.TSRFK.equals(type)) {
            //投诉人已反馈
            CZHJ = DispatchPaperEnums.complainantBack;
            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.CONSULT_FEEDBACK_TYPE.equals(alertFormValue.getFieldCode())) {
                    tempMap.put(TzsCommonParam.FKFS,alertFormValue.getFieldValue());
                } else if(TzsCommonParam.ACTION_RESULT.equals(alertFormValue.getFieldCode())) {
                    tempMap.put("action_result",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get(TzsCommonParam.FKFS)).replace("$feedbackResult",tempMap.get("action_result"));
        }
        AlertStageEnums RZHJ = AlertStageEnums.getEnumByCode(type);
        repairConsult.setType(RZHJ.getCode());
        repairConsult.setAlertStageCode(RZHJ.getId());
        repairConsult.setAlertStatus(RZHJ.getValue());
        repairConsult.setDescription(content);
        flag = this.save(repairConsult);
        if(flag) {
            // 记录处置记录后修改 案件状态
            alertCalledServiceImpl.updateAlertStage(alertCalledVo,CZHJ);
        }
        return flag;
    }




}