package com.yeejoin.equipmanage.service.impl;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecificAlarm;
import com.yeejoin.equipmanage.common.entity.EquipmentSystemSourceStatistics;
import com.yeejoin.equipmanage.common.entity.FireFightingSystemEntity;
import com.yeejoin.equipmanage.common.entity.WarehouseStructure;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentStateVo;
import com.yeejoin.equipmanage.common.entity.vo.MainIotMonitorItemContentVo;
import com.yeejoin.equipmanage.common.entity.vo.MainIotMonitorItemVo;
import com.yeejoin.equipmanage.common.entity.vo.MainIotMonitorVo;
import com.yeejoin.equipmanage.common.enums.ColorEnum;
import com.yeejoin.equipmanage.common.enums.EquipmentStateEnum;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.Token;
import com.yeejoin.equipmanage.common.vo.TopicEntityVo;
import com.yeejoin.equipmanage.mapper.ConfirmAlarmMapper;
import com.yeejoin.equipmanage.mapper.EquipmentManageMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificAlarmMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificIndexMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSystemSourceStatisticsMapper;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.mapper.WarehouseStructureMapper;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.IEquipmentDetailService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.IEquipmentSystemSourceStatisticsService;
import com.yeejoin.equipmanage.service.IMainIotMonitorSerivce;
import com.yeejoin.equipmanage.service.IWarehouseStructureService;
import com.yeejoin.equipmanage.service.MqttSendGateway;

/**
 * @Description: 物联监控首页
 * @Author: Wanglulu
 * @Date: 2020/12/24 21:06
 * @Version 0.0.1
 */
@Service
public class MainIotMonitorServiceImpl implements IMainIotMonitorSerivce {

    @Autowired
    public EquipmentManageMapper equipmentManageMapper;
    @Autowired
    public EquipmentSpecificMapper equipmentSpecificMapper;
    @Autowired
    public EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;
    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;
    @Autowired
    private EquipmentSystemSourceStatisticsMapper equipmentSystemSourceStatisticsMapper;
    @Autowired
    private WarehouseStructureMapper warehouseStructureMapper;

    @Autowired
    @Lazy
    IEquipmentSpecificSerivce iEquipmentSpecificSerivce;

    @Autowired
    IEquipmentDetailService iEquipmentDetailService;

    @Autowired
    EquipmentSpecificAlarmMapper equipmentSpecificAlarmMapper;

    @Autowired
    MqttSendGateway mqttSendGateway;

    @Autowired
    IWarehouseStructureService warehouseStructureService;

    @Autowired
    IEquipmentSystemSourceStatisticsService equipmentSystemSourceStatisticsService;

    @Autowired
    ConfirmAlarmMapper confirmAlarmMapper;

    @Autowired
    RemoteSecurityService remoteSecurityService;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${equip.iot.monitor.topic}")
    private String monitorTopic;

    @Value("${equip.system.alarm.code}")
    private String alarmSystemCode;

    @Override
    public List<MainIotMonitorVo> getMatrixReport() {
        List<MainIotMonitorVo> retList = new ArrayList<>();
        // 火灾报警系统 假数据
        retList.addAll(fireData());
        // 1. 查询不包括 火灾报警系统 列表
        List<Map<String, Object>> systemList = equipmentManageMapper.getNotFireSystemList(alarmSystemCode);
        // 2. 设备列表
        List<Map<String, Object>> equList = equipmentSpecificMapper.getEquipmentList(alarmSystemCode);
        //3. 性能指标列表
        List<Map<String, Object>> equIndexList = equipmentSpecificIndexMapper.getEquipmentSpeIndexList();
        // 遍历系统列表
        if (systemList != null && systemList.size() > 0) {
            for (Map<String, Object> map : systemList) {
                if (map != null) {
                    JSONObject jsonObj = new JSONObject(map);
                    List<MainIotMonitorItemVo> mainIotMonitorItemVos = new ArrayList<>();
                    String total = "0";
                    MainIotMonitorVo mainIotMonitorVo = new MainIotMonitorVo();
                    mainIotMonitorVo.setSystemName(jsonObj.getString("systemName"));
                    mainIotMonitorVo.setMatrixTypeName("设备状态矩阵");
                    mainIotMonitorVo.setMatrixElementName("设备");
                    // 处理设备
                    processEequipmentList(jsonObj.getString("systemId"), equList, equIndexList, mainIotMonitorItemVos, total);
                    mainIotMonitorVo.setMatrixElementTotal(mainIotMonitorItemVos.size() + "");
                    mainIotMonitorVo.setMatrixElementData(mainIotMonitorItemVos);
                    mainIotMonitorVo.setType("equip");
                    retList.add(mainIotMonitorVo);
                }
            }
        }
        return retList;
    }

    @Override
    public void handleMsg(EquipmentStateVo equipmentStateVo, TopicEntityVo entityVo) {
        QueryWrapper<EquipmentSpecific> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("iot_code", entityVo.getIotCode());
        EquipmentSpecific equipmentSpecific = iEquipmentSpecificSerivce.getOne(queryWrapper);
        List<Map<String, Object>> maps = equipmentSpecificMapper.getAlarmEquipmentById(equipmentSpecific.getId(), alarmSystemCode);
        Map<String, Object> map1;
        if (0 < maps.size()) {
            map1 = equipmentSpecificMapper.getAlarmEquipmentById(equipmentSpecific.getId(), alarmSystemCode).get(0);
        } else {
            return;
        }
        JSONObject jsonObj = new JSONObject(map1);
        Long systemId;
        Long areaId;
        String speName = null;
        String amount = null;
        String address = null;
        String systemCode = null;
        String id = null;
        List<MainIotMonitorItemVo> list = new ArrayList<>();
        if (null != map1) {
            id = jsonObj.getString("speId");
            systemCode = jsonObj.getString("systemCode");
            amount = jsonObj.getString("amount");
            address = jsonObj.getString("address");
            speName = jsonObj.getString("speName");
        }
        MainIotMonitorItemVo itemVo = new MainIotMonitorItemVo();
        String color = ColorEnum.GREEN.getCode();
        Boolean open = Boolean.FALSE;
        Boolean disable = Boolean.TRUE;
        String type = EquipmentStateEnum.ZC.getType();
        String statusType = "";
        if (alarmSystemCode.equals(systemCode)) {
            // 火灾告警系统业务处理
            updateEquipmentSystemSourceStatistics(equipmentSpecific, Integer.valueOf(equipmentStateVo.getStatus()));
            if (map1.get("areaId").toString() != null && !"".equals(map1.get("areaId").toString())) {
                WarehouseStructure warehouseStructure = warehouseStructureService.getById(Long.valueOf(map1.get("areaId").toString()));
                while (warehouseStructure.getParentId() != 0 &&  warehouseStructure.getParentId() != null) {
                    warehouseStructure = warehouseStructureService.getById(warehouseStructure.getParentId());
                }
                areaId = warehouseStructure.getId();
//              systemId = equipmentSpecific.getSystemId();
                systemId = 0L;
                Token toke = null;
                if (ObjectUtils.isEmpty(redisUtils.get("system_fas_system"))) {
                    toke = remoteSecurityService.getServerToken();
                } else {
                    toke = JSON.parseObject(redisUtils.get("system_fas_system").toString(), Token.class);
                }
                RequestContext.setToken(toke.getToke());
                RequestContext.setProduct(toke.getProduct());
                RequestContext.setAppKey(toke.getAppKey());
                List<DictionarieValueModel> dic = remoteSecurityService.listDictionaryByDictCode("IOT_MONITOR_STATE_WEIGHT");
                List<MainIotMonitorItemVo> lists = equipmentSystemSourceStatisticsMapper.getEquipmentAlarmSystemList(areaId, systemId);
                Map<String, DictionarieValueModel> ditMap = dic.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, Function.identity()));
                buildWeightData(ditMap, lists);
                Optional<MainIotMonitorItemVo> optional = lists.stream().max(Comparator.comparing(MainIotMonitorItemVo :: getWeight));
                if (optional.isPresent()) {
                    MainIotMonitorItemVo mainIotMonitorItemVo = optional.get();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    MainIotMonitorItemContentVo mainIotMonitorItemContentVo;
                    EquipmentSystemSourceStatistics equipmentSystemSourceStatistics = equipmentSystemSourceStatisticsMapper.selectById(mainIotMonitorItemVo.getId());
                    if (equipmentSystemSourceStatistics.getSourceId() != null) {
                        warehouseStructure = warehouseStructureMapper.selectById(equipmentSystemSourceStatistics.getSourceId());
                    }
                    if (warehouseStructure != null) {
                        address = warehouseStructure.getName();
                    }

                    //通过颜色区分报警类型
                    if ("#EF2805".equals(mainIotMonitorItemVo.getColor())) {
                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(sdf.format(equipmentSystemSourceStatistics.getUpdateTime()), address, EquipmentStateEnum.HZGJ.getType(), mainIotMonitorItemVo.getColor());
                    } else if ("#FFA500".equals(mainIotMonitorItemVo.getColor())) {
                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(sdf.format(equipmentSystemSourceStatistics.getUpdateTime()), address, EquipmentStateEnum.GZ.getType(), mainIotMonitorItemVo.getColor());
                    } else if ("#0000FF".equals(mainIotMonitorItemVo.getColor())) {
                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(sdf.format(equipmentSystemSourceStatistics.getUpdateTime()), address, EquipmentStateEnum.PB.getType(), mainIotMonitorItemVo.getColor());
                    } else {
                        mainIotMonitorItemContentVo = null;
                        mainIotMonitorItemVo.setColor(ColorEnum.GREEN.getCode());
                        mainIotMonitorItemVo.setOpen(Boolean.FALSE);
                        mainIotMonitorItemVo.setDisable(Boolean.TRUE);
                    }
                    mainIotMonitorItemVo.setAlarmContent(mainIotMonitorItemContentVo);
                    list.add(mainIotMonitorItemVo);
                }
            }
        } else {
            // 其他系统业务处理
            // 故障
            if ("3".equals(equipmentStateVo.getStatus())) {
                color = ColorEnum.ORANGE.getCode();
                open = Boolean.TRUE;
                disable = Boolean.FALSE;
                type = EquipmentStateEnum.GZ.getType();
                statusType = "fault";
            }
            // 屏蔽
            if ("5".equals(equipmentStateVo.getStatus())) {
                color = ColorEnum.GREY.getCode();
                open = Boolean.TRUE;
                disable = Boolean.FALSE;
                type = EquipmentStateEnum.PB.getType();
                statusType = "shield";
            }
            EquipmentSpecificAlarm idvo = confirmAlarmMapper.getIdAndConfirmType(id);
            Date time = new Date();
            if (idvo != null && idvo.getId() != null){
                itemVo.setAlamId(idvo.getId().toString());
                itemVo.setConfirmType(idvo.getConfirmType());
                time = idvo.getCreateDate();
            }
            itemVo.setId(id);
            itemVo.setColor(color);
            itemVo.setOpen(open);
            itemVo.setDisable(disable);
            itemVo.setTitle(speName);
            itemVo.setStatus(statusType);
            itemVo.setAlarmContent(new MainIotMonitorItemContentVo(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN).format(time), address, type, color));
            list.add(itemVo);
        }
        if (0 < list.size()) {
            log.println("共 " + list.size() + " 条数据，第一条数据状态码是" + list.get(0).getStatus() + " 颜色是" + list.get(0).getColor() +" （屏蔽-5, 火灾告警-4, 故障-3, 正常-2, 挂起-1）");
            mqttSendGateway.sendToMqtt(monitorTopic, JSON.toJSONString(list));
        } else {
            log.println("共 0 条数据 ");
        }
    }

    @Async("equipAsyncExecutor")
    void updateEquipmentSystemSourceStatistics(EquipmentSpecific equipmentSpecific, int status){
        QueryWrapper<EquipmentSystemSourceStatistics> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_specific_id",equipmentSpecific.getId());
        //插入统计区域设备关表，初始化数据
        List<EquipmentSystemSourceStatistics> list = equipmentSystemSourceStatisticsService.list(wrapper);
        EquipmentSystemSourceStatistics equipmentSystemSourceStatistics = new EquipmentSystemSourceStatistics();
        if (list.size()>0){
            equipmentSystemSourceStatistics = list.get(0);
        }

        if (null != equipmentSystemSourceStatistics) {
            equipmentSystemSourceStatistics.setStatus(status);
        }
        if (equipmentSpecific.getStockDetail() != null && equipmentSpecific.getStockDetail().getWarehouseStructureId() != null) {
            WarehouseStructure warehouseStructure = warehouseStructureService.getById(equipmentSpecific.getStockDetail().getWarehouseStructureId());
            while(warehouseStructure.getParentId()!=0 &&  warehouseStructure.getParentId()!=null){
                warehouseStructure = warehouseStructureService.getById(warehouseStructure.getParentId());
            }
            equipmentSystemSourceStatistics.setSourceId(warehouseStructure.getId());
        }
        equipmentSystemSourceStatistics.setUpdateTime(new Date());
        equipmentSystemSourceStatisticsService.updateById(equipmentSystemSourceStatistics);
    }

    /**
     * @Description: 处理设备列表
     * @Author: Wanglulu
     * @Date: 2020/12/24 21:39
     * @Version 0.0.1
     */
    private void processEequipmentList(String systemId, List<Map<String, Object>> equList, List<Map<String, Object>> equIndexList, List<MainIotMonitorItemVo> mainIotMonitorItemVos, String total) {
        if (StringUtil.isNotEmpty(systemId) && equList != null && equList.size() > 0) {
            for (Map<String, Object> map : equList) {
                if (map != null) {
                    JSONObject jsonObj = new JSONObject(map);
                    String equSystemId = jsonObj.getString("systemId");
                    /* 设备id */
                    String speId = jsonObj.getString("speId");
                    EquipmentSpecificAlarm idvo = confirmAlarmMapper.getIdAndConfirmType(speId);
                    if (systemId.equals(equSystemId) && StringUtil.isNotEmpty(speId)) {
                        /* 设备名称 */
                        String speName = jsonObj.getString("speName");
                        /* 设备数量 */
                        String amount = jsonObj.getString("amount");
                        /* 设备位置 */
                        String address = jsonObj.getString("address");
                        /* 颜色 默认是 正常绿色 */
                        String color = ColorEnum.GREEN.getCode();
                        /* 状态 默认是 正常*/
                        String type = EquipmentStateEnum.ZC.getType();
                        /* open ：true-显示弹框  false-不显示  默认 false */
                        Boolean open = Boolean.FALSE;
                        /* disable ：true-绿色  false-其他 默认 true */
                        Boolean disable = Boolean.TRUE;
                        String statusType = "";
                        MainIotMonitorItemVo mainIotMonitorItemVo = new MainIotMonitorItemVo();
                        mainIotMonitorItemVo.setId(speId);
                        mainIotMonitorItemVo.setSpeId(speId);
                        //处理设备性能指标 判断设备状态  EquipmentStateEnum   【"BREAKDOWN"-"故障" ,"SHIELD"-"屏蔽", OK-正常】
                        String result = processEequipmentIndexList(speId, equIndexList);
                        if (StringUtil.isNotEmpty(result)) {
                            if (EquipmentStateEnum.GZ.getCode().equals(result)) {
                                //故障
                                color = ColorEnum.ORANGE.getCode();
                                open = Boolean.TRUE;
                                disable = Boolean.FALSE;
                                type = EquipmentStateEnum.GZ.getType();
                                statusType = "fault";
                            }
                            if (EquipmentStateEnum.PB.getCode().equals(result)) {
                                //屏蔽
                                color = ColorEnum.GREY.getCode();
                                open = Boolean.TRUE;
                                disable = Boolean.FALSE;
                                type = EquipmentStateEnum.PB.getType();
                                statusType = "shield";
                            }
                        }
                        Date time = new Date();
                        if (idvo != null && idvo.getId() != null){
                            mainIotMonitorItemVo.setAlamId(idvo.getId().toString());
                            mainIotMonitorItemVo.setConfirmType(idvo.getConfirmType());
                            time = idvo.getCreateDate();
                        }
                        mainIotMonitorItemVo.setStatus(statusType);
                        mainIotMonitorItemVo.setColor(color);
                        mainIotMonitorItemVo.setOpen(open);
                        mainIotMonitorItemVo.setDisable(disable);
                        mainIotMonitorItemVo.setTitle(speName);
                        mainIotMonitorItemVo.setAlarmContent(new MainIotMonitorItemContentVo(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN).format(time), address, type, color));
                        mainIotMonitorItemVos.add(mainIotMonitorItemVo);
                        total = new BigDecimal(total).add(new BigDecimal(amount)).toPlainString();
                    }
                }
            }
        }

    }

    /**
     * @Description: 处理性能指标列表
     * @Author: Wanglulu
     * @Date: 2020/12/24 21:39
     * @Version 0.0.1
     */
    private String processEequipmentIndexList(String speId, List<Map<String, Object>> equIndexList) {
        String restCode = null;
        if (StringUtil.isNotEmpty(speId) && equIndexList != null && equIndexList.size() > 0) {
            for (Map<String, Object> map : equIndexList) {
                if (map != null) {
                    JSONObject jsonObj = new JSONObject(map);
                    String speIndexsId = jsonObj.getString("speId");
                    if (speId.equals(speIndexsId)) {
                        //typeCode  BREAKDOWN  SHIELD
                        //speIndexValue true
                        // EquipmentStateEnum   【"BREAKDOWN"-"故障" ,"SHIELD"-"屏蔽", OK-正常】
                        String typeCode = jsonObj.getString("typeCode");
                        String speIndexValue = jsonObj.getString("speIndexValue");
                        if (EquipmentStateEnum.GZ.getCode().equals(typeCode) && "true".equals(speIndexValue.toLowerCase())) {
                            //故障
                            return typeCode;
                        }
                        if (EquipmentStateEnum.PB.getCode().equals(typeCode) && "true".equals(speIndexValue.toLowerCase())) {
                            //屏蔽
                            restCode = typeCode;
                        }
                    }
                }
            }
        }
        if (StringUtil.isNotEmpty(restCode)) {
            return restCode;
        }
        return null;
    }

    /**
     * @Description: 火灾报警 假数据
     * @Author: Wanglulu
     * @Date: 2020/12/24 22:44
     * @Version 0.0.1
     */
    public List<MainIotMonitorVo> fireData() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MainIotMonitorVo> mainIotMonitorVoList = new ArrayList<>();
        QueryWrapper<FireFightingSystemEntity> fireFightingSystemEntityQueryWrapper = new QueryWrapper<>();
        fireFightingSystemEntityQueryWrapper.eq("sort", 1);
        List<FireFightingSystemEntity> list = fireFightingSystemMapper.selectList(fireFightingSystemEntityQueryWrapper);
        Token toke = null;
        if (ObjectUtils.isEmpty(redisUtils.get("system_fas_system"))) {
            toke = remoteSecurityService.getServerToken();
        } else {
            toke = JSON.parseObject(redisUtils.get("system_fas_system").toString(), Token.class);
        }
        RequestContext.setToken(toke.getToke());
        RequestContext.setProduct(toke.getProduct());
        RequestContext.setAppKey(toke.getAppKey());
        List<DictionarieValueModel> dic = remoteSecurityService.listDictionaryByDictCode("IOT_MONITOR_STATE_WEIGHT");
        Map<String, DictionarieValueModel> ditMap = dic.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, Function.identity()));
        List<MainIotMonitorItemVo> newList = new ArrayList<>();
        list.forEach(x -> {
            MainIotMonitorVo mainIotMonitorVo = new MainIotMonitorVo();
            mainIotMonitorVo.setSystemName(x.getName());
            mainIotMonitorVo.setMatrixTypeName("区域状态矩阵");
            mainIotMonitorVo.setMatrixElementName("风险区");

            List<MainIotMonitorItemVo> systemSourceStatistics = equipmentSystemSourceStatisticsMapper.getEquipmentSystemSourceStatisticsCount(x.getId());
            this.buildWeightData(ditMap, systemSourceStatistics);
            if (0 < systemSourceStatistics.size()) {
                Map<Long, Optional<MainIotMonitorItemVo>> map = systemSourceStatistics.stream().collect(
                        Collectors.groupingBy(MainIotMonitorItemVo :: getSourceId, Collectors.maxBy(Comparator.comparing(MainIotMonitorItemVo :: getWeight))));
                List<Long> keys = new ArrayList(map.keySet());
                keys.forEach(y -> {
                    Optional<MainIotMonitorItemVo> optional = map.get(y);
                    if (optional.isPresent()) {
                        MainIotMonitorItemVo mainIotMonitorItemVo = optional.get();
                        //查询需要的信息
                        MainIotMonitorItemContentVo mainIotMonitorItemContentVo;
                        EquipmentSystemSourceStatistics equipmentSystemSourceStatistics = equipmentSystemSourceStatisticsMapper.selectById(mainIotMonitorItemVo.getId());
                        WarehouseStructure warehouseStructure = null;
                        String address = null;
                        if (equipmentSystemSourceStatistics.getSourceId() != null) {
                            warehouseStructure = warehouseStructureMapper.selectById(equipmentSystemSourceStatistics.getSourceId());
                        }
                        if (warehouseStructure != null) {
                            address = warehouseStructure.getName();
                        }

                        //通过颜色区分报警类型
                        if ("#EF2805".equals(mainIotMonitorItemVo.getColor())) {
                            mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(mainIotMonitorItemVo.getTime(), address, EquipmentStateEnum.HZGJ.getType(), mainIotMonitorItemVo.getColor());
                        } else if ("#FFA500".equals(mainIotMonitorItemVo.getColor())) {
                            mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(mainIotMonitorItemVo.getTime(), address, EquipmentStateEnum.GZ.getType(), mainIotMonitorItemVo.getColor());
                        } else if ("#0000FF".equals(mainIotMonitorItemVo.getColor())) {
                            mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(mainIotMonitorItemVo.getTime(), address, EquipmentStateEnum.PB.getType(), mainIotMonitorItemVo.getColor());
                        } else {
                            mainIotMonitorItemContentVo = null;
                            mainIotMonitorItemVo.setColor(ColorEnum.GREEN.getCode());
                            mainIotMonitorItemVo.setOpen(Boolean.FALSE);
                            mainIotMonitorItemVo.setDisable(Boolean.TRUE);
                        }
                        mainIotMonitorItemVo.setAlarmContent(mainIotMonitorItemContentVo);
                    }
                });

                //封装end
                mainIotMonitorVo.setMatrixElementTotal(String.valueOf(new ArrayList(map.values()).size()));
                mainIotMonitorVo.setMatrixElementData(new ArrayList(map.values()));
                mainIotMonitorVo.setType("risk");
                mainIotMonitorVoList.add(mainIotMonitorVo);
            }

//            systemSourceStatistics.forEach(y -> {
//                Optional<MainIotMonitorItemVo> optional = systemSourceStatistics.stream().max(Comparator.comparing(MainIotMonitorItemVo :: getWeight));
//                if (optional.isPresent()) {
//                    MainIotMonitorItemVo mainIotMonitorItemVo = optional.get();
//                    //查询需要的信息
//                    MainIotMonitorItemContentVo mainIotMonitorItemContentVo;
//                    EquipmentSystemSourceStatistics equipmentSystemSourceStatistics = equipmentSystemSourceStatisticsMapper.selectById(mainIotMonitorItemVo.getId());
//                    WarehouseStructure warehouseStructure = null;
//                    String address = null;
//                    if (equipmentSystemSourceStatistics.getSourceId() != null) {
//                        warehouseStructure = warehouseStructureMapper.selectById(equipmentSystemSourceStatistics.getSourceId());
//                    }
//                    if (warehouseStructure != null) {
//                        address = warehouseStructure.getName();
//                    }
//
//                    //通过颜色区分报警类型
//                    if ("#EF2805".equals(mainIotMonitorItemVo.getColor())) {
//                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.HZGJ.getType(), mainIotMonitorItemVo.getColor());
//                    } else if ("#FFA500".equals(mainIotMonitorItemVo.getColor())) {
//                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.GZ.getType(), mainIotMonitorItemVo.getColor());
//                    } else if ("#0000FF".equals(mainIotMonitorItemVo.getColor())) {
//                        mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.PB.getType(), mainIotMonitorItemVo.getColor());
//                    } else {
//                        mainIotMonitorItemContentVo = null;
//                        mainIotMonitorItemVo.setColor(ColorEnum.GREEN.getCode());
//                        mainIotMonitorItemVo.setOpen(Boolean.FALSE);
//                        mainIotMonitorItemVo.setDisable(Boolean.TRUE);
//                    }
//                    mainIotMonitorItemVo.setAlarmContent(mainIotMonitorItemContentVo);
//                    newList.add(mainIotMonitorItemVo);
//                }
//            });

//            //封装报警提示信息 start
//            systemSourceStatistics.forEach(y -> {
//                //查询需要的信息
//                MainIotMonitorItemContentVo mainIotMonitorItemContentVo;
//                EquipmentSystemSourceStatistics equipmentSystemSourceStatistics = equipmentSystemSourceStatisticsMapper.selectById(y.getId());
//                WarehouseStructure warehouseStructure = null;
//                String address = null;
//                if (equipmentSystemSourceStatistics.getSourceId() != null) {
//                    warehouseStructure = warehouseStructureMapper.selectById(equipmentSystemSourceStatistics.getSourceId());
//                }
//                if (warehouseStructure != null) {
//                    address = warehouseStructure.getName();
//                }
//
//                //通过颜色区分报警类型
//                if ("#EF2805".equals(y.getColor())) {
//                    mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.HZGJ.getType(), y.getColor());
//                } else if ("#FFA500".equals(y.getColor())) {
//                    mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.GZ.getType(), y.getColor());
//                } else if ("#0000FF".equals(y.getColor())) {
//                    mainIotMonitorItemContentVo = new MainIotMonitorItemContentVo(y.getTime(), address, EquipmentStateEnum.PB.getType(), y.getColor());
//                } else {
//                    mainIotMonitorItemContentVo = null;
//                    y.setColor(ColorEnum.GREEN.getCode());
//                    y.setOpen(Boolean.FALSE);
//                    y.setDisable(Boolean.TRUE);
//                }
//                y.setAlarmContent(mainIotMonitorItemContentVo);
//            });

            //封装end
//            mainIotMonitorVo.setMatrixElementTotal(String.valueOf(newList.size()));
//            mainIotMonitorVo.setMatrixElementData(newList);
//            mainIotMonitorVo.setType("risk");
//            mainIotMonitorVoList.add(mainIotMonitorVo);
        });
        return mainIotMonitorVoList;
    }

    private void buildWeightData(Map<String, DictionarieValueModel> ditMap, List<MainIotMonitorItemVo> systemSourceStatistics) {
        systemSourceStatistics.forEach(y -> {
            y.setWeight(ditMap.get(y.getStatus()) != null ? ditMap.get(y.getStatus()).getDictDataValue() : "1");
            y.setColor(ditMap.get(y.getStatus()) != null ? ditMap.get(y.getStatus()).getDictDataDesc() : "#00E12E");
            if (y.getStatus() != null && ("1".equals(y.getStatus()) || "2".equals(y.getStatus()))) {
                y.setDisable(true);
            } else {
                y.setDisable(false);
            }
        });
    }

    /**
     * 当前登录用户信息
     */
    protected ReginParams getSelectedOrgInfo() {
        return JSONObject.parseObject(redisUtils.get(buildKey(getUserId(), getToken())).toString(), ReginParams.class);
    }

    protected String getUserId() {
        String userId = null;
        if (getUser() != null) {
            userId = getUser().getUserId();
        }
        return userId;
    }

    // redis缓存选择的用户信息
    private String buildKey(String userId, String token) {
    	 return RedisKey.buildReginKey(userId, token);
    }

    protected AgencyUserModel getUser() {
        AgencyUserModel userModel = null;
        if (getToken() != null) {
            RequestContext.setToken(getToken());
            RequestContext.setProduct(getProduct());
            RequestContext.setAppKey(getAppKey());
            FeignClientResult<?> feignClientResult;
            try {
                feignClientResult = Privilege.agencyUserClient.getme();
                userModel = (AgencyUserModel) feignClientResult.getResult();

            } catch (InnerInvokException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return userModel;
    }

    protected String getToken() {
        String authToken = request.getHeader("token");
        if (authToken == null) {
            authToken = request.getHeader("X-Access-Token");
        }
        return authToken;
    }

    protected String getProduct() {
        String authToken = request.getHeader("product");
        if (authToken == null) {
            authToken = request.getParameter("product");
        }
        return authToken;
    }

    protected String getAppKey() {
        String authToken = request.getHeader("appKey");
        if (authToken == null) {
            authToken = request.getParameter("appKey");
        }
        return authToken;
    }

    protected String getChannelType() {
        String channelType = request.getHeader("channelType");
        if (channelType == null) {
            channelType = request.getParameter("channelType");
        }
        return channelType;
    }
}
