package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.equipmanage.common.datasync.entity.FireEquipmentFireAlarm;
import com.yeejoin.equipmanage.common.dto.OrgUsrDto;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.AlarmDTO;
import com.yeejoin.equipmanage.common.entity.dto.EquipSpecificAlarmDTO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentSpecificVo;
import com.yeejoin.equipmanage.common.entity.vo.VideoVO;
import com.yeejoin.equipmanage.common.enums.AlarmGridColumnEnum;
import com.yeejoin.equipmanage.common.enums.AlarmTypeEnum;
import com.yeejoin.equipmanage.common.enums.ConfirmAlamEnum;
import com.yeejoin.equipmanage.common.enums.EquipmentDataEnum;
import com.yeejoin.equipmanage.common.utils.CommonPageInfoParam;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import com.yeejoin.equipmanage.fegin.SystemctlFeign;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@Service
public class EquipmentSpecificAlarmServiceImpl extends ServiceImpl<EquipmentSpecificAlarmMapper, EquipmentSpecificAlarm> implements IEquipmentSpecificAlarmService {

    @Autowired
    ConfirmAlarmMapper confirmAlarmMapper;

    @Autowired
    EquipmentSpecificAlarmMapper equipmentSpecificAlarmMapper;

    @Autowired
    EquipmentSpecificAlarmLogMapper equipmentSpecificAlarmLogMapper;

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificService;

    @Autowired
    IEquipmentDetailService iEquipmentDetailService;

    @Autowired
    IEquipmentSpecificIndexSerivce equipmentSpecificIndexService;

    @Autowired
    FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private IVideoService videoService;

    @Autowired
    private ISignalClassifyService signalClassifyService;

    @Autowired
    MarqueeDataMapper marqueeDataMapper;
    @Autowired
    private RemoteSecurityService remoteSecurityService;
    @Autowired
    private SystemctlFeign systemctlFeign;

    @Value("${window.vedioFormat}")
    String vedioFormat;

    @Value("${equipment.pressurepump.start}")
    private String pressurePumpStart;

    @Autowired
    JcsFeign jcsFeign;

    @Autowired
    private IotFeign iotFeign;


    @Autowired
    MqttSendGateway mqttSendGateway;

    @Override
    public void handleExport(HttpServletResponse response, List<Long> ids, String alarmType) {
        CommonPageInfoParam param = new CommonPageInfoParam();
        if (AlarmTypeEnum.GZGJ.getCode().equals(alarmType)) {
            param.setIsFireAlarm("false");
        } else if (AlarmTypeEnum.HZGJ.getCode().equals(alarmType)) {
            param.setAlarmType(alarmType);
        }
        List<HashMap<String, Object>> list = this.baseMapper.getAlarmList(param);
        List<EquipmentAlarmDownloadVO> equipmentDownloads = handleExportData(ids, list);
        if (0 == list.size()) {
            throw new RuntimeException("导出数据列表无数据！");
        }

        if(alarmType.equals("FIREALARM")){
            ExcelUtil.createTemplate(response, "设备火灾报警信息", "设备火灾报警信息", equipmentDownloads, EquipmentAlarmDownloadVO.class, null, false);

        }else if(alarmType.equals("BREAKDOWN")){
            ExcelUtil.createTemplate(response, "设备故障告警信息", "设备故障告警信息", equipmentDownloads, EquipmentAlarmDownloadVO.class, null, false);

        }else{
            ExcelUtil.createTemplate(response, "设备告警信息", "设备告警信息", equipmentDownloads, EquipmentAlarmDownloadVO.class, null, false);

        }

    }

    public List<EquipmentAlarmDownloadVO> handleExportData(List<Long> ids, List<HashMap<String, Object>> list) {
        List<EquipmentAlarmDownloadVO> equipmentDownloads = new ArrayList<>();
        if (!ObjectUtils.isEmpty(ids) && 0 < ids.size()) {
            if (0 < list.size()) {
                list.forEach(alarm -> {
                    ids.forEach(id -> {
                        EquipmentAlarmDownloadVO alarmDownloadVO = new EquipmentAlarmDownloadVO();
                        if ((alarm.get("id").toString()).equals(id.toString())) {
//                            alarmDownloadVO.setId((Long) alarm.get("id"));
                            alarmDownloadVO.setAlarmType(signalClassifyService.getTypeNameByCode(alarm.get("type").toString()).getTypeName());
                            alarmDownloadVO.setEquipName(alarm.get("fireEquipmentName").toString());
                            alarmDownloadVO.setAlarmContent(alarm.get("alarmContent").toString());
                            alarmDownloadVO.setEquipCode(StringUtil.isNotEmpty(alarm.get("fireEquipmentCode")) ? alarm.get("fireEquipmentCode").toString() : "");
                            alarmDownloadVO.setAlarmPosition(StringUtil.isNotEmpty(alarm.get("warehouseStructureName")) ? alarm.get("warehouseStructureName").toString() : "");
                            alarmDownloadVO.setProtectObj(StringUtil.isNotEmpty(alarm.get("equipmentName")) ? alarm.get("equipmentName").toString() : "");
                            alarmDownloadVO.setAlarmTime(StringUtil.isNotEmpty(alarm.get("createDate")) ? alarm.get("createDate").toString().replace("T", " ") : "");
                            alarmDownloadVO.setCleanStatus(alarm.get("cleanStatus").toString());
                            // 处理状态、处理类型无业务字段，后期业务功能实现之后需在此处返回相应字段
                            alarmDownloadVO.setHandleStatus(String.valueOf(alarm.get("handleStatus")));
                            if (ObjectUtils.isEmpty(alarm.get("handleType"))) {
                                alarmDownloadVO.setHandleType("");
                            } else {
                                String handleType = ConfirmAlamEnum.getTypeByCode(String.valueOf(alarm.get("handleType")));
                                alarmDownloadVO.setHandleType(StringUtil.isNotEmpty(handleType) ? handleType : signalClassifyService.getTypeNameByCode(String.valueOf(alarm.get("handleType"))).getTypeName());
                            }
                            alarmDownloadVO.setResolveResult(StringUtil.isNotEmpty(alarm.get("resolveResult")) ? alarm.get("resolveResult").toString() : "");
                            alarmDownloadVO.setConfirmDate(StringUtil.isNotEmpty(alarm.get("confirmDate")) ? alarm.get("confirmDate").toString().replace("T", " ") : "");
                            alarmDownloadVO.setAlarmReason(StringUtil.isNotEmpty(alarm.get("alarmReason")) ? alarm.get("alarmReason").toString() : "");
                            equipmentDownloads.add(alarmDownloadVO);
                        }
                    });
                });
            } else {
                return null;
            }
        } else {
            if (0 < list.size()) {
                list.forEach(alarm -> {
                    EquipmentAlarmDownloadVO alarmDownloadVO = new EquipmentAlarmDownloadVO();
//                    alarmDownloadVO.setId((Long) alarm.get("id"));
                    alarmDownloadVO.setAlarmType(signalClassifyService.getTypeNameByCode(alarm.get("type").toString()).getTypeName());
                    alarmDownloadVO.setEquipName(alarm.get("fireEquipmentName").toString());
                    alarmDownloadVO.setAlarmContent(alarm.get("alarmContent").toString());
                    alarmDownloadVO.setEquipCode(StringUtil.isNotEmpty(alarm.get("fireEquipmentCode")) ? alarm.get("fireEquipmentCode").toString() : "");
                    alarmDownloadVO.setAlarmPosition(StringUtil.isNotEmpty(alarm.get("warehouseStructureName")) ? alarm.get("warehouseStructureName").toString() : "");
                    alarmDownloadVO.setProtectObj(StringUtil.isNotEmpty(alarm.get("equipmentName")) ? alarm.get("equipmentName").toString() : "");
                    alarmDownloadVO.setAlarmTime(StringUtil.isNotEmpty(alarm.get("createDate")) ? alarm.get("createDate").toString().replace("T", " ") : "");
                    alarmDownloadVO.setCleanStatus(alarm.get("cleanStatus").toString());
                    // 处理状态、处理类型无业务字段，后期业务功能实现之后需在此处返回相应字段
                    alarmDownloadVO.setHandleStatus(String.valueOf(alarm.get("handleStatus")));
                    if (ObjectUtils.isEmpty(alarm.get("handleType"))) {
                        alarmDownloadVO.setHandleType("");
                    } else {
                        String handleType = ConfirmAlamEnum.getTypeByCode(String.valueOf(alarm.get("handleType")));
                        alarmDownloadVO.setHandleType(StringUtil.isNotEmpty(handleType) ? handleType : signalClassifyService.getTypeNameByCode(String.valueOf(alarm.get("handleType"))).getTypeName());
                    }
                    alarmDownloadVO.setResolveResult(StringUtil.isNotEmpty(alarm.get("resolveResult")) ? alarm.get("resolveResult").toString() : "");
                    alarmDownloadVO.setConfirmDate(StringUtil.isNotEmpty(alarm.get("confirmDate")) ? alarm.get("confirmDate").toString().replace("T", " ") : "");
                    alarmDownloadVO.setAlarmReason(StringUtil.isNotEmpty(alarm.get("alarmReason")) ? alarm.get("alarmReason").toString() : "");
                    equipmentDownloads.add(alarmDownloadVO);
                });
            } else {
                return null;
            }
        }
        return equipmentDownloads;
    }

    @Override
    public Page<Map<String, Object>> listPage(CommonPageInfoParam param) {
        Page result = new Page<>(param.getPageNumber(), param.getPageSize());
        if (AlarmTypeEnum.GZGJ.getCode().equals(param.getAlarmType())) {
            param.setAlarmType("");
            param.setIsFireAlarm("false");
        }
        Page<Map<String, Object>> resultPage = this.baseMapper.page(result, param);
        if (resultPage.getTotal() > 0) {
            for (Map<String, Object> x : resultPage.getRecords()) {
//                LocalDateTime createDate = (LocalDateTime) x.get("createDate");
//                x.put("createDate", Date.from(createDate.atZone(ZoneId.systemDefault()).toInstant()));
                if (ObjectUtils.isEmpty(x.get("handleType"))) {
                    x.put("handleType", null);
                } else {
                    String handleType = ConfirmAlamEnum.getTypeByCode(String.valueOf(x.get("handleType")));
                    x.put("handleType", StringUtil.isNotEmpty(handleType) ? handleType : signalClassifyService.getTypeNameByCode(String.valueOf(x.get("handleType"))).getTypeName());
                }
                // 冗余统一跑马灯显示字段取值
                x.put("equipmentSpecificIndexName", x.get("fireEquipmentSpecificIndexName"));
            }
        }
        return resultPage;
    }

    @Override
    public Page<Map<String, Object>> zlzxListPage(CommonPageInfoParam param) {
        Page result = new Page<>(param.getPageNumber(), param.getPageSize());
        if (AlarmTypeEnum.GZGJ.getCode().equals(param.getAlarmType())) {
            param.setAlarmType("");
            param.setIsFireAlarm("false");
        }
        Page<Map<String, Object>> resultPage = this.baseMapper.zlzxPage(result, param);
        if (resultPage.getTotal() > 0) {
            for (Map<String, Object> x : resultPage.getRecords()) {
                if (ObjectUtils.isEmpty(x.get("handleType"))) {
                    x.put("handleType", null);
                } else {
                    String handleType = ConfirmAlamEnum.getTypeByCode(String.valueOf(x.get("handleType")));
                    x.put("handleType", StringUtil.isNotEmpty(handleType) ? handleType : signalClassifyService.getTypeNameByCode(String.valueOf(x.get("handleType"))).getTypeName());
                }
            }
        }
        return resultPage;
    }

    @Override
    public Page<Map<String, Object>> pageQuery(CommonPageInfoParam param) {
        Page result = new Page<>(param.getPageNumber(), param.getPageSize());
        return this.baseMapper.pageQuery(result, param);
    }

    @Override
    public org.springframework.data.domain.Page<AlarmListDataVO> listAlarmsPage(CommonPageInfoParam param) {
        Page page = new Page(param.getPageNumber(), param.getPageSize());
//        page.setCurrent(param.getPageNumber() == 1 ? 0 : param.getPageNumber());
//        page.setSize(param.getPageNumber() * param.getPageSize());

        Page<Map<String, Object>> mybatisResult = this.baseMapper.pageAlarmsInfo(page, param);
        List<AlarmListDataVO> res = new ArrayList<>();
        if (mybatisResult.getSize() > 0) {
            mybatisResult.getRecords().forEach(x -> {
                AlarmListDataVO dataVO = new AlarmListDataVO();
                try {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern(DateUtils.DATE_TIME_PATTERN);
                    String time = df.format((TemporalAccessor) x.get("createDate"));
                    Date date = DateUtils.dateParse(time, DateUtils.DATE_TIME_PATTERN);
                    dataVO.setAlarmTime(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dataVO.setAlarmEquip(String.valueOf(x.get("fireEquipmentName")));
                Object alarmType = x.get("alarmType");
                dataVO.setAlarmType(StringUtil.isNotEmpty(alarmType) ? alarmType.toString() : "");
                dataVO.setType(String.valueOf(x.get("type")));
                dataVO.setAlarmInfo(x.get("fireEquipmentName") + dataVO.getAlarmType());
                dataVO.setEquipSpeId(Long.valueOf(String.valueOf(x.get("fireEquipmentId"))));
                dataVO.setAlarmId(Long.valueOf(String.valueOf(x.get("alarmId"))));
                dataVO.setAlarmTypeCode(String.valueOf(x.get("fireEquipmentSpecificIndexKey")));
                dataVO.setCleanStatus(String.valueOf(x.get("cleanStatus")));
                dataVO.setCleanStatusVal(String.valueOf(x.get("cleanStatusVal")));
                res.add(dataVO);
            });
        }
        //前端原有数据结构已经写好，所以分页又有mybatisplus(起始页为1)分页转为PageImpl（起始页为0）
        param.setPageNumber(param.getPageNumber() - 1);
        return new PageImpl<>(res, param, mybatisResult.getTotal());
    }

    @Override
    public org.springframework.data.domain.Page<TopographyAlarmVo> listAlarmsPageForTopography(CommonPageInfoParam param) {
        Page page = new Page(param.getPageNumber(), param.getPageSize());
        Page<Map<String, Object>> mybatisResult = this.baseMapper.pageAlarmsInfo(page, param);
        List<TopographyAlarmVo> res = new ArrayList<>();
        if (mybatisResult.getSize() > 0) {
            mybatisResult.getRecords().forEach(x -> {
                TopographyAlarmVo dataVO = new TopographyAlarmVo();
                try {
                    dataVO.setCreateDate(DateUtils.dateParse(String.valueOf(x.get("createDate")), DateUtils.DATE_TIME_T_PATTERN));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dataVO.setFireEquipmentSpecificIndexName(StringUtil.toString(x.get("fireEquipmentSpecificIndexName")));
                dataVO.setFireEquipmentName(StringUtil.toString(x.get("fireEquipmentName")));
                dataVO.setWarehouseStructureName(StringUtil.toString(x.get("warehouseStructureName")));
                dataVO.setEquipmentName(StringUtil.toString(x.get("equipmentName")));
                dataVO.setHandleStatus(StringUtil.toString(x.get("handleStatus")));
                dataVO.setStatus(StringUtil.toString(x.get("status")));
                Object type = x.get("type");
                if (AlarmTypeEnum.HZGJ.getCode().equals(type) || AlarmTypeEnum.GZGJ.getCode().equals(type) || AlarmTypeEnum.PB.getCode().equals(type)) {
                    dataVO.setAlarmType(AlarmTypeEnum.getTypeByCode(String.valueOf(type)));
                }
                dataVO.setAlarmContent(String.valueOf(x.get("alamContent")));
                dataVO.setHandleType(null == x.get("handleType") ? null : ConfirmAlamEnum.getTypeByCode(String.valueOf(x.get("handleType"))));
                res.add(dataVO);
            });
        }
        param.setPageNumber(param.getPageNumber() - 1);
        return new PageImpl<>(res, param, mybatisResult.getTotal());
    }

    @Override
    public Map<String, Object> getSpecificInfoById(Long id) {
        Map<String, Object> map = new HashMap<>();
        EquipmentSpecificAlarmLog alarm = equipmentSpecificAlarmLogMapper.selectById(id);
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(alarm.getEquipmentSpecificId());
        Map<String, Object> equipmentSpecificInfo = equipmentSpecificMapper.getEquipSpeInfo(alarm.getEquipmentSpecificId());
//        equipmentSpecific.setFullqrCode("01#" + equipmentSpecific.getQrCode());
//        EquipmentDetail equipmentDetail = iEquipmentDetailService.getOneById(equipmentSpecific.getEquipmentDetailId());
        List<Video> videos = equipmentSpecificIndexService.getVideoByEquipmentSecificId(alarm.getEquipmentSpecificId());
        List<VideoVO> videoVOS = new ArrayList<>();
        videos.forEach(x -> {
            VideoVO video = new VideoVO();
            video.setName(x.getName());
            video.setTokens(x.getToken());
            video.setUrl(x.getUrl());
            video.setVedioFormat(x.getVideoType());
            video.setUrl(videoService.getVideoUrl(x.getName(), x.getPresetPosition(), x.getUrl(), x.getCode()));
            video.setIp(x.getIp());
            video.setPort(x.getPort());
            video.setCode(x.getCode());
            video.setPresetPosition(x.getPresetPosition());
            videoVOS.add(video);
        });
        List<Map<String, Object>> list = this.baseMapper.getProObject(alarm.getEquipmentSpecificId());
        List<FireFightingSystemEntity> sys = new ArrayList<>();
        String[] ids;
        String sysIds = equipmentSpecific.getSystemId();
        if (StringUtil.isNotEmpty(sysIds)) {
            if (-1 != sysIds.indexOf(",")) {
                ids = sysIds.split(",");
                sys = fireFightingSystemMapper.getFightingSysByIds(ids);
            } else {
                FireFightingSystemEntity entity = fireFightingSystemMapper.selectById(Long.valueOf(sysIds));
                sys.add(entity);
            }
        }
        map.put("equipDetail", equipmentSpecificInfo);
        map.put("videoList", videoVOS);
        map.put("proObjectList", list);
        map.put("systemList", sys);
        return map;
    }

    @Override
    public Map<String, Object> getSpecificInfoByCode(String code) {
        QueryWrapper<EquipmentSpecific> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(equipmentSpecific)) {
            Map<String, Object> map = new HashMap<>();
            Long id = equipmentSpecific.getId();
            Map<String, Object> equipmentSpecificInfo = equipmentSpecificMapper.getEquipSpeInfo(id);
            List<Video> videos = equipmentSpecificIndexService.getVideoByEquipmentSecificId(id);
            List<VideoVO> videoVOS = new ArrayList<>();
            videos.forEach(x -> {
                VideoVO video = new VideoVO();
                video.setName(x.getName());
                video.setTokens(x.getToken());
                video.setUrl(x.getUrl());
                video.setIp(x.getIp());
                video.setPort(x.getPort());
                video.setCode(x.getCode());
                video.setPresetPosition(x.getPresetPosition());
                videoVOS.add(video);
            });
            List<Map<String, Object>> list = this.baseMapper.getProObject(id);
            List<FireFightingSystemEntity> sys = new ArrayList<>();
            String[] ids;
            String sysIds = equipmentSpecific.getSystemId();
            if (StringUtil.isNotEmpty(sysIds)) {
                if (-1 != sysIds.indexOf(",")) {
                    ids = sysIds.split(",");
                    sys = fireFightingSystemMapper.getFightingSysByIds(ids);
                } else {
                    FireFightingSystemEntity entity = fireFightingSystemMapper.selectById(Long.valueOf(sysIds));
                    sys.add(entity);
                }
            }
            map.put("equipDetail", equipmentSpecificInfo);
            map.put("videoList", videoVOS);
            map.put("proObjectList", list);
            map.put("systemList", sys);
            return map;
        }
        return Maps.newLinkedHashMap();
    }


    @Override
    public List<HashMap<String, Object>> getColumn(String alarmType) {
        List<HashMap<String, Object>> titleList = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", AlarmGridColumnEnum.GJLX.getKey());
        map.put("title", AlarmGridColumnEnum.GJLX.getTitle());
        map.put("dataIndex", AlarmGridColumnEnum.GJLX.getDataIndex());
        titleList.add(map);
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("key", AlarmGridColumnEnum.GJSB.getKey());
        map1.put("title", AlarmGridColumnEnum.GJSB.getTitle());
        map1.put("dataIndex", AlarmGridColumnEnum.GJSB.getDataIndex());
        titleList.add(map1);
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("key", AlarmGridColumnEnum.GJNR.getKey());
        map2.put("title", AlarmGridColumnEnum.GJNR.getTitle());
        map2.put("dataIndex", AlarmGridColumnEnum.GJNR.getDataIndex());
        titleList.add(map2);
        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("key", AlarmGridColumnEnum.SBBH.getKey());
        map3.put("title", AlarmGridColumnEnum.SBBH.getTitle());
        map3.put("dataIndex", AlarmGridColumnEnum.SBBH.getDataIndex());
        titleList.add(map3);
        HashMap<String, Object> map4 = new HashMap<>();
        map4.put("key", AlarmGridColumnEnum.GJWZ.getKey());
        map4.put("title", AlarmGridColumnEnum.GJWZ.getTitle());
        map4.put("dataIndex", AlarmGridColumnEnum.GJWZ.getDataIndex());
        titleList.add(map4);
        HashMap<String, Object> map5 = new HashMap<>();
        map5.put("key", AlarmGridColumnEnum.BHDX.getKey());
        map5.put("title", AlarmGridColumnEnum.BHDX.getTitle());
        map5.put("dataIndex", AlarmGridColumnEnum.BHDX.getDataIndex());
        titleList.add(map5);
        HashMap<String, Object> map6 = new HashMap<>();
        map6.put("key", AlarmGridColumnEnum.GJSJ.getKey());
        map6.put("title", AlarmGridColumnEnum.GJSJ.getTitle());
        map6.put("dataIndex", AlarmGridColumnEnum.GJSJ.getDataIndex());
        titleList.add(map6);
        HashMap<String, Object> map7 = new HashMap<>();
        map7.put("key", AlarmGridColumnEnum.CLZT.getKey());
        map7.put("title", AlarmGridColumnEnum.CLZT.getTitle());
        map7.put("dataIndex", AlarmGridColumnEnum.CLZT.getDataIndex());
        titleList.add(map7);
        HashMap<String, Object> map8 = new HashMap<>();
        map8.put("key", AlarmGridColumnEnum.CLLX.getKey());
        map8.put("title", AlarmGridColumnEnum.CLLX.getTitle());
        map8.put("dataIndex", AlarmGridColumnEnum.CLLX.getDataIndex());
        titleList.add(map8);
        return titleList;
    }

    @Override
    public List<AlarmDataVO> getAlarmDetailById(Long id, String alarmType) {
        List<HashMap<String, Object>> list = this.baseMapper.getAlarmDetail(id, alarmType);
        List<AlarmDataVO> lists = new ArrayList<>();
        if (0 < list.size()) {
            HashMap<String, Object> alarm = list.get(0);
            AlarmDataVO alarmDataVO = new AlarmDataVO();
            alarmDataVO.setKey(AlarmGridColumnEnum.GJLX.getTitle());
            alarmDataVO.setValue(AlarmTypeEnum.HZGJ.getCode().equals(alarm.get("type")) ? AlarmTypeEnum.HZGJ.getType() : AlarmTypeEnum.GZGJ.getType());
            lists.add(alarmDataVO);
            AlarmDataVO alarmDataVO1 = new AlarmDataVO();
            alarmDataVO1.setKey(AlarmGridColumnEnum.GJNR.getTitle());
            alarmDataVO1.setValue(StringUtil.isNotEmpty(alarm.get("alamContent")) ? alarm.get("alamContent").toString() : null);
            lists.add(alarmDataVO1);
            AlarmDataVO alarmDataVO2 = new AlarmDataVO();
            alarmDataVO2.setKey(AlarmGridColumnEnum.GJWZ.getTitle());
            alarmDataVO2.setValue(StringUtil.isNotEmpty(alarm.get("warehouseStructureName")) ? alarm.get("warehouseStructureName").toString() : null);
            lists.add(alarmDataVO2);
            AlarmDataVO alarmDataVO3 = new AlarmDataVO();
            alarmDataVO3.setKey(AlarmGridColumnEnum.GJSJ.getTitle());
            String createDate = "";
            if (StringUtil.isNotEmpty(alarm.get("createDate"))) {
                createDate = alarm.get("createDate").toString();
                createDate = createDate.substring(0, createDate.length() - 2);
            }
            alarmDataVO3.setValue(StringUtil.isNotEmpty(createDate) ? createDate : null);
            lists.add(alarmDataVO3);
            AlarmDataVO alarmDataVO4 = new AlarmDataVO();
            alarmDataVO4.setKey(AlarmGridColumnEnum.GJBH.getTitle());
            alarmDataVO4.setValue(StringUtil.isNotEmpty(alarm.get("id")) ? alarm.get("type") + alarm.get("id").toString() : null);
            lists.add(alarmDataVO4);
            AlarmDataVO alarmDataVO5 = new AlarmDataVO();
            alarmDataVO5.setKey(AlarmGridColumnEnum.GJSB.getTitle());
            alarmDataVO5.setValue(StringUtil.isNotEmpty(alarm.get("fireEquipmentName")) ? alarm.get("fireEquipmentName").toString() : null);
            lists.add(alarmDataVO5);
            AlarmDataVO alarmDataVO6 = new AlarmDataVO();
            alarmDataVO6.setKey(AlarmGridColumnEnum.SBBH.getTitle());
            alarmDataVO6.setValue(StringUtil.isNotEmpty(alarm.get("fireEquipmentCode")) ? alarm.get("fireEquipmentCode").toString() : null);
            lists.add(alarmDataVO6);
            AlarmDataVO alarmDataVO7 = new AlarmDataVO();
            alarmDataVO7.setKey("equipmentSpecificId");
            alarmDataVO7.setValue(StringUtil.isNotEmpty(alarm.get("fireEquipmentId")) ? alarm.get("fireEquipmentId").toString() : null);
            lists.add(alarmDataVO7);
        }
        return lists;
    }

    @Override
    public AlarmEquipMockDataVO getEquipmentDetailById(Long id, String alarmType) {
        List<Map<String, Object>> list = this.baseMapper.getEquipmentDetails(id, alarmType);
        int count = this.baseMapper.getEquipmentAlarmCount(id, alarmType);
        AlarmEquipMockDataVO alarmEquipMockDataVO = new AlarmEquipMockDataVO();
        List<AlarmDataVO> lists = new ArrayList<>();
        if (0 < list.size()) {
            Map<String, Object> sourceData = list.get(0);
            AlarmDataVO alarmDataVO1 = new AlarmDataVO();
            alarmDataVO1.setKey(EquipmentDataEnum.MC.getName());
            alarmDataVO1.setValue(StringUtil.isNotEmpty(sourceData.get("fireEquipmentName")) ? sourceData.get("fireEquipmentName").toString() : null);
            lists.add(alarmDataVO1);
            AlarmDataVO alarmDataVO2 = new AlarmDataVO();
            alarmDataVO2.setKey(EquipmentDataEnum.PP.getName());
            alarmDataVO2.setValue(StringUtil.isNotEmpty(sourceData.get("brand")) ? sourceData.get("brand").toString() : null);
            lists.add(alarmDataVO2);
            AlarmDataVO alarmDataVO3 = new AlarmDataVO();
            alarmDataVO3.setKey(EquipmentDataEnum.XH.getName());
            alarmDataVO3.setValue(StringUtil.isNotEmpty(sourceData.get("batchNum")) ? sourceData.get("batchNum").toString() : null);
            lists.add(alarmDataVO3);
            AlarmDataVO alarmDataVO4 = new AlarmDataVO();
            alarmDataVO4.setKey(EquipmentDataEnum.WZ.getName());
            alarmDataVO4.setValue(StringUtil.isNotEmpty(sourceData.get("warehouseStructureName")) ? sourceData.get("warehouseStructureName").toString() : null);
            lists.add(alarmDataVO4);
            AlarmDataVO alarmDataVO5 = new AlarmDataVO();
            alarmDataVO5.setKey(EquipmentDataEnum.XT.getName());
            alarmDataVO5.setValue(StringUtil.isNotEmpty(sourceData.get("systemName")) ? sourceData.get("systemName").toString() : null);
            lists.add(alarmDataVO5);
            alarmEquipMockDataVO.setPic(StringUtil.isNotEmpty(sourceData.get("imgUrl")) ? sourceData.get("imgUrl").toString() : null);
            alarmEquipMockDataVO.setAlarmCount(count);
            alarmEquipMockDataVO.setQrcode(StringUtil.isNotEmpty(sourceData.get("qrCode")) ? sourceData.get("qrCode").toString() : null);
            alarmEquipMockDataVO.setDetailUrl(null);
            alarmEquipMockDataVO.setItems(lists);
        }
        return alarmEquipMockDataVO;
    }

    @Override
    public Map<String, Object> detail(Long id) {
        QueryWrapper<EquipmentSpecificAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        EquipmentSpecificAlarm specificAlarm = this.baseMapper.selectOne(queryWrapper);
        String alarmType = specificAlarm.getType();
        List<AlarmDataVO> list = getAlarmDetailById(id, alarmType);
        Long equipId = null;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        AlarmEquipMockDataVO alarmEquipMockDataVO = new AlarmEquipMockDataVO();
        if (0 < list.size()) {
            for (AlarmDataVO alarm : list) {
                if ("equipmentSpecificId".equals(alarm.getKey())) {
                    equipId = Long.parseLong(alarm.getValue());
                    break;
                }
            }
            alarmEquipMockDataVO = getEquipmentDetailById(equipId, alarmType);
        }
        if (0 < list.size()) {
            for (int i = list.size() - 1; i >= 0; i--) {
                if ("equipmentSpecificId".equals(list.get(i).getKey())) {
                    list.remove(i);
                }
            }
        }
        map1.put("baseInfo", list);
        map1.put("processInfo", getProcessInfo(id));
        map.put("alarmData", map1);
        map.put("equipmentData", alarmEquipMockDataVO);
        return map;
    }

    @Override
    public List<FireEquipmentFireAlarm> getFireEquipAlarmDetailsByAlarmId(List<Long> specificAlarmIds, List<Long> equipIndexIds) {
        List<FireEquipmentFireAlarm> list = this.baseMapper.getFireEquipAlarmDetailsByAlarmId(specificAlarmIds, equipIndexIds);
        if (list != null && !list.isEmpty()) {
            return list;
        }
        return Lists.newArrayList();
    }

    private List<AlarmDataVO> getProcessInfo(Long id) {
        EquipmentSpecificAlarmLog alam = confirmAlarmMapper.getDetailsById(String.valueOf(id), null);

        List<AlarmDataVO> lists = new ArrayList<>();
        AlarmDataVO v1 = new AlarmDataVO();
        v1.setKey("确认类型");
        v1.setValue(ConfirmAlamEnum.getTypeByCode(alam.getConfirmType()));
        lists.add(v1);

        AlarmDataVO v2 = new AlarmDataVO();
        v2.setKey("报警原因");
        v2.setValue(alam.getAlarmReason());
        lists.add(v2);

        AlarmDataVO v3 = new AlarmDataVO();
        v3.setKey("处理措施");
        v3.setValue(alam.getResolveResult());
        lists.add(v3);

        AlarmDataVO v4 = new AlarmDataVO();
        v4.setKey("处理时间");
        v4.setValue(StringUtil.isNotEmpty(alam.getConfirmDate()) ? new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(alam.getConfirmDate()) : null);
        lists.add(v4);

        AlarmDataVO v5 = new AlarmDataVO();
        v5.setKey("处理人");
        v5.setValue(alam.getConfirmUserName());
        lists.add(v5);

        return lists;
    }

    private static String getInet4Address() {
        Enumeration<NetworkInterface> nis;
        String ip = null;
        try {
            nis = NetworkInterface.getNetworkInterfaces();
            for (; nis.hasMoreElements(); ) {
                NetworkInterface ni = nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                for (; ias.hasMoreElements(); ) {
                    InetAddress ia = ias.nextElement();
                    if (ia instanceof Inet4Address && !ia.getHostAddress().equals("127.0.0.1")) {
                        ip = ia.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }

    @Override
    public int getCountAlarmEquipment() {
        return equipmentSpecificAlarmMapper.getCountAlarmEquipment();
    }

    @Override
    public int getCountEquipment() {
        return equipmentSpecificAlarmMapper.getCountEquipment();
    }

    @Override
    public List<Map<String, Object>> getCountAlarm() {
        return equipmentSpecificAlarmMapper.getCountAlarm();
    }

    @Override
    public Page<EquipSpecificAlarmDTO> getAlarmPage(Page page, AlarmDTO dto) {
        return equipmentSpecificAlarmMapper.getAlarmPage(page, dto);
    }

    @Override
    public Page<EquipSpecificAlarmDTO> getEqPage(Page page, AlarmDTO dto) {
        return equipmentSpecificAlarmMapper.getEqPage(page, dto);
    }

    @Override
    public List<EquipmentSpecificAlarmLog> getConfirmUser() {
        List<EquipmentSpecificAlarmLog> equipSpecificAlarmDTOList = equipmentSpecificAlarmMapper.getConfirmUser();
        List<String> confirmUser = new ArrayList<>();
        equipSpecificAlarmDTOList.forEach(e -> confirmUser.add(e.getConfirmUser()));
        List<OrgUsrDto> result = jcsFeign.getByAmosId(confirmUser).getResult();
        equipSpecificAlarmDTOList.stream().forEach(e -> {
            result.forEach(a -> {
                if (a.getAmosOrgId().equals(e.getConfirmUser())) {
                    e.setJcsConfirmUserName(a.getBizOrgName());
                }
            });
            if (e.getJcsConfirmUserName() == null || e.getJcsConfirmUserName().equals("")) {
                e.setJcsConfirmUserName(e.getConfirmUserName());
            }
        });
        return equipSpecificAlarmDTOList;
    }

    @Override
    public Integer getcountAlarmtype(String tyep) {
        return equipmentSpecificAlarmMapper.getcountAlarmtype(tyep);
    }

    @Override
    public Integer getcountAlarmHandle(String tyep) {
        return equipmentSpecificAlarmMapper.getcountAlarmHandle(tyep);
    }

    @Override
    public List<EquipmentSpecificAlarm> getEquipListBySpecific(Boolean status, Long equipmentSpecificId) {
        return equipmentSpecificAlarmMapper.getEquipListBySpecific(status, equipmentSpecificId);
    }

    @Override
    public LinkedList<Map<String, Object>> equipStatusCount(HashMap<String, Object> hashMap) {
        LinkedList<Map<String, Object>> linkedList = new LinkedList<>();
        List<Map<String, Object>> list = equipmentSpecificAlarmMapper.equipStatusCount(hashMap);
        if (!CollectionUtils.isEmpty(list)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", "正常");
            map.put("value", Integer.parseInt(list.get(0).get("value").toString()) - Integer.parseInt(list.get(1).get("value").toString()));
            linkedList.add(map);
            linkedList.add(list.get(1));
        }
        return linkedList;
    }

    @Override
    public Map<String, Object> equipAlarmLine(HashMap<String, Object> hashMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<EquipAlarmLineVo> list = equipmentSpecificAlarmMapper.equipAlarmLine(hashMap);
        if (!CollectionUtils.isEmpty(list)) {
            LinkedHashSet<String> xAxis = new LinkedHashSet<>();
            List<Map<String, Object>> yAxis = new ArrayList<>();

            //  取出所有非空indexNamesortMap = {TreeMap@15960}  size = 7
            Set<String> indexKNameSet = list.stream().map(EquipAlarmLineVo::getIndexName).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
            Map<String, List<EquipAlarmLineVo>> dateCollect = list.stream().collect(Collectors.groupingBy(EquipAlarmLineVo::getDate));
            Map<String, List<EquipAlarmLineVo>> sortMap = new TreeMap<>((o1, o2) -> o2.compareTo(o1));
            sortMap.putAll(dateCollect);

            //  迭代器倒序遍历map
            String date = null;
            HashSet<String> dateSet = new HashSet<>();
            for (int i = 0; i < indexKNameSet.size(); i++) {
                HashMap<String, Object> dataMap = new HashMap<>();
                LinkedList<Object> yData = new LinkedList<>();
                dataMap.put("data", yData);
                yAxis.add(dataMap);
            }
            int index = 0;
            for (String indexName : indexKNameSet) {
                HashMap<String, Object> dataMap = (HashMap<String, Object>) yAxis.get(index++);
                LinkedList<Object> yData = (LinkedList<Object>) dataMap.get("data");
                //  解决迭代器遍历一次的问题
                ListIterator<Map.Entry<String, List<EquipAlarmLineVo>>> i = new ArrayList<Map.Entry<String, List<EquipAlarmLineVo>>>(sortMap.entrySet()).listIterator(sortMap.size());
                while (i.hasPrevious()) {
                    Map.Entry<String, List<EquipAlarmLineVo>> entry = i.previous();
                    String key = entry.getKey();
                    List<EquipAlarmLineVo> collect = entry.getValue().stream().filter(x -> indexName.equals(x.getIndexName())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        yData.add(collect.stream().mapToInt(EquipAlarmLineVo::getTotal).sum());
                    } else {
                        yData.add(0);
                    }
                    xAxis.add(key.substring(5));
                }
                dataMap.put("data", yData);
                dataMap.put("name", indexName);
            }
            resultMap.put("legend", indexKNameSet);
            resultMap.put("axisData", xAxis);
            resultMap.put("seriesData", yAxis);
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> fireFacilitiesList(String bizOrgCode, String startTime, String endTime) {
        return equipmentSpecificAlarmMapper.fireFacilitiesList(bizOrgCode, startTime, endTime);
    }

    @Override
    public Map<String, Object> dailyMaintenance(String bizOrgCode, String orgCode, String startTime, String endTime) {
        return equipmentSpecificAlarmMapper.dailyMaintenance(bizOrgCode, orgCode, startTime, endTime);
    }

    @Override
    public Map<String, Object> inspectionMessage(String orgCode, String startTime, String endTime) {
        return equipmentSpecificAlarmMapper.inspectionMessage(orgCode, startTime, endTime);
    }

    @Override
    public Map<String, Object> pressureMessage(String orgCode, String startTime, String endTime) {
        Map<String, Object> stringObjectMap = equipmentSpecificAlarmMapper.pressureMessage(orgCode, startTime, endTime);
        EquipmentSpecificVo vo = null;
        if(equipmentSpecificMapper.getEquipmentSpecificIotCodeWYB().get(0) != null) {
            vo = equipmentSpecificMapper.getEquipmentSpecificIotCodeWYB().get(0);
        }
        // 启停总数
        int allNum = 0;
        // 启动次数
        int startNum = 0;

        ResponseModel all = iotFeign.selectListNew(vo.getIotCode().substring(0,8),null, startTime, endTime,null, pressurePumpStart);
        if (200 == all.getStatus() && !ObjectUtils.isEmpty(all.getResult())) {
            String json1 = JSON.toJSONString(all.getResult());
            List<Map<String, String>> listObject1 = (List<Map<String, String>>) JSONArray.parse(json1);
            allNum = listObject1.size();
        }
        ResponseModel start = iotFeign.selectListNew(vo.getIotCode().substring(0,8),null, startTime, endTime,"true", pressurePumpStart);
        if (200 == start.getStatus() && !ObjectUtils.isEmpty(start.getResult())) {
            String json1 = JSON.toJSONString(start.getResult());
            List<Map<String, String>> listObject1 = (List<Map<String, String>>) JSONArray.parse(json1);
            startNum = listObject1.size();
        }

        Map<String, Object> retMap = new HashMap<>();

        // 计算平均每小时打压频率
        try {
            int hour = DateUtils.dateBetweenNew(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN),DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN));

            int hafHour = DateUtils.dateBetweenNew1(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN),DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN));

            int twoHour = DateUtils.dateBetweenNew2(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN),DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN));

            int fourHour = DateUtils.dateBetweenNew3(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN),DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN));
            if(allNum/hour > 15) {
                retMap.put("status","异常");
            } else  {
                retMap.put("status","正常");
            }
            if(startNum != 0) {
                retMap.put("name", stringObjectMap.get("name").toString());
                String frequency = "稳压泵总数"+stringObjectMap.get("allEqu").toString()+"台,平均近半小时启动"+(startNum/hafHour < 1 ? 1 : startNum/hafHour)+"次,"+
                        "平均2小时启动"+(startNum/twoHour < 1 ? 1 : startNum/twoHour)+"次，"+"平均4小时启动"+(startNum/fourHour < 1 ? 1 : startNum/fourHour)+"次";
                retMap.put("frequency",frequency);
            } else {
                retMap.put("name", stringObjectMap.get("name").toString());
                String frequency = "稳压泵总数"+stringObjectMap.get("allEqu").toString()+"台,平均近半小时启动0次,"+
                        "平均2小时启动0次，"+"平均4小时启动0次";
                retMap.put("frequency",frequency);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return retMap;
    }

    @Override
    public Page<Map<String, Object>> fireAlarmLogPage(CommonPageInfoParam param) {
        Page result = new Page<>(param.getPageNumber(), param.getPageSize());
        return this.baseMapper.fireAlarmLogPage(result, param);
    }

    @Override
    public Page<Map<String, Object>> dcFireAlarmLogPage(CommonPageInfoParam param) {
        Page result = new Page<>(param.getPageNumber(), param.getPageSize());
        return this.baseMapper.dcFireAlarmLogPage(result, param);
    }

    @Override
    public List<Map<String, Object>> alarmTrend(String bizOrgCode, String companyCode) {
        if (StringUtils.isNotEmpty(companyCode)) {
            bizOrgCode = fireFightingSystemMapper.queryByCompanyCode(companyCode);
            return this.baseMapper.alarmTrend(bizOrgCode);
        } else if (StringUtils.isNotEmpty(bizOrgCode)) {
            return this.baseMapper.alarmTrend(bizOrgCode);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> stationInfo() {
        return this.baseMapper.stationInfo();
    }

    @Override
    public List<Map<String, Object>> allList(CommonPageInfoParam param) {
        if (AlarmTypeEnum.GZGJ.getCode().equals(param.getAlarmType())) {
            param.setAlarmType("");
            param.setIsFireAlarm("false");
        }
        List<Map<String, Object>> list = marqueeDataMapper.selectAll(param);
        if (list.size() > 0) {
            for (Map<String, Object> x : list) {
                if (ObjectUtils.isEmpty(x.get("handleType"))) {
                    x.put("handleType", null);
                } else {
                    String handleType = ConfirmAlamEnum.getTypeByCode(String.valueOf(x.get("handleType")));
                    x.put("handleType", StringUtil.isNotEmpty(handleType) ? handleType : signalClassifyService.getTypeNameByCode(String.valueOf(x.get("handleType"))).getTypeName());
                }
                // 冗余统一跑马灯显示字段取值
                x.put("equipmentSpecificIndexName", x.get("fireEquipmentSpecificIndexName"));
            }
        }
        return list;
    }

    @Override
    public int updateReadStatus(String messageId) {
        MarqueeData marqueeData = marqueeDataMapper.selectById(messageId);
        marqueeData.setIsRead(1);
        int i = marqueeDataMapper.updateById(marqueeData);
//        MessageModel model = new MessageModel();
//        model.setMsgType("pressurePump");
//        model.setSendTime(new Date());
//        model.setIsSendWeb(true);
//        model.setCategory(1);
//        model.setIsSendApp(false);
//        model.setTerminal("WEB");
//        Map<String, String> ext = new HashMap<>();
//        ext.put("isRead", "1");
//        model.setExtras(ext);
        // Token token = remoteSecurityService.getServerToken();
//        systemctlFeign.create(token.getAppKey(), token.getProduct(), token.getToke(), model);
        // systemctlFeign.updateIsRead(Long.valueOf(messageId));
        // Systemctl.messageClient.updateIsRead(Long.valueOf(messageId));
        mqttSendGateway.sendToMqtt("pressurePump", "1");
        return i;
    }
}
