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


import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.KeySiteServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
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.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.constants.BizConstant;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrzhDto;
import com.yeejoin.amos.boot.module.common.api.dto.RequestData;
import com.yeejoin.amos.boot.module.common.api.feign.JcsControlServerClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.WaterResourceServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledTodyDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledZhDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ControllerDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ControllerEquipDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.KeyValueLabel;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerData;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.jcs.api.enums.ControllerTypeEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.DutyInfoEnum;
import com.yeejoin.amos.boot.module.jcs.api.mapper.AlertCalledMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.AlertSubmittedMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.TemplateMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IAlertCalledService;
import com.yeejoin.amos.component.rule.config.RuleConfig;

/**
 * 警情接警记录 服务实现类
 *
 * @author tb
 * @date 2021-06-17
 */
@Service
public class AlertCalledServiceImpl extends BaseService<AlertCalledDto, AlertCalled, AlertCalledMapper> implements IAlertCalledService {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    AlertCalledMapper alertCalledMapper;
    @Autowired
    RuleAlertCalledService ruleAlertCalledService;
    @Autowired
    TemplateMapper templateMapper;
    @Autowired
    PowerTransferMapper powerTransferMapper;
    @Autowired
    AlertSubmittedMapper alertSubmittedMapper;
    @Autowired
    private JcsControlServerClient jcsControlServerClient;
    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;
    @Autowired
    private ESAlertCalledService eSAlertCalledService;
    @Autowired
    private ControllerServiceImpl controllerService;
    @Autowired
    private ControllerEquipServiceImpl controllerEquipService;
    @Autowired
    FirefightersServiceImpl firefightersService;
    @Autowired
    KeySiteServiceImpl keySiteService;
    @Autowired
    AlertSubmittedServiceImpl alertSubmittedService;

    @Autowired
    private AlertLocationLogServiceImpl alertLocationLogService;

    @Autowired
    private EmqKeeper emqKeeper;
    @Value("${mqtt.topic.command.alert.notice}")
    private String topic;
    @Value("${redis.cache.failure.time}")
    private long time;

    @Autowired
    private OrgUsrServiceImpl iOrgUsrService;

    @Autowired
    AircraftServiceImpl aircraftService;

    @Autowired
    AlertFormValueServiceImpl alertFormValueService;

    private static int comparingByGroupVal(Map<String, Object> map, Map<String, Object> map2, String key) {
        int result = 0;
        if (map.get(key) instanceof DateTime) {
            long r1 = ((Date) map.get(key)).getTime();
            long r2 = ((Date) map2.get(key)).getTime();
            result = Long.compare(r1, r2);
        }
        return result;
    }

    /**
     * 指挥系统 未结束的警情列表
     **/
    @Override
    public List<AlertCalledZhDto> alertCalledListByAlertStatus(Integer pageNum, Integer pageSize, RequestData par) {

        List<AlertCalledZhDto> list = alertCalledMapper.alertCalledListByAlertStatus(pageNum, pageSize, par);
        return list;

    }

    @Override
    public int alertCalledListByAlertStatusCount(RequestData par) {
        return alertCalledMapper.alertCalledListByAlertStatusCount(par);
    }


    /**
     * 接警记录  列表分页查询
     **/   /* bug2407 筛选参数解析异常 修改筛选条件方法 XML中添加了selectAllPage 方法 data代表排序条件 lift 升降序 陈召 2021-09-03 开始*/
//    public IPage<AlertCalled> queryForCalledList(Page pageBean, Integer alertStatus,
//                                                 String alertTypeCode,
//                                                 String alertSourceCode,
//                                                 String startTime,
//                                                 String endTime,
//                                                 String sort) {
//        String data = null;
//        String lift = null;
//        if (StringUtils.isNotEmpty(sort)) {
//            String[] split = sort.split(",");
//            data = RedisKey.humpToLine(split[0]);
//            lift = split[1];
//        }
//
//        List<AlertCalled> list = alertCalledMapper.selectAllPage(pageBean.getCurrent(), pageBean.getSize(), alertStatus, alertTypeCode, alertSourceCode, startTime, endTime, data, lift);
//    }
    public IPage<AlertCalled> queryForCalledList(Page pageBean, Integer alertStatus,
                                                 String alertTypeCode,
                                                 String alertSourceCode,
                                                 String startTime,
                                                 String endTime,
                                                 String sort) {


        String[] split = sort != null ? sort.split(",") : null;
        /*2407 【web】日常值班>警情记录>接警记录，表头排序功能失效 chenzhao 09-28 start*/
        if (split != null){
            if (split[0] != null) {
                if (split[0].equals("alertType") || split[0].equals("alertSource") || split[0].equals("alarmType")) {
                    split[0] = split[0] + "Code";
                }
                if (split[0].equals("alertStatusStr")) {
                    split[0] = "alertStatus";
                }
            }
            if (split[1] != null){
                if (split[1].equals("ascend")){
                    split[1] = "ASC";
                }
                if (split[1].equals("descend")){
                    split[1] = "DESC";
                }
            }
        }

        String data = split != null ? RedisKey.humpToLine(split[0]) : null;
        /*2407 【web】日常值班>警情记录>接警记录，表头排序功能失效 chenzhao 09-28 end*/
        String lift = split != null ? split[1] : null;

        List<AlertCalled> list = alertCalledMapper.selectAllPage(pageBean.getCurrent(), pageBean.getSize(), alertStatus, alertTypeCode, alertSourceCode, startTime, endTime, data, lift);
        IPage<AlertCalled> iPage = new Page<>();
        iPage.setRecords(list);
        iPage.setTotal(alertCalledMapper.selectAllCount(alertStatus, alertTypeCode, alertSourceCode, startTime, endTime));
        return iPage;
        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 结束*/
    }


    /**
     * 根据灾情id 查询灾情详情
     **/
    @Override
    public Object selectAlertCalledById(Long id) {
        if (redisUtils.hasKey(RedisKey.ALERTCALLED_ID + id)) {
            Object obj = redisUtils.get(RedisKey.ALERTCALLED_ID + id);
            return obj;
        } else {
            // 警情基本信息
            AlertCalled alertCalled = this.getById(id);
            QueryWrapper<AlertFormValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("alert_called_id", id);
            // 警情动态表单数据
            List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
            List<FormValue> formValue = new ArrayList<FormValue>();
            if (list != null && list.size() > 0) {
                for (AlertFormValue alertFormValue : list) {
                    FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(), "text", alertFormValue.getFieldValue(), alertFormValue.getBlock());
                    formValue.add(value);
                }
            }
            AlertCalledFormDto alertCalledFormVo = new AlertCalledFormDto(alertCalled, formValue);

            redisUtils.set(RedisKey.ALERTCALLED_ID + id, JSON.toJSON(alertCalledFormVo), time);
            return alertCalledFormVo;
        }
    }

    /**
     * <pre>
     * 保存警情信息
     * </pre>
     *
     * @param alertCalledObjsDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public AlertCalledObjsDto createAlertCalled(AlertCalledObjsDto alertCalledObjsDto) {
        try {
            // 警情基本信息
            AlertCalled alertCalled = alertCalledObjsDto.getAlertCalled();
            if (alertCalled.getAddress() != null) {
                JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(alertCalled.getAddress());
                alertCalled.setAddress(address.getString(BizConstant.ADDRESS));
                alertCalled.setCoordinateX(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
                alertCalled.setCoordinateY(Double.valueOf(address.getString(BizConstant.LATITUDE)));
            }
            alertCalled.setCallTime(new Date());
            if (AlertStageEnums.RG.getValue().equals(alertCalled.getAlertSourceCode()) ||
                    AlertStageEnums.RG.getValue().equals(alertCalled.getAlertSourceCode())) {
                alertCalled.setType("0");
            } else {
                alertCalled.setType("1");
            }
            // 动态表单
            List<AlertFormValue> alertFormValuelist = alertCalledObjsDto.getAlertFormValue();
            //判断是否航空器救援 如果为航空器救援则保存冗余字段 response_level_code bug2542 bykongfm
            if (AlertStageEnums.HKJY.getCode().equals(alertCalled.getAlertTypeCode())) {
                alertFormValuelist.stream().forEach(alertFormValue -> {
                    if (alertFormValue.getFieldCode().equals("responseLevel")) {
                        alertCalled.setResponseLevelCode(alertFormValue.getFieldValueCode());
                        alertCalled.setResponseLevel(alertFormValue.getFieldValue());
                    }
                });
            }

            // 判断是否归并警情
            if (alertCalled.getFatherAlert() != null) {
                // 警情归并，设置当前警情状态为结束。
                alertCalled.setAlertStatus(true);
                alertCalled.setAlertStage(AlertStageEnums.JQJB.getValue());
                alertCalled.setAlarmType(AlertStageEnums.JQGB.getValue());
                alertCalled.setAlarmTypeCode(AlertStageEnums.JQGB.getCode());
                this.save(alertCalled);

                // 填充警情主键
                alertFormValuelist.stream().forEach(alertFormValue -> {
                    alertFormValue.setAlertCalledId(alertCalled.getSequenceNbr());
                    alertFormValue.setAlertTypeCode(alertCalled.getAlertTypeCode());
                });
                // 保存动态表单数据
                iAlertFormValueService.saveBatch(alertFormValuelist);
            } else {
                // 警情报送
                // ****************************************************待确认开发
                alertCalled.setAlertStatus(false);
                alertCalled.setIsDelete(false);
                alertCalled.setAlertStage(AlertStageEnums.LLDP.getValue());
                alertCalled.setAlarmType(AlertStageEnums.JQCB.getValue());
                alertCalled.setAlarmTypeCode(AlertStageEnums.JQCB.getCode());
                this.save(alertCalled);
                // 填充警情主键
                alertFormValuelist.stream().forEach(alertFormValue -> {
                    alertFormValue.setAlertCalledId(alertCalled.getSequenceNbr());
                    alertFormValue.setAlertTypeCode(alertCalled.getAlertTypeCode());
                });
                // 保存动态表单数据
                iAlertFormValueService.saveBatch(alertFormValuelist);
                alertCalledObjsDto.setAlertCalled(alertCalled);
                alertCalledObjsDto.setAlertFormValue(alertFormValuelist);
                //警情报送
                //调用规则
                ruleAlertCalledService.fireAlertCalledRule(alertCalledObjsDto);
                //通知实战指挥页面发送mqtt 默认发送 String 类型 0, 新警情 1 警情状态变化
                emqKeeper.getMqttClient().publish(topic, "0".getBytes(), RuleConfig.DEFAULT_QOS, true);
            }


            /**
             * 同步保存ES
             */
            eSAlertCalledService.saveAlertCalledToES(alertCalled);

            return alertCalledObjsDto;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("报送失败，系统异常!");
        }
    }

    /**
     * 根据id 修改警情
     * type：警情相关 操作类型  0警情续报   1非警情确认   2 警情结案
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateAlertCalled(Long id, String code) {
        // TODO Auto-generated method stub
        try {
            switch (code) {
                case "314":
                    alertCalledMapper.update(null, new UpdateWrapper<AlertCalled>().eq("sequence_nbr", id)
                            .set("alert_status", 1).set("alert_stage", AlertStageEnums.ZBQJ.getValue()).set("alarm_type", AlertStageEnums.FJQ.getValue()).set("alarm_type_code", AlertStageEnums.FJQ.getCode()));
                    break;
                case "315":
                    alertCalledMapper.update(null, new UpdateWrapper<AlertCalled>().eq("sequence_nbr", id)
                            .set("alert_status", 1).set("alert_stage", AlertStageEnums.CZJS.getValue()));
                    break;
                default:
                    alertCalledMapper.update(null, new UpdateWrapper<AlertCalled>().eq("sequence_nbr", id)
                            .set("alert_stage", AlertStageEnums.CZGZ.getValue()));

                    break;
            }

            AlertCalled alertCalled = this.getById(id);
            //删除缓存
            redisUtils.del(RedisKey.ALERTCALLED_ID + id);
            /**
             * 同步更新存ES
             */
            eSAlertCalledService.saveAlertCalledToES(alertCalled);

            //通知实战指挥页面发送mqtt 默认发送 String 类型 0新警情， 1警情状态变化
            emqKeeper.getMqttClient().publish(topic, "1".getBytes(), RuleConfig.DEFAULT_QOS, true);

            return true;
        } catch (Exception e) {
            throw new RuntimeException("系统异常!");
        }
    }

    /**
     * 根据时间区间查询警情列表信息
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     */
    public List<Map<String, Object>> listByDateRange(String beginDate, String endDate) {
        // 查询指定日期内的警情列表

        List<AlertCalled> alertCalledList =
                this.list(new LambdaQueryWrapper<AlertCalled>().apply(!ValidationUtil.isEmpty(beginDate),
                        "call_time >= '" + beginDate + "'").le(true, AlertCalled::getCallTime, endDate));
        Map<String, String> queryParams = Maps.newHashMap();
        queryParams.put("beginDate", beginDate);
        queryParams.put("endDate", endDate);
        List<Map<String, Object>> allList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(alertCalledList)) {
            Map<String, List<AlertCalled>> alertCalledMap =
                    alertCalledList.stream().collect(Collectors.groupingBy(AlertCalled::getAlertTypeCode));
            Map<Long, AlertCalled> calledMap =
                    alertCalledList.stream().collect(Collectors.toMap(AlertCalled::getSequenceNbr, Function.identity()));
            alertCalledMap.forEach((alertTypeCode, list) -> {
                allList.addAll(iAlertFormValueService.listAll(alertTypeCode, queryParams));
            });

            allList.forEach(i -> {
                //增加非空判断 cz 2021-10-08
                if (calledMap.get(Long.parseLong(i.get("instanceId").toString())) != null) {
                    AlertCalled alertCalled = calledMap.get(Long.parseLong(i.get("instanceId").toString()));
                    i.putAll(Bean.BeantoMap(alertCalled));
                }
            });
        }
        // 按接警时间正序排序
        allList.sort((e, o) -> comparingByGroupVal(e, o, "recDate"));
        return allList;
    }


    public Map<String, Object> getAlertInfoList(String beginDate, String endDate) {
        Map<String, Object> result = Maps.newHashMap();
        List<Map<String, Object>> list = listByDateRange(beginDate, endDate);
        // 获取接警情况模板
        List<Template> templateList =
                templateMapper.selectList(new LambdaQueryWrapper<Template>().eq(Template::getFormat, false).like(Template::getTypeCode,
                        DutyInfoEnum.接警情况.getKey() + "-"));
        Map<String, Template> templateMap = templateList.stream().collect(Collectors.toMap(Template::getTypeCode,
                Function.identity()));
        List<String> contentList = Lists.newArrayList();
        //增加非空判断 cz 2021-10-08
        list.forEach(i -> {
            if (i.get("alertTypeCode") != null) {
                String tempContent =
                        templateMap.get(DutyInfoEnum.接警情况.getKey() + "-" + i.get("alertTypeCode")).getContent();
                contentList.add(replaceTemplate(tempContent, i));
            }
        });
        Map<String, Integer> statusCountMap = alertCalledMapper.queryAlertStatusCount(beginDate, endDate);
        Integer unFinishedCount =
                this.count(new LambdaQueryWrapper<AlertCalled>().eq(AlertCalled::getAlertStatus, false));//bug2532 未结案警情统计错误 bykongfm

        result.put("alertInfoList", contentList);
        result.putAll(statusCountMap);
        result.put("unFinishedCount", unFinishedCount);
        return result;
    }

    /**
     * 替换模板
     *
     * @param tempContent 模板
     * @param objMap      对象map
     * @return
     */
    private String replaceTemplate(String tempContent, Map<String, Object> objMap) {
        int size = objMap.size();
        String[] keys = objMap.keySet().toArray(new String[size]);
        Object[] values = objMap.values().toArray(new Object[size]);
        List<String> strList = Lists.newArrayList();
        for (Object obj : values) {
            if (!ValidationUtil.isEmpty(obj)) {
                if (obj instanceof Date) {
                    obj = DateUtils.date2LongStr((Date) obj);
                }
                strList.add(obj.toString());
            } else {
                strList.add("");
            }
        }
        return StringUtils.replaceEach(tempContent, keys, strList.toArray(new String[strList.size()]));
    }

    @Override
    public Map<String, Object>  selectAlertCalledKeyValueLabelById(Long id) {

        // 警情基本信息
        AlertCalled alertCalled = this.getById(id);
        QueryWrapper<AlertFormValue> queryWrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "【" + alertCalled.getAlertType() + "】" + alertCalled.getAddress());
        queryWrapper.eq("alert_called_id", id);

        // 警情动态表单数据
        List<KeyValueLabel> listdate = new ArrayList<>();
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        listdate.add(new KeyValueLabel("接警时间", "callTime", alertCalled.getCallTime()));
        listdate.add(new KeyValueLabel("警情地点", "address", alertCalled.getAddress()));
        listdate.add(new KeyValueLabel("警情类型", "alertType", alertCalled.getAlertType()));
        listdate.add(new KeyValueLabel("警情阶段", "alertStage", alertCalled.getAlertStage()));
        listdate.add(new KeyValueLabel("警情等级", "responseLevel", "无"));
        listdate.add(new KeyValueLabel("被困人数", "trappedNum", alertCalled.getTrappedNum()));
        listdate.add(new KeyValueLabel("伤亡人数", "casualtiesNum", alertCalled.getCasualtiesNum()));
        listdate.add(new KeyValueLabel("联系人", "contactUser", alertCalled.getContactUser()));
        listdate.add(new KeyValueLabel("联系电话", "contactPhone", alertCalled.getContactPhone()));
//        listdate.add(new KeyValueLabel("联系人电话", "contactPhone", alertCalled.getContactPhone()));
        list.stream().forEach(alertFormValue -> {
            /*2661 灾情详情中字典类数据错误显示为code 改为value值 2021-09-23 陈召 开始 */
            String valueCode = alertFormValue.getFieldValue();
            /*2661 灾情详情中字典类数据错误显示为code 改为value值 2021-09-23 陈召 结束 */
        	/*if(null == valueCode) {
                valueCode = alertFormValue.getFieldValue();
        	}*/
            listdate.add(new KeyValueLabel(alertFormValue.getFieldName(), alertFormValue.getFieldCode(), valueCode));
        });
        map.put("data", listdate);

        return map;
    }

    @Override
    public List<KeyValueLabel> selectAlertCalledcount(Long id) {
        // 警情基本信息
        AlertCalled alertCalled = this.getById(id);

        List<KeyValueLabel> listdate = new ArrayList<>();
        listdate.add(new KeyValueLabel("被困人数", "trappedNum", alertCalled.getTrappedNum()));
        listdate.add(new KeyValueLabel("伤亡人数", "casualtiesNum", alertCalled.getCasualtiesNum()));
        return listdate;
    }

    @Override
    public List<KeyValueLabel> powercount(Long id) {
        Map<String, Integer> map = powerTransferMapper.getCarNum(id);
//		Map<String,Integer>  mapc=powerTransferMapper.getCompanyNum(id);
//		Map<String,Integer>  mapu= alertSubmittedMapper.getUseNum(id);
        //统计参与人员
        List<KeyValueLabel> listdate = new ArrayList<>();
        listdate.add(new KeyValueLabel("调动人力", "useNum", "0", "人"));
        //统计参与车辆
        listdate.add(new KeyValueLabel("调动人力", "carNum", map.get("carNum"), "辆"));
        //统计参与队伍
        listdate.add(new KeyValueLabel("调动单位", "companyNum", map.get("companyNum"), "个"));
        return listdate;

    }

    @Override
    public List<PowerData> getPowerDataList(Long id) {
        List<PowerData> list = powerTransferMapper.getPowerDataList(id);
        return list;
    }

    @Override
    public AlertCalled getAlertCalledById(Long id) {
        return this.getById(id);
    }

    @Override
    public Integer AlertCalledcountTime(int type) {
        return alertCalledMapper.AlertCalledcountTime(type);
    }

    @Override
    public List<AlertCalledTodyDto> getTodayAlertCalled() {
        return alertCalledMapper.getTodayAlertCalled();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean controlEquip() throws Exception {
        /**
         * 获取控制器设备
         */
        List<ControllerEquipDto> controllerEquipDtoList = controllerEquipService.queryAllForList();
        Map<Long, List<String>> controllerEquipMap = new HashMap<>();
        for (ControllerEquipDto controllerEquipDto : controllerEquipDtoList) {
            List<String> numList = controllerEquipMap.get(controllerEquipDto.getControllerSeq());
            if (ValidationUtil.isEmpty(numList)) {
                numList = new ArrayList<>();
            }
            numList.add(controllerEquipDto.getNum());
            controllerEquipMap.put(controllerEquipDto.getControllerSeq(), numList);
        }
        /**
         * 获取联动控制器
         */
        List<ControllerDto> controllerDtoList = controllerService.queryAllForList();
        StringBuilder bellNumSb = new StringBuilder();
        StringBuilder broadcastNumSb = new StringBuilder();
        for (ControllerDto controllerDto : controllerDtoList) {
            //消防警铃
            if (controllerDto.getType().equals(ControllerTypeEnum.BELL.getCode())) {
                List<String> bellNumList = controllerEquipMap.get(controllerDto.getSequenceNbr());
                if (!ValidationUtil.isEmpty(bellNumList)) {
                    for (String num : bellNumList) {
                        bellNumSb.append(num).append(",");
                    }
                }
            }
            //广播
            if (controllerDto.getType().equals(ControllerTypeEnum.BROADCAST.getCode())) {
                List<String> broadcastList = controllerEquipMap.get(controllerDto.getSequenceNbr());
                if (!ValidationUtil.isEmpty(broadcastList)) {
                    for (String num : broadcastList) {
                        broadcastNumSb.append(num).append(",");
                    }
                }
            }
        }
        /**
         * 打开消防警铃
         */
        if (!ValidationUtil.isEmpty(bellNumSb.toString())) {
            String bellNum = bellNumSb.toString();
            bellNum = bellNum.substring(0, bellNum.length() - 1);
            jcsControlServerClient.sendBellAction(bellNum, "1");
        }
        /**
         * 播放广播
         */
        if (!ValidationUtil.isEmpty(broadcastNumSb.toString())) {
            String broadcastNum = broadcastNumSb.toString();
            broadcastNum = broadcastNum.substring(0, broadcastNum.length() - 1);
            jcsControlServerClient.sendFileAction(broadcastNum, "1490075199246.mp3");
        }
        /**
         * 打开北站车库门
         */
        List<ControllerDto> northDoor = controllerService.queryForList("3", ControllerTypeEnum.DOOR.getCode());
        if (!ValidationUtil.isEmpty(northDoor)) {
            ControllerDto controllerDto = northDoor.get(0);
            //打开北站车库门
            jcsControlServerClient.writeStateAction(controllerDto.getIp(), controllerDto.getPort(), 100, "1,1,1,1");
            //打开北站车库门弱电警铃
            jcsControlServerClient.writeStateAction(controllerDto.getIp(), controllerDto.getPort(), 107, "1");
        }
        /**
         * 打开南站车库门
         */
        List<ControllerDto> southDoor = controllerService.queryForList("2", ControllerTypeEnum.DOOR.getCode());
        if (!ValidationUtil.isEmpty(southDoor)) {
            ControllerDto controllerDto = southDoor.get(0);
            //打开南站车库门
            jcsControlServerClient.writeStateAction(controllerDto.getIp(), controllerDto.getPort(), 100, "1");
            //打开南站车库门弱电警铃
            jcsControlServerClient.writeStateAction(controllerDto.getIp(), controllerDto.getPort(), 107, "1");
        }

        return true;
    }

    /**
     * 警情重新定位
     *
     * @param alertId   警情id
     * @param longitude 经度
     * @param latitude  纬度
     * @return
     */
    public Boolean reLocate(String alertId, String longitude, String latitude) {
        try {
            // 更新警情主表
            AlertCalled alertCalled = this.baseMapper.selectById(alertId);
            alertCalled.setCoordinateX(Double.valueOf(longitude));
            alertCalled.setCoordinateY(Double.valueOf(latitude));
            this.updateById(alertCalled);
            // 插入定位日志表
            AlertLocationLog alertLocationLog = new AlertLocationLog();
            alertLocationLog.setAlertId(Long.valueOf(alertId));
            alertLocationLog.setLongitude(longitude);
            alertLocationLog.setLatitude(latitude);
            alertLocationLogService.save(alertLocationLog);

            return true;
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new RuntimeException("警情定位失败!");
        }
    }

    @Override
    public Map<String, Object> queryAlertCalledById(Long id) {

        // 警情基本信息
        AlertCalled alertCalled = this.getById(id);
        QueryWrapper<AlertFormValue> queryWrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "【" + alertCalled.getAlertType() + "】" + alertCalled.getAddress());
        queryWrapper.eq("alert_called_id", id);

        // 警情动态表单数据
        List<KeyValueLabel> listdate = new ArrayList<>();
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        listdate.add(new KeyValueLabel("接警时间", "callTime", alertCalled.getCallTime()));
        listdate.add(new KeyValueLabel("警情地点", "address", alertCalled.getAddress()));
        listdate.add(new KeyValueLabel("警情类型", "alertType", alertCalled.getAlertType()));
        listdate.add(new KeyValueLabel("警情阶段", "alertStage", alertCalled.getAlertStage()));
        listdate.add(new KeyValueLabel("警情等级", "responseLevel", "无"));
        listdate.add(new KeyValueLabel("被困人数", "trappedNum", alertCalled.getTrappedNum()));
        listdate.add(new KeyValueLabel("伤亡人数", "casualtiesNum", alertCalled.getCasualtiesNum()));
        listdate.add(new KeyValueLabel("联系人", "contactUser", alertCalled.getContactUser()));
        listdate.add(new KeyValueLabel("联系电话", "contactPhone", alertCalled.getContactPhone()));
        listdate.add(new KeyValueLabel("联系人电话", "contactPhone", alertCalled.getContactPhone()));
        list.stream().forEach(alertFormValue -> {
            String valueCode = alertFormValue.getFieldValueCode();
            if (null == valueCode) {
                valueCode = alertFormValue.getFieldValue();
            }
            listdate.add(new KeyValueLabel(alertFormValue.getFieldName(), alertFormValue.getFieldCode(), valueCode));
            if ("fireTime".equals(alertFormValue.getFieldCode())) {
                map.put("occurrenceTime", alertFormValue.getFieldValue());
            }
        });
        map.put("data", listdate);

        // app警情首页使用alarmDetailInfo，alarmContactInfo
        if (!AlertStageEnums.YBHZ.getCode().equals(alertCalled.getAlertTypeCode())) {
            map.put("occurrenceTime", alertCalled.getCallTime());
        }
        map.put("alertType", alertCalled.getAlertType());
        map.put("address", alertCalled.getAddress());

        map.put("contactUser", alertCalled.getContactUser());
        map.put("contactPhone", alertCalled.getContactPhone());
        map.put("callTime", alertCalled.getCallTime());
        return map;
    }

    //未结案警情统计
    @Override
    public Integer AlertCalledcount(int type) {
        return alertCalledMapper.AlertCalledcount(0);
    }

    @Override
    public List<AlertCalled> AlertCalledStatusPage(Integer current, Integer size) {
        return alertCalledMapper.AlertCalledStatusPage(current, size);
    }


    @Override
    public List<JSONObject> queryDisposalObjectList(String alertId) {
        AlertCalled alertCalled = this.getById(Long.valueOf(alertId));
        String alertTypeCode = alertCalled.getAlertTypeCode();
        AlertStageEnums alertStage = AlertStageEnums.getEnum(alertTypeCode);
        List<JSONObject> resultList = Lists.newArrayList();
        if (alertStage != null) {
            switch (alertStage) {
                case YBHZ:
                case TFSJ:
                case QTJQ:
                    resultList = queryDisposalObjectUnit(alertCalled);
                    break;
                case HKJY:
                case LYXC:
                case ZJBZ:
                    resultList = queryDisposalObjectAircraft(alertCalled);
                default:
                    break;
            }
        }
        return resultList;
    }

    private List<JSONObject> queryDisposalObjectUnit(AlertCalled alertCalled) {
        List<JSONObject> resultList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(alertCalled.getUnitInvolved())) {
            List<OrgUsrzhDto> unitInvolvedDto = iOrgUsrService.getOrgUsrzhDto(alertCalled.getUnitInvolved());
            JSONObject a1 = new JSONObject();
            a1.put("name", "单位名称");
            a1.put("value", !ValidationUtil.isEmpty(unitInvolvedDto.get(0)) ? unitInvolvedDto.get(0).getBizOrgName() : "");
            JSONObject a2 = new JSONObject();
            a2.put("name", "单位性质");
            a2.put("value", !ValidationUtil.isEmpty(unitInvolvedDto.get(0)) ? unitInvolvedDto.get(0).getCompanyNature() :
                    "");
            JSONObject a3 = new JSONObject();
            a3.put("name", "单位电话");
            a3.put("value", !ValidationUtil.isEmpty(unitInvolvedDto.get(0)) ? unitInvolvedDto.get(0).getCompanyPhone() :
                    "");
            JSONObject a4 = new JSONObject();
            a4.put("name", "单位地址");
            a4.put("value", !ValidationUtil.isEmpty(unitInvolvedDto.get(0)) ? unitInvolvedDto.get(0).getCompanyLocation() :
                    "");
            JSONObject a5 = new JSONObject();
            a5.put("name", "重点部位数量");
            a5.put("value", !ValidationUtil.isEmpty(unitInvolvedDto.get(0)) ? unitInvolvedDto.get(0).getKeySiteCount()!=null?unitInvolvedDto.get(0).getKeySiteCount():0:0 + "个");
            resultList.add(a1);
            resultList.add(a2);
            resultList.add(a3);
            resultList.add(a4);
            resultList.add(a5);
        }
        return resultList;
    }

    private List<JSONObject> queryDisposalObjectAircraft(AlertCalled alertCalled) {
        // 警情动态表单数据
        List<AlertFormValue> list = alertFormValueService.getzqlist(alertCalled.getSequenceNbr());
        Aircraft aircraft = new Aircraft();
        for (AlertFormValue alertFormValue : list) {
            if ("aircraftModel".equals(alertFormValue.getFieldCode())) {
                String aircraftModel = alertFormValue.getFieldValue();
                aircraft = aircraftService.queryAircraftInfoByModel(aircraftModel);
                break;
            }
        }
        List<JSONObject> resultList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(aircraft)) {
            JSONObject a1 = new JSONObject();
            a1.put("name", "飞机型号");
            a1.put("value", aircraft.getAircraftModel());
            JSONObject a2 = new JSONObject();
            a2.put("name", "发动机类型");
            a2.put("value", aircraft.getEngineType());
            JSONObject a3 = new JSONObject();
            a3.put("name", "发动机数量");
            a3.put("value", aircraft.getEnginesmNum());
            JSONObject a4 = new JSONObject();
            a4.put("name", "燃油类型");
            a4.put("value", aircraft.getFuelType());
            JSONObject a5 = new JSONObject();
            a5.put("name", "主要燃烧物质");
            a5.put("value", aircraft.getCombustionMaterial());
            resultList.add(a1);
            resultList.add(a2);
            resultList.add(a3);
            resultList.add(a4);
            resultList.add(a5);
        }
        return resultList;
    }

    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 开始*/
    public List<Map<String,String>> getContactName() {
        List<Map<String,String>> firefightersName = firefightersService.getFirefightersName();
        List<Map<String,String>> contactNames = alertCalledMapper.getContactName();
        firefightersName.addAll(contactNames);

        return firefightersName;
    }

    public List<String> getCalledAddress() {
        List<String> keyAddress = keySiteService.getAddress();
        List<String> alertAddress = alertCalledMapper.getAddress();
        keyAddress.addAll(alertAddress);

        return keyAddress;
    }
    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 结束*/
}
