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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.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.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.text.SimpleDateFormat;
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 RepairConsultServiceImpl extends BaseService<RepairConsultDto,RepairConsult,RepairConsultMapper> implements IRepairConsultService {
    /**
     * 分页查询
     */
    public Page<RepairConsultDto> queryForRepairConsultPage(Page<RepairConsultDto> page)   {
        return this.queryForPage(page, null, false);
    }

    @Autowired
    TemplateServiceImpl templateServiceImpl;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    private AlertCalledServiceImpl alertCalledServiceImpl;

    @Autowired
    DispatchPaperServiceImpl dispatchPaperServiceImpl;

    @Autowired
    DispatchTaskServiceImpl dispatchTaskServiceImpl;

    @Autowired
    RescueProcessServiceImpl rescueProcessServiceImpl;

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

    @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
        QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.eq("type_code","RECORD-" + type);
        Template template = templateServiceImpl.getOne(templateQueryWrapper);
        String content = template.getContent();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = sdf.format(new Date());
        if("JJ".equals(type)) {
            String createUser = user.getUserName();
            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("PQ".equals(type)) {
            String createUser = user.getUserName();
            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("960".equals( alertCalledVo.getAlarmTypeCode())) {
                taskType = "救援任务单";
            } else if("961".equals( alertCalledVo.getAlarmTypeCode())) {
                taskType = "故障维修单";
            } else if("962".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("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);
        } else if("JC".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);
        } else if("JYHF".equals(type)) {
            String createUser = user.getUserName();
            String create = alertCalledVo.getEmergencyPerson();
            content = content.replace("$createTime",createTime).replace("$createUser",createUser).replace("$create",create);
        } else if("WXFK".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();
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                 if("fix_result".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",dispatchPaper.getFeedbackType()).replace("$fixResult",tempMap.get("fixResult"));
        } else if("WXFK-TS".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();
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            dynamicForm.stream().forEach(alertFormValue -> {
                if("action_result".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",dispatchPaper.getFeedbackType()).replace("$fixResult",tempMap.get("fixResult"));
            type = "WXFK";
        } else if("BXFK".equals(type)) {
            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("fix_feedback_type".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("FKFS",alertFormValue.getFieldValue());
                } else if("fix_result".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("fixResult",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get("FKFS")).replace("$feedbackResult",tempMap.get("fixResult"));
        } else if("TSRFK".equals(type)) {
            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("consult_feedback_type".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("FKFS",alertFormValue.getFieldValue());
                } else if("action_result".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("action_result",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get("FKFS")).replace("$feedbackResult",tempMap.get("action_result"));
        }
        repairConsult.setType(AlertStageEnums.getEnumByCode(type).getId());
        repairConsult.setAlertStageCode(AlertStageEnums.getEnumByCode(type).getId());
        repairConsult.setAlertStatus(AlertStageEnums.getEnumByCode(type).getValue());
        repairConsult.setDescription(content);
        flag = this.save(repairConsult);
        return flag;
    }




}