package com.yeejoin.amos.boot.module.jcs.biz.controller;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.module.jcs.api.entity.VoiceFusionLog;
import com.yeejoin.amos.boot.module.jcs.api.mapper.VoiceFusionLogMapper;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.event.RestEventTrigger;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
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.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.LatentDangerFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlarmGiveStatisticsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledRequestDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.FireAndDutyAndIOTDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStatusEnum;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.ESAlertCalledService;
import com.yeejoin.amos.component.rule.config.RuleConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
 * 警情接警记录
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "警情接警记录Api")
@RequestMapping(value = "/alert-called")
public class AlertCalledController extends BaseController {
	private final Logger logger = LogManager.getLogger(AlertCalledController.class);
    @Autowired
    LatentDangerFeignClient latentDangerFeignClient;
    @Autowired
    EquipFeignClient equipFeignClient;
    @Autowired
    AlertCalledServiceImpl iAlertCalledService;
    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;
    @Autowired
    private ESAlertCalledService eSAlertCalledService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    DataDictionaryServiceImpl dataDictionaryService;
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Value("${redis.cache.failure.time}")
    private long time;

    private static String ALETR_TYPE_AID = "1214";
    private static String ALETR_TYPE_AID_STATUS = "patientStatus";
    private static String FireAlarmNum = "FireAlarmNum";
    private static String FaultAlarmNum = "FaultAlarmNum";
    private static String MonitorEventNum = "monitorEventNum";


	@Autowired
	private EmqKeeper emqKeeper;
	
	@Value("${mqtt.topic.command.knowledgebase.alert.match}")
	private String topicMatch;

    @Autowired
    private VoiceFusionLogMapper voiceFusionLogMapper;

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/addVoiceFusionLog")
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增警情接警记录")
    @Transactional
    public ResponseModel<String> addVoiceFusionLog(@RequestBody VoiceFusionLog voiceFusionLog)  {


      try {
          AgencyUserModel agencyUserMode=getUserInfo();
          voiceFusionLog.setMsgTime(new Date());
          voiceFusionLog.setUsername(agencyUserMode.getUserName());
          voiceFusionLog.setIsDelete(false);
          voiceFusionLogMapper.insert(voiceFusionLog);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("新增失敗");
        }
        return ResponseHelper.buildResponse("新增成功！");
    };




        /**
         * 新增警情接警记录
         *
         * @return
         */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增警情接警记录", notes = "新增警情接警记录")
    @Transactional
    public ResponseModel<AlertCalled> saveAlertCalled(@RequestBody AlertCalledObjsDto alertCalledObjsDto) throws Exception {

        if (ValidationUtil.isEmpty(alertCalledObjsDto) || ValidationUtil.isEmpty(alertCalledObjsDto.getAlertCalled()))
            throw new BadRequest("参数校验失败.");
        ReginParams reginParams = getSelectedOrgInfo();
        //获取当前登录人公司
        String name = reginParams.getCompany().getCompanyName();
        AlertCalled alertCalled = alertCalledObjsDto.getAlertCalled();
        alertCalled.setCompanyName(name);
        if (alertCalled.getAlertTypeCode().equals(ALETR_TYPE_AID)) {
            List<AlertFormValue> alertFormValue = alertCalledObjsDto.getAlertFormValue();
            alertFormValue.forEach(e -> {
                if (e.getFieldCode().equals(ALETR_TYPE_AID_STATUS) && e.getFieldValue() != null ){
                        if (e.getFieldValue().contains(",")) {
                            String[] split = e.getFieldValue().split(",");
                            StringBuilder stringBuilder = new StringBuilder();
                            Arrays.stream(split).forEach(a->{
                                DataDictionary hzxz = dataDictionaryService.getByCode(a, "HZXZ");
                                stringBuilder.append(hzxz.getName() + " ");
                                e.setFieldValue(stringBuilder.toString());
                            });
                        } else {
                            DataDictionary hzxz = dataDictionaryService.getByCode(e.getFieldValue(), "HZXZ");
                            e.setFieldValue(hzxz.getName());
                        }
                }
            });
            alertCalledObjsDto.setAlertFormValue(alertFormValue);
        }
        alertCalledObjsDto.setAlertCalled(alertCalled);
        alertCalledObjsDto = iAlertCalledService.createAlertCalled(alertCalledObjsDto);
        toSendCompletePoliceSituationMatch(alertCalledObjsDto.getAlertCalled().getSequenceNbr());
        return ResponseHelper.buildResponse(alertCalledObjsDto.getAlertCalled());
    }
    
    @Async
	 public void toSendCompletePoliceSituationMatch(Long id){
		try {
			Object result =	iAlertCalledService.toCompletePoliceSituationMatch(id);
			List<Object> list= (List<Object>) result;
			if(list.size()>0) {
				emqKeeper.getMqttClient().publish(topicMatch, result.toString().getBytes(), RuleConfig.DEFAULT_QOS, false);
			}
			} catch (Exception e) {
				logger.info(topicMatch+":警情id"+id+"获取匹配的预案失败------------"+e.getMessage());
			}
	}
    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@PathVariable Long id) {
        return iAlertCalledService.removeById(id);
    }

    /**
     * 修改警情接警记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/updateById")
    @ApiOperation(httpMethod = "PUT", value = "修改警情接警记录", notes = "修改警情接警记录")
    public boolean updateByIdAlertCalled(@RequestBody AlertCalled alertCalled) {
        return iAlertCalledService.updateById(alertCalled);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/find/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<Object> selectById(@PathVariable Long id) {

        return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledById(id));

    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/list")
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<AlertCalled>> listPage(String pageNum, String pageSize, String sort, AlertCalled alertCalled, Integer alertStatus,
                                                      String alertTypeCode,
                                                      String alertSourceCode,
                                                      String callTimeEnd,
                                                      String callTimeStart,
                                                      String systemSourceCode,
                                                     @RequestParam(value ="isFatherAlert",required = false) String isFatherAlert) {
        /*分页存在问题 修改分页参数 陈召 2021-09-22 开始*/
        Page<AlertCalled> page = new Page<>();
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            page = new Page<>();
            page.setCurrent(0L);
            page.setSize(Long.MAX_VALUE);
        } else {
            page.setCurrent((Long.parseLong(pageNum) - 1) * Long.parseLong(pageSize));
            page.setSize(Long.parseLong(pageSize));
        }
        /*分页存在问题 修改分页参数 陈召 2021-09-22 结束*/

        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 开始*/
        /* bug2408 筛选参数解析异常  修改筛选条件方法 修改入参分离筛选条件
        alertStatus 警情状态  alertTypeCode 报警类型code  alertSourceCode 警情来源code
        陈召 2021-08-21 开始*/
        IPage<AlertCalled> alertCalledIPage = null;

        alertCalledIPage = iAlertCalledService.queryForCalledList(page, alertStatus, alertTypeCode, alertSourceCode, callTimeStart, callTimeEnd, sort,isFatherAlert,systemSourceCode);
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw start*/
        alertCalledIPage.getRecords().stream().forEach(e -> {
            if (e.getAlertStatus()) {
                e.setAlertStatusStr(AlertStatusEnum.CLOSED.getName());
            } else {
                e.setAlertStatusStr(AlertStatusEnum.UNCLOSED.getName());
            }
        });
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw end*/
        return ResponseHelper.buildResponse(alertCalledIPage);
        /* bug2408 筛选参数解析异常  修改筛选条件方法 陈召 2021-08-21 结束*/
        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 结束*/
    }

    /**
     * <pre>
     * 相似警情分页查询
     * </pre>
     *
     * @param
     * @param current
     * @param size
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "相似警情分页查询")
    @PostMapping(value = "/page/similar")
    public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar(
            @RequestBody ESAlertCalledRequestDto alertCalledVo,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size) throws Exception {
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        Page<ESAlertCalledDto> esAlertCalledDtoPage = eSAlertCalledService.queryByKeys(alertCalledVo, current, size);
        List<ESAlertCalledDto> records = esAlertCalledDtoPage.getRecords();

        for (ESAlertCalledDto data : records) {
            if (data.getResponseLevelCode() != null) {
                DataDictionary byCode = dataDictionaryService.getByCode(data.getResponseLevelCode(), "XYJBR");
                data.setResponseLevel(byCode.getName());
            }
        }
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        return ResponseHelper.buildResponse(esAlertCalledDtoPage);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "相似警情分页查询")
    @PostMapping(value = "/page/similarby120")
    public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar120(
            @RequestBody ESAlertCalledRequestDto alertCalledVo,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size) throws Exception {
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        Page<ESAlertCalledDto> esAlertCalledDtoPage = eSAlertCalledService.queryByKeys(alertCalledVo, current, size,"120");
        List<ESAlertCalledDto> records = esAlertCalledDtoPage.getRecords();

        for (ESAlertCalledDto data : records) {
            if (data.getResponseLevelCode() != null) {
                DataDictionary byCode = dataDictionaryService.getByCode(data.getResponseLevelCode(), "XYJBR");
                data.setResponseLevel(byCode.getName());
            }
        }
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        return ResponseHelper.buildResponse(esAlertCalledDtoPage);
    }





    /**
     * <pre>
     * 初始化ES
     * </pre>
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "初始化ES")
    @PutMapping(value = "/es/init")
    public ResponseModel<Boolean> initEs() throws Exception {
        return ResponseHelper.buildResponse(eSAlertCalledService.initEs());
    }

    /**
     * 列表无分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getList")
    @ApiOperation(httpMethod = "GET", value = "列表无分页查询", notes = "列表无分页查询")
    public ResponseModel<List<AlertCalled>> list(AlertCalled alertCalled) {
        QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();
        setQueryWrapper(alertCalledQueryWrapper, alertCalled, null);
        List<AlertCalled> list = iAlertCalledService.list(alertCalledQueryWrapper);
        return ResponseHelper.buildResponse(list);
    }

    private QueryWrapper<AlertCalled> setQueryWrapper(QueryWrapper<AlertCalled> queryWrapper, AlertCalled alertCalled, String sort) {
        Class<? extends AlertCalled> aClass = alertCalled.getClass();
        queryWrapper.eq("is_delete", 0);
        if (sort != null  ) {
            String[] date = sort.split(",");
            queryWrapper.orderBy(true, date[1].equals("ascend"),RedisKey.humpToLine(date[0]));
        }else {
            queryWrapper.orderByDesc("call_time");
        }
        if (alertCalled.getCallTimeStart() != null && alertCalled.getCallTimeEnd() != null) {
            queryWrapper.between("call_time", alertCalled.getCallTimeStart(), alertCalled.getCallTimeEnd());
        }
        if (alertCalled.getIsFatherAlert()) { // 0：接警；1：处警
            queryWrapper.isNull("father_alert");
        }
        if (!ValidationUtil.isEmpty(alertCalled.getAlertSourceCodeStr())) {
            String[] arr = alertCalled.getAlertSourceCodeStr().split(",");
            List<String> collect = Arrays.stream(arr).collect(Collectors.toList());
            queryWrapper.in("alert_source_code", collect);
        }
        Stream<Field> fieldStream = Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
            String name = NameUtils.camel2Underline(field.getName());
            return !("IS_FATHER_ALERT".equals(name) || "ALERT_SOURCE_CODE_STR".equals(name));
        });
        fieldStream.forEach(field -> {
            try {
                ReflectionUtils.makeAccessible(field);
                Object o = field.get(alertCalled);
                if (o != null && !"serialVersionUID".equals(field.getName())) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(Boolean.class)) {
                        Boolean fileValue = (Boolean) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class) || "long".equals(type.toString())) {
                        Long fileValue = (Long) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BadRequest("系统异常");
            }
        });

        queryWrapper.or().eq("sequence_nbr",alertCalled.getFatherAlert());
        return queryWrapper;
    }

    /**
     * 查询指定日期内警情列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/dateRange/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定日期内警情列表", notes = "查询指定日期内警情列表")
    public ResponseModel<Map<String, Object>> listByDateRange(@RequestParam(value = "beginDate", required = false) String beginDate,
                                                              @RequestParam("endDate") String endDate) {
        return ResponseHelper.buildResponse(iAlertCalledService.getAlertInfoList(beginDate, endDate));
    }


    /**
     * 查询120系统指定日期内警情列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/dateRange/listBy120")
    @ApiOperation(httpMethod = "GET", value = "查询120系统指定日期内警情列表", notes = "查询120系统指定日期内警情列表")
    public ResponseModel<Map<String, Object>> listByDateRangeAid
    (@RequestParam(value = "beginDate", required = false) String beginDate,
     @RequestParam("endDate") String endDate) {
        return ResponseHelper.buildResponse(iAlertCalledService.getAlertAidInfoList(beginDate, endDate));
    }

    /**
     * <pre>
     * 设备联动紧急响应
     * 启动所有消防队伍的警铃、广播，并自动开启所有车库门
     * </pre>
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/billsend")
    @ApiOperation(httpMethod = "POST", value = "设备联动紧急响应", notes = "启动所有消防队伍的警铃、广播，并自动开启所有车库门")
    @Transactional
    @RestEventTrigger(value = "opreateLogEventHandler")
    public ResponseModel<Boolean> controlEquip() throws Exception {

        return ResponseHelper.buildResponse(iAlertCalledService.controlEquip());
    }

    /**
     * 警情重新定位
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/reLocate")
    @ApiOperation(httpMethod = "PUT", value = "警情重新定位", notes = "警情重新定位")
    public ResponseModel<Boolean> reLocateById(@RequestParam String alertCalled, @RequestParam String longitude,
                                               @RequestParam String latitude) {
        return ResponseHelper.buildResponse(iAlertCalledService.reLocate(alertCalled, longitude, latitude));
    }
    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 开始*/

    /**
     * 警情填报联系人模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAmosId", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "警情填报联系人模糊查询", notes = "警情填报联系人模糊查询")
    public ResponseModel<Object> getContact() {

            List<Map<String, String>> contactName = iAlertCalledService.getContactName();
            return ResponseHelper.buildResponse(contactName);
        
    }

    /**
     * 警情填报地址模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAddress", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "警情填报地址模糊查询", notes = "警情填报地址模糊查询")
    public ResponseModel<List<String>> getAddress() {

        return ResponseHelper.buildResponse(iAlertCalledService.getCalledAddress());
    }
    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 结束*/

    /**
     * 警情填报地址模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAlarmGiveStatistics", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "app领导统计", notes = "app领导统计")
    public ResponseModel<AlarmGiveStatisticsDto> getAlarmGiveStatistics() {
        AlarmGiveStatisticsDto dto = new AlarmGiveStatisticsDto();
        LambdaQueryWrapper<AlertCalled> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(AlertCalled::getFatherAlert);
        queryWrapper.eq(AlertCalled::getAlertStatus, false);
        queryWrapper.eq(AlertCalled::getIsDelete, false);
        Integer alertNum = iAlertCalledService.getBaseMapper().selectCount(queryWrapper);
        dto.setAlarmNum(alertNum);

        ResponseModel<Map<String, Object>> fireAlarm = equipFeignClient.getFireAlarm();
        Map<String, Object> map = fireAlarm.getResult();
        int fireAlarmNum = !ValidationUtil.isEmpty(map.get(FireAlarmNum)) ? Integer.valueOf(map.get(FireAlarmNum).toString()) : 0;

        ResponseModel<Map<String, Object>> faultAlarm = equipFeignClient.getFaultAlarm();
        map = faultAlarm.getResult();
        int faultAlarmNum = !ValidationUtil.isEmpty(map.get(FaultAlarmNum)) ? Integer.valueOf(map.get(FaultAlarmNum).toString()) : 0;

        ResponseModel<Map<String, Object>> monitorEvent = equipFeignClient.getMonitorEvent();
        map = monitorEvent.getResult();
        int monitorEventNum = !ValidationUtil.isEmpty(map.get(MonitorEventNum)) ? Integer.valueOf(map.get(MonitorEventNum).toString()) : 0;

        dto.setIotDetection(fireAlarmNum + faultAlarmNum + monitorEventNum);

        ResponseModel<Object> currentHiddenDanger = latentDangerFeignClient.currentLandgerCount();
        Integer currentHiddenDangerNum = JSON.parseObject(JSON.toJSONString(currentHiddenDanger.getResult())).getInteger("count") ;
        dto.setCurrentHiddenDanger(currentHiddenDangerNum);

        dto.setAllNum(dto.getAlarmNum() + dto.getIotDetection() + currentHiddenDangerNum);

        return ResponseHelper.buildResponse(dto);
    }

    /**
     * 消防报警，在岗检测，物联告警
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getFireAndDutyAndIOT", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "消防报警，在岗检测，物联告警", notes = "消防报警，在岗检测，物联告警")
    public ResponseModel<FireAndDutyAndIOTDto> getFireAndDutyAndIOT() {
        FireAndDutyAndIOTDto dto = new FireAndDutyAndIOTDto();


        ResponseModel<Map<String, Object>> fireAlarm = equipFeignClient.getFireAlarm();
        Map<String, Object> map = fireAlarm.getResult();
        int fireAlarmNum = !ValidationUtil.isEmpty(map.get(FireAlarmNum)) ? Integer.valueOf(map.get(FireAlarmNum).toString()) : 0;

        ResponseModel<Map<String, Object>> faultAlarm = equipFeignClient.getFaultAlarm();
        map = faultAlarm.getResult();
        int faultAlarmNum = !ValidationUtil.isEmpty(map.get(FaultAlarmNum)) ? Integer.valueOf(map.get(FaultAlarmNum).toString()) : 0;

        ResponseModel<Map<String, Object>> monitorEvent = equipFeignClient.getMonitorEvent();
        map = monitorEvent.getResult();
        int monitorEventNum = !ValidationUtil.isEmpty(map.get(MonitorEventNum)) ? Integer.valueOf(map.get(MonitorEventNum).toString()) : 0;

        dto.setFireNum(fireAlarmNum);
        dto.setFaultAlarmNum(faultAlarmNum);
        dto.setIotNum(monitorEventNum);

        return ResponseHelper.buildResponse(dto);
    }

    /**
     * 获取坐席情况
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getLocation")
    @ApiOperation(httpMethod = "GET", value = "模糊获取地址的方法", notes = "模糊获取地址的方法")
    public ResponseModel<Object> getLocationLike(@RequestParam(required = false) String locationt) {
        return ResponseHelper.buildResponse(iAlertCalledService.getLocationLike(locationt));
    }
    
    /**
     * 警情预案匹配
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/police/situation/match")
    @ApiOperation(httpMethod = "GET", value = "警情预案匹配", notes = "警情预案匹配")
    public ResponseModel<Object> toCompletePoliceSituationMatch(@RequestParam Long id)throws Exception {
        return ResponseHelper.buildResponse(iAlertCalledService.toCompletePoliceSituationMatch(id));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/selectFlightNumber")
    @ApiOperation(httpMethod = "GET", value = "查询未结案的航空器报警存在的航班号", notes = "查询未结案的航空器报警存在的航班号")
    public ResponseModel<Object> toCompletePoliceSituationMatch() throws MqttException {
        return ResponseHelper.buildResponse(iAlertCalledService.selectFlightNumber());
    }


    /**
     *
     * 以下均为120接口
     *
     * */


    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/listBy120")
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<AlertCalled>> listPageBy120(String pageNum, String pageSize, String sort, AlertCalled alertCalled, Integer alertStatus,
                                                           String alertTypeCode,
                                                           String alertSourceCode,
                                                           String callTimeEnd,
                                                           String callTimeStart,
                                                           String systemSourceCode,
                                                           @RequestParam(value ="isFatherAlert",required = false) String isFatherAlert) {
        /*分页存在问题 修改分页参数 陈召 2021-09-22 开始*/
        Page<AlertCalled> page = new Page<>();
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            page = new Page<>();
            page.setCurrent(0L);
            page.setSize(Long.MAX_VALUE);
        } else {
            page.setCurrent((Long.parseLong(pageNum) - 1) * Long.parseLong(pageSize));
            page.setSize(Long.parseLong(pageSize));
        }
        /*分页存在问题 修改分页参数 陈召 2021-09-22 结束*/

        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 开始*/
        /* bug2408 筛选参数解析异常  修改筛选条件方法 修改入参分离筛选条件
        alertStatus 警情状态  alertTypeCode 报警类型code  alertSourceCode 警情来源code
        陈召 2021-08-21 开始*/
        IPage<AlertCalled> alertCalledIPage = null;

        //此接口为120系统自用 所以这里参数固定为120code值
        alertCalledIPage = iAlertCalledService.queryForCalledListByAid(page, alertStatus, alertTypeCode, alertSourceCode, callTimeStart, callTimeEnd, sort,isFatherAlert,systemSourceCode);
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw start*/
        alertCalledIPage.getRecords().stream().forEach(e -> {
            if (e.getAlertStatus()) {
                e.setAlertStatusStr(AlertStatusEnum.CLOSED.getName());
            } else {
                e.setAlertStatusStr(AlertStatusEnum.UNCLOSED.getName());
            }
        });
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw end*/
        return ResponseHelper.buildResponse(alertCalledIPage);
        /* bug2408 筛选参数解析异常  修改筛选条件方法 陈召 2021-08-21 结束*/
        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 结束*/
    }
}