package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.dto.OrgMenuDto;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.morphic.Morphic;
import com.yeejoin.amos.feign.morphic.model.ResourceDTO;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.equipmanage.common.datasync.entity.FireFightingSystem;
import com.yeejoin.equipmanage.common.dto.FireFightingSystemDto;
import com.yeejoin.equipmanage.common.dto.OrgUsrDto;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.EquipTypeAmountPageDTO;
import com.yeejoin.equipmanage.common.entity.vo.*;
import com.yeejoin.equipmanage.common.enums.*;
import com.yeejoin.equipmanage.common.utils.ChartsUtils;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.utils.WordTemplateUtils;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.*;
import liquibase.pro.packaged.S;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static java.lang.String.valueOf;

@Slf4j
@Service
public class FireFightingSystemServiceImpl extends ServiceImpl<FireFightingSystemMapper, FireFightingSystemEntity>
        implements IFireFightingSystemService {

    @Autowired
    FireFightingSystemMapper fireFightingSystemMapper;
    @Autowired
    IRiskSourceSceneService iRiskSourceSceneService;
    @Autowired
    private RemoteSecurityService remoteSecurityService;
    @Autowired
    private IUploadFileService iUploadFileService;

    @Autowired
    private EquipmentManageMapper equipmentManageMapper;
    @Autowired
    private EquipmentManageService equipmentManageService;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private FormInstanceMapper formInstanceMapper;
    @Autowired
    private SourceSceneMapper sourceSceneMapper;
    @Value("${equipment.fire.systemid}")
    private String fireSystemId;
    @Value("${morphic.projectSeq}")
    private Long projectSeq;
    @Value("${mqtt.scene.host}")
    private String sceneUrl;
    @Value("${equip.point.equipmentdata.topic}")
    private String wsTopic;

    @Value("${equip.point.speindex.url}")
    private String speindexUrl;
    @Value("${equip.point.equipmentDetail.url}")
    private String equipmentDetailUrl;

    @Value("${systemctl.dict.iot-core-param}")
    private String iotCoreParam;

    @Value("classpath:/json/systemIndex.json")
    private Resource systemIndex;

    @Value("classpath:/json/systemCode.json")
    private Resource systemCode;

    @Autowired
    JcsFeign jcsFeignClient;
    @Autowired
    private IEqDynamicFormGroupService iEqDynamicFormGroupService;

    @Autowired
    private IEqDynamicFormInstanceService instanceService;

    @Autowired
    @Lazy
    private IEquipmentSpecificSerivce equipmentSpecificSerivce;

    @Autowired
    private ISourceSceneService iSourceSceneService;

    @Autowired
    private ISyncDataService syncDataService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    MqttSendGateway mqttSendGateway;

    @Autowired
    private JCSRemoteService jcsRemoteService;

    @Value("${systemctl.sync.switch}")
    private Boolean syncSwitch;

    @Value("${auth-key-fire-system:fire_system_info}")
    private String authKey;

    @Value("${equipment.type}")
    String equipmentCategoryLeftTypeCode;

    @Autowired
    IEquipmentCategoryService iEquipmentCategoryService;

    @Autowired
    ISourceStatistics sourceStatistics;

    @Value("${redis_car_type_count}")
    private String carTypeAndCount;

    @Value("${redis_equip_type_count}")
    private String equipTypeAndCount;

    @Override
    public List<EquipCountBySystemVO> getEquipCountBySystemId(Long systemId) {
        return this.baseMapper.getEquipCountBySystemId(systemId);
    }

    @Override
    public List<EquiplistSpecificBySystemVO>
    getEquiplistBySystemId(Long systemId) {
        return this.baseMapper.getEquiplistBySystemId(systemId);
    }

    @Override
    public Map<String, Object> queryEquipmenInfoAndCount(String equimentName, String equimentCode, String construction,
                                                         String maintenance, String bizOrgCode, String formGroupId, int current, int pageSize, String controBoxBuildId,String companyId, String nameOrCode) {
        Map<String, Object> map = equipmentManageService.queryEquipmenInfoAndCount(equimentName, equimentCode,
                construction, maintenance, bizOrgCode, formGroupId, current, pageSize, controBoxBuildId, companyId, nameOrCode);
        List<EquipmentManageVo> dataList = (List<EquipmentManageVo>) map.get("dataList");
        StringBuilder stb = new StringBuilder();
        dataList.forEach(y -> {
            if (StringUtil.isNotEmpty(valueOf(stb))) {
                stb.append("," + y.getChargePerson());
            } else {
                stb.append(y.getChargePerson());
            }
        });
        //此userMap已被注掉  无用代码
    /*    Map<String, String> userMap = new HashMap<>();
        if (StringUtil.isNotEmpty(stb)) {
            List<AgencyUserModel> agencyUserModels = remoteSecurityService.listUserByUserIds(stb.toString());
            agencyUserModels.forEach(z -> {
                userMap.put(z.getUserId(), z.getRealName());
            });
        }*/
        dataList.forEach(x -> {
//            x.setChargePerson(userMap.get(x.getChargePerson()));
            x.setSystemimg(equipmentManageMapper.getFiles(valueOf(x.getId()), "face"));
        });
        map.put("dataList", dataList);
        return map;
    }

    @Override
    public FireFightingSystemEntity getOneById(Long id) {
        FireFightingSystemEntity fireFightingSystemEntity = this.baseMapper.selectById(id);
        return fireFightingSystemEntity;
    }

    @Override
    public String save(FireFightingSystemVo vo) {
        if (!systemCodeCheck(vo)) {
            throw new BadRequest("系统编号已存在，请重新输入");
        }
        List<DynamicFormInstance> formInstance = vo.getFormInstances();
        // 验证必填项 BUG 2725 by kongfm 2021-09-09
        formInstance.forEach(item -> {
            if (item.getNotNull() && StringUtils.isEmpty(item.getFieldValue())) {
                throw new BadRequest(item.getFieldLabel() + "为必填项，请确认");
            }
        });
        String userId = remoteSecurityService.getAgencyUser().getUserId();
        vo.setRecUserId(userId);
        // 冗余名称，数据同步使用
//        this.setChargePersonName(vo);
        String s = valueOf(System.currentTimeMillis());
        vo.setId(s);
        vo.setSort(s);
        DynamicFormGroup dynamicFormGroup = iEqDynamicFormGroupService.getById(vo.getFormGroupId());
        vo.setSystemType(dynamicFormGroup.getRelationId() != null ? dynamicFormGroup.getRelationId().toString() : "");
        // fireSystemId 为字典表火灾系统id 以此确保第一个生成的火灾报警系统排序为1
        if (vo.getSystemType().equals(fireSystemId)) {
            vo.setSort("1");
        }
        if ("".equals(vo.getInstallDate())) {
            vo.setInstallDate(null);
        }
        if ("".equals(vo.getFirstMaintenanceDate())) {
            vo.setFirstMaintenanceDate(null);
        }
        // 1.保存动态表单数据
        if (vo.getFormInstances() != null && vo.getFormInstances().size() > 0) {
            Long instanceId = instanceService.saveInstanceBatch(vo.getFormInstances());
            vo.setInstanceId(instanceId);
            s = s + "," + instanceId;
        }
        // 2.保存消防系统数据
        int save = fireFightingSystemMapper.save(vo);
        if (save > 0 && syncSwitch) {
            // AST数据同步
            List<FireFightingSystem> fireFightingSystemDetail = getFireFightingSystemDetail(vo);
            syncDataService.syncCreatedFireFightingSystem(fireFightingSystemDetail);
        }
        // 3.保存图片数据
        this.insertFiles(vo);
        return s;
    }

    @Override
    public String update(FireFightingSystemVo vo) {
        if (!systemCodeCheck(vo)) {
            throw new BadRequest("系统编号已存在，请重新输入");
        }
        // 验证必填项 BUG 2725 by kongfm 2021-09-09
        List<DynamicFormInstance> formInstance = vo.getFormInstances();
        formInstance.forEach(item -> {
            if (item.getNotNull() && StringUtils.isEmpty(item.getFieldValue())) {
                throw new BadRequest(item.getFieldLabel() + "为必填项，请确认");
            }
        });
        String userId = remoteSecurityService.getAgencyUser().getUserId();
        vo.setRecUserId(userId);
        // 冗余名称，数据同步使用
//        this.setChargePersonName(vo);
        if ("".equals(vo.getInstallDate())) {
            vo.setInstallDate(null);
        }
        if ("".equals(vo.getFirstMaintenanceDate())) {
            vo.setFirstMaintenanceDate(null);
        }

        int update = fireFightingSystemMapper.update(vo);
        if (update > 0 && syncSwitch) {
            // AST数据同步
            List<FireFightingSystem> fireFightingSystemDetail = getFireFightingSystemDetail(vo);
            syncDataService.syncCreatedFireFightingSystem(fireFightingSystemDetail);
        }
        // 1.更新消防系统数据
        String sequenceNbr = vo.getId();
        fireFightingSystemMapper.deleteFilre(sequenceNbr);
        // 2.更新动态表单数据
        if (vo.getInstanceId() != null && vo.getFormInstances().size() > 0) {
            instanceService.updateInstanceBatch(vo.getInstanceId(), vo.getFormInstances());
        }
        // 3.更新图片数据
        this.insertFiles(vo);
        return vo.getId();
    }

    private void setChargePersonName(FireFightingSystemVo vo) {
        if (StringUtil.isNotEmpty(vo.getChargePerson())) {

            FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient.queryByUserId(vo.getChargePerson());
            AgencyUserModel userModel = result == null ? new AgencyUserModel() : result.getResult();
            if (userModel != null && userModel.getRealName() != null) {
                vo.setChargePersonName(userModel.getRealName());
            }

        }
    }

    private boolean systemCodeCheck(FireFightingSystemVo systemVo) {
        if (StringUtils.isEmpty(systemVo.getId())) {
            // 新建系统时
            int count = this.baseMapper.selectCount(new LambdaQueryWrapper<FireFightingSystemEntity>()
                    .eq(FireFightingSystemEntity::getCode, systemVo.getCode()));
            return count < 1;
        } else {
            int count = this.baseMapper.selectCount(new LambdaQueryWrapper<FireFightingSystemEntity>()
                    .eq(FireFightingSystemEntity::getCode, systemVo.getCode())
                    .ne(FireFightingSystemEntity::getId, systemVo.getId()));
            return count < 1;
        }
    }

    @Override
    public FireFightingSystemVo createMorphic(FireFightingSystemVo model) {
        ResourceDTO resourceDTO = new ResourceDTO();
        resourceDTO.setSubjectId(projectSeq);
        resourceDTO.setSubjectid(projectSeq);
        resourceDTO.setName(model.getName());
        // 为首次 添加的画布添加mqtt 相关数据
        String content = "{\"layout\":\"\",\"boardConfig\":{\"modeType\":\"custom\",\"orientation\":\"lengthways\",\"autoRefresh\":true,\"name\":\"1\",\"showMode\":\"actual\",\"paperSize\":\"1280X900\"},\"boardStyle\":{\"backgroundImage\":\"\"},\"dataConfig\":{}}";
        Map parse = (Map) JSON.parse(content);
        Map<String, Object> dataConfig = new HashMap<>();
        dataConfig.put("msgType", "mqtt");
        dataConfig.put("wsUrl", sceneUrl);
        parse.put("dataConfig", dataConfig);
        content = JSONObject.toJSONString(parse);
        dataConfig.put("wsTopic", wsTopic);
        resourceDTO.setContent(content);
        ResourceDTO morphic = Morphic.morphicSubjectClient.create(resourceDTO).getResult();
        model.setSceneId(morphic.getId());
//        fireFightingSystemMapper.setSceneId(model);
        return model;
    }

    @Override
    @Transactional
    public ResourceDTO updateMorphic(ResourceDTO resourceDTO) {
        try {
            // 1.更新画布信息
            resourceDTO.setSubjectId(projectSeq);
            resourceDTO.setSubjectid(projectSeq);
            String content = resourceDTO.getContent();
            Map parse = (Map) JSON.parse(content);
            Map<String, Object> dataConfig = new HashMap<>();
            dataConfig.put("msgType", "mqtt");
            dataConfig.put("wsUrl", sceneUrl);
            dataConfig.put("wsTopic", wsTopic);
            parse.put("dataConfig", dataConfig);
            content = JSONObject.toJSONString(parse);
            resourceDTO.setContent(content);
            FeignUtil.remoteCall(() -> Morphic.morphicSubjectClient.update(resourceDTO));
            // 2.更新业务关联的画布id
            Long systemId = Long.valueOf(resourceDTO.getCode());
            FireFightingSystemVo systemVo = new FireFightingSystemVo();
            systemVo.setId(valueOf(systemId));
            systemVo.setSceneId(resourceDTO.getId());
            fireFightingSystemMapper.setSceneId(systemVo);
            // 3.保存场景关联信息表
            SourceScene sourceScene = sourceSceneMapper
                    .selectOne(new LambdaQueryWrapper<SourceScene>().eq(SourceScene::getSceneId, resourceDTO.getId()));
            if (sourceScene == null) {
                sourceScene = new SourceScene();
                sourceScene.setProjectId(valueOf(projectSeq));
                sourceScene.setSourceId(systemId);
                sourceScene.setSourceName(resourceDTO.getName());
                sourceScene.setSceneId(resourceDTO.getId());
                sourceScene.setSourceType("system");
            }
            // TODO 获取画布下 绑定的装备点、摄像头，目前消防系统只能绑定装备，不能绑定摄像头（树未返回摄像头）
            List<Map> children = (List<Map>) parse.get("children");
            String pointInScene = "";
            String videoInScene = "";
            if (!CollectionUtils.isEmpty(children)) {
                for (Map<String, String> map : children) {
                    String key = map.get("key");
                    if (!"".equals(key) && "equipment".equals(key)) {
                        pointInScene = "".equals(pointInScene) ? map.get("sequenceNbr")
                                : pointInScene + "," + map.get("sequenceNbr");
                    }
                    if (!"".equals(key) && "video".equals(key)) {
                        videoInScene = "".equals(videoInScene) ? map.get("sequenceNbr")
                                : videoInScene + "," + map.get("sequenceNbr");
                    }
                }
            }
            sourceScene.setPointInScene(pointInScene);
            sourceScene.setVideoInScene(videoInScene);
            iSourceSceneService.saveOrUpdate(sourceScene);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BadRequest("保存画布失败");
        }
        return resourceDTO;
    }

    @Override
    public List<PointTreeVo> getPointTree(String id, String orgCode, String type) {
//        CommonResponse se = riskModelFeign.getRiskSourceList(orgCode);
//        List<Map<String, Object>> list = (List<Map<String, Object>>) se.getDataList();
//        List<PointTreeVo> responses = new ArrayList<>();
//        list.forEach(m -> {
//            RiskSourceTreeResponse r = new RiskSourceTreeResponse();
//            PointTreeVo p = new PointTreeVo();
//            mapToBean(m, r);
//            p.setDisplayName(r.getName());
//            p.setParentId(r.getParentId());
//            p.setSequenceNbr(r.getId());
//            p.setIsRegion(r.getIsRegion());
//            responses.add(p);
//        });
//        List<PointTreeVo> regionList = responses.stream().filter(r -> "TRUE".equals(r.getIsRegion())).collect(Collectors.toList());
        if("dl".equals(type)){
            FeignClientResult<List<OrgUsrDto>> feignClientResult = jcsFeignClient.getCompanyDeptListWithAuth(authKey, "COMPANY", "dl");
            orgCode = feignClientResult.getResult().get(0).getBizOrgCode();
        }
        List<PointTreeVo> buildList = buildingMapper.getBuildList(orgCode, null);
        return transferListToPointTree(buildList, id, null);
    }

    @Override
    public List<SpeIndexVo> getSpeIndex(Long id, int flag) {
        //  因此处代码其他地方有调用 增加表示判断 flag == 1 为 消防点位图处需要iot编码所用
        if (flag == 1) {
            List<SpeIndexVo> speIndexVos = makeStatus(fireFightingSystemMapper.getSpeIndex(id));
            if (!ValidationUtil.isEmpty(speIndexVos)) {
                EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getBaseMapper().selectById(id);
                if (!ValidationUtil.isEmpty(equipmentSpecific)) {
                    SpeIndexVo speIndexVo = new SpeIndexVo();
                    speIndexVo.setName("设备编码");
                    speIndexVo.setValue(equipmentSpecific.getCode());
                    speIndexVos.add(0, speIndexVo);
                }
            }
            return speIndexVos;
        }
        return makeStatus(fireFightingSystemMapper.getSpeIndex(id));
    }

    private void insertFiles(FireFightingSystemVo vo) {
        List<FileUploadVo> video = vo.getVideo();
        if (video.size() > 0) {
            for (FileUploadVo f : video) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("video");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }
        List<FileUploadVo> faceimg = vo.getFaceimg();
        if (faceimg.size() > 0) {
            for (FileUploadVo f : faceimg) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("face");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }
        List<FileUploadVo> instruction = vo.getInstruction();
        if (instruction.size() > 0) {
            for (FileUploadVo f : instruction) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("instruction");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }
        List<FileUploadVo> asser = vo.getAsser();
        if (asser.size() > 0) {
            for (FileUploadVo f : asser) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("certificate");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }

        List<FileUploadVo> spotimg = vo.getSpotimg();
        if (spotimg.size() > 0) {
            for (FileUploadVo f : spotimg) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("spotimg");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }

        List<FileUploadVo> tdmod = vo.getTdmod();
        if (tdmod.size() > 0) {
            for (FileUploadVo f : tdmod) {
                f.setId(valueOf(System.currentTimeMillis()));
                f.setUserId(vo.getRecUserId());
                f.setFileType("tdmod");
                f.setObjectId(vo.getId());
                fireFightingSystemMapper.insertFile(f);
            }
        }
    }

    /**
     * 生成树结构
     *
     * @param allRiskSource
     * @param id
     * @return
     */
    public List<PointTreeVo> transferListToPointTree(List<PointTreeVo> allRiskSource, String id, String instanceId) {
        //TODO id为空，为消防建筑使用；id不为空，为点位图使用
        List<PointTreeVo> pointData = fireFightingSystemMapper.getPointData(id, instanceId);
        if (!CollectionUtils.isEmpty(pointData)) {
            // 查询所有wl_source_scene，判断是否绑定
            LambdaQueryWrapper<SourceScene> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isEmpty(id)) {
                wrapper.eq(SourceScene::getSourceType, "building");
            } else {
                wrapper.eq(SourceScene::getSourceType, "system");
            }
            List<SourceScene> sourceSceneList = sourceSceneMapper.selectList(wrapper);
            Map<Long, String> sourceSceneMap = null;
            String equipSpecificIds = null;
            if (!CollectionUtils.isEmpty(sourceSceneList)) {
                sourceSceneMap = sourceSceneList.stream().collect(Collectors.toMap(SourceScene::getSourceId, SourceScene::getPointInScene));
                List<String> equipSpecificIdList = sourceSceneList.stream().map(SourceScene::getPointInScene).collect(Collectors.toList());
                equipSpecificIds = String.join(",", equipSpecificIdList);
            }
            // 优化不查指标
            for (PointTreeVo p : pointData) {
                Long buildOrSysId = p.getParentId();
                Long equipSpecificId = p.getSequenceNbr();
                Map map = new HashMap(7);
                map.put("imgPath", p.getImgPath());
                map.put("equipCode", p.getEquipCode());
                map.put("equipSyetemId", p.getEquipSyetemId());
                map.put("equipTypeId", p.getEquipId());
                map.put("speindexApi", speindexUrl + equipSpecificId);
                map.put("detailInfoApi", equipmentDetailUrl + p.getSequenceNbr());
                map.put("detailApi", equipmentDetailUrl + p.getSequenceNbr());
                p.setDataConfig(map);
                if (StringUtils.isEmpty(id)) {
                    //  建筑
                    if (equipSpecificIds.contains(valueOf(equipSpecificId))) {
                        p.setBinding(true);
                    } else {
                        p.setBinding(false);
                    }
                } else {
                    if (sourceSceneMap != null) {
                        String pointInScene = sourceSceneMap.get(buildOrSysId);
                        if (!StringUtils.isEmpty(pointInScene)) {
                            //  系统
                            if (pointInScene.contains(valueOf(equipSpecificId))) {
                                p.setBinding(true);
                            } else {
                                p.setBinding(false);
                            }
                        }
                    }
                }
            }
            allRiskSource.addAll(pointData);
            // 树组装优化
            Map<Long, PointTreeVo> map = new HashMap<>(allRiskSource.size());
            allRiskSource.forEach(e -> map.put(e.getSequenceNbr(), e));
            Set<? extends Map.Entry<Long, ? extends PointTreeVo>> entries = map.entrySet();
            List<PointTreeVo> treeList = new ArrayList<>();
            entries.forEach(entry -> {
                PointTreeVo value = entry.getValue();
                if (value != null) {
                    PointTreeVo treeDto = map.get(value.getParentId());
                    if (treeDto != null) {
                        List<PointTreeVo> children = treeDto.getChildren();
                        if (children == null) {
                            children = new ArrayList<>();
                            treeDto.setChildren(children);
                        }
                        children.add(value);
                    } else {
                        treeList.add(value);
                    }
                }
            });
            return treeList;
        }
        return Collections.emptyList();
    }

    /**
     * 生成树结构
     *
     * @param allRiskSource
     * @param id
     * @return
     */
    public List<PointTreeVo> transferListToPointTreeNew(List<PointTreeVo> allRiskSource, String id, String instanceId, String displayName) {
        //TODO id为空，为消防建筑使用；id不为空，为点位图使用
        List<PointTreeVo> pointData = fireFightingSystemMapper.getPointDataNew(id, instanceId, displayName);
        if (!CollectionUtils.isEmpty(pointData)) {
            // 查询所有wl_source_scene，判断是否绑定
            List<SourceScene> sourceSceneList = sourceSceneMapper.selectList(null);
            Map<Long, String> sourceSceneMap = null;
            String equipSpecificIds = null;
            if (!CollectionUtils.isEmpty(sourceSceneList)) {
                sourceSceneMap = sourceSceneList.stream().collect(Collectors.toMap(SourceScene::getSourceId, SourceScene::getPointInScene));
                List<String> equipSpecificIdList = sourceSceneList.stream().map(SourceScene::getPointInScene).collect(Collectors.toList());
                equipSpecificIds = String.join(",", equipSpecificIdList);
            }
            // 优化不查指标
            for (PointTreeVo p : pointData) {
                Long buildOrSysId = p.getParentId();
                Long equipSpecificId = p.getSequenceNbr();
                Map map = new HashMap(7);
                map.put("imgPath", p.getImgPath());
                map.put("equipCode", p.getEquipCode());
                map.put("equipSyetemId", p.getEquipSyetemId());
                map.put("equipTypeId", p.getEquipId());
                map.put("speindexApi", speindexUrl + equipSpecificId);
                map.put("detailInfoApi", equipmentDetailUrl + p.getSequenceNbr());
                map.put("detailApi", equipmentDetailUrl + p.getSequenceNbr());
                p.setDataConfig(map);
                if (StringUtils.isEmpty(id)) {
                    //  建筑
                    if (equipSpecificIds.contains(valueOf(equipSpecificId))) {
                        p.setBinding(true);
                    } else {
                        p.setBinding(false);
                    }
                } else {
                    if (sourceSceneMap != null) {
                        String pointInScene = sourceSceneMap.get(buildOrSysId);
                        if (!StringUtils.isEmpty(pointInScene)) {
                            //  系统
                            if (pointInScene.contains(valueOf(equipSpecificId))) {
                                p.setBinding(true);
                            } else {
                                p.setBinding(false);
                            }
                        }
                    }
                }
            }
            allRiskSource.addAll(pointData);
            // 树组装优化
            Map<Long, PointTreeVo> map = new HashMap<>(allRiskSource.size());
            allRiskSource.forEach(e -> map.put(e.getSequenceNbr(), e));
            Set<? extends Map.Entry<Long, ? extends PointTreeVo>> entries = map.entrySet();
            List<PointTreeVo> treeList = new ArrayList<>();
            entries.forEach(entry -> {
                PointTreeVo value = entry.getValue();
                if (value != null) {
                    PointTreeVo treeDto = map.get(value.getParentId());
                    if (treeDto != null) {
                        List<PointTreeVo> children = treeDto.getChildren();
                        if (children == null) {
                            children = new ArrayList<>();
                            treeDto.setChildren(children);
                        }
                        children.add(value);
                    } else {
                        treeList.add(value);
                    }
                }
            });
            return treeList;
        }
        return Collections.emptyList();
    }


    /**
     * 生成树结构
     *
     * @param allRiskSource
     * @return
     */
    public List<PointTreeVo> transferListTo3dPointTree(List<PointTreeVo> allRiskSource) {
        List<PointTreeVo> treeList = new ArrayList<>();
        List<PointTreeVo> pointData = fireFightingSystemMapper.get3dPointData();
        if (!CollectionUtils.isEmpty(pointData)) {
            allRiskSource.addAll(pointData);
            for (PointTreeVo tree : allRiskSource) {
                if (tree.getParentId() == null || tree.getParentId() == -1) {
                    treeList.add(tree);
                }
                for (PointTreeVo treeNode : allRiskSource) {
                    if (tree.getSequenceNbr().equals(treeNode.getParentId())) {
                        if (tree.getChildren() == null) {
                            tree.setChildren(new ArrayList<>());
                        }
                        tree.getChildren().add(treeNode);
                    }
                }
            }
            return treeList;
        }
        return Lists.newArrayList();
    }

    private static <T> void mapToBean(Map<String, Object> map, T bean) {
        try {
            BeanUtils.populate(bean, map);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Set<?> set = new HashSet<>();

    }

    /**
     * 生成 性能指标数据
     *
     * @param list
     * @return
     */
    private List<SpeIndexVo> makeStatus(List<SpeIndexVo> list) {
        if (list == null || list.size() == 0) {
            return new ArrayList<>();
        }
//        List<SpeIndexVo> newList = new ArrayList<>();
        List<SpeIndexVo> statusList = new ArrayList<>();
        // 按照http://36.46.149.14:5080/zentao/task-view-5911.html的问题改动如下
//        for (SpeIndexVo vo : list) {
//            int status = vo.getIsAlarm();
//            if (AlarmStatusEnum.BJ.getCode() == status) {
//                statusList.add(vo);
//            }
//            newList.add(vo);
//        }
//        if (statusList.size() == 0) {
//            return newList;
//        }
        SpeIndexVo spe = new SpeIndexVo();
        spe.setKey(EquipmentSpeIndexEnum.YXZT.getCode());
        SpeIndexVo latestVo = list.get(0);
        org.springframework.beans.BeanUtils.copyProperties(latestVo, spe);
        spe.setName("当前状态");
        Map<String, String> map = getStatus(list);
        spe.setValue(map.get("runStatus"));
        spe.setColor(map.get("color"));
        statusList.clear();
        statusList.add(spe);
        statusList.addAll(list);
        return statusList;
    }

    /**
     * 判断 装备状态
     *
     * @param statusList
     * @return
     */
    private Map<String, String> getStatus(List<SpeIndexVo> statusList) {
        Map<String, String> map = new HashMap<>();
        SpeIndexVo indexVo = statusList.get(0);
        int i = 0;
        for (SpeIndexVo x : statusList) {
            if (StringUtil.isNotEmpty(x.getIndexValue())) {
                i = i + 1;
            }
        }
        if (0 == i) {
            map.put("runStatus", "无");
            map.put("color", "");
            return map;
        }
        if (StringUtil.isNotEmpty(indexVo.getIndexValue()) && AlarmStatusEnum.HF.getCode() == indexVo.getIsAlarm()) {
            map.put("runStatus", indexVo.getIndexName());
            map.put("color", "");
            return map;
        }
        if (StringUtil.isNotEmpty(indexVo.getIndexValue()) && TrueOrFalseEnum.real.value.toUpperCase().equals(indexVo.getIndexValue().toUpperCase())) {
            map.put("runStatus", indexVo.getIndexName());
            map.put("color", indexVo.getColor());
            return map;
        }

        map.put("runStatus", "运行");
        map.put("color", "");
        return map;
    }

    @Override
    public List<FireFightingSystemEntity> getList() {
        return this.list();
    }

    @Override
    @Transactional
    public Boolean deleteSystem(Long id) {
        FireFightingSystemEntity entity = baseMapper.selectById(id);
        if (entity.getSceneId() != null) {
            try {
                FeignUtil.remoteCall(() -> Morphic.morphicSubjectClient.delete(entity.getSceneId()));
            } catch (Exception e) {
                log.error("远程调用 MORPHIC 服务的删除操作出错:" + e.getMessage().toString(), e);
            }
        }
        formInstanceMapper.clearSystemId(id);
        // 解除装备与消防系统关系
        this.removeBondSystemId(id);
        this.baseMapper.deleteFilre(valueOf(id));
        int i = this.baseMapper.deleteById(id);
        if (i > 0 && syncSwitch) {
            syncDataService.syncDeletedFireFightingSystem(Arrays.asList(id));
        }
        //删除系统图与设备关系表
        QueryWrapper<SourceScene> ssWrapper = new QueryWrapper<SourceScene>();
        ssWrapper.lambda().eq(SourceScene::getSourceId, id);
        sourceSceneMapper.delete(ssWrapper);
        //删除动态关联表单实例数据
        if (entity.getInstanceId() != null) {
            instanceService.remove(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId,
                    entity.getInstanceId()));
        }
        return i > 0;
    }

    private void removeBondSystemId(Long id) {
        List<EquipmentSpecific> equipmentSpecifics = equipmentSpecificSerivce
                .list(new LambdaQueryWrapper<EquipmentSpecific>().like(EquipmentSpecific::getSystemId, id));
        equipmentSpecifics.forEach(equipmentSpecific -> {
            List<String> ids = new ArrayList<>();
            if (StringUtil.isNotEmpty(equipmentSpecific.getSystemId())) {
                ids = Arrays.asList(equipmentSpecific.getSystemId().split(","));
                ids = new ArrayList<>(ids);
                ids.remove(id.toString());
            }
            equipmentSpecific.setSystemId(Joiner.on(",").join(ids));
        });
        if (!equipmentSpecifics.isEmpty()) {
            equipmentSpecificSerivce.saveOrUpdateBatch(equipmentSpecifics);
        }
    }

    @Override
    public Boolean isDeleteCanvas(Long id) {
        FireFightingSystemEntity system = baseMapper
                .selectOne(new QueryWrapper<FireFightingSystemEntity>().eq("scene_id", id));
        if (system != null) {
            return true;
        } else {
            FeignUtil.remoteCall(() -> Morphic.morphicSubjectClient.delete(id));
            return false;
        }
    }

    @Override
    public IPage<EquipTypeImgAmountVO> getColaCategoryAmountList(int hierarchy, String codeHead,
                                                                 EquipTypeAmountPageDTO equipTypeAmountPage) {
        String type = equipTypeAmountPage.getType();
        if (!"".equals(type) && "car".equals(type)) {
            equipTypeAmountPage.setSystemId(null);
            equipTypeAmountPage.setStatus(null);
        }
        IPage<EquipTypeImgAmountVO> list = fireFightingSystemMapper
                .getColaCategoryAmountList(equipTypeAmountPage.getPage(), hierarchy, codeHead, equipTypeAmountPage);
        list.getRecords().forEach(x -> {
            if (!x.getEqtype().startsWith("4") && StringUtil.isNotEmpty(x.getAmount())) {
                x.setAmount(x.getAmount().split("\\.")[0]);
            }
        });
        return list;
    }

    @Override
    public IPage<EquipTypeImgAmountVO> getColaCategoryAmountListIot(int hierarchy, String codeHead,
                                                                    EquipTypeAmountPageDTO equipTypeAmountPage) {
        String type = equipTypeAmountPage.getType();
        if (!"".equals(type) && "car".equals(type)) {
            equipTypeAmountPage.setSystemId(null);
            equipTypeAmountPage.setStatus(null);
        }
        IPage<EquipTypeImgAmountVO> list = fireFightingSystemMapper
                .getColaCategoryAmountListIot(equipTypeAmountPage.getPage(), hierarchy, codeHead, equipTypeAmountPage);
        list.getRecords().forEach(x -> {
            if (!x.getEqtype().startsWith("4") && StringUtil.isNotEmpty(x.getAmount())) {
                x.setAmount(x.getAmount().split("\\.")[0]);
            }
        });
        return list;
    }

    @Override
    public IPage<EquipTypeImgAmountVO> getColaCategoryAmountCarList(int hierarchy, String codeHead,
                                                                    EquipTypeAmountPageDTO equipTypeAmountPage) {
        String type = equipTypeAmountPage.getType();
        if (!"".equals(type) && "car".equals(type)) {
            equipTypeAmountPage.setSystemId(null);
            equipTypeAmountPage.setStatus(null);
        }
        IPage<EquipTypeImgAmountVO> list = fireFightingSystemMapper
                .getColaCategoryAmountCarList(equipTypeAmountPage.getPage(), hierarchy, codeHead, equipTypeAmountPage);
        list.getRecords().forEach(x -> {
            if (!x.getEqtype().startsWith("4") && StringUtil.isNotEmpty(x.getAmount())) {
                x.setAmount(x.getAmount().split("\\.")[0]);
            }
        });
        return list;
    }

    @Override
    public IPage<EquipTypeImgAmountVO> getColaCategoryAmountEquList(int hierarchy, String codeHead,
                                                                    EquipTypeAmountPageDTO equipTypeAmountPage) {
        String type = equipTypeAmountPage.getType();
        if (!"".equals(type) && "car".equals(type)) {
            equipTypeAmountPage.setSystemId(null);
            equipTypeAmountPage.setStatus(null);
        }
        IPage<EquipTypeImgAmountVO> list = fireFightingSystemMapper
                .getColaCategoryAmountEquList(equipTypeAmountPage.getPage(), hierarchy, codeHead, equipTypeAmountPage);
        list.getRecords().forEach(x -> {
            if (!x.getEqtype().startsWith("4") && StringUtil.isNotEmpty(x.getAmount())) {
                x.setAmount(x.getAmount().split("\\.")[0]);
            }
        });
        return list;
    }

    @Override
    public List<EquipmentManageVo> getSystemCategory() {
        return equipmentManageMapper.getSystemList();
    }

    @Override
    public List<FireFightingSystem> getFireFightingSystemDetail(FireFightingSystemVo fireFightingSystemVo) {
        return fireFightingSystemMapper.getFireFightingSystemDetail(fireFightingSystemVo);
    }

    @Override
    public List<FireFightingSystemEntity> getFightingSysByCodes(String[] idsArr) {
        List<FireFightingSystemEntity> fightingSystemList = fireFightingSystemMapper.getFightingSysByCodes(idsArr);
        if (fightingSystemList != null && !fightingSystemList.isEmpty()) {
            return fightingSystemList;
        }
        return Lists.newArrayList();
    }

    @Override
    public List<FireFightingSystem3dVo> get3dFightingSystemList() {
        FeignClientResult<List<DictionarieValueModel>> dictValues = Systemctl.dictionarieClient
                .dictValues(iotCoreParam);
        Optional.ofNullable(dictValues).orElseThrow(() -> new BadRequest("查询字段数据为空"));
        List<DictionarieValueModel> values = dictValues.getResult();
        if (!CollectionUtils.isEmpty(values)) {
            List<String> collect = values.stream().map(DictionarieValueModel::getDictDataKey)
                    .collect(Collectors.toList());
            List<FireFightingSystem3dVo> list = fireFightingSystemMapper.get3dFightingSystemList(collect);
            if (!CollectionUtils.isEmpty(list)) {
                return list;
            }
        }
        return Lists.newArrayList();
    }

    @Override
    public FireFightingSystemEntity getDetailByCode(String systemCode) {
        LambdaQueryWrapper<FireFightingSystemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FireFightingSystemEntity::getCode, systemCode);
        List<FireFightingSystemEntity> systemEntities = this.list(wrapper);
        if (systemEntities.isEmpty()) {
            throw new RuntimeException("code" + systemCode + "不存在");
        }
        return systemEntities.get(0);
    }

    @Override
    public List<Map<String, Object>> getEquip(String bizOrgCode, String systemCode) {
        List<Map<String, Object>> list = fireFightingSystemMapper.getEquip(bizOrgCode, systemCode);
        List<Map<String, Object>> resList = new ArrayList<>();
        int i = 1;
        if (0 < list.size()) {
            for (Map<String, Object> m : list) {
                List<Map<String, Object>> list1 = new ArrayList();
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> statusMap = new HashMap<>();
                map.put("key", i);
                map.put("name", m.get("name"));
                map.put("code", m.get("code"));
                map.put("systemTypeCode", systemCode);
                map.put("img", m.get("shbzImg"));
                statusMap.put("name", m.get("status"));
                if ("正常".equals(String.valueOf(m.get("status")))) {
                    statusMap.put("level", "success");
                } else {
                    statusMap.put("level", "warning");
                }
                list1.add(statusMap);
                map.put("status", list1);
                resList.add(map);
                i++;
            };
        }
        return resList;
    }

    @Override
    public List<Map<String, Object>> getFireSystemEquipStatusList(String bizOrgCode, String systemCode, String categoryCodes) {
        List<Map<String, Object>> list = fireFightingSystemMapper.getFireSystemEquipStatusList(bizOrgCode, systemCode, categoryCodes);
        List<Map<String, Object>> resList = new ArrayList<>();
        int i = 1;
        if (0 < list.size()) {
            for (Map<String, Object> m : list) {
                List<Map<String, Object>> list1 = new ArrayList();
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> statusMap = new HashMap<>();
                map.put("key", i);
                map.put("name", m.get("name"));
                map.put("code", m.get("code"));
                map.put("systemTypeCode", systemCode);
                map.put("img", m.get("shbzImg"));
                statusMap.put("name", m.get("status"));
                if ("正常".equals(String.valueOf(m.get("status")))) {
                    statusMap.put("level", "success");
                } else {
                    statusMap.put("level", "warning");
                }
                list1.add(statusMap);
                map.put("status", list1);
                resList.add(map);
                i++;
            };
        }
        return resList;
    }

    @Override
    public List<AlarmDataVO> getSystemById(Long id) {
        return this.baseMapper.getSystemById(id);
    }

    @Override
    public IPage<EquipmentAlarmBySystemIdOrSourceIdVO> getEquipmentAlarmBySystemIdOrSourceIdVO(IPage<EquipmentAlarmBySystemIdOrSourceIdVO> page, Long sourceId, Long systemId, Integer confirmType, String createDate, String type, String equipmentId) {
        return this.baseMapper.getEquipmentAlarmBySystemIdOrSourceIdVO(page, sourceId, systemId, confirmType, createDate, type, equipmentId);
    }

    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 Map<String, Object> integrationPageSysData(String systemCode, Boolean isUpdate) {
        // TODO Auto-generated method stub
        if (!StringUtil.isNotEmpty(SystemTypeEnum.getEnum(systemCode))) {
            return null;
        }
        Map<String, Object> data;
        if (isUpdate) {
            data = saveIntegrationPageSysData(systemCode);
        } else {
            if (redisUtils.hasKey(systemCode)) {
                data = JSONObject.parseObject(redisUtils.get(systemCode).toString(), Map.class);
            } else {
                data = saveIntegrationPageSysData(systemCode);
            }

        }
        if (!ObjectUtils.isEmpty(data)) {
            mqttSendGateway.sendToMqtt(String.format("%s%s", "INTEGRATE_TOPIC/", systemCode), JSON.toJSONString(data));
        }
        return null;
    }

    public Map<String, Object> saveIntegrationPageSysData(String systemCode) {
        Map<String, Object> data = null;
        if (SystemTypeEnum.fireAlarmSys.getCode().equals(systemCode)) {
            data = fireFightingSystemMapper.fireAlarmSysEquipmentNumber();
            this.putAll(data, fireFightingSystemMapper.fireAlarmSysIndexNumber());
        } else if (SystemTypeEnum.fireCAFSSys.getCode().equals(systemCode)) {
            data = fireFightingSystemMapper.getFireCafsSystem();
        } else if (SystemTypeEnum.fireONLSys.getCode().equals(systemCode)) {
            data = fireFightingSystemMapper.getFireOnlSystem();
            this.putAll(data, fireFightingSystemMapper.getFireOnlSystemThreeSmall());
        } else if (SystemTypeEnum.fireFoamSys.getCode().equals(systemCode)) {
            data = fireFightingSystemMapper.fireFoamSysEquipmentIndexNumber();
        } else if (SystemTypeEnum.fireFoamMistSys.getCode().equals(systemCode)
                || SystemTypeEnum.envMonitoringSys.getCode().equals(systemCode)) {
            // TODO 灯泡及门状态，实时数据库刷新,存放数据，套用后续逻辑进行数据的发送
            data = new HashMap<>();
            data.put("waitRefresh", true);
        } else if (SystemTypeEnum.fireWaterSys.getCode().equals(systemCode)) {
            data = fireFightingSystemMapper.fireWaterSysCollectingDevice();
            this.putAll(data, fireFightingSystemMapper.fireWaterSysPool());
            this.putAll(data, fireFightingSystemMapper.fireWaterSysWaterPump());
            this.putAll(data, fireFightingSystemMapper.fireWaterSysHydrant());
            this.putAll(data, fireFightingSystemMapper.fireWaterSysPipeNetwork());
//            this.putAll(data, fireFightingSystemMapper.fireWaterSysPipeStatus());
        } else {
            data = fireFightingSystemMapper.otherSysIndexNumAndTotal();
        }
        if (!ObjectUtils.isEmpty(data)) {
            redisUtils.set(systemCode, JSONObject.toJSONString(data));
        }
        return data;
    }

    private void putAll(Map<String, Object> data, Map<String, Object> addMap) {
        if (!CollectionUtils.isEmpty(addMap)) {
            data.putAll(addMap);
        }
    }

    @Override
    public List<FireFightingSystemTreeVo> getSystemTreeByOrgCode(String bizOrgCode) {
        // 获取公司部门list
        List<OrgUsrDto> orgUsrLists = jcsRemoteService.getCompanyDeptListWithAuth("COMPANY,DEPARTMENT", bizOrgCode, null);
        List<FireFightingSystemTreeVo> fireFightingSystemTreeList = orgUsrLists.stream().map(key -> {
            FireFightingSystemTreeVo vo = new FireFightingSystemTreeVo();
            vo.setId(valueOf(key.getSequenceNbr()));
            vo.setName(key.getBizOrgName());
            vo.setType(key.getBizOrgType());
            vo.setBizOrgCode(key.getBizOrgCode());
            vo.setParentId(key.getParentId());
            return vo;
        }).collect(Collectors.toList());

        // 根据bizOrgCode获取系统list
        List<String> bizOrgCodes = fireFightingSystemTreeList.stream().map(FireFightingSystemTreeVo::getBizOrgCode)
                .collect(Collectors.toList());
        LambdaQueryWrapper<FireFightingSystemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(FireFightingSystemEntity::getBizOrgCode, bizOrgCodes);
        List<FireFightingSystemEntity> fireFightingSystemEntityList = this.baseMapper.selectList(wrapper);
        List<FireFightingSystemTreeVo> systemList = fireFightingSystemEntityList.stream().map(key -> {
            FireFightingSystemTreeVo vo = new FireFightingSystemTreeVo();
            vo.setId(valueOf(key.getId()));
            vo.setName(key.getName());
            vo.setType("system");
            vo.setBizOrgCode(key.getBizOrgCode());
            return vo;
        }).collect(Collectors.toList());

        // 组装公司部门树
        fireFightingSystemTreeList.addAll(systemList);
        return fireFightingSystemTreeList.stream().filter(d -> !"system".equals(d.getType()))
                .peek((m) -> m.setChildren(getChildren(m, fireFightingSystemTreeList))).collect(Collectors.toList());
    }

    private List<FireFightingSystemTreeVo> getChildren(FireFightingSystemTreeVo root,
                                                       List<FireFightingSystemTreeVo> all) {
        return all.stream()
                .filter(d -> StringUtil.isNotEmpty(d.getParentId()) && d.getParentId().equals(root.getId())
                        || (StringUtil.isNotEmpty(d.getBizOrgCode()) && d.getBizOrgCode().equals(root.getBizOrgCode())
                        && !"system".equals(root.getType()) && !d.getId().equals(root.getId())))
                .peek(m -> m.setChildren(getChildren(m, all))).collect(Collectors.toList());
    }

    @Override
    public List<OrgMenuDto> companyTreeByUserAndType(String type) {
        return jcsRemoteService.getCompanyDeptTreeWithAuth(authKey, type);
    }

    @Override
    public List<FireFightingSystemTypeTreeVo> systemTypeTree(String bizOrgCode) {
        // 获取所有系统分类list
        LambdaQueryWrapper<DynamicFormGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DynamicFormGroup::getGroupType, "fireSystem");
        wrapper.eq(DynamicFormGroup::getParentId, 0);
        List<DynamicFormGroup> list = iEqDynamicFormGroupService.list(wrapper);
        List<Map<String, Object>> typeList = fireFightingSystemMapper.listByBizOrgCode(bizOrgCode);
        List<FireFightingSystemTypeTreeVo> childrenList = list.stream().map(item -> {
            FireFightingSystemTypeTreeVo vo = new FireFightingSystemTypeTreeVo();
            vo.setName(item.getGroupName());
            typeList.forEach(obj -> {
                if (item.getId().equals(Long.valueOf(obj.get("typeId").toString()))) {
                    vo.setTotal(obj.get("total").toString());
                }
            });
            vo.setType(item.getGroupType());
            vo.setId(valueOf(item.getId()));
            return vo;
        }).collect(Collectors.toList());
        // 计算总数
        long total = typeList.stream().mapToLong(o -> {
            if (!ObjectUtils.isEmpty(o.get("total"))) {
                return (long) o.get("total");
            }
            return 0;
        }).sum();
        // 自定义根节点返回树
        FireFightingSystemTypeTreeVo parentNode = new FireFightingSystemTypeTreeVo();
        parentNode.setType("all");
        parentNode.setName("全部分类");
        parentNode.setId("-1");
        parentNode.setParentId("-1");
        parentNode.setTotal(valueOf(total));
        parentNode.setChildren(childrenList);
        return Collections.singletonList(parentNode);
    }

    @Override
    public Object getEquipmentTypeAndCount(String bizOrgCode) {
//        if (redisUtils.hasKey(equipTypeAndCount + bizOrgCode)) {
//            return JSONArray.parseArray(
//                    JSONArray.toJSONString(redisUtils.get(equipTypeAndCount + bizOrgCode)), EquipmentCategory.class);
//        } else {
        return refreshEquipmentTypeAndCount(bizOrgCode);
        // }
    }

    @Override
    public Object refreshEquipmentTypeAndCount(String bizOrgCode) {
        List<EquipmentCategory> responseList = this.typeList();
        if (responseList == null || responseList.size() < 1) {
            return null;
        }
        List<EquipmentCategory> equipmentTypeList = responseList.stream()
                .filter(i -> !i.getCode().startsWith("2") && "2".equals(i.getIndustryCode()))
                .filter(m -> !m.getCode().startsWith("9306") && "2".equals(m.getIndustryCode()))
                .collect(Collectors.toList());
        List<EquipmentCategory> list = typeListTree(equipmentTypeList, bizOrgCode, SourceTypeEnum.EQUIPMENT);
        redisUtils.set(equipTypeAndCount + bizOrgCode, list, 86400);
        return list;
    }

    @Override
    public Object getCarTypeAndCount(String bizOrgCode) {
        if (redisUtils.hasKey(carTypeAndCount + bizOrgCode)) {
            return JSONArray.parseArray(
                    JSONArray.toJSONString(redisUtils.get(carTypeAndCount + bizOrgCode)), EquipmentCategory.class);
        } else {
            return refreshCarTypeAndCount(bizOrgCode);
        }
    }

    @Override
    public Object iotgetEquipmentTypeAndCount(String bizOrgCode) throws Exception {
        if (redisUtils.hasKey("iotTypeAndCount" + bizOrgCode)) {
            return JSONArray.parseArray(
                    JSONArray.toJSONString(redisUtils.get("iotTypeAndCount" + bizOrgCode)), EquipmentCategory.class);
        } else {
            return iotrefreshEquipmentTypeAndCount(bizOrgCode);
        }
    }

    public Object iotrefreshEquipmentTypeAndCount(String bizOrgCode) {
//        List<EquipmentCategory> responseList = this.typeList();
//        if (responseList == null || responseList.size() < 1) {
//            return null;
//        }
//        List<EquipmentCategory> list = typeListTree(responseList, bizOrgCode, SourceTypeEnum.IOT);


        List<EquipmentCategory> responseList = this.typeList();
        if (responseList == null || responseList.size() < 1) {
            return null;
        }
        List<EquipmentCategory> equipmentTypeList = responseList.stream()
                .filter(i -> !i.getCode().startsWith("2") && "2".equals(i.getIndustryCode()))
                .collect(Collectors.toList());
        List<EquipmentCategory> list = typeListTree(equipmentTypeList, bizOrgCode, SourceTypeEnum.IOT);
        redisUtils.set("iotTypeAndCount" + bizOrgCode, list, 86400);
        return list;
    }

    @Override
    public Object refreshCarTypeAndCount(String bizOrgCode) {
        List<EquipmentCategory> responseList = this.typeList();
        if (responseList == null || responseList.size() < 1) {
            return null;
        }
        List<EquipmentCategory> equipmentTypeList = responseList.stream()
                .filter(i -> i.getCode().startsWith("2") && "2".equals(i.getIndustryCode()))
                .collect(Collectors.toList());
        List<EquipmentCategory> list = typeListTree(equipmentTypeList, bizOrgCode, SourceTypeEnum.CAR);
        redisUtils.set(carTypeAndCount + bizOrgCode, list);
        return list;
    }


    public List<EquipmentCategory> typeList() {
        return this.iEquipmentCategoryService
                .getEquipmentCategoryList(Integer.valueOf(equipmentCategoryLeftTypeCode));
    }

    public List<EquipmentCategory> typeListTree(List<EquipmentCategory> equipmentCategorys, String bizOrgCode,
                                                SourceTypeEnum sourceTypeEnum) {
        List<EquipmentCategory> list = new ArrayList<>();
        Map<String, List<EquipmentCategory>> tmpMap = new HashMap<String, List<EquipmentCategory>>();
        equipmentCategorys.forEach(action -> {
            int num = sourceStatistics.equipCategoryStatistics(bizOrgCode, sourceTypeEnum, action.getCode());
            action.setCount(Double.parseDouble(num + ""));
            if (action.getParentId() == null) {
                list.add(action);
            } else {
                if (tmpMap.get(action.getParentId().toString()) == null) {
                    ArrayList<EquipmentCategory> tmplist = new ArrayList<EquipmentCategory>();
                    tmplist.add(action);
                    tmpMap.put(action.getParentId().toString(), tmplist);
                } else {
                    if (!tmpMap.get(action.getParentId().toString()).contains(action)) {
                        tmpMap.get(action.getParentId().toString()).add(action);
                    }
                }
            }
        });
        getChildren(list, tmpMap);
        return list;
    }

    private void getChildren(List<EquipmentCategory> list, Map<String, List<EquipmentCategory>> tmpMap) {
        for (EquipmentCategory equipmentCategory : list) {
            if (tmpMap.get(equipmentCategory.getId().toString()) != null
                    && tmpMap.get(equipmentCategory.getId().toString()).size() > 0) {
                List<EquipmentCategory> equipcliss = tmpMap.get(equipmentCategory.getId().toString());
                equipmentCategory.setHasLowerClassification(true);
                equipmentCategory.setChildren(equipcliss);
                getChildren(equipcliss, tmpMap);
            }
        }
    }

    @Override
    public List<FireFightingSystemEntity> systemListByBziOrgCode(String bizOrgCode) {
        LambdaQueryWrapper<FireFightingSystemEntity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtil.isNotEmpty(bizOrgCode)) {
            wrapper.likeRight(FireFightingSystemEntity::getBizOrgCode, bizOrgCode);
        }
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getSystemStatus(HashMap<String, Object> hashMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> map = fireFightingSystemMapper.getFireSystemInfo(hashMap);
        if (!map.isEmpty()) {
            ArrayList<Object> status = new ArrayList<>();
            status.add(map.get(0).get("status"));
            resultMap.put("values", status);
            resultMap.put("labels", status);
        }
        return resultMap;
    }

    @Override
    public Integer getSystemStatusBySuper(HashMap<String, Object> hashMap) {
        Integer systemStatus = fireFightingSystemMapper.getSystemStatus(hashMap);
        return systemStatus;
    }

    @Override
    public Map<String, Object> getSystemName(HashMap<String, Object> hashMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> map = fireFightingSystemMapper.getFireSystemInfo(hashMap);
        if (!map.isEmpty()) {
            resultMap.put("name", map.get(0).get("name"));
        }
        return resultMap;
    }


    @Override
    public Map<String, Object> equipAlarmTOP(HashMap<String, Object> hashMap) {
        Map<String, Object> resultMap = new HashMap<>();
        String id = fireFightingSystemMapper.equipmentId(hashMap);
        hashMap.put("systemId", id);
        List<Map<String, Object>> list = fireFightingSystemMapper.equipAlarmTOP(hashMap);
        if (!CollectionUtils.isEmpty(list)) {
            LinkedHashSet<String> yAxis = new LinkedHashSet<>();
            ArrayList<String> xAxis = new ArrayList<>();
            String yKey = "";
            String xResult = "";
            for (Map<String, Object> stringObjectMap : list) {
                yKey = stringObjectMap.get("equipName").toString();
                xResult = stringObjectMap.get("total").toString();
                yAxis.add(yKey);
                xAxis.add(xResult);
            }
            resultMap.put("xAxis", xAxis);
            resultMap.put("yAxis", yAxis);
        }
        return resultMap;
    }

    @Override
    public Page<Map<String, Object>> equipmentState(Page res, HashMap<String, Object> hashMap) {
        Page result = new Page<>(res.getCurrent(), res.getSize());
        String id = fireFightingSystemMapper.equipmentId(hashMap);
        Page<Map<String, Object>> mapPage = fireFightingSystemMapper.equipmentState(result, id);
        return mapPage;
    }

    @Override
    public Page<Map<String, Object>> equipmentStateBySuper(Page res, HashMap<String, Object> hashMap) {
        Page result = new Page<>(res.getCurrent(), res.getSize());
        String id = fireFightingSystemMapper.equipmentIdBySuper(hashMap);
        if (!StringUtil.isNotEmpty(id)) {
            return null;
        }
        Page<Map<String, Object>> mapPage = fireFightingSystemMapper.equipmentStateBySuper(result, id);
        return mapPage;
    }

    @Override
    public Page<Map<String, Object>> getSmallWaterInfo(Page page, HashMap<String, Object> hashMap) {
        String bizOrgCode = null;
        String systemCode = null;
        if (hashMap.containsKey("bizOrgCode")) {
            bizOrgCode = hashMap.get("bizOrgCode").toString();
        }
        if (hashMap.containsKey("systemCode")) {
            systemCode = hashMap.get("systemCode").toString();
        }
        return fireFightingSystemMapper.getWaterInfo(page, bizOrgCode, systemCode);
    }

    @Override
    public Map<String, Object> statisticsByStation(String bizOrgCode) {
        return fireFightingSystemMapper.statisticsByStation(bizOrgCode);
    }
    @Override
    public Map<String, Object> todayAlarmEquipment(String bizOrgCode) {
        Map<String, Object> map = fireFightingSystemMapper.todayAlarmEquipment(bizOrgCode);

        BigDecimal dayAbs = new BigDecimal(map.get("dayAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("dayAbs", dayAbs.toString().replace(".00", "") + "%");
        BigDecimal monthAbs = new BigDecimal(map.get("monthAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("monthAbs", monthAbs.toString().replace(".00", "") + "%");
        return map;
    }

    @Override
    public Map<String, Object> todayAlarmMessage(String bizOrgCode) {
        Map<String, Object> map = fireFightingSystemMapper.todayAlarmMessage(bizOrgCode);
        BigDecimal dayAbs = new BigDecimal(map.get("dayAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("dayAbs", dayAbs.toString().replace(".00", "") + "%");
        BigDecimal monthAbs = new BigDecimal(map.get("monthAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("monthAbs", monthAbs.toString().replace(".00", "") + "%");
        return map;
    }

    @Override
    public Map<String, Object> todayAlarmUnEliminateEquipment(String bizOrgCode) {
        Map<String, Object> map = fireFightingSystemMapper.todayAlarmUnEliminateEquipment(bizOrgCode);
        BigDecimal dayAbs = new BigDecimal(map.get("dayAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("dayAbs", dayAbs.toString().replace(".00", "") + "%");
        BigDecimal monthAbs = new BigDecimal(map.get("monthAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("monthAbs", monthAbs.toString().replace(".00", "") + "%");
        return map;
    }

    @Override
    public Map<String, Object> todayAlarmUnEliminateMessage(String bizOrgCode) {
        Map<String, Object> map = fireFightingSystemMapper.todayAlarmUnEliminateMessage(bizOrgCode);
        BigDecimal dayAbs = new BigDecimal(map.get("dayAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("dayAbs", dayAbs.toString().replace(".00", "") + "%");
        BigDecimal monthAbs = new BigDecimal(map.get("monthAbs").toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        map.put("monthAbs", monthAbs.toString().replace(".00", "") + "%");
        return map;
    }

    @Override
    public List<Map<String, Object>> monthAlarm(String bizOrgCode) {
        return fireFightingSystemMapper.monthAlarm(bizOrgCode);
    }

    @Override
    public List<Map<String, Object>> yearsAlarm(String bizOrgCode) {
        return fireFightingSystemMapper.yearsAlarm(bizOrgCode);
    }

    @Override
    public Page<Map<String, Object>> alarmList(Page page, String bizOrgCode) {
        return fireFightingSystemMapper.alarmList(page, bizOrgCode);
    }

    @Override
    public Page<Map<String, Object>> equipList(Page page, String bizOrgCode) {
        return fireFightingSystemMapper.equipList(page, bizOrgCode);
    }
    @Override
    public BigScreenVo getSystemAlarmInfoNum(String companyCode) {
        BigScreenVo bigScreenVo = new BigScreenVo();
        List<Map<String, Object>> infoList = new ArrayList<>();
//        Map<String, Object> systemAlarmInfoNum = fireFightingSystemMapper.getSystemAlarmInfoNum(companyCode);
////        bigScreenVo.setSystemAlarmInfoNum(systemAlarmInfoNum);
//        infoList.add(systemAlarmInfoNum);
//        Map<String, Object> pool = fireFightingSystemMapper.getWaterPoolInfoNum(companyCode, "pool");
////        bigScreenVo.setPool(pool);
//        infoList.add(pool);
//        Map<String, Object> industryPool = fireFightingSystemMapper.getWaterPoolInfoNum(companyCode, "industryPool");
//        bigScreenVo.setIndustryPool(industryPool);
//        infoList.add(industryPool);
        List<Map<String, Object>> carInfoList = new ArrayList<>();
        Integer carNum = fireFightingSystemMapper.getCarNum(companyCode);
        Map<String, Object> carInfo = new HashMap<>();
        carInfo.put("carNum", carNum);
        carInfoList.add(carInfo);
//        bigScreenVo.setCarNum(carNum);
        bigScreenVo.setCarNumInfo(carInfoList);
        bigScreenVo.setInfoList(infoList);
        return bigScreenVo;
    }

    @Override
    public BigScreenVo getCarInfo(String companyCode) {
        String bizOrgCode = null;
        if (StringUtil.isNotEmpty(companyCode)) {
            bizOrgCode = fireFightingSystemMapper.queryByCompanyCode(companyCode);
        }
        BigScreenVo bigScreenVo = new BigScreenVo();
        List<Map<String, Object>> carInfo = fireFightingSystemMapper.getCarInfo(bizOrgCode);
        bigScreenVo.setCarNumInfo(carInfo);
        List<Map<String, Object>> systemAlarmInfoNum = fireFightingSystemMapper.getSystemAlarmInfoNum(bizOrgCode);
        List<Map<String, Object>> pool = fireFightingSystemMapper.getWaterPoolInfoNum(bizOrgCode);
        List<Map<String, Object>> industryPool = fireFightingSystemMapper.getWaterIndustryPoolInfoNum(bizOrgCode);
        bigScreenVo.setSystemAlarmInfoNum(systemAlarmInfoNum);
        bigScreenVo.setIndustryPool(industryPool);
        bigScreenVo.setPool(pool);
        List<Map<String, Object>> equipInfo = fireFightingSystemMapper.getEquipInfo(bizOrgCode, null);
        List<Map<String, Object>> breakdown = fireFightingSystemMapper.getEquipInfo(bizOrgCode, "BREAKDOWN");
        bigScreenVo.setEquipInfo(equipInfo);
        bigScreenVo.setBreakdownInfo(breakdown);
        return bigScreenVo;
    }

    private Map<String, Object> getData(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> map = new HashMap<>();
        // 查询该站信息以及所有系统
        List<Map<String, Object>> system = fireFightingSystemMapper.selectSystemByBizOrgCode(bizOrgCode);

        String json = null;
        try {
            json = IOUtils.toString(systemIndex.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 系统对应指标配置
        List<Map> indicatorConfiguration = JSONObject.parseArray(json, Map.class);

        // 系统循环数据填充
        ArrayList<Map<String, Object>> systemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(system)) {
            // 换流站信息
            if (!ObjectUtils.isEmpty(system.get(0).get("stationName"))){
                map.put("station", system.get(0).get("stationName"));
            }else {
                map.put("station", "");
            }

            map.put("time", startDate.substring(0,7));
            // 单个系统数据
            for (Map<String, Object> sys : system) {
                HashMap<String, Object> systemData = new HashMap<>();

                List<Map> collect = indicatorConfiguration.stream().
                        filter(item -> item.get("code").equals(String.valueOf(sys.get("typeCode")))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    // 系统名称
                    systemData.put("systemName", ObjectUtils.isEmpty(sys.get("name")) ? "" : String.valueOf(sys.get("name")));
                    // 系统对应指标
                    String indicator = String.valueOf(collect.get(0).get("index"));
                    List<Map<String, Object>> alarmMessageList = fireFightingSystemMapper.selectAlarmList(bizOrgCode, startDate.substring(0, 7), String.valueOf(sys.get("id")));
                    // 单个系统循环列表
                    ArrayList<Map<String, Object>> maps = new ArrayList<>();
                    // 系统下告警统计列表
                    if (!CollectionUtils.isEmpty(alarmMessageList)) {

                        for (Map<String, Object> alarm : alarmMessageList) {
                            HashMap<String, Object> alarmMap = new HashMap<>();
                            // 设备类型
                            alarmMap.put("equipment_name", ObjectUtils.isEmpty(alarm.get("equipment_name")) ? "" : String.valueOf(alarm.get("equipment_name")));
                            // 设备总数
                            alarmMap.put("num", ObjectUtils.isEmpty(alarm.get("num")) ? "" : String.valueOf(alarm.get("num")));
                            // 正常设备总数
                            alarmMap.put("normalEquipNum", ObjectUtils.isEmpty(alarm.get("normalEquipNum")) ? "" : String.valueOf(alarm.get("normalEquipNum")));
                            // 设备正确率
                            alarmMap.put("normalEquipPercent", ObjectUtils.isEmpty(alarm.get("normalEquipPercent")) ? "" : String.valueOf(alarm.get("normalEquipPercent")));
                            // 设备故障总数
                            alarmMap.put("fault_equip_num", ObjectUtils.isEmpty(alarm.get("fault_equip_num")) ? "" : String.valueOf(alarm.get("fault_equip_num")));
                            // 故障信息条数
                            alarmMap.put("alarm_info_num", ObjectUtils.isEmpty(alarm.get("fault_info_num")) ? "" : String.valueOf(alarm.get("fault_info_num")));
                            // 设备故障率
                            alarmMap.put("faultEquipPercent", ObjectUtils.isEmpty(alarm.get("faultEquipPercent")) ? "" : String.valueOf(alarm.get("faultEquipPercent")));
                            // 报警设备总数
                            alarmMap.put("alarm_equip_num", ObjectUtils.isEmpty(alarm.get("alarm_equip_num")) ? "" : String.valueOf(alarm.get("alarm_equip_num")));
                            // 报警设备占比
                            alarmMap.put("alarmEquipPercent", ObjectUtils.isEmpty(alarm.get("alarmEquipPercent")) ? "" : String.valueOf(alarm.get("alarmEquipPercent")));
                            // 信息总数
                            alarmMap.put("total_info_num", ObjectUtils.isEmpty(alarm.get("total_info_num")) ? "" : String.valueOf(alarm.get("total_info_num")));
                            maps.add(alarmMap);
                        }

                    } else {
                        HashMap<String, Object> alarmMap = new HashMap<>();
                        alarmMap.put("equipment_name", "");
                        alarmMap.put("num", "");
                        alarmMap.put("normalEquipNum", "");
                        alarmMap.put("normalEquipPercent", "");
                        alarmMap.put("fault_equip_num", "");
                        alarmMap.put("alarm_info_num", "");
                        alarmMap.put("faultEquipPercent", "");
                        alarmMap.put("alarm_equip_num", "");
                        alarmMap.put("alarmEquipPercent", "");
                        alarmMap.put("total_info_num", "");
                        maps.add(alarmMap);
                    }
                    systemData.put("list", maps);
                    // 系统对应总结
                    Map<String, Object> summarize = fireFightingSystemMapper.selectMonthSummarize(startDate.substring(0, 7), String.valueOf(sys.get("id")));
                    if (!ObjectUtils.isEmpty(summarize)) {
                        systemData.put("summarize", ObjectUtils.isEmpty(summarize.get("summary_info")) ? "" : String.valueOf(summarize.get("summary_info")));

                    } else {
                        systemData.put("summarize", "");
                    }

                    // echarts图
                    String[] split = indicator.split(",");
                    List<String> indicatorList = Arrays.asList(split);
                    List<Map<String, Object>> pieChartList = fireFightingSystemMapper.selectMonthPieChart(String.valueOf(sys.get("code")), startDate, endDate);
                    List<Map<String, Object>> pieChartListTwo = fireFightingSystemMapper.selectMonthPieChartTwo(String.valueOf(sys.get("code")), startDate, endDate, indicatorList);

                    List<Map<String, Object>> selectMonthPolyline = fireFightingSystemMapper.selectMonthPolyline(String.valueOf(sys.get("code")), startDate, endDate,  indicatorList);


                    String pieChart = ChartsUtils.pieChart(pieChartList, "故障设备类型占比");
                    systemData.put("bing1", pieChart);
                    if (!CollectionUtils.isEmpty(pieChartListTwo)) {
                        String pieChart1 = ChartsUtils.pieChart(pieChartListTwo, "告警设备占比");
                        systemData.put("bing2", pieChart1);
                    } else {
                        List<Map<String, Object>> data = new ArrayList<>();
                        HashMap<String, Object> dataMap = new HashMap<>();
                        dataMap.put("type", "火警");
                        dataMap.put("value", 0);
                        data.add(dataMap);
                        String pieChart1 = ChartsUtils.pieChart(data, "报警趋势");
                        systemData.put("bing2", pieChart1);
                    }


                    if (!CollectionUtils.isEmpty(selectMonthPolyline)) {
                        String pieChart2 = ChartsUtils.manyLineChart(selectMonthPolyline, "报警趋势", "日期", "报警数量", "month");
                        systemData.put("bing3", pieChart2);
                    } else {
                        systemData.put("bing3", "");
                    }

                    systemList.add(systemData);
                    map.put("datalist", systemList);
                }

            }


        }else {
            return null;
        }


        return map;
    }

    private static byte[] file2byte(File file) {
        try {
            FileInputStream in = new FileInputStream(file);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String iotMonthReport(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> DataMap = getData(bizOrgCode, startDate, endDate);
        if (DataMap == null){
            return null ;
        }
        WordTemplateUtils instance = WordTemplateUtils.getInstance();
        String pdfUrlString = "";
        File filepdf = null;
        try {
            filepdf = instance.getWordFileItem(DataMap, null, WordTemplateTypeEum.iotMonthReport.getTemplateFile());
            filepdf.getAbsolutePath();
            Token token = remoteSecurityService.getServerToken();
            RequestContext.setToken(token.getToke());
            RequestContext.setProduct(token.getProduct());
            RequestContext.setAppKey(token.getAppKey());
            MultipartFile multipartFile = new MyByteArrayMultipartFile("file", "file.pdf", "application/pdf", file2byte(filepdf));
            FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
            if (result != null) {
                Iterator<String> it = result.getResult().keySet().iterator();
                while (it.hasNext()) {
                    pdfUrlString = it.next();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (filepdf != null) {
                filepdf.delete();
            }
        }

        try {
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUrl(pdfUrlString);
            uploadFile.setFileType("image");
            uploadFile.setObjectType("m-report");
            long time = DateUtils.longStr2Date(startDate+" 00:00:00").getTime();
            uploadFile.setObjectId(time);
            uploadFile.setName("换流站月总结分析报告");
            uploadFile.setDepartmentOrgcode(bizOrgCode);
            iUploadFileService.save(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pdfUrlString;

    }

    private Map<String, Object> getWeekData(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> map = new HashMap<>();
        // 查询该站信息以及所有系统
        List<Map<String, Object>> systemList = fireFightingSystemMapper.selectSystemByBizOrgCode(bizOrgCode);
        String json = null;
        try {
            json = IOUtils.toString(systemIndex.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 系统对应指标配置
        List<Map> indicatorConfiguration = JSONObject.parseArray(json, Map.class);

        // 一周内所有系统情况
        if (!CollectionUtils.isEmpty(systemList)) {
            // 换流站信息
            if (!ObjectUtils.isEmpty(systemList.get(0).get("stationName"))) {
                map.put("station", systemList.get(0).get("stationName"));
            } else {
                map.put("station", "");
            }
            map.put("time", startDate + "至" + endDate);
            // 系统循环数据填充
            ArrayList<Map<String, Object>> dataList = new ArrayList<>();
            for (Map<String, Object> system : systemList) {
                HashMap<String, Object> systemData = new HashMap<>();
                List<Map> collect = indicatorConfiguration.stream().
                        filter(item -> item.get("code").equals(String.valueOf(system.get("typeCode")))).collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(collect)) {
                    // 系统名称
                    systemData.put("systemName", ObjectUtils.isEmpty(system.get("name")) ? "" : String.valueOf(system.get("name")));

                    // 系统对应指标
                    String indicator = String.valueOf(collect.get(0).get("index"));
                    String[] split = indicator.split(",");
                    List<String> indicatorList = Arrays.asList(split);
                    List<Map<String, Object>> weekReportList = fireFightingSystemMapper.selectWeekReportList(String.valueOf(system.get("id")), startDate, endDate);
                    ArrayList<Map<String, Object>> list = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(weekReportList)) {
                        for (Map<String, Object> weekItem : weekReportList) {
                            HashMap<String, Object> listItem = new HashMap<>();
                            // 设备类型
                            listItem.put("name", ObjectUtils.isEmpty(weekItem.get("name")) ? "" : String.valueOf(weekItem.get("name")));
                            // 设备总数
                            listItem.put("num", ObjectUtils.isEmpty(weekItem.get("num")) ? "" : String.valueOf(weekItem.get("num")));
                            // 无异常设备总数
                            listItem.put("normalNum", ObjectUtils.isEmpty(weekItem.get("normalNum")) ? "" : String.valueOf(weekItem.get("normalNum")));
                            // 物联指标
                            listItem.put("type_name", ObjectUtils.isEmpty(weekItem.get("type_name")) ? "" : String.valueOf(weekItem.get("type_name")));
                            // 监测数据
                            listItem.put("monitoringData", ObjectUtils.isEmpty(weekItem.get("monitoringData")) ? "" : String.valueOf(weekItem.get("monitoringData")));
                            // 获取方式
                            listItem.put("acquisition", ObjectUtils.isEmpty(weekItem.get("acquisition")) ? "" : String.valueOf(weekItem.get("acquisition")));
                            // 正常标准
                            listItem.put("normal", ObjectUtils.isEmpty(weekItem.get("normal")) ? "" : String.valueOf(weekItem.get("normal")));
                            // 7日告警设备数
                            if (!ObjectUtils.isEmpty(weekItem.get("type_code")) && !ObjectUtils.isEmpty(weekItem.get("code"))) {
                                Integer integer = fireFightingSystemMapper.selectWeekAlarmsEquip(valueOf(system.get("id")), valueOf(weekItem.get("type_code")), valueOf(weekItem.get("code")), startDate, endDate, String.valueOf(weekItem.get("type_code")));
                                listItem.put("alarmEquipNum", String.valueOf(integer));
                            } else {
                                listItem.put("alarmEquipNum", String.valueOf(0));
                            }
                           // listItem.put("alarmEquipNum", ObjectUtils.isEmpty(weekItem.get("alarmEquipNum")) ? "" : String.valueOf(weekItem.get("alarmEquipNum")));
                            // 7日告警条数
                            if (!ObjectUtils.isEmpty(weekItem.get("type_code")) && !ObjectUtils.isEmpty(weekItem.get("code"))) {
                                Integer integer = fireFightingSystemMapper.selectAlarms(valueOf(system.get("id")), valueOf(weekItem.get("type_code")), valueOf(weekItem.get("code")), startDate, endDate, indicatorList);
                                listItem.put("trueNum", String.valueOf(integer));
                            } else {
                                listItem.put("trueNum", String.valueOf(0));
                            }
                            list.add(listItem);
                        }
                    } else {
                        HashMap<String, Object> listItem = new HashMap<>();
                        listItem.put("name", "");
                        listItem.put("num", "");
                        listItem.put("normalNum", "");
                        listItem.put("type_name", "");
                        listItem.put("monitoringData", "");
                        listItem.put("acquisition", "");
                        listItem.put("normal", "");
                        listItem.put("alarmEquipNum", "");
                        listItem.put("trueNum", "");
                        list.add(listItem);
                    }

                    // 总结
                    Map<String, Object> summarize = fireFightingSystemMapper.selectWeekSummarize(valueOf(system.get("id")), startDate, endDate, indicatorList);
//                    if (!ObjectUtils.isEmpty(summarize.get("contant"))) {
//                        systemData.put("summarize", String.valueOf(summarize.get("contant")));
//                    } else {
//                        systemData.put("summarize", "");
//                    }
                    systemData.put("summarize", ObjectUtils.isEmpty(summarize.get("name"))?0:summarize.get("name")
                            +"设备总数"+(ObjectUtils.isEmpty(summarize.get("equipNum"))?0:summarize.get("equipNum"))
                            +"台，正常设备"+(ObjectUtils.isEmpty(summarize.get("normalNum"))?0:summarize.get("normalNum"))
                            +"台，正常率"+(ObjectUtils.isEmpty(summarize.get("normalRate"))?0:summarize.get("normalRate"))
                            +"%，故障设备"+(ObjectUtils.isEmpty(summarize.get("faultNum"))?0:summarize.get("faultNum"))
                            +"台，故障率为"+(ObjectUtils.isEmpty(summarize.get("faultRate"))?0:summarize.get("faultRate"))
                            +"%，七日告警设备为"+(ObjectUtils.isEmpty(summarize.get("exepctionNum"))?0:summarize.get("exepctionNum"))
                            +"台，同比上周"+(ObjectUtils.isEmpty(summarize.get("status1"))?"增加":summarize.get("status1"))+(ObjectUtils.isEmpty(summarize.get("exepctionWOW"))?0:summarize.get("exepctionWOW"))
                            +"%，七日告警总数为"+(ObjectUtils.isEmpty(summarize.get("alarmNum"))?0:summarize.get("alarmNum"))
                            +"条，同比上周"+(ObjectUtils.isEmpty(summarize.get("status2"))?"增加":summarize.get("status2"))+(ObjectUtils.isEmpty(summarize.get("alarmWOW"))?0:summarize.get("alarmWOW"))
                            +"%。"
                    );


                    // echarts 图表
                    //List<Map<String, Object>> mapList = fireFightingSystemMapper.selectWeekEquipEchart(valueOf(system.get("code")), startDate, endDate, indicatorList);

                    ArrayList<Map<String, Object>> mapList = new ArrayList<>();
                    HashMap<String, Object> dayEchartsDate = new HashMap<>();
                    dayEchartsDate.put("type","正常设备");
                    dayEchartsDate.put("value",ObjectUtils.isEmpty(summarize.get("normalNum"))?0:summarize.get("normalNum"));
                    mapList.add(dayEchartsDate);
                    HashMap<String, Object> dayEchartsDate1 = new HashMap<>();
                    dayEchartsDate1.put("type","异常设备");
                    if (!ObjectUtils.isEmpty(summarize.get("equipNum")) || !ObjectUtils.isEmpty(summarize.get("normalNum"))){
                        dayEchartsDate1.put("value",Integer.parseInt(String.valueOf(summarize.get("equipNum")))
                                -Integer.parseInt(String.valueOf(summarize.get("normalNum"))));
                    }else {
                        dayEchartsDate1.put("value",0);
                    }
                    mapList.add(dayEchartsDate1);
                    String pieChart1 = ChartsUtils.pieChart(mapList, "告警设备占比");
                    systemData.put("pictureLeft", pieChart1);

                    List<Map<String, Object>> weekEchart = fireFightingSystemMapper.selectWeekEchart(valueOf(system.get("code")), startDate, endDate);
                    String pieChart2 = ChartsUtils.pieChart(weekEchart, "故障设备类型占比");
                    systemData.put("pictureCenter", pieChart2);

                    List<Map<String, Object>> linesEchart = fireFightingSystemMapper.selectWeekLinesEchart(valueOf(system.get("code")), startDate, endDate, indicatorList);
                    String lines = ChartsUtils.manyLineChart(linesEchart, "报警趋势", "日期", "报警数量", "week");
                    systemData.put("lines", lines);

                    systemData.put("sysData", list);
                    dataList.add(systemData);
                    map.put("data", dataList);
                }

            }

        }else {
           return null;
        }


        return map;
    }

    @Override
    public String iotWeekReport(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> dataMap = getWeekData(bizOrgCode, startDate, endDate);
        if (dataMap == null) {
            return null;
        }
        WordTemplateUtils instance = WordTemplateUtils.getInstance();
        String pdfUrlString = "";
        File filepdf = null;
        try {
            filepdf = instance.getWordFileItem(dataMap, null, WordTemplateTypeEum.iotWeekReport.getTemplateFile());
            filepdf.getAbsolutePath();
            Token token = remoteSecurityService.getServerToken();
            RequestContext.setToken(token.getToke());
            RequestContext.setProduct(token.getProduct());
            RequestContext.setAppKey(token.getAppKey());
            MultipartFile multipartFile = new MyByteArrayMultipartFile("file", "file.pdf", "application/pdf", file2byte(filepdf));
            FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
            if (result != null) {
                Iterator<String> it = result.getResult().keySet().iterator();
                while (it.hasNext()) {
                    pdfUrlString = it.next();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (filepdf != null) {
                filepdf.delete();
            }
        }
        try {
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUrl(pdfUrlString);
            uploadFile.setFileType("image");
            uploadFile.setObjectType("w-report");
            long time = DateUtils.longStr2Date(startDate+" 00:00:00").getTime();
            uploadFile.setObjectId(time);
            uploadFile.setName("换流站周总结分析报告");
            uploadFile.setDepartmentOrgcode(bizOrgCode);
            iUploadFileService.save(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfUrlString;
    }

    private Map<String, Object> getDayData(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> map = new HashMap<>();
        // 查询该站信息以及所有系统
        List<Map<String, Object>> systemList = fireFightingSystemMapper.selectSystemByBizOrgCode(bizOrgCode);
        String json = null;
        try {
            json = IOUtils.toString(systemIndex.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 系统对应指标配置
        List<Map> indicatorConfiguration = JSONObject.parseArray(json, Map.class);

        if (!CollectionUtils.isEmpty(systemList)) {
            // 换流站信息
            if (!ObjectUtils.isEmpty(systemList.get(0).get("stationName"))) {
                map.put("station", systemList.get(0).get("stationName"));
            } else {
                map.put("station", "");
            }
            map.put("time", startDate);
            // 系统循环数据填充
            ArrayList<Map<String, Object>> dataList = new ArrayList<>();
            for (Map<String, Object> system : systemList) {
                HashMap<String, Object> systemData = new HashMap<>();
                List<Map> collect = indicatorConfiguration.stream().
                        filter(item -> item.get("code").equals(String.valueOf(system.get("typeCode")))).collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(collect)) {
                    // 系统名称
                    systemData.put("systemName", ObjectUtils.isEmpty(system.get("name")) ? "" : String.valueOf(system.get("name")));

                    // 系统对应指标
                    String indicator = String.valueOf(collect.get(0).get("index"));
                    String[] split = indicator.split(",");
                    List<String> indicatorList = Arrays.asList(split);
                    List<Map<String, Object>> weekReportList = fireFightingSystemMapper.selectWeekReportList(String.valueOf(system.get("id")), startDate, endDate);
                    ArrayList<Map<String, Object>> list = new ArrayList<>();
                    ArrayList<Map<String, Object>> alarmMapList = new ArrayList<>();
                    Map<String, Object> binMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(weekReportList)) {
                        for (Map<String, Object> weekItem : weekReportList) {
                            HashMap<String, Object> listItem = new HashMap<>();
                            // 设备类型
                            listItem.put("name", ObjectUtils.isEmpty(weekItem.get("name")) ? "" : String.valueOf(weekItem.get("name")));
                            // 设备总数
                            listItem.put("num", ObjectUtils.isEmpty(weekItem.get("num")) ? "" : String.valueOf(weekItem.get("num")));
                            // 无异常设备总数
                            listItem.put("normalNum", ObjectUtils.isEmpty(weekItem.get("normalNum")) ? "" : String.valueOf(weekItem.get("normalNum")));
                            // 物联指标
                            listItem.put("type_name", ObjectUtils.isEmpty(weekItem.get("type_name")) ? "" : String.valueOf(weekItem.get("type_name")));
                            // 监测数据
                            listItem.put("monitoringData", ObjectUtils.isEmpty(weekItem.get("monitoringData")) ? "" : String.valueOf(weekItem.get("monitoringData")));
                            // 获取方式
                            listItem.put("acquisition", ObjectUtils.isEmpty(weekItem.get("acquisition")) ? "" : String.valueOf(weekItem.get("acquisition")));
                            // 正常标准
                            listItem.put("normal", ObjectUtils.isEmpty(weekItem.get("normal")) ? "" : String.valueOf(weekItem.get("normal")));
                            // 日告警设备数
                            listItem.put("alarmEquipNum", ObjectUtils.isEmpty(weekItem.get("alarmEquipNum")) ? "" : String.valueOf(weekItem.get("alarmEquipNum")));
                            // 日告警条数
                            if (!ObjectUtils.isEmpty(weekItem.get("type_code")) && !ObjectUtils.isEmpty(weekItem.get("code"))) {
                                Integer integer = fireFightingSystemMapper.selectAlarms(valueOf(system.get("id")), valueOf(weekItem.get("type_code")), valueOf(weekItem.get("code")), startDate, endDate, indicatorList);
                                listItem.put("trueNum", String.valueOf(integer));
                            } else {
                                listItem.put("trueNum", String.valueOf(0));
                            }
                            if (!ObjectUtils.isEmpty(weekItem.get("type_code")) && String.valueOf(weekItem.get("type_code")).endsWith("Fault")){
                                if (!ObjectUtils.isEmpty(binMap) && !ObjectUtils.isEmpty(listItem.get("name")) && binMap.containsKey(String.valueOf(listItem.get("name")))){
                                    int newValue = Integer.parseInt(String.valueOf(listItem.get("alarmEquipNum")));
                                    int oldValue = Integer.parseInt(String.valueOf(binMap.get(String.valueOf(listItem.get("name")))));
                                    binMap.put(String.valueOf(listItem.get("name")),newValue + oldValue);
                                }else {
                                    binMap.put(String.valueOf(listItem.get("name")),listItem.get("alarmEquipNum"));
                                }

                            }
                            list.add(listItem);
                        }
                        ArrayList<String> strings = new ArrayList<>(binMap.keySet());
                        for (String string : strings) {
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("type", string);
                            hashMap.put("value", binMap.get(string));
                            alarmMapList.add(hashMap);
                        }

                    } else {
                        HashMap<String, Object> listItem = new HashMap<>();
                        listItem.put("name", "");
                        listItem.put("num", "");
                        listItem.put("normalNum", "");
                        listItem.put("type_name", "");
                        listItem.put("monitoringData", "");
                        listItem.put("acquisition", "");
                        listItem.put("normal", "");
                        listItem.put("alarmEquipNum", "");
                        listItem.put("trueNum", "");
                        list.add(listItem);
                    }

                    // 总结
                    Map<String, Object> summarize = fireFightingSystemMapper.selectDaySummarize(valueOf(system.get("id")), startDate, endDate, indicatorList);
//                    if (!ObjectUtils.isEmpty(summarize.get("contant"))) {
//                        systemData.put("summarize", String.valueOf(summarize.get("contant")));
//                    } else {
//                        systemData.put("summarize", "");
//                    }
                    systemData.put("summarize", ObjectUtils.isEmpty(summarize.get("name"))?0:summarize.get("name")+"设备总数"+(ObjectUtils.isEmpty(summarize.get("equipNum"))?0:summarize.get("equipNum"))
                    +"台，今日告警设备为"+(ObjectUtils.isEmpty(summarize.get("dayNum"))?0:summarize.get("dayNum"))+"台，告警总数为"+(ObjectUtils.isEmpty(summarize.get("alarmNum"))?0:summarize.get("alarmNum"))+
                            "条，正常设备"+(ObjectUtils.isEmpty(summarize.get("normalNum"))?0:summarize.get("normalNum"))+"台，正常率"+(ObjectUtils.isEmpty(summarize.get("normalRate"))?0:summarize.get("normalRate"))+"%");

                    // echarts 图表
                    List<Map<String, Object>> mapList = fireFightingSystemMapper.selectDayEquipEchart(valueOf(system.get("code")), startDate, endDate);
                    String pieChart1 = ChartsUtils.pieChart(alarmMapList, "故障设备类型占比");

                   // List<Map<String, Object>> dayEcharts = fireFightingSystemMapper.selectDayEchart(valueOf(system.get("id")), startDate, indicatorList);
                    ArrayList<Map<String, Object>> dayEchart = new ArrayList<>();
                    HashMap<String, Object> dayEchartsDate = new HashMap<>();
                    dayEchartsDate.put("type","正常设备");
                    dayEchartsDate.put("value",ObjectUtils.isEmpty(summarize.get("normalNum"))?0:summarize.get("normalNum"));
                    dayEchart.add(dayEchartsDate);
                    HashMap<String, Object> dayEchartsDate1 = new HashMap<>();
                    dayEchartsDate1.put("type","异常设备");
                    if (!ObjectUtils.isEmpty(summarize.get("equipNum")) || !ObjectUtils.isEmpty(summarize.get("normalNum"))){
                        dayEchartsDate1.put("value",Integer.parseInt(String.valueOf(summarize.get("equipNum")))
                                -Integer.parseInt(String.valueOf(summarize.get("normalNum"))));
                    }else {
                        dayEchartsDate1.put("value",0);
                    }

                    dayEchart.add(dayEchartsDate1);
                    String pieChart2 = ChartsUtils.pieChart(dayEchart, "告警设备占比");
                    systemData.put("pictureRight", pieChart1);
                    systemData.put("pictureLeft", pieChart2);


                    systemData.put("sysData", list);
                    dataList.add(systemData);
                    map.put("data", dataList);
                }

            }

        }else {
            return null ;
        }


        return map;
    }

    @Override
    public String iotDayReport(String bizOrgCode, String startDate, String endDate) {
        Map<String, Object> dataMap = getDayData(bizOrgCode, startDate, endDate);
        if (dataMap == null){
            return null;
        }
        WordTemplateUtils instance = WordTemplateUtils.getInstance();
        String pdfUrlString = "";
        File filepdf = null;
        try {
            filepdf = instance.getWordFileItem(dataMap, null, WordTemplateTypeEum.iotDayReport.getTemplateFile());
            filepdf.getAbsolutePath();
            Token token = remoteSecurityService.getServerToken();
            RequestContext.setToken(token.getToke());
            RequestContext.setProduct(token.getProduct());
            RequestContext.setAppKey(token.getAppKey());
            MultipartFile multipartFile = new MyByteArrayMultipartFile("file", "file.pdf", "application/pdf", file2byte(filepdf));
            FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
            if (result != null) {
                Iterator<String> it = result.getResult().keySet().iterator();
                while (it.hasNext()) {
                    pdfUrlString = it.next();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (filepdf != null) {
                filepdf.delete();
            }
        }
        try {
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUrl(pdfUrlString);
            uploadFile.setFileType("image");
            uploadFile.setObjectType("d-report");
            long time = DateUtils.longStr2Date(startDate+" 00:00:00").getTime();
           // DateUtils.getCurrentDayStartTime(new Date()).getTime();
            uploadFile.setObjectId(time);
            uploadFile.setName("换流站日总结分析报告");
            uploadFile.setDepartmentOrgcode(bizOrgCode);
            iUploadFileService.save(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfUrlString;
    }

    @Override
    public Page<Map<String, Object>> getWaterInfo(Page page, String companyCode, String systemCode) {
        String bizOrgCode = null;
        if (StringUtil.isNotEmpty(companyCode)) {
            bizOrgCode = fireFightingSystemMapper.queryByCompanyCode(companyCode);
        }
        return fireFightingSystemMapper.getWaterInfo(page, bizOrgCode, null);
    }

    @Override
    public Page<Map<String, Object>> getSystemInfo(Page page, String companyCode, String systemCode) {
        String bizOrgCode = null;
        if (StringUtil.isNotEmpty(companyCode)) {
            bizOrgCode = fireFightingSystemMapper.queryByCompanyCode(companyCode);
        }
        return fireFightingSystemMapper.getSystemInfo(page, bizOrgCode, null);
    }

    @Override
    public List<Map<String, Object>> getEquipExpiryStatistics(String bizOrgCode, Integer expiryDayNum) {
        List<Map<String, Object>> equipExpiryStatistics = fireFightingSystemMapper.getEquipExpiryStatistics(bizOrgCode, expiryDayNum);
        equipExpiryStatistics.forEach(item -> {
            item.put("value", Integer.parseInt(item.get("value").toString()));
        });
        return equipExpiryStatistics;
    }

    @Override
    public Page<Map<String, String>> getEquipExpiryListByPage(String bizOrgCode, Integer expiryDayNum, Page page) {
        return fireFightingSystemMapper.getEquipExpiryListByPage(page, bizOrgCode, expiryDayNum);
    }

    @Override
    public List<Map<String, Integer>> getStockEquipStatistics(String bizOrgCode) {
        return fireFightingSystemMapper.getStockEquipStatistics(bizOrgCode);
    }

    @Override
    public List<Map<String, Object>> getSystemInfoList() {
        List<Map<String, Object>> list = fireFightingSystemMapper.getSystemInfoList();
        if (0 < list.size()) {
            list.forEach(x -> {
                List<Map<String, Object>> list1 = new ArrayList();
                Map<String, Object> map = new HashMap<>();
                map.put("name", x.get("status"));
                if ("正常".equals(String.valueOf(x.get("status")))) {
                    map.put("level", "success");
                } else {
                    map.put("level", "failure");
                }
                list1.add(map);
                x.put("status", list1);
            });
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getSystemAlarmInfoList(String startDate, String endDate) {
        if (!StringUtil.isNotEmpty(startDate)) {
            startDate = null;
        }
        if (!StringUtil.isNotEmpty(endDate)) {
            endDate = null;
        }
        return fireFightingSystemMapper.getSystemAlarmInfoList(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getSystemRunningInfoList() {
        Map<String, Object> totalMap = fireFightingSystemMapper.getSystemCountInfo();
        Map<String, Object> alarmNumMap = fireFightingSystemMapper.getSystemRunningInfoList();
        String json = null;
        try {
            json = IOUtils.toString(systemCode.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> mapList = JSONObject.parseArray(json, Map.class);
        Map<String, Object> map = new HashMap<>();
        mapList.forEach(x -> map.put(String.valueOf(x.get("nameKey")), x.get("code")));
        List<Map<String, Object>> list = new ArrayList<>();
        mapList.forEach(y -> {
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("name", y.get("name"));
            tempMap.put("code", y.get("code"));
            tempMap.put("total", totalMap.get(y.get("code")));
            tempMap.put("alarmNum", alarmNumMap.get(y.get("code")));
            list.add(tempMap);
        });
        return list;
    }

    @Override
    public Page<FireFightingSystemDto> fireSysRunStatusPage(Page<Map<String, Object>> page, String bizOrgCode) {
        //  消防系统物联部件统计
        Page<FireFightingSystemDto> pages = equipmentSpecificSerivce.fireSysIotEquipCount(page, bizOrgCode);
        List<FireFightingSystemDto> records = pages.getRecords();
        //  系统状态及今日告警设备统计
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> idList = records.stream().map(FireFightingSystemDto::getId).collect(Collectors.toList());
            List<FireFightingSystemDto> list = equipmentSpecificSerivce.fireSysIotEquipAlarmCount(new Date(), bizOrgCode);
            if (!CollectionUtils.isEmpty(list)) {
                //使用stream流把list1和list2根据属性userId合并一个list集合，并根据状态倒序、系统排序升序
                List<FireFightingSystemDto> collect = records.stream().peek(m -> list.stream().filter(m2 -> Objects.equals(m.getId(), m2.getId())).forEach(m2 -> {
                    m.setAlarmEquipTotal(m2.getAlarmEquipTotal());
                    m.setStatus(m2.getStatus());
                })).sorted(Comparator.comparing(FireFightingSystemDto::getStatus, Comparator.reverseOrder())
                        .thenComparing(FireFightingSystemDto::getSort)).collect(Collectors.toList());
                pages.setRecords(collect);
            }
        }
        return pages;
    }

    @Override
    public List<OrgMenuDto> systemAndEquipmentTreeByBziOrgCode() {
        FeignClientResult<List<OrgUsrDto>> feignClientResult = jcsFeignClient.getCompanyDeptListWithAuth(authKey, "COMPANY", "dl");
        String bizOrgCode = feignClientResult.getResult().get(0).getBizOrgCode();
        List<Map<String, Object>> list = fireFightingSystemMapper.systemAndEquipment(bizOrgCode);
        return systemAndEquipmentTree(list);
    }

    @Override
    public Map<String,Object> getSystemDetailByCode(String systemCode) {
        Map<String,Object> map = new HashMap<>();
        LambdaQueryWrapper<FireFightingSystemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FireFightingSystemEntity::getCode, systemCode);
        List<FireFightingSystemEntity> systemEntities = this.list(wrapper);
        if (systemEntities.isEmpty()) {
            // throw new RuntimeException("code" + systemCode + "不存在");
            map.put("isExist", false);
            return map;
        }
        map.put("isExist", true);
        if (systemEntities != null) {
            FireFightingSystemVo fireFightingSystemVo = fireFightingSystemMapper.getFightingSysInfo(systemEntities.get(0).getCode(), systemEntities.get(0).getId());
            map.put("systemStatus", "异常".equals(fireFightingSystemVo.getStatus()) ? false : true);
        } else {
            map.put("systemStatus", true);
        }
        map.put("name",systemEntities.get(0).getName());
        map.put("code",systemEntities.get(0).getCode());
        map.put("installDate",systemEntities.get(0).getInstallDate());
        map.put("chargePersonPhone",systemEntities.get(0).getChargePersonPhone());
        map.put("chargePersonName",systemEntities.get(0).getChargePersonName());
        map.put("designOrg",systemEntities.get(0).getDesignOrg());
        map.put("designOrgTelephone",systemEntities.get(0).getDesignOrgTelephone());
        map.put("leadDesigner",systemEntities.get(0).getLeadDesigner());
        Long num = this.baseMapper.selectEquipCountBySystemId(systemEntities.get(0).getId());
        String systemType = this.baseMapper.selectEquipSystemType(systemCode);
        map.put("systemType",systemType);
        map.put("num",num);
        return map;
    }

    public static List<OrgMenuDto> systemAndEquipmentTree(List<Map<String,Object>> list) {

        List<OrgMenuDto> menuList = list.stream()
                .map(o -> new OrgMenuDto(Long.parseLong(o.get("id").toString()), o.get("name").toString(),
                        ObjectUtils.isEmpty(o.get("parentId")) ? 0L : Long.parseLong(o.get("parentId").toString()),
                        ObjectUtils.isEmpty(o.get("code")) ? "": o.get("code").toString(),
                        false, o.get("bizOrgCode").toString()))
                .collect(Collectors.toList());
        List<OrgMenuDto> result = new ArrayList<>();
        Map<Long, OrgMenuDto> map = new HashMap<>(menuList.size());
        menuList.forEach(e -> map.put(e.getKey(), e));
        Set<? extends Map.Entry<Long, ? extends OrgMenuDto>> entries = map.entrySet();
        // 此处多线程，会value 出现null 的情况
        // entries.parallelStream().forEach(entry -> {
        entries.forEach(entry -> {
            OrgMenuDto value = entry.getValue();
            if (value != null) {
                OrgMenuDto treeDto = map.get(value.getParentId());
                if (treeDto != null) {
                    List<OrgMenuDto> children = treeDto.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        treeDto.setChildren(children);
                    }

                    children.add(value);
                } else {
                    result.add(value);
                }
            }
        });
        return result;
    }


    @Override
    public Map<String, Object> getStationConnectStatus() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> resultMap = fireFightingSystemMapper.getStationConnectStatus();
        map.put("online", resultMap.get("online"));
        map.put("notOnline", resultMap.get("notOnline"));
        return map;
    }

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

}
