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.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.entity.AlertFormValue;
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.boot.module.tzs.api.vo.AlertCalledVo;
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;

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

    @Override
    public Boolean saveRepairConsultByAlertIdType(Long alertId, String type, Long taskId) {
        Boolean flag = false;
        RepairConsult repairConsult = new RepairConsult();
        repairConsult.setParentId(alertId);
        AlertCalledFormDto alertCallFrom = alertCalledServiceImpl.selectAlertCalledByIdNoCache(alertId);
        if(alertCallFrom == null || alertCallFrom.getAlertCalledVo() == null) {
            throw new BadRequest("未找到警情信息");
        }
        AlertCalledVo alertCalledVo  = alertCallFrom.getAlertCalledVo();
        // 获取模板 拼接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 = getUser().getUserName();
            String emergency_call = alertCalledVo.getEmergencyCall();
            String area = alertCalledVo.getAddress();
            String alertType = alertCalledVo.getAlarmType();
            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 = getUser().getUserName();

            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String unit = dispatchTask.getResponseOrgName();
            String person = dispatchTask.getResponseUserName();
            String phone = dispatchTask.getResponseUserTel();
            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();
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            content = content.replace("$createTime",createTime).replace("$person",person);
            dynamicForm.stream().forEach(alertFormValue -> {
                if("arrive_feedback_type".equals(alertFormValue.getFieldCode())) {
                    String FKFS = alertFormValue.getFieldValue();
                    repairConsult.setDescription(FKFS);
                }
            });
            content = content.replace("$FKFS",repairConsult.getDescription());
        } else if("JC".equals(type)) {
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            DispatchPaperFormDto dispatchPaperFormDto = dispatchPaperServiceImpl.selectDispatchPaperDtoByAlertId(alertId);
            List<AlertFormValue> dynamicForm = dispatchPaperFormDto.getDynamicFormAlert();
            Map<String,String> tempMap = new HashMap<String,String>();
            content = content.replace("$createTime",createTime).replace("$person",person);
            dynamicForm.stream().forEach(alertFormValue -> {
                if("arrive_feedback_type".equals(alertFormValue.getFieldCode())) {
                    tempMap.put("FKFS",alertFormValue.getFieldValue());
                }
            });
            content = content.replace("$FKFS",tempMap.get("FKFS"));
        } else if("JYHF".equals(type)) {
            String createUser = getUser().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();
            String fix_result =
                    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("$fixResult",tempMap.get("fixResult"));
        } else if("BXFK".equals(type)) {
            DispatchTask dispatchTask = dispatchTaskServiceImpl.getById(taskId);
            String person = dispatchTask.getResponseUserName();
            String fix_result =
                    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();
            String fix_result =
                    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(type);
        repairConsult.setAlertStageCode(AlertStageEnums.getEnumByCode(type).getId());
        repairConsult.setAlertStatus(AlertStageEnums.getEnumByCode(type).getValue());
        repairConsult.setDescription(content);
        flag = this.save(repairConsult);
        return flag;
    }

    private AgencyUserModel getUser() {
        ReginParams reginParams =
                JSONObject.parseObject(null != redisUtils.get(buildKey(getToken())) ?
                        redisUtils.get(buildKey(getToken())).toString() : null, ReginParams.class);
        return  reginParams.getUserModel();
    }

    protected String buildKey(String token) {
        // 由于用户id 不是接口携带参数，为了避免，公共字段填充时频繁访问平台，缓存用户信息时，
        return "region_" + token;

    }

    /**
     * 获取token
     **/
    protected String getToken() {
        return RequestContext.getToken();
    }


}