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

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

var myMap,
    graphicslayer,//区域选择绘画结果图层
    graphicslayer_points,//空间查询结果图层
    graphicslayer_grid,//高层网格遮盖图层
    graphicslayer_lowGrid,//底层网格图层
    graphicslayer_border,//社区轮廓和网格边界
    graphicslayer_mb,//蒙版
    graphicslayer_gj,//社区轨迹
    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);
            });
            myMap.addLayer(graphicslayer_lowGrid);
            //业务图层
            createSpecialTopicLayer();
            //人员轨迹图层
            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!='null'){
                    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) {
                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定义
 */
//左侧面板
var vue_left=new Vue({
    el:'#leftVue',
    data:{
        zdry_list:zdry_conf,
        tree_list:treelist_conf,
        selectedItem:{},
        searchText:'',
    },
    methods:{
        locate:function (item) {
            myMap.infoWindow.hide();
            var point = null;
           if(item.x&&item.y){
                point=new esri.geometry.Point(item.x, item.y)
            }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);
        },
    },
    computed:{
       data_filter: function () {
            if (this.searchText) {
                var temp = [];
                for (var i = 0; i < this.selectedItem.data.length; i++) {
                    if (this.selectedItem.data[i].name&&this.selectedItem.data[i].name.strcontains(this.searchText)) {
                        temp.push(this.selectedItem.data[i]);
                    }
                }
                return temp;
            }
            return this.selectedItem.data;
        }
    }
});

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(){
            let copyobj=Object.assign({}, this.user);
            copyobj.password='';
            copyobj.newpassword='';
            vue_user.user=copyobj;
            editUser();
        },
        setTab:function(item){
            vue_left.selectedItem=item;
            //控制左侧面板显示隐藏
            if(item.mark=="list"&&!item.show){  //列表数据
                $(".left-nav").css("display", "block"); 
                vue_left.selectedItem.data=this.businessLayers[item.index].data;
                if(vue_left.selectedItem.data.length==1){
                    vue_left.locate(vue_left.selectedItem.data[0]);
                }
            }else if(item.mark=="tree"&&!item.show){//树结构
                $(".left-nav").css("display", "block");
                for (var i = 0; i < item.data.length; i++) { //遍历一级树
                    var tempList=[];
                    for (var j = 0; j < this.businessLayers[item.index].data.length; j++) { //遍历集合数据，塞入一级树结构中
                        if (this.businessLayers[item.index].data[j].marktype && this.businessLayers[item.index].data[j].marktype.strcontains(item.data[i].marktype)) {
                            tempList.push(this.businessLayers[item.index].data[j]);
                        }
                    }
                    vue_left.tree_list[i].children=tempList;
                    vue_left.tree_list[i].show = true;
                }
                for (let j = i; j < vue_left.tree_list.length; j++) {//其他隐藏
                    vue_left.tree_list[j].show = false;
                }
            }else if(item.mark=="iframe"&&!item.show){//嵌入形式
                $(".left-nav").css("display", "block"); 
                document.getElementById("myIframe").src =item.data[0];
            }else{
                $(".left-nav").css("display", "none"); 
            }
            if(item.iframe=="LayuiOpen"&&!item.show){
                layerOpen({
                    area: item.layui_open_option.area,
                    content: item.layui_open_option.content,
                    type: item.layui_open_option.type,
                });
            }else if(item.iframe=="url"&&!item.show){
                window.open(item.data[0]);
            }
             //控制图层显示隐藏
            this.setPanelRecursion(item,this.modules);
            this.controlLayer();
            //控制右侧面板显示隐藏
            vue_right.currentView=(item.show?(item.rightView):(""));
        },
        setPanelRecursion:function(item,Panels){
            Panels.forEach((elem,index) => {
                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();
        },
        setMyGrid:function (id) {
            setGrid(id);
        },
        setVisibility1(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 == 'null') {
                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;
        }
    }
});
//右侧统计
let viewNameList=["hjws","jmzx","gdgl","spaq","dagl","zsysq","wyryfb","hdgl","hjbh","zaaq","aqsc","rkgl","zdry","dqfwzx","ggfw","zyzfwz","sbsx"];
let viewList={};
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:"",
    },
    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) {
            if(x==2){
                var  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{
                var  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();
    }
    //myMap.hideZoomSlider();
}
//画完成(逻辑代码包括测距测面、绘画上图、标注)
function drawEnd(geometry) {
    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":
                var symbol = new esri.symbol.SimpleLineSymbol(
                    esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                    new dojo.Color([255, 0, 0]),
                    1
                );
                break;
            case "polygon":
                var 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":
                var 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":
                var 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;
             if (vue_top.businessLayers[i].event=="building"&&data[j].wkt) {//房屋
               var  polygon = new esri.geometry.Polygon({
                    rings: (Terraformer.WKT.parse(data[j].wkt)).coordinates,
                    spatialReference: {
                        wkid: 4326
                    }
                });
                var 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].color){//重点人员
                    symbolx=getSymbol("#ff0000", "#C4C4C4",vue_top.businessLayers[i].icon.color);
                }
                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","#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{
                        layer.add(new esri.Graphic(polygon.getExtent().getCenter(), new esri.symbol.PictureMarkerSymbol(" img/" + vue_top.businessLayers[i].icon.img, 30, 30),{type: vue_top.businessLayers[i].text,data: data[j]}));
                    }
                }
                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/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(layer,layerdata) {
    let event=layerdata.event;
    if(event=='monitor'){//监控
        layer.on('click',function(evt){
            bfsp(evt.graphic.attributes.data);
        });
        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));
        });
        layer.on('mouse-out',function(evt){
            myMap.infoWindow.hide();
        });
    }else if(event=='gridMan'){//安保人员
        layer.on('click',function(evt){
            var id=evt.graphic.attributes.id;
            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("+id+")' >查询轨迹</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(now.getHours(),2) + ":" + fix(now.getMinutes(),2);
            now=new Date();
            var str2 = now.getFullYear() + "-" + fix((now.getMonth() + 1),2) + "-" + fix(now.getDate(),2) + "T" + fix(now.getHours(),2) + ":" + fix(now.getMinutes(),2);
            $("#htmlsjst").val(str1);
            $("#htmlsjed").val(str2);
            myMap.infoWindow.show(myMap.toScreen(evt.graphic.geometry));
        });
    }else if(event=='building'){//房屋人口
        layer.on('click',function (evt) {
            if(evt.graphic.attributes==undefined){
                return;
            }
            queryBuildingStructure(evt.graphic.attributes.data,evt.graphic.attributes.type);
        });
        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"));
        });
        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'){
        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,
            });
        });
        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));
        });
        layer.on('mouse-out',function (evt) {
          myMap.infoWindow.hide();
        });
    }else if(event=='rightview'){//
        layer.on('click',function (evt) {
            if(evt.graphic.attributes==undefined){
                return;
            }
            require(["js/incident.bundle.js"], function ($root) {
                incident = $root['incident'];
                vue_right.$refs.mychild.show(evt.graphic.attributes.data);
            });
        });
        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));
        });
        layer.on('mouse-out',function (evt) {
          myMap.infoWindow.hide();
        });
    }else if(event=='picture'){//照片
        layer.on('click',function (evt) {
            if(evt.graphic.attributes==undefined){
                return;
            }
            showPicture(evt.graphic.attributes.data.id);
        });
        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));
        });
        layer.on('mouse-out',function (evt) {
          myMap.infoWindow.hide();
        });
    }else {//其他
        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));
        });
        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 != 'null') {
        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 playPath(UserId){
    graphicslayer_gj.clear();
    var st = $('#htmlsjst').val().replace('T', ' ');
    var ed = $('#htmlsjed').val().replace('T', ' ');
    require(["js/intercom.bundle.js"], function ($root) {
        var intercom = $root['intercom'];
        // 调用设备起止时间内的历史轨迹位置
        var queryRequest = new intercom.QueryRequest({
            tokenId: uuid(),
            queryTrackLog: {
                "deviceId": 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',
            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 }
                });
                // var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([0, 0, 255]), 2);
                // var graphic2 = new esri.Graphic(polyline, symbol);
                // graphicslayer_gj.add(graphic2);
                myMap.setExtent(polyline.getExtent(), 19);
                drawWithanimation(0,[line],new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([0, 0, 255]), 2),graphicslayer_gj);
            },
            error: function (message) {
                layer.msg('未查到此人员该时段轨迹');
            }
        });
    });
}

/**
 * 楼盘人口
 */
//获取房间
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) {
    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('');//清空房屋结构
    let 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);
                            myDiv.append('<p class="roomnum">'+temp.name+'</p>');
                            //房间绑定数据和事件
                            myDiv[0].attributes.tag = temp;
                            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
            }
            eventType.target((data.length>0?data[0]:data_building),()=>{
                layerOpen(layui_open_option);
            });
        });
    }
}
//房间添加颜色或者图标
function addRoomMark(divx, item) {
    //租赁过期
    if (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 (item.zdry) {
        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 (item.dy) { //只有房主才会是党员
        divx.append('<img src="img/dangyuan.png" style="float: left;width:15px;margin-left:5px ">');
    }
    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.zdry_list.length; jx++) {
            if (zdrys[i]==(vue_left.zdry_list[jx].marktype)) {
                vue_left.zdry_list[jx].icon&&(result.icons.indexOf(vue_left.zdry_list[jx].icon)==-1)&&result.icons.push(vue_left.zdry_list[jx].icon);
                result.color=vue_left.zdry_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: 'yhzgx', title: '关系',width: 90, align: 'center'},
                    { field: 'name', title: '姓名',width: 80, 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: '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: 'hkdjd', title: '户口登记地', width: 240, 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'}
                ]]
                , data: data,
                done:function(res,curr,count){
                    $("[data-field='zdryextenddata']").css('display','none');
                    $("[data-field='dysl']").css('display','none');
                    LayUIDataTable.SetJqueryObj($);
                    var currentRowDataList = LayUIDataTable.ParseDataTable("czry",function (index, currentData, rowData) {
                    });
                    // 对相关数据进行判断处理-
                    addPersonMark(currentRowDataList);
                }
            });
            getByAjax("./rest/queryldrk/"+data_house.id,data1=>{
                table.render({
                    elem: '#tbx1',
                    height: 190,
                    cellMinWidth: 50,
                    cols: [[ //标题栏
                        { field: 'zlksrq', title: '租赁开始日期', width: 140, align: 'center'},
                        { field: 'zljzrq', title: '租赁到期日期', width: 140, align: 'center'},
                        { field: 'name', title: '姓名',width: 90, 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: '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: 'hkdjd', title: '户口登记地', width: 240, 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'}
                    ]]
                    , data: data1,
                    done:function(res,curr,count){
                        $("[data-field='zdryextenddata']").css('display','none');
                        $("[data-field='dysl']").css('display','none');
                        LayUIDataTable.SetJqueryObj($);
                        var currentRowDataList = LayUIDataTable.ParseDataTable("zkry",function (index, currentData, rowData) {
                        });
                        addPersonMark(currentRowDataList);
                    }
                });
            });
            callback();
        });
    });
}
function addPersonMark(currentRowDataList) {
    $.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 (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 () {
                            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 (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);
        }
    });
}

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){
    getByAjax("./rest/queryphotos/"+id,result=>{
        var json = { title: "照片", data:result };
        layer.photos({
            photos: json,
            anim: 5
        });
    })
}

/**
 websocket前后台双向连接
 */
function initWebsocket(layer) {
    require(["js/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");
           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) {
    console.log(array_abry);
    layer.clear();
    if(array_abry.length==0){
        return;
    }
    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);
    }
}

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

var vue_nt=new Vue({
  el:'.jqxq',
  data:{
      flag:true,
      item_ss:[]
  },
  methods:{
      rightClickSpan:function(){
        if (this.flag == true) {
            $(".jqxq").animate({ "right": "10px" }, "slow", "linear");
            $("#rightClickSpan").css("margin-right","392px");
            $("#rightClickSpan i").html("");
            $(".dqjq").removeClass("dqjq").addClass("dqjq1");
            $(".dqjq1").css("display","none");
            this.flag = false;
        } else {
            $(".jqxq").animate({ "right": "-402px" }, "slow", "linear");
            $("#rightClickSpan i").html("");
            $(".dqjq1").removeClass("dqjq1").addClass("dqjq");
            this.flag = true;
        }
        $(window).trigger('resize');
      },sure:function(item){
        if(item.operate=="未确认"){
          item.operate="已确认";
          ws.send(myUser.userid);
        }
    }
  },
  computed:{
      arr_data:function(){
          if(this.item_ss.length>5){
            this.item_ss.splice(0,1);
          }
          return this.item_ss;
      }
  }
});
vue_top.community.notification.url&&createWebSocketFactory(vue_top.community.notification.url,false,data=>{
    let obj = JSON.parse(data);
    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);
    }
});

vue_top.community.serverparameter.url && createWebSocketFactory(vue_top.community.serverparameter.url, true, data => {
    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 {
        wsObj = new WebSocket("ws://" + window.location.host + "/" + 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(vue_top.community.serverparameter.id);
        };
        wsObj.onmessage = function (evt) {
            callback(evt.data);
        }
      }
      function reconnect(url) {
        if(lockReconnect) {
          return;
        };
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
          createWebSocket(url);
          lockReconnect = false;
        }, 4000);
      }
      createWebSocket(wsUrl);
 }

/**
 *其他方法
 */
function getCookie(c_name) {
    if (document.cookie.length>0){
        var c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1){
            c_start=c_start + c_name.length+1;
            var c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
}

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;
}
