projectMap.js 13.7 KB

let action = null;
let mapObj = null;
var app = null;

layui.config({
    base: "/js/",
    version: 1
}).use(['system'], function () {
    var form = layui.form,
        $ = layui.jquery,
        element = layui.element,
        table = layui.table,
        system = layui.system,
        laypage = layui.laypage,
        sentData = {
            page: 1,
            limit: 20,
            isPage: true
        },
        sysU = new system.u(),
        sendDataWhere = null,
        areaName = "configure",
        controllerName = "BaseProject",
        sysNowClickEle = -1;
    vueApp = null;

    action = {

    }

    app = {
        data: {
            mapEle: "container",
            refreshDataTimeEle: document.getElementById('refreshDataTime'),
            clicktaberightEle: document.getElementById('xiangmu'),
            timeoutTime: null,
           
            projectData: null
        },
        methods: {
            /**
              * 初始化地图
             */
            initMap() {
                try {
                    mapObj = mapApp(app.data.mapEle).initMap();
                } catch (e) {
                    mapObj = null;
                    layer.alert(`百度地图加载失败!请确认本地电脑能否浏览外网(https://map.baidu.com),或者有VPN操作设置。错误原因: ${e.message}`, { icon: sysU.config.iconoError, shade: 0.4, time: sysU.config.errorTime });
                }
            },

            /**
              * 获取项目数据
             */
            getProjectDataList() {
                var ajaxConfig = {
                    data: null,
                    url: `/configure/BaseProject/GetProjectMapList`,
                    loading: false,
                    success: function (result) {
                      
                        if (sysU.successBefore(result)) return false;
                        if (mapObj == null) return;
                        result.Result.list = result.Result.list.uniqueFunc("projectCode")
                        app.methods.createMarkerInfo(result);
                        app.methods.initVueDataValue(result);
                         
                        app.methods.createSidebarList(result);
                        app.methods.initPagination(result.sumEqCount);


                        if (sysNowClickEle != -1) {
                            $("#a_" + sysNowClickEle).click().css("color", "#42b983");
                        }
                    }
                };
                sysU.ajax(ajaxConfig);
            },
            /**
              * 创建marker标注
             */
            createMarkerInfo(json) {
                let index = 1
                json.Result.list.forEach(item => {
                    var content = `<h4 style = 'margin:0;'>地址:${item.projectAddress}</h4>
                                     设备总数:${item.eqCount}
                                     运行:<span style='color:blue;'>${item.eqRunCount}</span>
                                     待机:${item.eqFreeCount}
                                     故障:${item.eqFailureCount}<br/>
                                     离线(5m):<span style='color:red;'>${item.eqOfflineCount}</span> &nbsp;&nbsp;
                                     <span style='color:red;font-weight:bold'>${item.isHaveAlarm ? "有未处理报警" : ""}</span>
                                     <span style='color:red;font-weight:bold'>${item.isHaveMaintain ? "有待保养设备" : ""}</span>
                                   <div style = 'display: flex;' >
                                      <div><a style='text-decoration: underline;color: blue;' onclick='app.methods.projectOverviewClick(${JSON.stringify(item)})'  href='#'>项目概述</a></div>
                                      <div><a style='text-decoration: underline;color: blue;margin-left:12px' onclick='app.methods.projectAreasMapClick(${JSON.stringify(item)})'  href='#'>设备区域图</a></div>
                                   </div >` ;//定义大标题  html语句标签
                    mapObj.createMarkerInfo(content, {
                        title: `项目名称[${index++}]:` + item.projectName,
                        longitude: item.longitude,
                        latitude: item.latitude,
                        id: item.id
                    });
                })

                //设置默认选择的地图定位的项目
                setTimeout(() => {
                    var defaultSelectProjectId = localStorage.getItem("defaultSelectProjectId");
                    if (defaultSelectProjectId) {
                        $("#a_" + defaultSelectProjectId).click().css("color", "#42b983");
                    }
                }, 200)
            },
            //项目概述点击
            projectOverviewClick(item) {
                var title = "项目概述";
                localStorage.setItem("projectMapKeys", item.keys);
                localStorage.setItem("projectMapName", item.projectName);
                localStorage.setItem("projectCode", item.projectCode);
                var tabsEle = window.parent.document.querySelectorAll("#top_tabs cite");
                for (var i = 0; i < tabsEle.length; i++) {
                    if (tabsEle[i].innerText == title) {
                        $(tabsEle[i]).next().click()
                        break;
                    }
                }

                var url = `/configure/BaseProject/ProjectOverview?id=${item.id}&keys=${item.keys}&projectName=${item.projectName}&projectCode=${item.projectCode}`;
                var urlHtml = $(`<a title="${title}"  data-url="${url}"><i class="layui-icon" data-icon=""></i><cite>${title}</cite></a>`)
                window.top.tab.tabAdd(urlHtml);
            },
            //项目区域图点击
            projectAreasMapClick(item) {
                var title = "项目设备区域图";
                localStorage.setItem("projectMapKeys", item.keys);
                localStorage.setItem("projectMapName", item.projectName);
                localStorage.setItem("projectCode", item.projectCode);
                var tabsEle = window.parent.document.querySelectorAll("#top_tabs cite");
                for (var i = 0; i < tabsEle.length; i++) {
                    if (tabsEle[i].innerText == title) {
                        $(tabsEle[i]).next().click();
                        break;
                    }
                }
                debugger
                var url = `/configure/BaseProject/ProjectEqAreaView?id=${item.id}&keys=${item.keys}&projectName=${item.projectName}&projectCode=${item.projectCode}`;
                var urlHtml = $(`<a title="${title}" data-url="${url}"><i class="layui-icon" data-icon=""></i><cite>${title}</cite></a>`);
                window.top.tab.tabAdd(urlHtml);
            },
            /**
              * 创建右侧项目列表
             */
            createSidebarList(json) {
                var sidebarList = [];
                var index = 1;
                this.projectData = json.Result.list

                json.Result.list.forEach(item => {
                    var content = `<dd><a id='a_${item.id}' title='${item.projectName}' class='projectListA'   onclick='app.methods.findLocateMarker(${item.id.toString()},event)' href="javascript:;">${index++}${item.projectName} </a></dd>`;//定义大标题  写html语句标签
                    sidebarList.push(content)
                })
                if (sidebarList.length > 0) {
                    $(".sidebar-list-item").empty().append(sidebarList.join(" "))
                }
            },
            //分页初始化
            initPagination(sumEqCount) {
              
                laypage.render({
                    elem: 'pagination', 
                    count: 100,
                    limit: 10,
                    jump: function (obj, first) {
                        console.log(obj.curr); // 得到当前页,以便向服务端请求对应页的数据。
                        console.log(obj.limit); // 得到每页显示的条数
                        if (!first) {
                            fetchData(obj.curr);
                        }
                    }
                });
            },
            /**
              * 查找Marker并打开对应的infoWindow信息框
             */
            findLocateMarker(markerId, event) {
                mapObj.getLocateMarker(markerId);
                sysNowClickEle = markerId;
                $(".projectListA").css("color", "rgba(255, 255, 255, .7)")
                $(event.currentTarget).css("color", "#42b983")
                localStorage.setItem("defaultSelectProjectId", markerId);
              
            },
            /** 
              * 初始化vue
              */
            initVue: function () {
                vueApp = new Vue({
                    el: '.vueApp',
                    data: {
                        footer: {
                            projectCount: 0,
                            eqCount: 0,
                            eqOnlineRate: ""
                        }
                    },
                    methods: {

                    }
                });
            },
            /**
              * vue 集合赋值
              */
            initVueDataValue: (result) => {
                var res = result.Result;
                vueApp.footer.projectCount = res.list.length;//项目总数
                vueApp.footer.eqCount = res.sumEqCount;//设备总数
                vueApp.footer.eqOnlineRate = res.onlineRate;//在线率
            },

            refreshDataMethod: function () {
                const tabsEle = Array.from(window.parent.document.querySelectorAll("#top_tabs .layui-this"));
                const isOK = tabsEle.some(tab => tab.innerText === "项目地图");
                if (!isOK) return;

                let currenttime = parseInt(app.data.refreshDataTimeEle.innerHTML);
                if (currenttime === 0) {
                    currenttime = 20;
                    app.methods.getProjectDataList();
                } else {
                    currenttime--;
                }
                app.data.refreshDataTimeEle.innerHTML = currenttime;
            },

            // 控制项目列表输入框
            clicktaberightEleMethod: function () {
                const inputField = app.data.clicktaberightEle;
                if (inputField.style.display === 'none') {
                    inputField.style.display = 'block';
                } else {
                    inputField.style.display = 'none';
                } 
            },

            // 项目列表-支持模糊查询
            debouncedCheckInputValue: function () {
                clearTimeout(this.timeoutTime);
                this.timeoutTime = setTimeout(() => {
                    const inputField = app.data.clicktaberightEle;
                    const inputValue = inputField.value.trim();
                    const allProjects = this.projectData; 
                    if (inputValue) {
                        app.stopDataRefresh();
                    } else {
                        app.startDataRefresh()
                    }
                    // 每次清空前面旧数据
                    $(".sidebar-list-item").empty();

                    if (inputValue) {
                        const firstChar = inputValue.charAt(0);
                        const filteredProjects = allProjects.filter(project =>
                            project.projectName.startsWith(firstChar)
                        );
                      
                        if (filteredProjects.length > 0) {
                            app.methods.assignmentRightList(filteredProjects)
                        } else {
                            $(".sidebar-list-item").append(`
                                    <div style="text-align: center; font-size: 12px; color: #999;">
                                        <dd>没有符合条件的项目</dd>
                                    </div>
                                `);
                        }
                    } else {
                        inputField.value =''
                        app.methods.assignmentRightListAll(allProjects)
                    }
                }, 900);
            },
            // 项目列表筛选后的数据赋值
            assignmentRightList: function (filteredProjects) {
                const sidebarList = filteredProjects.map((project, index) => {
                    return `<dd><a id='a_${project.id}' title='${project.projectName}' class='projectListA' onclick='app.methods.findLocateMarker(${project.id.toString()},event)' href="javascript:;">${index + 1}${project.projectName}</a></dd>`;
                });
                $(".sidebar-list-item").append(sidebarList.join(" "));

            },
            // 项目列表所有数据赋值 
            assignmentRightListAll: function (allProjects) {
                const sidebarList = allProjects.map((project, index) => {
                    return `<dd><a id='a_${project.id}' title='${project.projectName}' class='projectListA' onclick='app.methods.findLocateMarker(${project.id.toString()},event)' href="javascript:;">${index + 1}${project.projectName}</a></dd>`;
                });
                $(".sidebar-list-item").append(sidebarList.join(" ")); 
            }

        },

        registerEvent: function () {

        },
        startDataRefresh: function () {    
            this.dataRefreshInterval = setInterval(app.methods.refreshDataMethod, 1000);
        },
        stopDataRefresh: function () {
            clearInterval(this.dataRefreshInterval);
        },

        init: function () {
            app.methods.initMap();
            app.methods.initVue();
            app.methods.getProjectDataList();
            app.startDataRefresh();
            app.registerEvent();
        }
    };
    app.init();
});