﻿var newMapConfig = {
    //configUrl: 'ajax/configurationservice.ashx?type=map',
    //configUrl:'<%=Url.Content("~/Home/ConfigurationServer/map")%>',
    //configUrl:'../Interfaces/Home/ConfigurationServer/map',
    configUrl: '',
    map: null,
    globemap: null,
    keymap_scale_ary: [],
    map_srs: '',
    map_units: '',
    markers: null,
    usedTools: [],
    q_layer: null,

    markerLayers: {},
    vectorLayers: {},

    tm_markers: null,
    ad_markers: null,
    queryLayers: [],
    onAfterInit: null,
    curLayer: null,
    init: function(mapdiv) {
        this.initMap(mapdiv);
    },

    initQueryLayers: function() {
        var curUserLayers = 'fs_dm,fslw_line,fs_road,fs_theme,fs_gggl,fs_jtys,fs_jrbx,fs_fclp,fs_shfw,fs_zs,fs_cy,fs_xxyl,fs_ylws,fs_lyfw,fs_whmt,fs_zrys,fs_other';
        $.get("ajax/InitLayerList.ashx", { layerid: curUserLayers }, function(ret) {
            var appf = ret;
            var qLayersInfo = newMapConfig.queryLayers;

            if (ret.layers) {
                var numf = (appf.layers.length > 1) ? appf.layers.length : 1;
                for (var k = 0; k < numf; k++) {
                    var qlyr, qLayer;
                    if (numf > 1)
                        qlyr = appf.layers[k];
                    else
                        qlyr = appf.layers;

                    if (qlyr.running == 1) {
                        qLayer = new NQueryLayer(qlyr.name, qlyr.onlineresource, { queryfields: qlyr.queryfields, statfields: qlyr.statfields });
                        qLayer.id = qlyr.id;
                        qLayersInfo.push(qLayer);
                    }
                }
            } else {
                var qlyr, qLayer;
                qlyr = appf;

                if (qlyr.running == 1) {
                    qLayer = new NQueryLayer(qlyr.name, qlyr.onlineresource, { queryfields: qlyr.queryfields, statfields: qlyr.statfields });
                    qLayersInfo.push(qLayer);
                }
            }
            if (newMapConfig.onAfterInit) {
                newMapConfig.onAfterInit();
            }
        }, 'json');
    },

    initMap: function(mapdiv) {
        //newMapConfig.q_layer = new NVectorLayer();
        newMapConfig.markers = new NMarkersLayer('markers');
        //newMapConfig.tm_markers = new NMarkersLayer('tm_markers');
        //newMapConfig.ad_markers = new NMarkersLayer('ad_markers');

        var cofigUrl = this.configUrl;

        $.getJSON(cofigUrl, function(res) {
            if (res.success) {
                var app = res.data.Application;
                var mapSet = app.MapSet;
                var app_name = mapSet.Name;
                var app_bbox_ary = mapSet.BoundingBox.split(',');
                var app_scale_ary = mapSet.Scales.split(','); //地图比例尺

                newMapConfig.keymap_scale_ary = mapSet.KeyScales.split(',');

                newMapConfig.map_srs = mapSet.SRS;

                newMapConfig.map_units = 'm';

                if (newMapConfig.map_srs == 'epsg:4326' || newMapConfig.map_srs == 'epsg:4214' || newMapConfig.map_srs == 'epsg:4610' || newMapConfig.map_srs == 'epsg:4055') {
                    newMapConfig.map_units = 'dd';
                }

                newMapConfig.map = new NMap(mapdiv, {
                    projection: newMapConfig.map_srs,
                    units: newMapConfig.map_units
                });

                var extent = new NBounds(app_bbox_ary[0], app_bbox_ary[1], app_bbox_ary[2], app_bbox_ary[3]);

                newMapConfig.map.scales = app_scale_ary;
                newMapConfig.map.maxExtent = extent;

                var num = (mapSet.MapLayers.Layer.length > 1) ? mapSet.MapLayers.Layer.length : 1;

                for (var i = 0; i < num; i++) {
                    var lyr, layer;

                    if (num > 1)
                        lyr = mapSet.MapLayers.Layer[i];
                    else
                        lyr = mapSet.MapLayers.Layer;

                    var type = lyr.Type.toLowerCase();

                    if (type == 'ncachelayer' || type == 'cachelayer')//添加cachelayer图层
                    {
                        layer = new NCacheLayer(lyr.Name, lyr.OnlineResource, { layers: lyr.Layers, format: lyr.Format }, { transitionEffect: lyr.transitionEffect, isBasicLayer: (lyr.isBasicLayer == 'true') ? true : false });
                    }
                    else if (type == 'owslayer')//添加owslayer图层
                    {
                        layer = new NWMSLayer(lyr.Name, lyr.OnlineResource, { layers: lyr.Layers, format: lyr.Format, transparent: lyr.transparent }, { isBasicLayer: (lyr.isBasicLayer == 'true') ? true : false });
                    } else if (type == 'ntilecachelayer' || type == 'tilecachelayer') {
                        layer = new NTileCacheLayer(lyr.Name, lyr.OnlineResource, lyr.Layers, { isBasicLayer: (lyr.isBasicLayer == 'true') ? true : false, tileOrigin: new NLatLng(-180, 90) });
                    } else if (type == 'nwmtslayer' || type == 'wmtslayer') {
                        newMapConfig.map.limitedZoomExtent = extent;
                        lyr.OnlineResource += '&style=default&TILEMATRIXSET=' + newMapConfig.map_srs;
                        var resolutions = lyr.Resolutions.split(',');
                        layer = new NWMTSLayer(lyr.Name, lyr.OnlineResource, { isBasicLayer: (lyr.isBasicLayer == 'true') ? true : false, tileOrigin: new NLatLng(-180, 90), format: lyr.Format, resolutions: resolutions });
                    } else if (type == 'nmaplayer' || type == 'maplayer') {
                        layer = new NATCacheLayer(lyr.Name, lyr.OnlineResource);

                    }


                    // var temLayerVisible = (lyr.isBasicLayer == 'true') ? true : false

                    //if (!temLayerVisible)
                    layer.isBasicLayer = (lyr.isBasicLayer == 'true') ? true : false;
                    layer.visible = (lyr.initVisible == 'true') ? true : false;
                    //layer.opacity = 0.1;
                    layer.redraw();
                    newMapConfig.map.addLayer(layer);
                }

                //newMapConfig.markers.showInLayerList = false;
                //newMapConfig.q_layer.showInLayerList = false;
                //newMapConfig.tm_markers.showInLayerList = false;
                //newMapConfig.ad_markers.showInLayerList = false;

                //newMapConfig.map.addLayer(newMapConfig.markers);
                //newMapConfig.map.addLayer(newMapConfig.tm_markers);
                //newMapConfig.map.addLayer(newMapConfig.q_layer);
                //newMapConfig.map.addLayer(newMapConfig.ad_markers);

                //初始化地图控件,包括各工具、控件
                newMapConfig.initButtonsControls(app);

                newMapConfig.map.zoomToExtent(extent);

                //可查询图层
                //newMapConfig.queryLayers = app.QueryLayers.Layer;

                //初始化可查询涂层
                //newMapConfig.initQueryLayers();
                if (newMapConfig.onAfterInit) {
                    newMapConfig.onAfterInit();
                }
            }
            else {
                alert(res.msg);
            }
        });
    },

    getMarkerLayer: function(key, lysort) {

        var markerLayer = this.markerLayers[key];
        if (!markerLayer) {
            markerLayer = new NMarkersLayer(key);
            if (lysort)
                markerLayer.layersort = lysort;

            markerLayer.showInLayerList = false;
            this.markerLayers[key] = markerLayer;

            this.map.addLayer(markerLayer);
        }

        return markerLayer;
    },
    getFeatureLayer: function(key, symbol, lysort) {
        var vectorLayer = this.vectorLayers[key];
        if (!vectorLayer) {
            vectorLayer = new NVectorLayer(key);

            if (symbol)
                vectorLayer.symbols = symbol;

            if (lysort)
                vectorLayer.layersort = lysort;

            vectorLayer.showInLayerList = false;
            this.vectorLayers[key] = vectorLayer;

            this.map.addLayer(vectorLayer);
        }

        return vectorLayer;
    },

    initButtonsControls: function(app) {
        var interfaceSet = app.InterfaceSet;
        var controlSet = interfaceSet.Controls;
        newMapConfig.initControls(controlSet);
        var buttonSet = interfaceSet.Buttons;
        newMapConfig.initButtons(buttonSet);
    },

    initControls: function(controls) {

        if (controls == null) {
            return;
        }

        var controlEnable = controls.Enable;

        if (controlEnable == 'false') {
            alert('disabled');
            return;
        }

        var controlsItems = controls.ListItem;
        var controlsNum = controlsItems.Item.length;

        for (var i = 0; i < controlsNum; i++) {
            var tempcontrol;
            if (controlsNum > 1)//从配置文件获得各控件
            {
                tempcontrol = controlsItems.Item[i];
            }
            else {
                tempcontrol = controlsItems.Item;
            }

            var tempControlChecked = tempcontrol.checked; //控件是否添加true、false

            if (tempControlChecked == 'true') {
                var tempControlName = tempcontrol.Name;
                newMapConfig.addControlByName(tempControlName);
            }
        }
    },

    initButtons: function(buttonSet) {
        if (buttonSet == null) {
            return;
        }
        var buttonEnable = buttonSet.Enable;
        if (buttonEnable == 'false') {
            alert('disabled');
            return;
        }

        var buttonsList = buttonSet.ListItem;
        var buttonNum = buttonsList.Item.length;

        for (var i = 0; i < buttonNum; i++) {
            var tempButton;
            if (buttonNum > 1) {
                tempButton = buttonsList.Item[i];
            }
            else {
                tempButton = buttonsList.Item;
            }

            var tempButtonChecked = tempButton.checked;
            if (tempButtonChecked == 'true') {
                var tempButtonName = tempButton.Name;
                var tempButtonKey = tempButton.Key;
                newMapConfig.addButtons2Map(tempButtonName, tempButtonKey);
            }
        }
    },

    addButtons2Map: function(name, key) {
        newMapConfig.addTool2Map(name, key);
    },

    //在地图上添加工具
    addTool2Map: function(toolName, toolKey) {
        //debugger;
        var curcontrol;
        if (toolName == '全图' || toolName == '全图显示') {
            curcontrol = new NZoomToMaxExtentTool();
        }
        else if (toolName == '放大' || toolName == '地图放大') {
            curcontrol = new NZoomBoxInTool();
        }
        else if (toolName == '缩小' || toolName == '地图缩小') {
            curcontrol = new NZoomBoxOutTool();
        }
        else if (toolName == '移动' || toolName == '地图漫游') {
            curcontrol = new NDragPanTool();
        }
        else if (toolName == '清除' || toolName == '地图清除') {
            curcontrol = new NClearFeatureTool();
        }
        else if (toolName == '打印' || toolName == '地图打印') {
            curcontrol = new NPrintTool();
        }
        else if (toolName == '测距' || toolName == '距离量测') {
            curcontrol = new NMeasureTool({ mode: "length", "div": "toolMeasure", resultDiv: document.getElementById("divoutput") });
        }
        else if (toolName == '测面' || toolName == '面积量测') {
            curcontrol = new NMeasureTool({ mode: "area", "div": "toolMeasure", resultDiv: document.getElementById("divoutput") });
        }
        else if (toolName == "矩形查询") {
            curcontrol = new NRectQueryTool();
        }
        else if (toolName == "圆形查询") {
            curcontrol = new NCircleQueryTool();
        }
        else if (toolName == "多边形查询") {
            curcontrol = new NPolygonQueryTool({ "callback": "ad.showResult" });
        }
        else if (toolName == "矩形统计") {
            curcontrol = new NRectStatTool();
        }
        else if (toolName == "圆形统计") {
            curcontrol = new NCircleStatTool();
        }
        else if (toolName == "多边形统计") {

            curcontrol = new NPolygonStatTool();

        }
        else {
            alert('无法找到' + toolName + '对应的工具!');
            return;
        }
        //添加控件到map
        if (newMapConfig.map != null && curcontrol != undefined && curcontrol != null) {
            newMapConfig.map.addTool(curcontrol);
            newMapConfig.usedTools[toolKey] = curcontrol;
        }
    },

    switchMode: function(id) {
        //newMapConfig.map.events.unbind('click', newMapConfig.map, query.click);

        if (id == "IDZoomToMaxExtent") { newMapConfig.map.zoomToMaxExtent(); return; }
        for (var key in newMapConfig.usedTools) {

            if (key != "remove" && key != "indexOf" && key != 'forEach') {
                var toolid = newMapConfig.usedTools[key].id;

                if (key == id || id == toolid) {

                    if (key == "IDMeasureLength" || key == "IDMeasureArea") {

                        document.getElementById("divoutput").style.display = "block";

                    } else {

                        //document.getElementById("divoutput").style.display = "none";
                    }

                    newMapConfig.usedTools[key].enable();

                    if (id == 'IDClear') {

                        var markers = newMapConfig.markerLayers;

                        for (var key in markers) {
                            if (markers[key]) {
                                markers[key].clearMarkers();
                            }
                        }

                        var vectors = newMapConfig.vectorLayers;
                        var vector;
                        for (var key in vectors) {
                            if (vectors[key]) {
                                vector = vectors[key];
                                vector.disposeFeatures(vector.features);
                            }
                        }

                        var dLength = newMapConfig.map.dialogs.length;
                        var dialogToRemove = null;

                        while (dLength > 0) {

                            dialogToRemove = newMapConfig.map.dialogs[dLength - 1];
                            newMapConfig.map.removeDialog(dialogToRemove);
                            dialogToRemove.dispose();

                            dLength--;
                        }
                    }

                } else {

                    newMapConfig.usedTools[key].disable();

                }
            }
        }

    },

    addControlByName: function(name) {

        var control;

        if (name == '比例尺') {
            control = new NScaleBarControl();
            newMapConfig.map.addControl(control);
        }
        else if (name == '鹰眼图') {
            control = new NOverviewMapControl({
                'div': NUtility.getElement('overviewmap'),
                //'div':overviewmap,
                //'backgroundColor': 'white',
                mapOptions: {
                    projection: newMapConfig.map_srs,
                    units: newMapConfig.map_units,
                    scales: newMapConfig.keymap_scale_ary
                },

                'size': new NSize(130, 130)
            });
            newMapConfig.map.addControl(control);
        }

        else if (name == '图层列表') {
            control = new NLayerListControl({ "div": NUtility.getElement('mapctl_div') });
            control.playInSolidDiv = false;
            control.gFontSize = "2px";
            control.gFontColor = "#518eb8";
            control.gFont = "微软雅黑";
            control.layerNameFontSize = "1px";
            control.layerNameFont = "宋体";
            control.layerNameFontColor = "#153957";
            newMapConfig.map.addControl(control);
        }
        else if (name == '鼠标坐标') {
            control = new NCursorPositionControl({ "div": NUtility.getElement('cursorPosition') });
            newMapConfig.map.addControl(control);
        }
        else if (name == '浏览工具条') {
            control = new NPanZoomBarControl();
            newMapConfig.map.addControl(control);
        }
        else {
            alert("不存在[" + name + "]类型的控件");
            return;
        }
    },

    cursorHand: function() {
        this.map.div.style.cursor = 'hand';
    },

    cursorDrag: function() {
        newMapConfig.usedTools['IDDragPan'].enable();
    },

    panTo: function(lon, lat) {
        var latlng = new NLatLng(lon, lat);
        newMapConfig.map.panTo(latlng);
    }
};


