/**
 * 全局变量定义
 *
 */
layui.use(['form', 'element', 'layer'], function () {
    form = layui.form,
        element = layui.elementx,
        layer = layui.layer;

});

var myUser = getCookie('user');
if (!myUser) {
    layer.msg('无权限进入');
} else {
    myUser = JSON.parse(myUser);
}



var myMap, yjhj_wsObj,
    graphicslayer,//区域选择绘画结果图层
    graphicslayer_points,//空间查询结果图层
    graphicslayer_grid,//高层网格遮盖图层
    graphicslayer_lowGrid,//底层网格图层
    graphicslayer_border,//社区轮廓和网格边界
    graphicslayer_mb,//蒙版
    graphicslayer_gj,//社区轨迹
    heatLayer,//轨迹热区
    toolbar, measureTool;

dojo.require("esri.map");
dojo.require("esri.toolbars.draw");

/**
 * 地图初始化
 */
function init() {
    getGridData().then(function (promiseData) {
        createMapLoad("arcgisDiv", promiseData.extent, vue_top.community.map, function (map) {
            myMap = map;
            //绘画
            toolbar = new esri.toolbars.Draw(map);
            dojo.connect(toolbar, "onDrawEnd", drawEnd);
            graphicslayer = new esri.layers.GraphicsLayer();
            myMap.addLayer(graphicslayer);
            //底层网格图层
            graphicslayer_lowGrid = new esri.layers.GraphicsLayer();
            graphicslayer_lowGrid.on('mouse-over', function (evt) {
                $(".shuju_table").addClass("change");
                setRight(evt.graphic.attributes.data);
            });
            // graphicslayer_lowGrid.on('mouse-ount',function (evt) {
            //     console.log(3)
            // });
            myMap.addLayer(graphicslayer_lowGrid);
            //业务图层
            createSpecialTopicLayer();
            //人员轨迹热区图层
            heatLayer = getFeatureLayer();
            myMap.addLayer(heatLayer);
            //人员轨迹图层
            graphicslayer_gj = new esri.layers.GraphicsLayer();
            graphicslayer_gj.on('mouse-move', function (evt) {
                myMap.infoWindow.hide();
                myMap.infoWindow.setTitle("人员轨迹结果");
                var n = evt.graphic.geometry.paths[0].length;
                var tempLength = measureTool.getLength_(evt.graphic.geometry.paths[0]);
                tempLength = (tempLength) / 1000;
                tempLength = tempLength.toFixed(1);
                myMap.infoWindow.setContent("地点数:" + n + '<br>里程:' + tempLength);
                myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
            });
            graphicslayer_gj.on('mouse-out', function (evt) {
                myMap.infoWindow.hide();
            });
            myMap.addLayer(graphicslayer_gj);
            //空间查询结果
            graphicslayer_points = new esri.layers.GraphicsLayer();
            myMap.addLayer(graphicslayer_points);
            //测量
            measureTool = new MeasureTool(map);
            //高层遮盖网格图层
            graphicslayer_grid = new esri.layers.GraphicsLayer({ id: 'wgxx' });
            graphicslayer_grid.on('click', function (evt) {
                if (evt.graphic.geometry.type == 'point' || evt.graphic.geometry.type == 'polyline' || (vue_top.user.gridid)) {
                    return;
                }
                setGrid(evt.graphic.attributes.data.id);
            });
            graphicslayer_grid.on('mouse-over', function (evt) {
                if (evt.graphic.geometry.type == 'point' || evt.graphic.geometry.type == 'polyline') {
                    return;
                }
                $(".shuju_table").addClass("change");
                setRight(evt.graphic.attributes.data);
                evt.graphic.setSymbol(getSymbol(evt.graphic.attributes.data.color, "#59A6EB"));
            });
            graphicslayer_grid.on('mouse-out', function (evt) {
                console.log(2)
                if (evt.graphic.geometry.type == 'point' || evt.graphic.geometry.type == 'polyline') {
                    return;
                }
                evt.graphic.setSymbol(getSymbol(evt.graphic.attributes.data.color, evt.graphic.attributes.data.color));
            });
            myMap.addLayer(graphicslayer_grid);
            //社区轮廓图层加各个网格轮廓用于过渡右侧字的变化
            graphicslayer_border = new esri.layers.GraphicsLayer();
            graphicslayer_border.on('mouse-over', function (evt) {
                $(".shuju_table").removeClass("change");
            });
            // graphicslayer_border.on('mouse-out',function (evt){
            //     setRight(null);
            // });
            myMap.addLayer(graphicslayer_border);
            //蒙版
            graphicslayer_mb = new esri.layers.GraphicsLayer({ id: "mb" });
            graphicslayer_mb.on('mouse-over', function (evt) {
                setRight(null);
            });
            myMap.addLayer(graphicslayer_mb);
            //处理网格数据
            resolveGridData(promiseData.data);
        });
    }).catch(function (error) {
        layer.msg(error);
    });
}
dojo.ready(init);

/**
 * vuejs定义
 */
//上方vue
var vue_top = new Vue({
    el: '#topVue',
    data: {
        community: community_conf,
        user: myUser,
        businessLayers: serviceLayers_conf,
        gridList: [],
        //模块配置
        modules: modules_conf,
        servervalue: {
            temperature: "",
            humidity: ""
        },
        blnGridLayer: false
    },
    methods: {
        logout: function () {
            window.location = "logout";
        },
        edituser: function () {
            var copyobj = Object.assign({}, this.user);
            copyobj.password = '';
            copyobj.newpassword = '';
            vue_user.user = copyobj;
            editUser();
        },
        setTab: function (item) {
            graphicslayer_gj.clear();//清除轨迹
            vue_left.selectedItem = item;
            vue_right.widthData = item.width == null || item.width === undefined ? "400px" : item.width;
            vue_right.heightData = item.height == null || item.height === undefined ? "390px" : item.height;
            //var leftview=item.leftView;
            //控制左侧面板显示隐藏
            // if(leftview.mark=="list"&&!item.show){  //列表数据
            //     $(".left-nav").css("display", "block"); 
            //     leftview.data=this.businessLayers[leftview.index].data;
            //     if(leftview.data.length==1){
            //         vue_left.locate(leftview.data[0]);
            //     }
            // }else if(leftview.mark=="tree"&&!item.show){//树结构 
            //     $(".left-nav").css("display", "block");
            //     for (var i = 0; i < leftview.data.length; i++) { //遍历本模块的一级树
            //         var tempList=[];
            //         for (var j = 0; j < this.businessLayers[leftview.index].data.length; j++) { //遍历集合数据，塞入一级树结构中
            //             if (this.businessLayers[leftview.index].data[j].marktype && this.businessLayers[leftview.index].data[j].marktype.strcontains(leftview.data[i].marktype)) {
            //                 tempList.push(this.businessLayers[leftview.index].data[j]);
            //             }
            //         }
            //         //chilren tianchong
            //         vue_left.tree_list[vue_left.tree_list.arrfindindex(leftview.data[i],"marktype")].children=tempList;
            //     }
            //     for (var j = 0; j < vue_left.tree_list.length; j++) {//遍历所有模块的一级
            //         if (j >= leftview.position.start && j<=leftview.position.end) {
            //             vue_left.tree_list[j].show = true;
            //         } else {
            //             vue_left.tree_list[j].show = false;
            //         }
            //     }
            // }else if(leftview.mark=="iframe"&&!item.show){//嵌入形式
            //     $(".left-nav").css("display", "block"); 
            //     document.getElementById("myIframe").src =leftview.data[0];
            // }else{
            //     $(".left-nav").css("display", "none"); 
            // }

            //嵌入或者打开
            if (item.iframe && item.iframe.type == "layui_open" && !item.show) {
                // layerOpen({
                //     area: item.layui_open_option.area,
                //     content: item.layui_open_option.content,
                //     type: item.layui_open_option.type,
                // });
                layerOpen(item.iframe.data);
            } else if (item.iframe && item.iframe.type == "tab_page" && !item.show) {
                window.open(item.iframe.data);
            }
            //控制图层显示隐藏
            this.setPanelRecursion(item, this.modules);
            this.controlLayer();
            //控制左侧面板显示隐藏
            if (item.show && item.leftView.view) {
                $(".left-nav").css("display", "block");
                vue_left.currentView = item.leftView.view;//视图
                vue_left.currentTitle = item.text;//标题
                var tx = item.leftView.index.map(function (ele) {
                    return vue_top.businessLayers[ele];
                });
                vue_left.currentData = { title: item.text, data: tx };//数据
            } else {
                $(".left-nav").css("display", "none");
            }

            //控制右侧面板显示隐藏
            vue_right.currentView = (item.show ? (item.rightView) : (""));
        },
        setPanelRecursion: function (item, Panels) {
            Panels.forEach((elem, index, arr) => {
                if (elem.text == item.text) {//选择的模块状态要和原来相反
                    elem.show = !elem.show;
                } else {
                    elem.show = false;
                }
                this.setPanelRecursion(item, elem.children);
            });
        },
        controlLayer: function () {//控制图层显示隐藏
            for (var key in this.getVisibilityLayerxx) {
                var temp_visible = (key == 'visibleLayers' ? true : false);
                for (var i = 0; i < this.getVisibilityLayerxx[key].length; i++) {

                    for (var j = 0; j < this.businessLayers.length; j++) {
                        if (this.businessLayers[j].layerID == this.getVisibilityLayerxx[key][i]) {
                            this.businessLayers[j].status = temp_visible;
                        }
                    }
                }
            }
            this.setLayerVisibility();
        },
        setLayerStatus: function (item) {
            item.status = !item.status;
            this.setLayerVisibility();
        },
        setLayerStatusbyId: function (id, visible) {
            this.businessLayers.forEach(item => {
                if (item.layerID == id) {
                    item.status = visible;
                    myMap.getLayer(item.layerID).setVisibility(visible);
                }
            });
        },
        setMyGrid: function (id) {
            setGrid(id);
        },
        setVisibility1: function (m, visibilityLayer) {
            if (m.show) {
                visibilityLayer.visibleLayers = visibilityLayer.visibleLayers.concat(m.layers);
            } else {
                visibilityLayer.hiddenLayers = visibilityLayer.hiddenLayers.concat(m.layers);
            }
            if (m.children) {
                for (var j = 0; j < m.children.length; j++) {
                    this.setVisibility1(m.children[j], visibilityLayer);
                }
            }
        },
        setLayerVisibility: function () {
            this.businessLayers.forEach(item => {
                myMap.getLayer(item.layerID).setVisibility(item.status);
            });
        },//控制网格图层
        controlGridLayer: function () {
            this.blnGridLayer = !this.blnGridLayer;
            if (!vue_top.user.gridid) {
                graphicslayer_grid.setVisibility(!this.blnGridLayer);
            } else {
                layer.msg('无此权限');
            }
        }
    },
    computed: {
        getVisibilityLayerxx: function () {//存放所有图层的显示隐藏
            var visibilityLayer = { hiddenLayers: [], visibleLayers: [] };
            for (var i = 0; i < this.modules.length; i++) {
                this.setVisibility1(this.modules[i], visibilityLayer);
            }
            return visibilityLayer;
        }
    }
});

//左侧面板
var leftviewList = {};
vue_top.community.leftviewNameList.forEach(item => {
    leftviewList[item] = httpVueLoader('./components/leftview/' + item + ".vue");
});
var vue_left = new Vue({
    el: '#leftVue',
    data: {
        currentView: "",//视图模板
        currentTitle: "",//标题
        currentData: null,//数据
        zdry_list: zdry_conf,
        tree_list: treelist_conf,
        selectedItem: {
            // leftView: {
            //     mark: "none"
            // }
        },
        searchText: '',
    },
    methods: {
        locate: function (item) {
            myMap.infoWindow.hide();
            var point = null;
            if (item.x && item.y) {
                point = new esri.geometry.Point(parseFloat(item.x), parseFloat(item.y));
            } else if (item.long && item.lat) {
                point = new esri.geometry.Point(parseFloat(item.long), parseFloat(item.lat));
            } else if (item.wkt) {
                point = new esri.geometry.Polygon({
                    rings: (Terraformer.WKT.parse(item.wkt)).coordinates,
                    spatialReference: {
                        wkid: 4326
                    }
                }).getExtent().getCenter();
            }
            if (!point) {
                layer.msg("无空间信息，无法定位");
                return;
            }
            myMap.infoWindow.setTitle(item.name);
            myMap.infoWindow.setContent("名称:" + item.name);
            myMap.infoWindow.show(myMap.toScreen(point));
            myMap.centerAndZoom(point, 20);
        },
        showright: function (item) {
            vue_right.currentView = (item.show ? (item.rightview) : (""));
            vue_right.widthData = item.width + 'px';
            vue_right.heightData = item.height + 'px';
        },
        playPaths: function (item) {

            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle("轨迹查看");
            myMap.infoWindow.setContent("开始时间:<input id='htmlsjst' type='datetime-local' step='01'><br/>" + "结束时间:<input id='htmlsjed' type='datetime-local' step='01'>" + "<br/>" + "<br/><br/><a style='color: #242af3;cursor: pointer;' onclick='playPath(\"" + item.deviceId + "\")' >查询轨迹</a>" + "<br/><a style='color: #242af3;cursor: pointer;' onclick='heatanalysis()' >全社区活动轨迹热区分析</a>");
            var now = new Date(new Date().getTime() - 30 * 60 * 1000);
            var str1 = now.getFullYear() + "-" + fix((now.getMonth() + 1), 2) + "-" + fix(now.getDate(), 2) + "T" + fix(08, 2) + ":" + fix(00, 2);
            now = new Date();
            var str2 = now.getFullYear() + "-" + fix((now.getMonth() + 1), 2) + "-" + fix(now.getDate(), 2) + "T" + fix(20, 2) + ":" + fix(00, 2);
            $("#htmlsjst").val(str1);
            $("#htmlsjed").val(str2);
            let point = esri.geometry.Point(item.long, item.lat);
            myMap.infoWindow.show(myMap.toScreen(point));

        }

    },
    computed: {
        //    data_filter: function () {
        //         if (this.searchText) {
        //             var temp = [];
        //             for (var i = 0; i < this.selectedItem.leftView.data.length; i++) {
        //                 if (this.selectedItem.leftView.data[i].name&&this.selectedItem.leftView.data[i].name.strcontains(this.searchText)) {
        //                     temp.push(this.selectedItem.leftView.data[i]);
        //                 }
        //             }
        //             return temp;
        //         }
        //         return this.selectedItem.leftView.data;
        //     }
    },
    components: leftviewList
});

//右侧统计
// let viewNameList=["hjws","jmzx","gdgl","spaq","dagl","zsysq","wyryfb","hdgl","hjbh","zaaq","aqsc","rkgl","zdry","dqfwzx","ggfw","zyzfwz","sbsx"];
let viewList = {};
vue_top.community.viewNameList.forEach(item => {
    viewList[item] = httpVueLoader('./components/rightview/' + item + ".vue");
});
var vue_right = new Vue({
    el: '#rightvue',
    data: {
        title: vue_top.community.name,
        xq: vue_top.community.sqjbxx,
        currentView: "",
        currentData: null,
        widthData: '400px',
        heightData: '390px'
    },
    methods: {

    },
    components: viewList
});
//用户编辑
var vue_user = new Vue({
    el: '#edituser',
    data: {
        user: { userid: '', username: '', password: '', newpassword: '' },
        imgsrc: './img/eye_grey.png',
        imgsrc_new: './img/eye_grey.png',
    },
    methods: {
        showpwd: function (x) {
            var inputx;
            if (x == 2) {
                inputx = $(".td_add_input4")[0];
                inputx.type = (inputx.type == 'password' ? 'text' : 'password');
                this.imgsrc_new = (this.imgsrc_new == './img/eye_grey.png' ? './img/eye.png' : './img/eye_grey.png');
            } else {
                inputx = $(".td_add_input3")[0];
                inputx.type = (inputx.type == 'password' ? 'text' : 'password');
                this.imgsrc = (this.imgsrc == './img/eye_grey.png' ? './img/eye.png' : './img/eye_grey.png');
            }
        }
    }
});

/**
 * 地图操作
 */
//测距
function measureMentL() {
    measureTool.bolDraw = true;
    toolbar.activate(esri.toolbars.Draw.POLYLINE);
}
//测面
function measureMentA() {
    measureTool.bolDraw = true;
    toolbar.activate(esri.toolbars.Draw.POLYGON);
}
//画
function Draw(x) {
    if (x == "矩形")
        toolbar.activate(esri.toolbars.Draw.RECTANGLE);
    else if (x == "点")
        toolbar.activate(esri.toolbars.Draw.POINT);
    else if (x == "多边形")
        toolbar.activate(esri.toolbars.Draw.POLYGON);
    else if (x == "圆形")
        toolbar.activate(esri.toolbars.Draw.CIRCLE);
    else if (x == "不规则图形")
        toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYGON);
    else if (x == "清除") {
        graphicslayer.clear();
        graphicslayer_points.clear();
        graphicslayer_gj.clear();
        heatLayer.clear();
        heatLayer.refresh();
    }
    //myMap.hideZoomSlider();
}
//画完成(逻辑代码包括测距测面、绘画上图、标注)
function drawEnd(geometry) {
    var symbol;
    toolbar.deactivate();  // 关闭工具栏并激活地图导航.
    myMap.setMapCursor("url(default.cur),auto");
    if (measureTool.bolDraw) {
        if (geometry.type == 'polygon') {
            measureTool.getArea(geometry);
        } else {
            measureTool.getLength(geometry);
        }
        measureTool.bolDraw = false;
    } else {
        // 判断几何图形的类型
        switch (geometry.type) {
            case "polyline":
                symbol = new esri.symbol.SimpleLineSymbol(
                    esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                    new dojo.Color([255, 0, 0]),
                    1
                );
                break;
            case "polygon":
                symbol = new esri.symbol.SimpleFillSymbol(
                    esri.symbol.SimpleFillSymbol.STYLE_SOLID,
                    new esri.symbol.SimpleLineSymbol(
                        esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
                        new dojo.Color([255, 0, 0]),
                        2
                    ),
                    new dojo.Color([255, 255, 0, 0.25])
                );
                break;
            case "extent":
                symbol = new esri.symbol.SimpleFillSymbol(
                    esri.symbol.SimpleFillSymbol.STYLE_SOLID,
                    new esri.symbol.SimpleLineSymbol(
                        esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
                        new dojo.Color([255, 0, 0]),
                        2
                    ),
                    new dojo.Color([255, 255, 0, 0.25])
                );
                break;
            case "multipoint":
                symbol = new esri.symbol.SimpleMarkerSymbol(
                    esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND,
                    20,
                    new esri.symbol.SimpleLineSymbol(
                        esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                        new dojo.Color([0, 0, 0]),
                        1
                    ),
                    new dojo.Color([255, 255, 0, 0.5])
                );
                break;
        }
        graphicslayer.clear();
        var graphic = new esri.Graphic(geometry, symbol);
        graphicslayer.add(graphic);  // 将绘图加入到图层中
        checkPoint(geometry);
        if (geometry.type == "polygon") {
            layer.confirm('是否将空间wkt属性导出?', {
                btn: ['确定', '取消'] //按钮
            }, function (index) { //确定删除 
                var blob = new Blob([Terraformer.WKT.convert({ "type": "Polygon", "coordinates": graphic.geometry.rings })], { type: "text/plain;charset=utf-8" });
                saveAs(blob, "空间数据.wkt");
                layer.close(index);
            });
        }
    }
}
//判断点在内部还是在外部
function checkPoint(geometry) {
    // graphicslayer_points.clear();
    // for(var i=0;i<graphicslayer_spjk.graphics.length;i++){
    //     if(geometry.contains(graphicslayer_spjk.graphics[i].geometry)){
    //         graphicslayer_points.add(new esri.Graphic(graphicslayer_spjk.graphics[i].geometry,graphicslayer_spjk.graphics[i].symbol,{type:'0',tag:graphicslayer_spjk.graphics[i].attributes.tag}));
    //     }
    // }
    // graphicslayer_spjk.setVisibility(false);
    // graphicslayer_abry.setVisibility(false);
}

//创建专题图层
function createSpecialTopicLayer() {
    for (var i = 0; i < vue_top.businessLayers.length; i++) {
        var layer = new esri.layers.GraphicsLayer({ id: vue_top.businessLayers[i].layerID, visible: false });
        listenLayer(layer, vue_top.businessLayers[i]);
        myMap.addLayer(layer);
        //图层数据
        if (vue_top.businessLayers[i].layerID == "reportMattersLayer") {
            getreportMattersData(layer, i);
        }
        else if (vue_top.businessLayers[i].http) {
            getData(layer, i);
        } else {
            initWebsocket(layer);
        }
    }
}
//查询业务数据
function getData(layer, i) {
    getByAjax('./business/' + vue_top.businessLayers[i].http, data => {
        for (var j = 0; j < data.length; j++) {
            var polygon = null, symbolx;
            if (vue_top.businessLayers[i].event == "building" && data[j].wkt) {//房屋
                polygon = new esri.geometry.Polygon({
                    rings: (Terraformer.WKT.parse(data[j].wkt)).coordinates,
                    spatialReference: {
                        wkid: 4326
                    }
                });
                symbolx = getSymbol("#000000", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                if (data[j].dy) {//党员
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "dangyuan" + ".png", 15, 15).setOffset(20, 0)));
                } if (data[j].zljzrq) {//流动人口
                    symbolx = getSymbol("#0000ff", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                    if (data[j].zljzrq.strcontains("1")) {//租客过期
                        layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "zlbs" + ".png", 15, 15).setOffset(-20, 0)));
                    }
                }
                if (data[j].fydq) {//防疫人员
                    symbolx = getSymbol("#0000ff", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                    if (data[j].fydq.strcontains("1")) {//防疫到期
                        layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "fy" + ".png", 30, 30).setOffset(-20, 0)));
                    }
                }
                if (data[j].rmfx) {//人民防线
                    symbolx = getSymbol("#0000ff", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "rmfx" + ".png", 20, 20).setOffset(40, 0)));
                }

                if (data[j].ldls && data[j].ldls.strcontains("1")) {//流动留守儿童
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "ldlschildren" + ".png", 18, 18).setOffset(40, 0)));
                }
                else if (data[j].ldls && data[j].ldls.strcontains("2")) {//流动留守儿童
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "ldls" + ".png", 18, 18).setOffset(40, 0)));
                }

                if (data[j].color) {//重点人员
                    symbolx = getSymbol("#ff0000", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                }
                if (data[j].fl)  {//妇联
                    // symbolx = getSymbol("#0000ff", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/icon/" + "fl" + ".png", 25, 25).setOffset(40, 0)));
                }
                if (data[j].qsn)  {//青少年
                    layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "qsn" + ".png", 25, 25).setOffset(40, 0)));
                }
                var g1 = new esri.Graphic(polygon, symbolx, {
                    data: data[j],
                    symbol: symbolx,
                    type: vue_top.businessLayers[i].text
                });
                layer.add(g1);
            } else if (data[j].wkt) {
                polygon = new esri.geometry.Polygon({
                    rings: (Terraformer.WKT.parse(data[j].wkt)).coordinates,
                    spatialReference: {
                        wkid: 4326
                    }
                });
                if (vue_top.businessLayers[i].symbols && vue_top.businessLayers[i].symbols.color) {
                    symbolx = new esri.symbol.SimpleFillSymbol(vue_top.businessLayers[i].symbols.color);
                } else {
                    symbolx = getSymbol("#00CD00", data[j].color ? data[j].color : "#C0FF3E", vue_top.businessLayers[i].icon.color);
                }
                if (vue_top.businessLayers[i].icon.img) {
                    if (vue_top.businessLayers[i].symbols && vue_top.businessLayers[i].symbols.img) {
                        layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(vue_top.businessLayers[i].symbols.img), { type: vue_top.businessLayers[i].text, data: data[j] }));
                    }
                    else {
                        let point_change = {};
                        if (data[j].name == '14号网格') {
                            point_change = new esri.geometry.Point(118.82824780800004, 32.11227862550004);
                        } else if (data[j].name == '15号网格') {
                            point_change = new esri.geometry.Point(118.82874780800004, 32.11027862550004);
                        } else if (data[j].name == '12号网格') {
                            point_change = new esri.geometry.Point(118.82992889400003, 32.11635553650006);
                        } else {
                            point_change = new esri.geometry.Point(polygon.getExtent().getCenter().x, polygon.getExtent().getCenter().y);
                        }
                        layer.add(new esri.Graphic(point_change, new esri.symbol.PictureMarkerSymbol(" img/" + vue_top.businessLayers[i].icon.img, 30, 30), { type: vue_top.businessLayers[i].text, data: data[j] }));
                        //社区网格文字
                        var textSymbol = new esri.symbol.TextSymbol(data[j].name).setColor(
                            new esri.Color([0, 0, 0])).setAlign(esri.symbol.Font.ALIGN_START).setAngle(0).setFont(
                                new esri.symbol.Font("10pt").setWeight(esri.symbol.Font.WEIGHT_BOLD));
                        textSymbol.yoffset = -30;
                        layer.add(new esri.Graphic(new esri.geometry.Point(point_change.x, point_change.y), textSymbol, { type: vue_top.businessLayers[i].text, data: data[j] }));
                    }
                }
                if (data[j].fydq) {//防疫人员
                    symbolx = getSymbol("#0000ff", "#C4C4C4", vue_top.businessLayers[i].icon.color);
                    if (data[j].fydq.strcontains("1")) {//防疫到期
                        layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + "fy" + ".png", 30, 30).setOffset(-20, 0)));
                    }
                }

                layer.add(new esri.Graphic(polygon, symbolx, { type: vue_top.businessLayers[i].text, data: data[j] }));
            } else if (data[j].x) {
                if (vue_top.businessLayers[i].symbols && vue_top.businessLayers[i].symbols.img) {
                    symbolx = new esri.symbol.PictureMarkerSymbol(vue_top.businessLayers[i].symbols.img);
                }
                else {
                    symbolx = new esri.symbol.PictureMarkerSymbol(" img/" + vue_top.businessLayers[i].icon.img, 30, 30);
                }
                if (data[j].angle) {
                    symbolx.setAngle(data[j].angle);
                }
                layer.add(new esri.Graphic(new esri.geometry.Point(data[j].x, data[j].y), symbolx, { type: vue_top.businessLayers[i].text, data: data[j] }));
            }
        }
        vue_top.businessLayers[i].data = data;
    });
}

function getreportMattersData(layer, i) {
    require(["js/bundle/incident.bundle.js"], function ($root) {
        var incident = $root['incident'];
        var date = new Date();
        date.setDate(date.getDate() - 24);
        var date1 = new Date();
        var buffer = incident.CaseQueryRequest.encode({
            token: uuid(),
            request: {
                orgId: vue_top.community.socketId,
                beginDate: date.toshortcustomstring(),
                endDate: date1.toshortcustomstring()
            }
        }).finish();
        $.ajax({
            type: "POST",
            url: vue_top.businessLayers[i].http,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                buffer: buffer
            }),
            dataType: "json",
            success: function (res) {
                var resultDecoded = incident.CaseQueryResponse.decode(res.data);
                var data = resultDecoded.response;
                var temp = [];
                for (var j = 0; j < data.length; j++) {
                    if (!data[j].longitude) {
                        continue;
                    }
                    temp.push({ name: data[j].caseType, x: data[j].longitude, y: data[j].latitude });
                    var symbolx;
                    if (vue_top.businessLayers[i].symbols && vue_top.businessLayers[i].symbols.img) {
                        symbolx = new esri.symbol.PictureMarkerSymbol(vue_top.businessLayers[i].symbols.img);
                    }
                    else {
                        symbolx = new esri.symbol.PictureMarkerSymbol(" img/" + vue_top.businessLayers[i].icon.img, 30, 30);
                    }
                    if (data[j].angle) {
                        symbolx.setAngle(data[j].angle);
                    }
                    layer.add(new esri.Graphic(new esri.geometry.Point(data[j].longitude, data[j].latitude), symbolx, {
                        type: vue_top.businessLayers[i].text,
                        data: data[j]
                    }));
                }
                vue_top.businessLayers[i].data = temp;
            },
            error: function (message) {

            }
        });

    });
}

//图层事件
function listenLayer(v_layer, layerdata) {
    let event = layerdata.event;
    // vue_right.widthData='400px';
    // vue_right.heightData='390px';
    if (event == 'monitor') {//监控
        v_layer.on('click', function (evt) {

            if (evt.graphic.attributes.data.url.strcontains('http')) {
                layui_open_option = {
                    type: 2,
                    title: '<span class="layer_span9">监控画面</span>',
                    area: ['1077px', '878px'], //宽高
                    content: evt.graphic.attributes.data.url
                };
                layerOpen(layui_open_option);
            }
            else {
                var sd = "/api/v1/getchannels?channel=" + evt.graphic.attributes.data.url;
                var hostname = window.location.hostname;
                var port = window.location.port;
                var easynvr = window.location.protocol + "//" + hostname + ":" + port + sd;
                $.ajax({
                    url: easynvr, type: "GET", data: {}, success: function (data) {
                        var online = data.EasyDarwin.Body.Channels[0].Online;
                        if (online == "1") {
                            bfsp(evt.graphic.attributes.data);
                        } else if (online == "0") {
                            layer.msg("视频不在线");
                        }
                    }
                });
            }
        });
        v_layer.on('mouse-over', function (evt) {
            myMap.infoWindow.hide();
            var point = new esri.geometry.Point(evt.graphic.attributes.data.x, evt.graphic.attributes.data.y);
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            myMap.infoWindow.setContent("编码:" + evt.graphic.attributes.data.id + "<br />名称:" + evt.graphic.attributes.data.name + "<br/><br/>");
            myMap.infoWindow.show(myMap.toScreen(point));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    } else if (event == 'gridMan') {//安保人员
        v_layer.on('click', function (evt) {
            var id = evt.graphic.attributes.id;

            // if(id.substring(0, 3) == "PU_")
            // {
            //     layui_open_option = {
            //         type: 2,
            //         title:  '<span class="layer_span9">执法记录仪</span>',
            //         area: ['977px', '678px'], //宽高
            //         content: "/intercom?device_id="+id
            //     };
            //     layerOpen(layui_open_option);

            // }else{
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle("轨迹查看");
            let content = "开始时间:<input id='htmlsjst' type='datetime-local' step='01'><br/>" + "结束时间:<input id='htmlsjed' type='datetime-local' step='01'>" + "<br/>" + "<br/><br/><a style='color: #242af3;cursor: pointer;' onclick=playPath('" + id + "') >查询轨迹</a>" + "<br/><a style='color: #242af3;cursor: pointer;' onclick='heatanalysis()' >全社区活动轨迹热区分析</a>"

            if (id.substring(0, 3) == "PU_") {
                content = content + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style='color: #242af3;cursor: pointer;' onclick=showzfjly('" + id + "')>执法记录仪</a>"
            }
            myMap.infoWindow.setContent(content);
            var now = new Date(new Date().getTime() - 30 * 60 * 1000);
            var str1 = now.getFullYear() + "-" + fix((now.getMonth() + 1), 2) + "-" + fix(now.getDate(), 2) + "T" + fix(08, 2) + ":" + fix(00, 2);
            now = new Date();
            var str2 = now.getFullYear() + "-" + fix((now.getMonth() + 1), 2) + "-" + fix(now.getDate(), 2) + "T" + fix(20, 2) + ":" + fix(00, 2);
            $("#htmlsjst").val(str1);
            $("#htmlsjed").val(str2);
            myMap.infoWindow.show(myMap.toScreen(evt.graphic.geometry));
            // }
        });
    } else if (event == 'building') {//房屋人口
        v_layer.on('click', function (evt) {
            if (evt.graphic.attributes == undefined) {
                return;
            }
            queryBuildingStructure(evt.graphic.attributes.data, evt.graphic.attributes.type);
        });
        v_layer.on('mouse-move', function (evt) {
            if (evt.graphic.attributes == undefined) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            myMap.infoWindow.setContent("地址:" + evt.graphic.attributes.data.name + "<br />" + "<br/>");
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
            evt.graphic.setSymbol(getSymbol("#000000", "#96e1f0"));
        });
        v_layer.on('mouse-out', function (evt) {
            if (evt.graphic.attributes == undefined) {
                return;
            }
            myMap.infoWindow.hide();
            evt.graphic.setSymbol(evt.graphic.attributes.symbol);
        });
    } else if (event == 'LayuiOpen') {
        v_layer.on('click', function (evt) {
            let temp = layerdata.layui_open_option.content + "/" + evt.graphic.attributes.data.id;
            layerOpen({
                area: layerdata.layui_open_option.area,
                content: shiftLan(temp),
                type: layerdata.layui_open_option.type,
            });
        });
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "名称:" + evt.graphic.attributes.data.name + "<br>";
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    } else if (event == 'rightview') {//
        v_layer.on('click', function (evt) {
            if (evt.graphic.attributes == undefined) {
                return;
            }
            require(["js/bundle/incident.bundle.js"], function ($root) {
                incident = $root['incident'];
                vue_right.currentView = layerdata.rightview;
                //延迟加载以便能够保证子组件已经加载完毕再调用其方法
                setTimeout(() => {
                    vue_right.$refs.mychild.show(evt.graphic.attributes.data);
                }, 300);
            });
        });
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "";
            var data = evt.graphic.attributes.data;
            data.name && (str += "名称:" + data.name + "<br>");
            data.caseType && (str += "事项类型:" + data.caseType + "<br>");
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    } else if (event == 'rightview1') {//
        v_layer.on('click', function (evt) {
            for (var i = 0; i < v_layer.graphics.length; i++) {
                if (v_layer.graphics[i].attributes.sym != null) {
                    v_layer.graphics[i].setSymbol(v_layer.graphics[i].attributes.sym);
                }
            }
            evt.graphic.attributes.sym = evt.graphic.symbol;
            if (evt.graphic.attributes == undefined) {
                return;
            }
            require(["js/bundle/incident.bundle.js"], function ($root) {
                incident = $root['incident'];
                vue_right.currentView = layerdata.rightview;
                //延迟加载以便能够保证子组件已经加载完毕再调用其方法
                setTimeout(() => {
                    vue_right.$refs.mychild.show(evt.graphic.attributes.data);
                }, 300);
            });
            evt.graphic.setSymbol(null);

        });
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "";
            var data = evt.graphic.attributes.data;
            data.name && (str += "名称:" + data.name + "<br>");
            data.caseType && (str += "事项类型:" + data.caseType + "<br>");
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    }
    else if (event == 'picture') {//照片
        v_layer.on('click', function (evt) {
            if (evt.graphic.attributes == undefined) {
                return;
            }
            showPicture(evt.graphic.attributes.data.id, evt.graphic.attributes.data.typeid);
        });
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "名称:" + evt.graphic.attributes.data.name + "<br>";
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    } else if (event == 'zyzxq') {//志愿者信息
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = evt.graphic.attributes.data.ryname + " " + evt.graphic.attributes.data.xb + "<br>";
            str += evt.graphic.attributes.data.zjhm + "<br>";
            str += evt.graphic.attributes.data.xjzd + "<br>";
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    }
    else if (event == 'rightviewfy') {//
        v_layer.on('click', function (evt) {

            evt.graphic.attributes.sym = evt.graphic.symbol;
            if (evt.graphic.attributes == undefined) {
                return;
            }

            getByAjax("./business/queryfyryBybuildingid/" + evt.graphic.attributes.data.id + "/" + layerdata.typeid + "/" + layerdata.foreigntypeid, data => {
                require(["js/bundle/incident.bundle.js"], function ($root) {
                    incident = $root['incident'];
                    vue_right.currentView = layerdata.rightview;
                    vue_right.widthData = layerdata.width;
                    vue_right.heightData = layerdata.height;
                    //延迟加载以便能够保证子组件已经加载完毕再调用其方法
                    setTimeout(() => {
                        vue_right.$refs.mychild.show(data.data1, data.data2);
                    }, 300);
                });
            });
            // evt.graphic.setSymbol(null);  

        });
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "";
            var data = evt.graphic.attributes.data;
            data.name && (str += "名称:" + data.name + "<br>");
            data.caseType && (str += "事项类型:" + data.caseType + "<br>");
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    }

    else if (event == 'zjbuilding') {//
        v_layer.on('click', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "地址:" + evt.graphic.attributes.data.name + "<br>";
            str += "负责人:" + evt.graphic.attributes.data.zjfzr + "<br>";
            str += "联系电话:" + evt.graphic.attributes.data.zjfzrlxdh + "<br>";
            str += "宗教信仰:" + evt.graphic.attributes.data.zjfzrxy + "<br>";
            str += "参会人员:" + evt.graphic.attributes.data.zjchry + "<br>";
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));

        });
    }
    else if (event == 'gridevent') {//
        v_layer.on('click', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.data.name);
            let str = "网格地址:" + evt.graphic.attributes.data.address + "<br>";
            str += "姓名:" + evt.graphic.attributes.data.wgz + "<br>";
            str += "出生年月:" + evt.graphic.attributes.data.csny + "<br>";
            str += "性别:" + evt.graphic.attributes.data.xb + "<br>";
            str += "电话:" + evt.graphic.attributes.data.wgylxdh + "<br>";
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
            for (var i = 0; i < graphicslayer_grid.graphics.length; i++) {
                if (typeof (graphicslayer_grid.graphics[i].attributes) != 'undefined' && evt.graphic.attributes.data.id == graphicslayer_grid.graphics[i].attributes.data.id) {
                    setRight(graphicslayer_grid.graphics[i].attributes.data);
                }
            }
        });


    }
    else if (event == 'twgridevent') {//
        v_layer.on('mouse-move', function (evt) {
            if (evt.graphic.geometry.type == 'point' || evt.graphic.geometry.type == 'polyline') {
                return;
            }
            evt.graphic.setSymbol(getSymbol(evt.graphic.attributes.data.color, "#59A6EB"));
            for (var i = 0; i < graphicslayer_grid.graphics.length; i++) {
                if (typeof (graphicslayer_grid.graphics[i].attributes) != 'undefined' && evt.graphic.attributes.data.id == graphicslayer_grid.graphics[i].attributes.data.id) {
                    setRight(graphicslayer_grid.graphics[i].attributes.data);
                }
            }
            vue_right.currentView = layerdata.rightview;
            vue_right.widthData = layerdata.width == null || layerdata.width === undefined ? "400px" : layerdata.width;
            vue_right.heightData = layerdata.height == null || layerdata.height === undefined ? "390px" : layerdata.height;
        });

        v_layer.on('mouse-out', function (evt) {
            if (evt.graphic.geometry.type == 'point' || evt.graphic.geometry.type == 'polyline') {
                return;
            }
            evt.graphic.setSymbol(getSymbol(evt.graphic.attributes.data.color, evt.graphic.attributes.data.color));
        });
    }
    else {//其他
        v_layer.on('mouse-move', function (evt) {
            if (!evt.graphic.attributes || !evt.graphic.attributes.type) {
                return;
            }
            myMap.infoWindow.hide();
            myMap.infoWindow.setTitle(evt.graphic.attributes.type);
            let str = "";
            var data = evt.graphic.attributes.data;
            data.name && (str += "名称:" + data.name + "<br>");
            data.caseType && (str += "事项类型:" + data.caseType + "<br>");
            if (evt.graphic.attributes.data.contentx) {
                evt.graphic.attributes.data.contentx.split(",").forEach(item1 => {
                    str += item1 + "<br>";
                });
            }
            myMap.infoWindow.setContent(str);
            myMap.infoWindow.show(myMap.toScreen(evt.mapPoint));
        });
        v_layer.on('mouse-out', function (evt) {
            myMap.infoWindow.hide();
        });
    }
}

/**
 * 网格和地图轮廓
 * @param gridData
 */
//查询网格数据
function getGridData() {
    return new Promise(function (resolve, reject) {
        getByAjax('./rest/gridquery/' + vue_top.community.shp, datax => {
            let gridData = datax.grid;
            vue_top.gridList = gridData;
            if (gridData != null) {
                var extent = new esri.geometry.Extent(vue_top.community.extent);
                for (var i = 0; i < gridData.length; i++) {
                    //辖区定位
                    if (myUser.gridid == gridData[i].id) {
                        extent = new esri.geometry.Polyline({
                            paths: (Terraformer.WKT.parse(gridData[i].wkt)).coordinates,
                            spatialReference: {
                                wkid: 4326
                            }
                        }).getExtent();
                        break;
                    }
                }
                resolve({
                    data: datax,
                    extent: extent
                });
            } else {
                reject('error');
            }
        });
    });
}
//处理网格数据
function resolveGridData(gridData) {
    let shp = gridData.shp;
    gridData = gridData.grid;
    for (var i = 0; i < gridData.length; i++) {
        // //高层网格遮盖
        var myGeometry, mySymbol;
        if (myUser.gridid == gridData[i].id) {//登录人拥有查看本网格信息的权限
            myGeometry = new esri.geometry.Polyline({
                paths: (Terraformer.WKT.parse(gridData[i].wkt)).coordinates,
                spatialReference: { wkid: 4326 }
            });
            mySymbol = new esri.symbol.SimpleLineSymbol(
                esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                new dojo.Color([0, 0, 255, 0]),
                8
            );
        } else {
            myGeometry = new esri.geometry.Polygon({//其他网格遮盖
                rings: (Terraformer.WKT.parse(gridData[i].wkt)).coordinates,
                spatialReference: { wkid: 4326 }
            });
            mySymbol = getSymbol(gridData[i].color, gridData[i].color);
        }
        graphicslayer_grid.add(new esri.Graphic(myGeometry, mySymbol, { data: gridData[i] }));

        //社区网格文字
        var textSymbol = new esri.symbol.TextSymbol(gridData[i].gridman).setColor(
            new esri.Color([0, 0, 0])).setAlign(esri.symbol.Font.ALIGN_START).setAngle(0).setFont(
                new esri.symbol.Font("10pt").setWeight(esri.symbol.Font.WEIGHT_BOLD));
        graphicslayer_grid.add(new esri.Graphic(new esri.geometry.Point(gridData[i].x, gridData[i].y), textSymbol));

        //低层遮盖，不用显示，只要能触发mouse事件就行
        graphicslayer_lowGrid.add(new esri.Graphic(new esri.geometry.Polygon({
            rings: (Terraformer.WKT.parse(gridData[i].wkt)).coordinates,
            spatialReference: { wkid: 4326 }
        }), new esri.symbol.SimpleFillSymbol(
            esri.symbol.SimpleFillSymbol.STYLE_SOLID,
            new esri.symbol.SimpleLineSymbol(
                esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                new dojo.Color([0, 0, 0, 0]),
                2
            ),
            new dojo.Color([0, 0, 0, 0])
        ), { data: gridData[i] }));

        //网格轮廓，此线条为过渡，过渡网格与网格之间，删除class左右
        var g2 = new esri.Graphic(new esri.geometry.Polyline({
            paths: (Terraformer.WKT.parse(gridData[i].wkt)).coordinates,
            spatialReference: { wkid: 4326 }
        }), new esri.symbol.SimpleLineSymbol(
            esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new dojo.Color([0, 0, 0, 0]),
            8
        ));
        graphicslayer_border.add(g2);
    }
    //shp文件内容
    if (shp && shp.length != 0) {
        for (var i = 0; i < shp.length; i++) {
            if (shp[i].properties.Type == "SQ") {
                var polyline = new esri.geometry.Polyline(shp[i].geometry.coordinates);
                var polylineSymbol = new esri.symbol.SimpleLineSymbol(
                    esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
                    new dojo.Color([0, 0, 255]),
                    7);
                var g_LINE = new esri.Graphic(polyline, polylineSymbol);
                graphicslayer_border.add(g_LINE);
            }
            if (shp[i].properties.Type == "MB") {
                //蒙版
                graphicslayer_mb.add(new esri.Graphic(new esri.geometry.Polygon(shp[i].geometry.coordinates), getSymbolAll("blue", 0, "#787878", 0.7)));
            }
        }
    }
}
//选中网格
function setGrid(tag) {
    if (vue_top.user.gridid && vue_top.user.gridid != tag) {
        layer.msg('无此权限');
        return;
    }
    if (typeof (tag) == 'undefined') {
        return;
    }
    if (tag == "0") {
        myMap.setExtent(new esri.geometry.Extent(vue_top.community.extent), 20);
        graphicslayer_grid.setVisibility(true);
    }
    for (var i = 0; i < graphicslayer_grid.graphics.length; i++) {
        if (typeof (graphicslayer_grid.graphics[i].attributes) != 'undefined' && graphicslayer_grid.graphics[i].attributes.data.id == tag) {
            myMap.setExtent(graphicslayer_grid.graphics[i].geometry.getExtent(), 20);
            graphicslayer_grid.graphics[i].setGeometry(new esri.geometry.Polyline({
                paths: (Terraformer.WKT.parse(graphicslayer_grid.graphics[i].attributes.data.wkt)).coordinates,
                spatialReference: { wkid: 4326 }
            }));
            graphicslayer_grid.graphics[i].setSymbol(new esri.symbol.SimpleLineSymbol(
                esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                new dojo.Color([0, 0, 255, 0]),
                8
            ));
        } else if (typeof (graphicslayer_grid.graphics[i].attributes) != 'undefined' && graphicslayer_grid.graphics[i].attributes.data.id != tag) {
            graphicslayer_grid.graphics[i].setGeometry(new esri.geometry.Polygon({
                rings: (Terraformer.WKT.parse(graphicslayer_grid.graphics[i].attributes.data.wkt)).coordinates,
                spatialReference: { wkid: 4326 }
            }));
            graphicslayer_grid.graphics[i].setSymbol(getSymbol(graphicslayer_grid.graphics[i].attributes.data.color, graphicslayer_grid.graphics[i].attributes.data.color));
        }
    }
}
//右侧数据
function setRight(tag) {
    if (tag == null) {
        vue_right.title = vue_top.community.name;
        vue_right.xq = vue_top.community.sqjbxx;
    } else {
        vue_right.title = tag.gridman;
        vue_right.xq = tag;
        vue_right.xq.type = '网格长信息';
    }
}

//查看监控
function bfsp(tag) {
    if (!tag.url) {
        layer.msg("待接入的监控!");
        return;
    }
    layui_open_option = {
        type: 2,
        title: '<span class="layer_span9">监控画面</span>',
        area: ['977px', '678px'], //宽高
        content: "nvrurl/play.html?channel=" + tag.url + "&iframe=yes&aspect=640x360"
    };
    layerOpen(layui_open_option);
}
/**
 * 安保人员
 */

//执法记录仪 

function showzfjly(UserId) {
    layui_open_option = {
        type: 2,
        title: '<span class="layer_span9">执法记录仪</span>',
        area: ['977px', '678px'], //宽高
        content: "http://gisc-vge.gitee.io/xingwei-vcs/intercom-detail.html?device_id=" + UserId
    };
    layerOpen(layui_open_option);

}

//安保人员轨迹
function playPath(UserId) {
    graphicslayer_gj.clear();
    var st = $('#htmlsjst').val().replace('T', ' ');
    var ed = $('#htmlsjed').val().replace('T', ' ');
    require(["js/bundle/intercom.bundle.js"], function ($root) {
        var intercom = $root['intercom'];
        // 调用设备起止时间内的历史轨迹位置
        var queryRequest = new intercom.QueryRequest({
            tokenId: uuid(),
            queryTrackLog: {
                "deviceId": String(UserId),
                "startTime": st,
                "endTime": ed
            }
        }),
            bufMsg = intercom.QueryRequest.create(queryRequest),
            buffer = intercom.QueryRequest.encode(bufMsg).finish();
        var index = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        $.ajax({
            type: "POST",
            // url: 'https://58.213.133.181:7773/patrol/intercom/query',
            url: 'https://community.stycloud.com/patrol/intercom/query',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                buffer: buffer
            }),
            dataType: "json",
            success: function (res) {
                layer.close(index);
                var resultDecoded = intercom.QueryResponse.decode(res.data);
                if (!resultDecoded.trackLogs || !resultDecoded.trackLogs.items || resultDecoded.trackLogs.items.length == 0) {
                    layer.msg("未查到此人员该时段轨迹");
                    return;
                }
                var data = resultDecoded.trackLogs.items;
                var line = [];
                for (var i = data.length - 1; i >= 1; i--) {//返回的数据按照时间从大到小，因此轨迹需要过回来
                    line.push([parseFloat(data[data.length - i].long), parseFloat(data[data.length - i].lat)]);
                }
                var polyline = new esri.geometry.Polyline({
                    paths: [line],
                    spatialReference: { wkid: 4326 }
                });
                myMap.setExtent(polyline.getExtent(), 19);
                drawWithanimation(0, [line], new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 255, 0]), 4), graphicslayer_gj);
            },
            error: function (message) {
                layer.msg('未查到此人员该时段轨迹');
            }
        });

    });
}

function heatanalysis() {
    //热区
    heatLayer.clear();
    heatLayer.refresh();
    var st = $('#htmlsjst').val().replace('T', ' ');
    var ed = $('#htmlsjed').val().replace('T', ' ');
    var index = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });
    require(["js/bundle/intercomlocation.bundle.js"], function ($root1) {
        var intercomlocation = $root1['intercomlocation'];
        var buffer1 = intercomlocation.QueryRequest.encode({
            token: uuid(),
            request: {
                queryClusterLocation: {
                    area: { //四至范围
                        // east: 121.372584,
                        // west: 121.293533,
                        // north: 31.324816,
                        // south: 31.2673
                        east: 180,
                        west: 0,
                        north: 90,
                        south: 0
                    },
                    groupId: "fdda7757-25cc-40bf-a0bb-2046ee0b2956", //兴卫单位标识 125733
                    // deviceId: UserId,
                    beginTime: st, //当前时间  2月份有聚类数据
                    endTime: ed, //取值 day week month  当天凌晨至当前时刻 当周周1凌晨至当前时刻 当月1号凌晨至当前时刻
                    layer: myMap.getLevel() //当前窗口地图层级  需要根据窗口地图层级，来动态请求数据
                }
            }
        }).finish();
        $.ajax({
            type: "POST",
            url: "https://community.stycloud.com/rest/v1/intercom/cluster/",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                buffer: buffer1
            }),
            dataType: "json",
            success: function (res) {
                layer.close(index);
                var resultDecoded = intercomlocation.QueryResponse.decode(res["data"]);
                if (resultDecoded.response && resultDecoded.response.clusterLocations && resultDecoded.response.clusterLocations.length) {
                    var arr = resultDecoded.response.clusterLocations;
                    for (var i = 0; i < arr.length; i++) {
                        heatLayer.add(new esri.Graphic(new esri.geometry.Point(arr[i].longitude, arr[i].latitude, new esri.SpatialReference({
                            wkid: 4326
                        })), new esri.symbol.SimpleMarkerSymbol(), { weight: arr[i].value }));
                    }
                }
            },
            error: function (message) {
                layer.close(index);
                layer.msg(message);
            }
        });
    });
}

/**
 * 楼盘人口
 */
//获取房间
function getRoom(data, k, i, j) {
    for (var n = 0; n < data.length; n++) {
        if (data[n].unitorder == k && data[n].floororder == i && data[n].roomorder == j)
            return data[n];
    }
    return null;
}
//查询建筑内人和房屋信息
function queryBuildingStructure(data_building, buildingType) {
    data_building.showtype=buildingType;
    var eventType = {};
    if (buildingType == "企业楼栋") {
        eventType.url = "1";
        eventType.target = showRoomCompany;
        eventType.dom = $('.tanchucompany');
    } else {//楼盘信息、重点人员
        eventType.url = "0";
        eventType.target = showRoomMember;
        eventType.dom = $('.tanchutable');
    }
   
    $(".fwjbxx input.districtname").val(data_building.xqm);
    $(".fwjbxx input.building").val(data_building.ldh);
    $('.tanchu  .right-div').empty();//清空右侧
    $('#mydiv').html('');//清空房屋结构
    var layui_open_option = {
        title: '<span class="layer_span6">' + data_building.gridid + '号网格楼栋信息</span>',
        content: $(".tanchu"),
        area: ['1280px', '660px'], //宽高
        type: 1
    };
    if (data_building.unitnum && data_building.floornum && data_building.roomnum) { //有房屋结构
        $('.tanchu  .right-div').append(eventType.dom.html());//重新填充右侧
        getByAjax("./rest/queryfwjg/" + eventType.url + "/" + data_building.id, data => {
            var unitnum = data_building.unitnum;
            var pienum = data_building.floornum;
            var roomnum = data_building.roomnum;
            for (var k = 0; k <= unitnum - 1; k++) {
                var div_unit = $('<div class="div_unit"></div>');
                var unit_num = k + 1;
                var addclass = "unit" + k;
                div_unit.addClass(addclass);
                var title_unit = $('<div class="title_unit"><span>第' + unit_num + '单元</span></div>');
                div_unit.append(title_unit);
                for (var i = pienum; i >= 1; i--) {
                    var myPlie = $('<div class="myplienum"></div>');
                    var mypie = "myPie" + i;
                    myPlie.addClass(mypie);
                    for (var j = 1; j < roomnum + 1; j++) {
                        var temp = getRoom(data, k + 1, i, j);
                        var myDiv = $('<div class="myroom"></div>');
                        if (temp != null) {
                            addRoomMark(myDiv, temp,buildingType);
                            myDiv.append('<p class="roomnum">' + temp.name + '</p>');
                            //房间绑定数据和事件
                            myDiv[0].attributes.tag = temp;
                            myDiv[0].attributes.tag.showtype = buildingType;
                            myDiv.click(function () {
                                eventType.target(this.attributes.tag, () => { });
                            });
                        } else {//不存在此户
                            myDiv.css('background-image', "url('img/emptyhouse.png')");
                            myDiv.css('cursor', 'default');
                        }
                        //房间加入楼房
                        myPlie.append(myDiv);
                        div_unit.append(myPlie);
                    }
                }
                $('#mydiv').append(div_unit);
            }
        });
        eventType.target(data_building, () => {
            layerOpen(layui_open_option);
        });
    } else { //无房屋结构
        getByAjax("./rest/queryfwjg/" + eventType.url + "/" + data_building.id, data => {
            layui_open_option = {
                title: '<span class="layer_span7">' + data_building.gridid + '号网格房屋信息</span>',
                content: eventType.dom,
                area: ['780px', '630px'], //宽高
                type: 1
            };
            if(data.length > 0)data[0].showtype=buildingType;
            eventType.target((data.length > 0 ? data[0] : data_building), () => {
                layerOpen(layui_open_option);
            });
        });
    }
}
//房间添加颜色或者图标
function addRoomMark(divx, item,buildingType) {
    //租赁过期
    vuezdry.show=buildingType;
    if (buildingType=="流动人口" && item.zljzrq) {
        divx.css('background-color', "#00B0F0");
        if (item.zljzrq.strcontains("1")) {
            divx.append('<img src="img/zlbs.png" style="float: left;width:15px ;margin-left:5px ">');
        }
    }

    if (buildingType=="防疫人员" && item.fydq) {
        //divx.css('background-color', "#00B0F0");
        if (item.fydq.strcontains("1")) {
            divx.append('<img src="img/fy.png" style="float: left;width:15px ;margin-left:5px ">');
        }
    }
    if (buildingType=="人民防线" && item.rmfx) {
        //divx.css('background-color', "#00B0F0");
        divx.append('<img src="img/rmfx.png" style="float: left;width:15px ;margin-left:5px ">');
    }


    //重点人员
    if (buildingType=="重点人员" &&  item.zdry && item.zdry.indexOf("16")<0) {
        divx.find("p").css("font-weight", "900");
        divx.find("p").css("font-size", "20px");
        var zdrys_obj = getPeopleIcon(item.zdry);
        zdrys_obj.color && (divx.css('background-color', zdrys_obj.color));
        //20190215 暂时去掉模型图中重点人员图标
        // zdrys_obj.icons.forEach((value,index,array)=>{
        //     divx.append('<img src="'+value+'" style="float: left;width:15px ;margin-left:5px">');
        // });
    }
    //党员
    if (buildingType=="党员" &&  item.dy) { //只有房主才会是党员
        divx.append('<img src="img/dangyuan.png" style="float: left;width:15px;margin-left:5px ">');
    }
    //青少年
    if (buildingType=="青少年" &&  item.qsn) {
        divx.append('<img src="img/qsn.png" style="float: left;width:15px;margin-right:5px ">');
    }

    //流动留守儿童
    if (buildingType=="流动留守儿童" &&  item.ldls && item.ldls.strcontains("1")) {
        divx.append('<img src="img/ldlschildren.png" style="float: left;width:15px;margin-right:17px ">');
    }
    else if (buildingType=="流动留守儿童" &&item.ldls && item.ldls.strcontains("2")) {
        divx.append('<img src="img/ldls.png" style="float: left;width:15px;margin-right:17px ">');
    }
    //妇联、
    if (buildingType=="巾帼风采" && item.zdry && item.zdry.strcontains("16")) {
        divx.append('<img src="img/icon/fl.png" style="float: left;width:15px;margin-right:17px ">');
    }

    divx.append('<br>');
}
//根据重点人员id获取对应的颜色和图标，key可能是逗号隔开的多个
function getPeopleIcon(key) {
    let result = { color: "", icons: [] };
    let zdrys = key.split(",");
    for (var i = 0; i < zdrys.length; i++) {
        for (var jx = 0; jx < vue_left.tree_list.length; jx++) {
            if (zdrys[i] == (vue_left.tree_list[jx].marktype)) {
                vue_left.tree_list[jx].icon && (result.icons.indexOf(vue_left.tree_list[jx].icon) == -1) && result.icons.push(vue_left.tree_list[jx].icon);
                result.color = vue_left.tree_list[jx].color;
                break;
            }
        }
    }
    result.icons.length > 1 && (result.color = "red");
    return result;
}

//查询某个住宅户
function showRoomMember(data_house, callback) {
    $(".housejbxx .dz").val(data_house.name);
    $(".housejbxx .mj").val(data_house.mj);
    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        getByAjax("./rest/queryczrk/" + data_house.id, data => {
            table.render({
                elem: '#tbx',
                height: 190,
                cellMinWidth: 50,
                cols: [[ //标题栏  
                    { field: 'lrsj', title: '录入时间', width: 120, align: 'center' },
                    { field: 'name', title: '姓名', width: 100, align: 'center' },
                    { field: 'zjhm', title: '身份证号码', width: 170, align: 'center' },
                    { field: 'lxdh', title: '联系电话', width: 130, align: 'center' },
                    { field: 'xb', title: '性别', width: 60, align: 'center' },
                    { field: 'mz', title: '民族', width: 60, align: 'center' },
                    { field: 'csny', title: '出生年月', width: 100, align: 'center' },
                    { field: 'hkdjd', title: '户口登记地', width: 280, align: 'center' },
                    { field: 'yhzgx', title: '关系', width: 90, align: 'center' },
                    { field: 'hyzk', title: '婚姻', width: 60, align: 'center' },
                    { field: 'zjhmqfrq', title: '证件号码签发日期', width: 160, align: 'center' },
                    { field: 'whcd', title: '文化程度', width: 100, align: 'center' },
                    { field: 'xx', title: '血型', width: 100, align: 'center' },
                    { field: 'jg', title: '籍贯', width: 100, align: 'center' },
                    { field: 'csd', title: '出生地', width: 100, align: 'center' },
                    { field: 'cym', title: '曾用名', width: 100, align: 'center' },
                    { field: 'sg', title: '身高', width: 100, align: 'center' },
                    { field: 'zzmm', title: '政治面貌', width: 100, align: 'center' },
                    { field: 'gzdw', title: '工作单位', width: 100, align: 'center' },
                    { field: 'zdryextenddata', title: 'tag', width: 0, align: 'center', display: 'none' },
                    { field: 'dysl', title: 'tag', width: 0, align: 'center' },
                    { field: 'qsnsl', title: 'tag', width: 0, align: 'center' },
                    { field: 'ldlssl', title: 'tag', width: 0, align: 'center' },
                    { field: 'rmfx', title: 'tag', width: 0, align: 'center' },
                    { field: 'fldj', title: 'tag', width: 0, align: 'center' }
                ]], data: data,
                done: function (res, curr, count) {
                    $("[data-field='zdryextenddata']").css('display', 'none');
                    $("[data-field='dysl']").css('display', 'none');
                    $("[data-field='qsnsl']").css('display', 'none');
                    $("[data-field='ldlssl']").css('display', 'none');
                    $("[data-field='rmfx']").css('display', 'none');
                    $("[data-field='fldj']").css('display', 'none');
                    LayUIDataTable.SetJqueryObj($);
                    var currentRowDataList = LayUIDataTable.ParseDataTable("czry", function (index, currentData, rowData) {
                    });
                    // 对相关数据进行判断处理-
                    addPersonMark(currentRowDataList,data_house.showtype);
                }
            });
            getByAjax("./rest/queryldrk/" + data_house.id, data1 => {
                table.render({
                    elem: '#tbx1',
                    height: 190,
                    cellMinWidth: 50,
                    cols: [[ //标题栏
                        { field: 'lrsj', title: '录入时间', width: 120, align: 'center' },
                        { field: 'hkdjd', title: '户口登记地', width: 280, align: 'center' },
                        { field: 'name', title: '姓名', width: 100, align: 'center' },
                        { field: 'zjhm', title: '身份证号码', width: 174, align: 'center' },
                        { field: 'lxdh', title: '联系电话', width: 136, align: 'center' },
                        { field: 'xb', title: '性别', width: 70, align: 'center' },
                        { field: 'mz', title: '民族', width: 60, align: 'center' },
                        { field: 'csny', title: '出生年月', width: 120, align: 'center' },
                        { field: 'zlksrq', title: '租赁开始日期', width: 140, align: 'center' },
                        { field: 'zljzrq', title: '租赁到期日期', width: 140, align: 'center' },
                        { field: 'zjhmqfrq', title: '证件号码签发日期', width: 160, align: 'center' },
                        { field: 'whcd', title: '文化程度', width: 100, align: 'center' },
                        { field: 'xx', title: '血型', width: 100, align: 'center' },
                        { field: 'jg', title: '籍贯', width: 100, align: 'center' },
                        { field: 'csd', title: '出生地', width: 100, align: 'center' },
                        { field: 'cym', title: '曾用名', width: 100, align: 'center' },
                        { field: 'sg', title: '身高', width: 100, align: 'center' },
                        { field: 'zzmm', title: '政治面貌', width: 100, align: 'center' },
                        { field: 'gzdw', title: '工作单位', width: 100, align: 'center' },
                        { field: 'zdryextenddata', title: 'tag', width: 0, align: 'center' },
                        { field: 'dysl', title: 'tag', width: 0, align: 'center' },
                        { field: 'qsnsl', title: 'tag', width: 0, align: 'center' },
                        { field: 'ldlssl', title: 'tag', width: 0, align: 'center' },
                        { field: 'rmfx', title: 'tag', width: 0, align: 'center' },
                        { field: 'fldj', title: 'tag', width: 0, align: 'center' }
                    ]]
                    , data: data1,
                    done: function (res, curr, count) {
                        $("[data-field='zdryextenddata']").css('display', 'none');
                        $("[data-field='dysl']").css('display', 'none');
                        $("[data-field='qsnsl']").css('display', 'none');
                        $("[data-field='ldlssl']").css('display', 'none');
                        $("[data-field='rmfx']").css('display', 'none');
                        $("[data-field='fldj']").css('display', 'none');
                        LayUIDataTable.SetJqueryObj($);
                        var currentRowDataList = LayUIDataTable.ParseDataTable("zkry", function (index, currentData, rowData) {
                        });
                        addPersonMark(currentRowDataList,data_house.showtype);
                    }
                });
            });
            callback();
        });
    });
}
function addPersonMark(currentRowDataList,showtype) {
    $.each(currentRowDataList, function (index, obj) {
        if (obj["zdryextenddata"] && obj["zdryextenddata"].value ) {
            obj["zdryextenddata"].value.split(",").forEach((val, n, array) => {
                var tmp = val.split(":");
                var temobj = getPeopleIcon(tmp[0]);
                obj['name'].cell.css("color", temobj.color);
                if (showtype=="重点人员" && temobj.icons[0]) { //重点人员没有图标，只有重点服务对象有图标
                    var img = createImg(temobj.icons[0]);
                    if (tmp.length > 1 && tmp[1]) { //部分重点服务对象有详情
                        img.style.cursor = "pointer";
                        img.flagtag = tmp[1];
                        img.onclick = function () {
                            if (tmp[0] == "10" || tmp[0] == "6") {
                                layerOpen({
                                    "title": '<span class="layer_span8">重点人员详细信息' + '</span>',
                                    "type": 2,
                                    "content": "localx/zdry/" + this.flagtag + "/" + obj['zjhm'].value,
                                    "area": ['532px', '480px']
                                }, layerindex => {
                                    layer.close(layerindex);
                                });

                            }
                            else {

                                var flagtag = this.flagtag;
                                layer.prompt({
                                    title: '输入口令，并确认',
                                    formType: 1
                                }, function (pass, index) {
                                    if (pass == "admin12345") {
                                        layer.close(index);
                                        layerOpen({
                                            "title": '<span class="layer_span8">重点人员详细信息' + '</span>',
                                            "type": 2,
                                            "content": "localx/zdry/" + flagtag + "/" + obj['zjhm'].value,
                                            "area": ['532px', '380px']
                                        }, layerindex => {
                                            layer.close(layerindex);
                                        });
                                    } else {
                                        layer.msg("验证失败！");
                                    }
                                });
                            }
                        }
                    }
                }
                obj['name'].cell.append(img);
            });
        }
        if (showtype=="党员" && obj["dysl"] && obj["dysl"].value != "0") {
            var img = createImg('./img/dangyuan.png');
            img.style.cursor = "pointer";
            img.onclick = function () {
                layerOpen({
                    "title": '<span class="layer_span8">党员详细信息' + '</span>',
                    "type": 2,
                    "content": "localx/dygrxx/" + obj['zjhm'].value,
                    "area": ['543px', '355px']
                }, layerindex => {
                    layer.close(layerindex);
                });
            };
            obj['name'].cell.append(img);
        }

        if (showtype=="青少年" && obj["qsnsl"] && obj["qsnsl"].value != "" && obj["qsnsl"].value != "0") {
            var img = createImg('./img/qsn.png');
            obj['name'].cell.append(img);
        }
        if (showtype=="巾帼风采"&& obj["fldj"] && obj["fldj"].value=="" &&obj["zdryextenddata"] && obj["zdryextenddata"].value && obj["zdryextenddata"].value.indexOf("jgfc")>-1 ) {
            var img = createImg('./img/icon/fl.png');           
            img.onclick = function () {
            layerOpen({
                "title": '<span class="layer_span8">重点关爱详情</span>',
                "type": 2,
                "content": "localx/local_fl/" + obj['zjhm'].value,
                "area": ['543px', '550px']
            }, layerindex => {
                layer.close(layerindex);
            });
        };
            obj['name'].cell.append(img);
        }
         //判断妇联红灯
         if(obj["fldj"] && obj["fldj"].value != ""){
            var img =""; 
            if(obj["fldj"].value =="1"){
                img = createImg('./img/icon/flgreen.png'); 
        
            }
            else  if(obj["fldj"].value=="2"){
                    img =  createImg('./img/icon/flyellow.png');

                 } 
                  else  if(obj["fldj"].value=="3"){
                    img =createImg('./img/icon/florange.png'); 
                }
                else if(obj["fldj"].value=="4"){
                    img=createImg('./img/icon/flred.png');
                }
                img.onclick = function () {
                layerOpen({
                    "title": '<span class="layer_span8">家庭关护详情</span>',
                    "type": 2,
                    "content": "localx/local_fl/" + obj['zjhm'].value,
                    "area": ['543px', '600px']
                }, layerindex => {
                    layer.close(layerindex);
                });
            };
          obj['name'].cell.append(img);
        
        }


        if (showtype=="流动留守儿童" &&  obj["ldlssl"] && obj["ldlssl"].value != "" && obj["ldlssl"].value != "0") {
            var img = createImg('./img/ldlschildren.png');
            img.style.cursor = "pointer";
            var title = "流动留守儿童";
            var height = '365px';
            if (obj["ldlssl"].value == "2") {
                title = "困境青少年";
                img = createImg('./img/ldls.png');
                height = '665px';
            }
            img.onclick = function () {
                layerOpen({
                    "title": '<span class="layer_span8">' + title + '</span>',
                    "type": 2,
                    "content": "localx/local_ldlschildren/" + obj['zjhm'].value,
                    "area": ['543px', height]
                }, layerindex => {
                    layer.close(layerindex);
                });
            };
            obj['name'].cell.append(img);
        }

        if (showtype=="人民防线" &&  obj["rmfx"] && obj["rmfx"].value) {
            obj["rmfx"].value.split(",").forEach((val, n, array) => {
                var img = createImg('./img/rmfx.png');
                img.style.cursor = "pointer";
                img.onclick = function () {
                    layer.prompt({
                        title: '输入口令，并确认',
                        formType: 1
                    }, function (pass, index) {
                        if (pass == "admin12345") {
                            layer.close(index);
                            layerOpen({
                                "title": '<span class="layer_span8">人民防线' + '</span>',
                                "type": 2,
                                "content": "localx/local_rmfx/" + obj['zjhm'].value + "/" + val,
                                "area": ['543px', '765px']
                            }, layerindex => {
                                layer.close(layerindex);
                            });
                        } else {
                            layer.msg("验证失败！");
                        }
                    });
                };
                obj['name'].cell.append(img);
            });
        }

    }
    );
}

function createImg(src) {
    var img = document.createElement("img");
    img.src = src;
    img.style.width = "10px";
    img.style.heigth = "10px";
    img.style.marginLeft = "5px";
    return img;
}
//查询某个企业户
function showRoomCompany(data_house, callback) {
    $(".housejbxx .dz").val(data_house.name);
    $(".housejbxx .mj").val(data_house.mj);
    layui.use('element', function () {
        var $ = layui.jquery,
            element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块
        $(".companylist .layui-tab-title li").each(function () {///清除上一个留下的所有标题
            if (!$(this).attr('defaultattr')) {
                $(this).remove();
            }
        });
        $(".companylist .layui-tab-content >div").each(function () {//清除上一个留下的所有内容
            if (!$(this).attr('defaultattr')) {
                $(this).remove();
            }
        });
        window.localStorage.clear();
        getByAjax("rest/querybusiness/" + data_house.id, result => {
            for (var i = 0; i < result.data1.length; i++) {
                element.tabAdd('companyfilter', {
                    title: result.data1[i].dwxxmc,
                    content: '<iframe  id="' + i + 'enterpriseId" src="' + 'page/enterprise.html?id=' + i + '" style="width:100%;height:388px;" frameborder="0" ></iframe>',
                    id: new Date().getTime()
                });
                window.localStorage.setItem(i + 'enterpriseId', JSON.stringify(result.data1[i]));
                //document.getElementById(i+'enterpriseId').contentWindow.paramFromParent =result.data1[i];
                console.log(window.localStorage.getItem(i + 'enterpriseId'));
            }
            for (var i = 0; i < result.data2.length; i++) {
                element.tabAdd('companyfilter', {
                    title: result.data2[i].gtjyhmc,
                    content: '<iframe id="' + i + 'selfemployeeId" src="' + 'page/selfemployee.html?id=' + i + '" style="width:100%;height:388px;" frameborder="0" ></iframe>',
                    id: new Date().getTime()
                });
                window.localStorage.setItem(i + 'selfemployeeId', JSON.stringify(result.data2[i]));
                //document.getElementById(i+'selfemployeeId').contentWindow.paramFromParent =result.data2[i];
            }
            $(".companylist .layui-tab-content >div").first().addClass("layui-show");
            $(".companylist .layui-tab-title >li").first().addClass("layui-this");
            if ((result.data1.length + result.data2.length) > 2) {
                $(".layui-tab-bar").show();
            }
            callback();
        });
    });
}

//layui打开
function layerOpen(layui_open_option, callback) {
    layer.open({
        type: layui_open_option.type,
        title: layui_open_option.title,
        area: layui_open_option.area, //宽高
        content: layui_open_option.content,
        offset: ['50px'],
        btn: ["关闭"],
        resize: false,
        maxmin: true,
        shade: 0,
        yes: function (index, layero) {
            if (!callback) {
                layer.closeAll();
            } else {
                callback(index);
            }
        }
    });
}

function showPicture(id, folder) {
    if (id) {
        getByAjax("./rest/queryphotos/" + id + "/" + folder, result => {
            var json = { title: "照片", data: result };
            layer.photos({
                photos: json,
                anim: 5
            });
        });
    }
}

function showPictureWithoutHttp(data) {
    if (data) {
        var json = { title: "照片", data: [data] };
        layer.photos({
            photos: json,
            anim: 5
        });
    }
}

/**
 websocket前后台双向连接
 */
function initWebsocket(layer) {
    require(["js/bundle/intercom.bundle.js"], function ($root) {
        var intercom = $root['intercom'];
        if ("WebSocket" in window) {
            // 打开一个 web socket，v2版本：按组过滤推送的设备信息
            // var wss = new WebSocket("wss://58.213.133.181:7773/wspatrol/intercom/v2/fetch");
            var wss = new WebSocket("wss://community.stycloud.com/wspatrol/intercom/v2/fetch");
            wss.binaryType = 'arraybuffer';
            wss.onopen = function () {
                // 打开websocket连接后，发送protobuf消息
                let bufferMsg = new intercom.AuthInfo({
                    username: 'geteng',
                    token: uuid(),
                    groupId: vue_top.community.socketId     // groupId为数据库group中万寿社区对应的标识，若不是，则不予返回万寿社区的设备数据
                }), buffer = intercom.AuthInfo.encode(bufferMsg).finish();
                wss.send(buffer)
            };
            wss.onmessage = function (evt) {
                var received_msg = evt.data;

                refresh_abry(intercom.QueryResponse.decode(new Uint8Array(received_msg)).deviceList.items, layer);
            };
            wss.onclose = function () {
                // 关闭 websocket
                layer.msg("连接已关闭...");
            };
        }
        else {
            // 浏览器不支持 WebSocket
            layer.msg("您的浏览器不支持 WebSocket!");
        }
    });
}
//安保人员位置实时更新
function refresh_abry(array_abry, layer) {
    layer.clear();
    if (array_abry.length == 0) {
        return;
    }
    vue_top.businessLayers[2].data = array_abry;
    for (var i = 0; i < array_abry.length; i++) {
        if (array_abry[i].long && array_abry[i].lat) {
            var point = new esri.geometry.Point(array_abry[i].long, array_abry[i].lat);
            var pointSymbol = new esri.symbol.PictureMarkerSymbol("img/" + (array_abry[i].status == 'close' ? 'unperson.png' : 'person.png'), 30, 30);
            var attribute = {
                id: array_abry[i].deviceId
            };
            var g = new esri.Graphic(point, pointSymbol, attribute);
            var textSymbol = new esri.symbol.TextSymbol(array_abry[i].name).setColor(
                new esri.Color([255, 0, 0])).setAlign(esri.symbol.Font.ALIGN_START).setAngle(0).setFont(
                    new esri.symbol.Font("10pt")).setOffset(0, -20);
            var g1 = new esri.Graphic(point, textSymbol, attribute);
            layer.add(g);
            layer.add(g1);
        }
    }
}

/*
 * 用户权限
 */
function editUser() {
    layer.open({
        type: 1,
        title: '<span class="layer_add_person">用户信息修改</span>',
        area: ['350px', '300px'], //宽高
        content: $(".add_person"),
        offset: ['180px'],
        btn: ["保存", "取消"],
        yes: function (index) {
            if (vue_user.password || vue_user.newpassword) {
                layer.msg('密码不能为空');
                return;
            }
            postByAjax('./updatepwd', vue_user.user, result => {
                if (result == 1) {
                    vue_top.user.username = vue_user.user.username;
                    layer.closeAll();
                    layer.msg('修改成功')
                } else {
                    layer.closeAll();
                    layer.msg('修改失败')
                }
            });
        }
    });
}

function getSymbol(lineColor, fillColor, a) {
    return new esri.symbol.SimpleFillSymbol(
        esri.symbol.SimpleFillSymbol.STYLE_SOLID,
        new esri.symbol.SimpleLineSymbol(
            esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new dojo.Color(lineColor),
            2
        ),
        new dojo.Color((a != undefined ? rgbTranform(fillColor, a) : fillColor))
    );
}

function getSymbolAll(lineColor, a1, fillColor, a) {
    return new esri.symbol.SimpleFillSymbol(
        esri.symbol.SimpleFillSymbol.STYLE_SOLID,
        new esri.symbol.SimpleLineSymbol(
            esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new dojo.Color((a1 != undefined ? rgbTranform(lineColor, a1) : fillColor)),
            1
        ),
        new dojo.Color((a != undefined ? rgbTranform(fillColor, a) : fillColor))
    );
}
//动态画多边形
function drawWithanimation(myI, points, symbol, layer) {
    var gLine = new esri.Graphic(
        new esri.geometry.Polyline({
            "paths": [
                [
                    [points[0][myI][0], points[0][myI][1]],
                    [points[0][myI + 1][0], points[0][myI + 1][1]]
                ]
            ],
            "spatialReference": {
                "wkid": 4326
            }
        }),
        symbol
    );
    layer.add(gLine);
    if (myI < points[0].length - 2) {
        myI++;
        t = setTimeout(function () {
            drawWithanimation(myI, points, symbol, layer)
        }, 1500 / points[0].length);
    } else {
        clearInterval(t);
    }
}
//创建featurelayer，并用heatmapRenderer渲染器
function getFeatureLayer() {
    var layerDefinition = {
        "geometryType": "esriGeometryPoint",
        "fields": [{
            "name": "ID",
            "type": "esriFieldTypeInteger",
            "alias": "ID"
        }]
    };
    var featureCollection = {
        layerDefinition: layerDefinition,
        featureSet: null
    };
    var hFeatureLayer = new esri.layers.FeatureLayer(featureCollection, {
        mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
        opacity: 1,
        visible: true
    });

    var heatmapRenderer = new esri.renderer.HeatmapRenderer({
        field: "weight",//graphic的attributes对象的属性名，代表权重
        blurRadius: 12,
        maxPixelIntensity: 20,
        minPixelIntensity: 0
    });
    heatmapRenderer.setColorStops([{
        ratio: 0,
        color: "rgb(255, 219, 0, 0)"
    },
    {
        ratio: 0.35,
        color: "rgb(0, 128, 0)"
    },
    {
        ratio: 0.65,
        color: "rgb(233 , 150 , 122)"
    },
    {
        ratio: 0.95,
        color: "rgba(255, 0, 0)"
    }
    ]);
    // var sliders = document.querySelectorAll(".rqcjDiv p~input[type=range]");
    // var addLiveValue = function (ctrl) {
    //     var val = ctrl.previousElementSibling.querySelector("span");
    //     ctrl.addEventListener("input", function (evt) {
    //         val.innerHTML = evt.target.value;
    //     });
    // };
    // for (var i = 0; i < sliders.length; i++) {
    //     addLiveValue(sliders.item(i));
    // }

    // var blurCtrl = document.getElementById("blurControl");
    // var maxCtrl = document.getElementById("maxControl");
    // var minCtrl = document.getElementById("minControl");

    // blurCtrl.addEventListener("change", function (evt) {
    //     var r = +evt.target.value;
    //     if (r !== heatmapRenderer.blurRadius) {
    //         heatmapRenderer.blurRadius = r;
    //         hFeatureLayer.redraw();
    //     }
    // });
    // maxCtrl.addEventListener("change", function (evt) {
    //     var r = +evt.target.value;
    //     if (r !== heatmapRenderer.maxPixelIntensity) {
    //         heatmapRenderer.maxPixelIntensity = r;
    //         hFeatureLayer.redraw();
    //     }
    // });
    // minCtrl.addEventListener("change", function (evt) {
    //     var r = +evt.target.value;
    //     if (r !== heatmapRenderer.minPixelIntensity) {
    //         heatmapRenderer.minPixelIntensity = r;
    //         hFeatureLayer.redraw();
    //     }
    // });

    hFeatureLayer.setRenderer(heatmapRenderer);
    return hFeatureLayer;
}

/*
通知中心
*/
var vue_button = new Vue({
    el: '.dqjq',
    data: {
        ssjq: 0,
    },
    methods: {
        show_jq: function () {
            this.ssjq = 0;
            rightClickSpan();
        }
    },
    watch: {
        ssjq: function (val, oldVal) {
            $(".dqjq").css("display", "block");
        }
    }
});

var vue_nt = new Vue({
    el: '#hjid',
    data: {
        item_ss: [],
        bjjldata: [],
    },
    methods: {
        sure: function (item) {
            if (item.operate == "未确认") {
                item.operate = "已确认";
                ws.send(myUser.userid);
            }
        },
        querybjjl: function () {
            var sjid = $("#test6").val();
            if (sjid == "") {
                layer.msg("请选择查询日期");
            } else {
                var kssj = sjid.substring(0, 10);
                var jssj = sjid.substring(13, 23);
                var sj = "";
                sj += kssj + "," + jssj;
                if (yjhj_wsObj.readyState === 1) {
                    yjhj_wsObj.send(JSON.stringify({ "querycondition": sj }));
                }
            }
        },
    },
    computed: {
        arr_data: function () {
            if (this.item_ss.length > 5) {
                this.item_ss.splice(0, 1);
            }
            return this.item_ss;
        }
    }
});

//一键呼叫弹出层
function rightClickSpan() {
    layerOpen({
        "title": '<span class="layer_span6">一键呼叫信息' + '</span>',
        "type": 1,
        "content": $(".yjhj-div"),
        area: ['1280px', '660px'], //宽高
    }, layerindex => {
        layer.close(layerindex);
        $(".dqjq").css("display", "none");
    });
};
//layui时间插件
layui.use('laydate', function () {
    var laydate = layui.laydate;
    //日期范围
    laydate.render({
        elem: '#test6'
        , range: true
    });
});

vue_top.community.notification.url && yjhjcreateWebSocketFactory(vue_top.community.notification.url, true, (data, v_wsObj) => {
    yjhj_wsObj = v_wsObj;
    let obj = JSON.parse(data);
    if (obj.realrecord) {
        obj = JSON.parse(obj.realrecord);
        let n = vue_nt.item_ss.length;
        vue_nt.item_ss.distinctconcat([obj], "bjsj");
        let m = vue_nt.item_ss.length - n;
        m && (vue_button.ssjq++);
        if (obj.x && obj.y) {
            obj.name = obj.yhmc;
            vue_left.locate(obj);
        }
    } if (obj.historyrecord) {
        //绑定表格
        vue_nt.bjjldata = obj.historyrecord.recordset;
    }
});

vue_top.community.serverparameter.url && createWebSocketFactory(vue_top.community.serverparameter.url, true, (data, v_wsObj) => {
    if (data.indexOf("#") >= 0) {
        var text = data.substring(data.indexOf("#") + 1, data.length);
        var arr = JSON.parse(text);
        vue_nt.item_ss.distinctconcat(arr, "bjsj");
        vue_button.ssjq = vue_button.ssjq + arr.length;
    }
    if (data.split(";").length >= 2 && data.strcontains("T1") && data.strcontains("H1")) {
        vue_top.servervalue.temperature = "" + data.split(";")[2].replace("T1=", "") + "℃     ";
        vue_top.servervalue.humidity = data.split(";")[3].replace("H1=", "") + "%";
    }
});

/**
 * websocket实例化以及心跳监测
 */
function createWebSocketFactory(wsUrl, parameter, callback) {
    var lockReconnect = false;//避免重复连接
    var tt, wsObj;
    function createWebSocket() {
        try {
            if (wsUrl.indexOf("://") == -1) {
                //判断 http 还是https请求
                if (window.location.protocol == "http:") {
                    wsObj = new WebSocket("ws://" + window.location.host + "/" + wsUrl);
                }
                else {
                    wsObj = new WebSocket("wss://" + window.location.host + "/" + wsUrl);
                }
            } else {
                wsObj = new WebSocket(wsUrl);
            }
            init();
        } catch (e) {
            console.log('catch');
            reconnect(wsUrl);
        }
    }

    function init() {
        wsObj.onclose = function () {
            console.log('链接关闭');
            reconnect(wsUrl);
        };
        wsObj.onerror = function () {
            console.log('发生异常了');
            reconnect(wsUrl);
        };
        wsObj.onopen = function () {
            console.log('正常连接');
            parameter && wsObj.send(JSON.stringify({ "communityflag": vue_top.community.serverparameter.id }));
        };
        wsObj.onmessage = function (evt) {
            callback(evt.data, wsObj);
        }
    }
    function reconnect(url) {
        if (lockReconnect) {
            return;
        };
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 4000);
    }
    createWebSocket(wsUrl);
}

function yjhjcreateWebSocketFactory(wsUrl, parameter, callback) {
    var lockReconnect = false;//避免重复连接
    var tt, ywsObj;
    function createWebSocket() {
        try {
            if (wsUrl.indexOf("://") == -1) {
                //判断 http 还是https请求
                if (window.location.protocol == "http:") {
                    ywsObj = new WebSocket("ws://" + window.location.host + "/" + wsUrl);
                }
                else {
                    ywsObj = new WebSocket("wss://" + window.location.host + "/" + wsUrl);
                }
            } else {
                ywsObj = new WebSocket(wsUrl);
            }
            init();
        } catch (e) {
            console.log('catch');
            reconnect(wsUrl);
        }
    }

    function init() {
        ywsObj.onclose = function () {
            console.log('链接关闭');
            reconnect(wsUrl);
        };
        ywsObj.onerror = function () {
            console.log('发生异常了');
            reconnect(wsUrl);
        };
        ywsObj.onopen = function () {
            console.log('正常连接');
            parameter && ywsObj.send(JSON.stringify({ "communityflag": vue_top.community.serverparameter.id }));
        };
        ywsObj.onmessage = function (evt) {
            callback(evt.data, ywsObj);
        }
    }
    function reconnect(url) {
        if (lockReconnect) {
            return;
        };
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 4000);
    }
    createWebSocket(wsUrl);
}

/**
 *其他方法
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}

//颜色转换
function rgbTranform(rgb, a) {
    if (rgb.length == 7) {
        return [parseInt(rgb.substr(1, 2), 16), parseInt(rgb.substr(3, 2), 16), parseInt(rgb.substr(5, 2), 16), a];
    } else {
        return [0, 0, 0, 0];
    }
}

function fix(num, length) {
    return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}

//动态加载建筑物里面重点人员

var vuezdry = new Vue({
    el: "#zdrylabel",
    data: {
        zdry: zdry_conf,
        show:""
    }
})
