var projectPolyline = []; // 会议,审批等坐标线
var projectPolygon = []; // 会议,审批等坐标面
var projectPoint = null; // 会议,审批等坐标点

define([
    'lib/BaseWidget',
    'dojo/topic',
    'dojo/_base/lang',
    'dojo/_base/declare',
    "esri/Graphic",
    "esri/geometry/Point",
    "esri/geometry/Polygon",
    "esri/geometry/Polyline",
    'esri/geometry/SpatialReference',
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol",
    "lib/WebUpLoader",
    "lib/shapefile",
    "lib/DxfParser",
], function(
    BaseWidget, topic, lang, declare, Graphic, Point, Polygon, Polyline, SpatialReference, SimpleFillSymbol, PictureMarkerSymbol, SimpleMarkerSymbol, SimpleLineSymbol, d_WebUpLoader, d_shapefile, d_DxfParser
){
    var GM = null;
    var clazz = declare([BaseWidget], {
        type: 'lib',
        name: 'GraphicManager',
        view: null, // 地图主控件
        edit: null, // 是否可写
        contextId: null,
        projectCode: null,  // 项目标识
        projectType: null,  // 项目类型
        projectTitle: null, // 项目名称
        projectNumber: null,  // 项目编号
        projectInoffice: null, // 项目所属单位
        projectMapObject: {}, // 审批,会议等项目对象
        /**
         *  组件构造方法
         */
        constructor: function (view) {
            this.view = window['mapview'];
            this.initGraphicManager();
        },
        startup: function () {
            console.log("startup");
        },

        initGraphicManager: function () {
            this.edit  = this.checkEmpty(this.getQueryString("state"));
            this.projectType = this.checkEmpty(this.getQueryString("type"));
            this.contextId = this.checkEmpty(this.getQueryString("contextid"));
            this.projectCode = this.checkEmpty(this.getQueryString("projectid"));
            this.projectNumber = this.checkEmpty(this.getQueryString("projectno"));
            this.projectInoffice = this.checkEmpty(this.getQueryString("inoffice"));
            this.projectTitle = this.checkEmpty(decodeURI(decodeURI(this.getQueryString("title")))); // 编码用encodeURI,解码用decodeURI
            window.OA_USERNAME = this.checkEmpty(decodeURI(decodeURI(this.getQueryString("username"))));
            window.OA_USERID = this.checkEmpty(this.getQueryString("userid")) || -1;

            this.setDdocumentTitle(this.projectTitle);

            //this.GraphicAttrManager();
        },

        layerTypeSymbol: [{
            type: "项目用地",
            symbol: { type: "simple-fill", color: [255, 255, 255, 0], style: "solid", outline: { color: [234, 0 , 11, 255], width: 1.5 } }
        }, {
            type: "代征道路",
            symbol: { type: "simple-fill", color: [30, 159, 255, 255], style: "backward-diagonal", outline: { color: [30, 159, 255, 255], width: 1.5 } }
        }, {
            type: "代征绿地",
            symbol: { type: "simple-fill", color: [0,255,0, 255], style: "backward-diagonal", outline: { color: [0, 255, 0, 255], width: 1.5 } }
        }],

        GraphicAttrManager: function () {
            //this.getProjectData();

            var projectType = this.projectType;
            if (this.isEmpty(projectType) ) {

            } else if (projectType == 'HY') {

                //this.HYGraphicAttrManager();

            } else if (projectType == 'SP'){

                //this.SPGraphicAttrManager();

            }
        },

        SPGraphicAttrManager: function () {
            // .....
        },

        HYGraphicAttrManager: function (){
            // .....
        },

        getProjectData: function() {
            var these = this;
            var projectno = these.projectCode;
            if (!these.checkEmpty(projectno)) return null;

            $.ajax({
                type: "POST",
                url: ONEMAP_SERVER+"/projectMap/findProjectMapByProjectCode",
                data: {'projectCode': projectno},
                success: function (result){
                    if (result) {
                        these.projectMapObject = these.NewProjectMapClass(result);
                    }
                },
                error:function(e){
                    console.log("请求出错----->" + JSON.stringify(e));
                }
            });
        },

        ProjectMapClass: function (params) {
            if (params === null || params === undefined) {
                params = {};
            }
            this.id = params.id || "";
            this.gid = params.gid || "";
            this.geom = params.geom || [];
            this.area = params.area || "";
            this.type = params.type || "";
            this.axis = params.axis || "";
            this.userid = params.userid || "";
            this.axisType = params.axisType || "";
            this.landType = params.landType || [];
            this.landArea = params.landArea || "";
            this.createTime = params.createTime || "";
            this.projectCode = params.projectCode || "";
            this.projectLayers = params.projectLayers || [];
            this.Polyline = [];
            this.Polygon = [];
            this.Point = [];

            if (Array.isArray(this.projectLayers)) {
                this.projectLayers.forEach( function (value) {
                    var geom = value.geom;
                    var symbol = value.layerStyle;
                    var geomjson = typeof geom === 'string' ? JSON.parse(geom) : geom;
                    var symboljson = symbol ? JSON.parse(symbol) : '';
                    value.geom = geomjson ? geomjson : '';
                    value.layerStyle = symboljson ? symboljson : '';
                })
            }

            if (typeof this.geom === 'string') {
                this.geom = JSON.parse(this.geom);
            }

            if (typeof this.landType === 'string') {
                this.landType = JSON.parse(this.landType);
            }
        },

        NewProjectMapClass: function(data) {
            /*var mapClass = new this.ProjectMapClass(
                data['gid'],
                data['projectCode'],
                data['type'],
                data['axis'],
                data['axisType'],
                data['geom'],
                data['area'],
                data['landType'],
                data['createTime'],
                data['projectLayers']
            );*/
            var mapClass = new this.ProjectMapClass(data);
            return mapClass;
        },
        /**
         *
         */
        PolylineManager: {
            drawPolyline: function() {
                var object = this.projectMapObject;
                var polyline = object.Polyline;
            }
        },

        /**
         * 获取分析类型
         */
        getAnalyseType: function () {
            return this.projectType === 'railtransit' ? 'separate' : 'merge'
        },
        /**
         * 读取dxf文件
         * @param fileid    文件ID
         * @param file      dxf文件对象
         * @param obj       Object对象,读取文件触发方法 (参考FileReader)
         */
        _dxfReader: function (fileid, file, obj) {
            var reader = new FileReader();
            // 读取过程中周期性触发
            reader.onprogress = obj['onprogress'];
            // 读取数据后触发,在读取成功或读取失败后触发
            reader.onloadend = obj['onloadend'];
            // 中止读取后触发
            reader.onabort = obj['onabort'];
            // 读取数据时抛异常时触发
            reader.onerror = obj['onerror'];
            // 读取数据成功后触发
            reader.onload = function (e) {
                var result = (new window.DxfParser).parseSync(e.target.result);
                obj['onload'] && obj.onload(fileid, result);
            };
            //将文件以文本形式读入页面
            reader.readAsText(file);
        },

        /**
         * 解析dxf数据
         * @param dxfdata   dxf数据
         * @returns {Array} 坐标数组
         */
        parserForDxf: function (dxfdata) {
            var paths = [];
            if(dxfdata && dxfdata.entities){
                dxfdata.entities.forEach ( function (entitie) {
                    if ( typeof entitie == 'object' && Array.isArray(entitie.vertices) ) {
                        var arry = [];
                        entitie.vertices.forEach(function (vertice) {
                            arry.push([vertice.x, vertice.y]);
                        })
                        paths.push(arry);
                    }
                })
            } else {
                console.log("dxf数据为空!");
            }

            if (paths.length === 0) {
                layer.msg("解析dxf数据是空的");
                throw new Error("paths.length === 0");
            }
            return paths;
        },

        /**
         * 读取shp文件
         * @param fileid    文件ID
         * @param file      shp文件对象
         * @param obj       Object对象,读取文件触发方法 (参考FileReader)
         */
        _shpReader: function (fileid, file, obj) {
            topic.subscribe("shpReader", lang.hitch(this, function (reader) {
                reader.onprogress = obj['onprogress'];
                reader.onloadend = obj['onloadend'];
                reader.onabort = obj['onabort'];
                reader.onerror = obj['onerror'];
            }));
/*            new window.Shapefile({ shp: file }, lang.hitch(this, function (result) {
                obj['onload'] && obj.onload(fileid, result);
            }))*/
            var shpArray = [];
            var reader = new FileReader();
            reader.onload = function(e) {
                d_shapefile.open(e.target.result)
                    .then( function (source) {
                        source.read().then(function sourceRead(result) {
                                if (result.done) {
                                    return obj['onload'] && obj.onload(fileid, shpArray);
                                } else {
                                    shpArray.push(result.value);
                                    return source.read().then(sourceRead);
                                }
                        }).catch( function (error) {
                            obj['onerror'] && obj.onerror(error);
                        })
                }).catch( function (error) {
                    obj['onerror'] && obj.onerror(error);
                })
            };
            reader.readAsArrayBuffer(file);
        },

        /**
         * 解析shp数据
         * @param shpdata   shp数据
         * @returns {Array} 坐标数组
         */
        parserForShp: function (shpdata) {
            var paths = [];
            shpdata.forEach( function (feature) {
                var type = feature.geometry['type'];
                type = type && type.toString().toLocaleLowerCase();
                if ( type.indexOf('polygon') != -1 || type.indexOf('polyline') != -1) {
                    feature.geometry.coordinates.forEach( function (coordinate) {
                        paths.push(coordinate);
                    });
                } else {
                    layer.msg("单前仅支持导入多段线的地块图形。当前导入类型:[" + type +']');
                    throw new Error("");
                }
            })
            if (paths.length === 0) {
                layer.msg("解析shp数据是空的");
                throw new Error("paths.length === 0");
            }
            return paths;
        },

        /**
         * 读取txt文件
         * @param fileid    文件ID
         * @param file      shp文件对象
         * @param obj       Object对象,读取文件触发方法 (参考FileReader)
         */
        _txtReader: function (fileid, file, obj) {
            var reader = new FileReader();
            reader.onprogress = obj['onprogress'];
            reader.onloadend = obj['onloadend'];
            reader.onabort = obj['onabort'];
            reader.onerror = obj['onerror'];
            reader.onload = obj['onload']
            reader.readAsText(file, "gb2312");
        },

        /**
         * 解析txt数据
         * @param txtdata   txt数据
         * @returns {Array} 坐标数组
         */
        parserForTxt: function (txtdata) {
            var gam = this, paths = [];

            var hintMsg = function (i, msg) {
                var tip = "";
                if (gam.isNotEmpty(i)) {
                    tip = "第" + (parseInt(i)+1) + "行错误, ";
                }
                layer.msg(tip + msg);
                throw new Error("数据格式错误");
            };

            if(this.checkEmpty(txtdata)){
                var splitn = txtdata.split("\n");
                // 确保数组最后一个是空字符串
                var endStr = splitn[splitn.length-1];
                this.isNotEmpty(endStr) &&splitn.push("");

                var xyArray = [];
                for (var i in splitn) {
                    var spliti = splitn[i];
                    // 如果是空行,
                    if (!spliti.trim()) {
                        paths.push(xyArray);
                        xyArray = [];
                        continue;
                    }
                    var array = [];
                    var xycoord = spliti.split(",");
                    if (xycoord.length == 2) {
                        // 必须是数字,否则抛出异常
                        !gam.isNumber(xycoord[0]) && hintMsg(i, "必须是数字!");
                        !gam.isNumber(xycoord[1]) && hintMsg(i, "必须是数字!");
                        // 添加xy坐标(默认第一个是X坐标)
                        array.push(parseFloat(xycoord[0]));
                        array.push(parseFloat(xycoord[1]));
                        xyArray.push(array);
                    } else {
                        hintMsg(i,"格式不正确!");
                        paths = [];
                    }
                }
            } else {
                console.log("txt数据为空!");
            }
            gam.deleteArrayEmptyObject(paths);
            if (paths.length == 0) {
                hintMsg(null, "数据格式错误");
            }
            return paths;
        },

        drawProjectGraphic: function (ringArray, blockType) {
            var gam = this, graphicList = [];
            var projectLayers = this.projectMapObject.projectLayers;
            if (Array.isArray(projectLayers)) {
                projectLayers.map( function (item, index) {
                    var coordinates = item.geom.coordinates;
                    var symbol = gam.getSymbolByType(item.layerType);
                    var graphic = gam.NewGraphicPolygon(coordinates[0], symbol);
                    graphic ? graphicList.push(graphic) : console.warn('new Graphic() 失败!');
                })
            }

            projectPolyline && projectPolyline.forEach( function (graphic, index) {
                gam.view.graphics.remove(graphic);
            })

            graphicList.forEach( function (graphic, index) {
                gam.view.graphics.add(graphic);
            })

            projectPolyline = graphicList;
        },
        drawprojectPolyline: function () {
            this.drawProjectGraphic();
        },
        /**
         *
         */
        NewGraphicPolygon: function (array, symbol) {
            if (Array.isArray(array)) {
                var newarray = JSON.parse(JSON.stringify(array));
                array = this.deleteArrayEmptyObject(newarray, true);
            } else {
                return null;
            }

            if (array.length === 0) {
                return null;
            } else if(array.length === 1) {
                if (Array.isArray(array[0]) && array[0].length === 1 && Array.isArray(array[0][0]) && array[0][0].length === 2) {
                    return this.NewGraphicPoint(array[0][0][0], array[0][0][1]);
                }
            } else if(array.length === 2) {
                return this.NewGraphicPolyline(array);
            } else if (!this.isPathsOrRings(array)) {
                return null;
            }

            var polygon = new Polygon();
            polygon.rings = array;
            polygon.spatialReference = this.view.spatialReference;
            if (this.isEmpty(symbol)) {
                symbol = {
                    type: "simple-fill",
                    color: [255, 255, 255, 0],
                    style: "solid",
                    outline: { color: [234, 0 , 11, 255], width: 1 }
                };
            }
            return new Graphic(polygon, symbol);
        },
        /**
         *
         */
        NewGraphicPolyline: function (array) {
            if (this.isEmpty(array)) return null;
            var polyline = new Polyline({ "paths": array, "spatialReference": { "wkid": 2381 }});
            var lineSymbol = { type: "simple-line", color: "#FF5722", width: 2 };
            return new Graphic(polyline, lineSymbol);
        },

        getSymbolByType: function (type) {
            var symbol;
            for (var key in this.layerTypeSymbol) {
                var layer = this.layerTypeSymbol[key];
                if ( type == layer.type ) {
                    symbol = layer.symbol;
                    break;
                }
            }
            return symbol || { type: "simple-fill", color: [255, 255, 255, 0], style: "solid", outline: { color: [234, 0 , 11, 255], width: 1.5 } };
        },
        /**
         *
         */
        drawProjectPoint: function (graphic) {
            if (!graphic) return false;
            projectPoint && this.view.graphics.remove(projectPoint);
            this.view.graphics.add(graphic);
            projectPoint = graphic;
        },
        /**
         *
         */
        NewGraphicPoint: function (xcoord, ycoord) {
            if (this.isEmpty(xcoord) || this.isEmpty(ycoord)) return false;
            var point = new Point(xcoord, ycoord, this.view.spatialReference);
            var graphic = new Graphic();
            graphic.geometry = point;
            graphic.symbol = new PictureMarkerSymbol('widgets/MapTool/images/tag.png', 10, 10);
            return graphic;
        },
        /**
         *
         */
        getProjectPolylineString: function () {
            var xyAxis = [];
            if (this.isEmpty(projectPolyline)) return "";
            projectPolyline.forEach( function (polyline) {
                var paths = polyline.geometry['paths'] || polyline.geometry['rings'];
                paths.map( function (val) {
                    var xy = [];
                    val.forEach(function (value) {
                        xy.push(value[0] + " " + value[1]);
                    });
                    xyAxis.push(xy.join(','));
                })
            });
            return 'MultiPolygon(((' + xyAxis.join("),(") + ")))";
        },
        GeometryToMultiPolygon: function (arry) {
            var xyAxis = [];
            var isempty = this.isEmpty(arry);
            var ispathsorrings = this.isPathsOrRings(arry);
            if ( isempty || !ispathsorrings ){ return ""; }
            arry.map( function (val) {
                var xy = [];
                val.forEach(function (value) {
                    xy.push(value[0] + " " + value[1]);
                });
                xyAxis.push(xy.join(','));
            })
            return 'MultiPolygon(((' + xyAxis.join("),(") + ")))";
        },
        /**
         *
         */
        getPolygonString: function (rings) {
            this.deleteArrayEmptyObject(rings, true);
            if ( !this.isPathsOrRings(rings) ) {
                return "";
            }
            var gam = this;
            var xyAxis = [];
            rings.map( function (ring) {
                if (ring.length > 2 ) {
                    ring = gam.closingCoord(ring);
                }
                var xy = [];
                ring.forEach(function (value) {
                    xy.push(value[0] + " " + value[1]);
                });
                xyAxis.push(xy.join(','));
            })
            return "MultiPolygon(((" + xyAxis.join("),(") + ")))";
        },

        /**
         * 是否超出地图范围
         * @param extent 最大最小坐标对象
         * @returns {number} 几个坐标超出范围
         */
        OffMapCoord: function (extent) {
            var that = this, num = 0;
            if (that.isEmpty(extent) || that.isEmpty(extent.xmax) || that.isEmpty(extent.ymax) || that.isEmpty(extent.xmin) || that.isEmpty(extent.ymin)) return num;
            // 判断是否在地图范围
            var viewExtent = this.view.extent;
            var _xmax = viewExtent.xmax < extent.xmax;
            var _ymax = viewExtent.ymax < extent.ymax;
            var _xmin = viewExtent.xmin > extent.xmin;
            var _ymin = viewExtent.ymin > extent.ymin;
            _xmax && num++; _xmin && num++;
            _ymax && num++; _ymin && num++;
            return num;
        },
        OffMapCoord2: function (point) {
            var viewExtent = this.view.extent;
            var _xmax = viewExtent.xmax > point[0];
            var _ymax = viewExtent.ymax > point[1];
            var _xmin = viewExtent.xmin < point[0];
            var _ymin = viewExtent.ymin < point[1];
            if (_xmax && _ymax && _xmin && _ymin) {
                return false;
            } else {
                return true;
            }
        },
        /**
         * 设置缩放
         */
        setViewZoom: function (extent) {
            var scale = this.getZoomScale(extent);
            this.view.scale = scale;
        },
        /**
         * 计算缩放比例尺
         */
        getZoomScale: function (extent) {
            var empty = this.isEmpty;
            if (empty(extent)) return false;
            if (empty(extent.xmax) || empty(extent.ymax) || empty(extent.xmin) || empty(extent.ymin)) return false;
            var xmax = extent.xmax, ymax = extent.ymax, xmin = extent.xmin, ymin = extent.ymin;
            var width = (ymax-ymin) > (xmax-xmin) ? (ymax-ymin) : (xmax-xmin);
            var scale = width*7/(this.view.extent.width/this.view.scale);
            return scale;
        },
        /**
         * 设置中心点
         * @param extent 坐标范围
         */
        setViewCentral: function (extent) {
            var empty = this.isEmpty;
            if (empty(extent)) return false;
            if (empty(extent.xmax) || empty(extent.ymax) || empty(extent.xmin) || empty(extent.ymin)) return false;
            var xmax = parseFloat(extent.xmax), ymax = parseFloat(extent.ymax), xmin = parseFloat(extent.xmin), ymin = parseFloat(extent.ymin);
            this.view.goTo(new Point((xmax+xmin)/2, (ymax+ymin)/2, this.view.spatialReference));
        },
        /**
         * 设置中心点
         * @param point 坐标点
         */
        setViewCentral2: function (point) {
            if (this.isCoord(point)) {
                this.view.goTo(new Point(point[0], point[1], this.view.spatialReference));
            }
        },
        /**
         * 获取做最大最小XY
         * geometry数组
         */
        PolyMaxOrMin: function () {
            var mapObject = this.projectMapObject;
            var layers = mapObject.projectLayers;
            if (Array.isArray(layers)===false) {
                return false;
            }
            var xmax, xmin, ymax, ymin;
            var gam = this;
            layers.forEach(function (layer, index) {
                if (layer.geom && Array.isArray(layer.geom.coordinates)) {
                    var coordinates = layer.geom.coordinates;
                    coordinates.forEach( function (coordinate1, index1) {
                        coordinate1.forEach( function (coordinate2, index2) {
                            coordinate2.forEach( function (coordinate3, index3) {
                                if (gam.isCoord(coordinate3)) {
                                    var xcoord = coordinate3[0], ycoord = coordinate3[1];
                                    (gam.isNotEmpty(xmax) || (xmax = xcoord)) && xmax<xcoord && (xmax=xcoord);
                                    (gam.isNotEmpty(ymax) || (ymax = ycoord)) && ymax<ycoord && (ymax=ycoord);
                                    (gam.isNotEmpty(xmin) || (xmin = xcoord)) && xmin>xcoord && (xmin=xcoord);
                                    (gam.isNotEmpty(ymin) || (ymin = ycoord)) && ymin>ycoord && (ymin=ycoord);
                                }
                            })
                        })
                    })
                }
            });
            return {'xmax': xmax, 'xmin': xmin, 'ymax': ymax, 'ymin': ymin};
        },
        /**
         * 获取数组最大最小XY
         */
        ArrayMaxOrMin: function (array) {
            if ( !this.isPathsOrRings(array)){
                return false;
            }
            var gam = this;
            var xmax, xmin, ymax, ymin;
            array.forEach( function (value) {
                value.map( function (val) {
                    var xcoord = val[0], ycoord = val[1];
                    gam.isNotEmpty(xcoord) && (gam.isNotEmpty(xmax) || (xmax = xcoord)) && xmax<xcoord && (xmax=xcoord);
                    gam.isNotEmpty(ycoord) && (gam.isNotEmpty(ymax) || (ymax = ycoord)) && ymax<ycoord && (ymax=ycoord);
                    gam.isNotEmpty(xcoord) && (gam.isNotEmpty(xmin) || (xmin = xcoord)) && xmin>xcoord && (xmin=xcoord);
                    gam.isNotEmpty(ycoord) && (gam.isNotEmpty(ymin) || (ymin = ycoord)) && ymin>ycoord && (ymin=ycoord);
                })
            })
            return {'xmax': xmax, 'xmin': xmin, 'ymax': ymax, 'ymin': ymin};
        },
        /**
         *
         */
        isPathsOrRings: function (array) {
            for ( var i=0; i<array.length; i++) {
                var _value = array[i];
                if (Array.isArray(_value) && _value.length == 2) {
                    return false;
                }
                for (var key in _value){
                    if (!this.isCoord(_value[key])) {
                        return false;
                    }
                }
            }
            return true;
        },

        verificationCoordinate: function (coordinate) {
            var _this = this;
            if (Array.isArray(coordinate) === false) {
                layer.msg("坐标信息错误");
                throw new Error("坐标信息错误");
            }
            coordinate.forEach(function(itemArray) {
                if (Array.isArray(itemArray)) {
                    itemArray.forEach(function(item) {
                        if (_this.isCoord(item)) {
                            var x = parseInt(item[0]).toString();
                            var y = parseInt(item[1]).toString();
                            if (x.length === 8 && x.substring(0, 2) === '36') {
                                var xStr = item[0].toString();
                                item[0] = Number(xStr.substring(2, xStr.length));
                            }
                            if (y.length === 9 && y.substring(0, 2) === '36') {
                                var yStr = item[1].toString();
                                item[1] = Number(yStr.substring(2, yStr.length));
                            }
                            if (item[0]>672512 || item[0]<463417 || item[1]>3892165 || item[1]<3725140) {
                                layer.msg("导入坐标不在西安市坐标范围内");
                                throw new Error("导入坐标超出西安市坐标范围");
                            }
                        } else {
                            layer.msg("坐标信息错误");
                            throw new Error("坐标信息错误");
                        }
                    });
                } else {
                    layer.msg("坐标信息错误");
                    throw new Error("坐标信息错误");
                }
            })
        },

        verificationLayer: function () {
            var util=this,
                message = new Array(),
                layerArray = new Array();

            if (Array.isArray(util.projectMapObject.projectLayers) === false) {
                return {
                    'status': false,
                    'layerArray': layerArray,
                    'message': '获取坐标信息失败!'
                }
            }

            var projectno = util.projectCode;
            var projectlayers = util.projectMapObject.projectLayers;
            var newlayers = JSON.parse(JSON.stringify(projectlayers));

            newlayers.forEach(function (item, i) {
                // 项目编号
                item['projectCode'] || (item.projectCode = projectno);
                // 图层名称默认是地块+下标
                item['layerName'] || (item.layerName = ('地块' + util.NoToChinese(i+1)));
                // 图层类型默认是项目用地
                item['layerType'] || (item.layerType = '项目用地');

                // 检测坐标信息是否正确
                if (item.geom && Array.isArray(item.geom.coordinates)) {
                    //
                    if (Array.isArray(item.geom.coordinates[0]) && Array.isArray(item.geom.coordinates[0][0])) {
                        //
                        var coordinates = item.geom.coordinates[0][0];
                        for (var j=0; j<coordinates.length; j++) {
                            // 检测x,y坐标
                            if (util.isCoord(coordinates[j])) {
                                continue;
                            }
                            coordinates.splice(j,1);
                            j--;
                        }
                        if (coordinates.length === 0) {
                            console.warn('出现空地块');
                        }else if (coordinates.length < 3) {
                            message.push('图层[' + item.layerName + '], 请输入至少三个点!');
                        } else {
                            var newcoord = util.closingCoord(JSON.parse(JSON.stringify(coordinates)));
                            item.geom = util.getPolygonString(new Array(newcoord));
                            layerArray.push(item);
                        }
                    } else {
                        message.push('图层[' + item.layerName + '], 格式不正确!');
                    }
                } else {
                    message.push('图层[' + item.layerName + '], 格式不正确!');
                }
            });

            return {
                'status': layerArray.length ? false : true,
                'message': message.join('</br>'),
                'layerArray': layerArray
            }
        },

        /**
         * 闭合数组
         * @param array
         */
        closingCoord: function (array) {
            if (!Array.isArray(array)) {
                return array;
            }
            // 闭合数组
            var gem = this;
            var fun = function (_array) {
                if ( gem.isClosing(_array) ) return _array;
                var first = _array[0];
                var firstx = first[0], firsty = first[1];
                _array.push([firstx, firsty]);
                return _array;
            }
            // 去空
            this.deleteArrayEmptyObject(array, true);
            // 判断类型
            if (gem.isPathsOrRings(array)) {
                var closingArray = [];
                array.forEach( function (val) {
                    closingArray.push(fun(val));
                })
                return closingArray;
            };

            return fun(array);
        },

        /**
         * 取消数组闭合
         * @param array
         */
        closingCancel: function (array) {
            if (this.isClosing(array)) {
                array.splice(array.length-1, 1);
            }
            return array;
        },

        /**
         * 判断是否闭合
         * @param array
         */
        isClosing: function (array) {
            if (!Array.isArray(array) || array.length < 3) return false;
            for (var key in array) {
                if (!this.isCoord(array[key])) return false;
            }
            var first = array[0], last = array[array.length-1];
            var firstx = first[0], lastx = last[0], firsty = first[1], lasty = last[1];
            return (this.isNotEmpty(firstx) && this.isNotEmpty(lastx) && this.isNotEmpty(firsty) && this.isNotEmpty(lasty) && firstx == lastx && firsty == lasty) ? true : false;
        },

        /**
         * 是否是xy坐标
         * @param array xy坐标数组。
         * 第一元素X坐标,第二个元素Y坐标
         */
        isCoord: function (array) {
            if (!Array.isArray(array) || array.length!=2) return false;
            var xcoord = array[0], ycoord = array[1];
            xcoord = this.isNotEmpty(xcoord) && this.isNumber(xcoord);
            ycoord = this.isNotEmpty(ycoord) && this.isNumber(ycoord);
            return (xcoord && ycoord) ? true : false;
        },

        hiddenLayer: function(index) {
                var elm = document.getElementById("layui-layer" + index);
                elm && (elm.style.display = 'none');
        },

        /**
         *  设置浏览器标签页title
          */
        setDdocumentTitle: function (DocTitle) {
            if ( this.checkEmpty(DocTitle) ) {
                document.title = DocTitle;
            }
        },

        /**
         * 获取URL参数
         * @param name
         */
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },

        /**
         * 判断对象是否可以转为json对象
         */
        isJson: function (str) {
            try {
                if (typeof JSON.parse(str) == "object") {
                    return true;
                }
            } catch(e) {
                console.log(str + ":不是json!");
            }
            return false;
        },

        /**
         *  生成唯一ID
         * @returns {*}
         */
        GUID: function (){
            function S4() {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            }
            return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
        },

        /**
         * 删除数组空对象
         * @param array
         * @param recur 为ture时会递归遍历子数组
         */
        deleteArrayEmptyObject: function (array, recur) {
             if ( !Array.isArray(array) ) return [];
             var gam = this, length = array.length;
             for (var i=0; i<length; i++) {
                 var obj = array[i];
                 if ( recur && Array.isArray(obj) ) {
                     gam.deleteArrayEmptyObject(obj, recur);
                 };
                 if (gam.isEmpty(obj)) {
                    array.splice(i,1);
                    --i, --length;
                 }
             }
             return array;
        },

        /**
         * 判断是否为空
         * 可判断空对象,空数组,空字符串等
         */
        isEmpty: function (obj) {
            //检验null和undefined
            if (!obj && obj !== 0 && obj !== '') {
                return true;
            }
            //检验空字符串
            if (obj.toString().length === 0) {
                return true;
            }
            //检验字符串null和undefined
            if (obj == "null" || obj == "undefined") {
                return true;
            }
            //检验数组
            if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
                return true;
            }
            //检验对象
            if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {
                return true;
            }
            return false;
        },
        /**
         * 判断是否不为空
         */
        isNotEmpty : function (obj) {
            return !this.isEmpty(obj);
        },
        /**
         * 检查是否是空值
         */
        checkEmpty: function (obj) {
            return this.isEmpty(obj) ? null : obj;
        },

        /**
         * 判断参数对象是否是数字
         */
        isNumber: function (obj) {
            if ( this.isEmpty(obj) ) {
                return false;
            } else {
                return parseFloat(obj).toString() != "NaN"
            }
        },

        /**
         *  阿拉伯数字转中文数字
         */
        NoToChinese: function (num) {
            if (!/^\d*(\.\d*)?$/.test(num)) {
                alert("Number is wrong!");
                return "Number is wrong!";
            }
            var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
            var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
            var a = ("" + num).replace(/(^0*)/g, "").split("."),
                k = 0,
                re = "";
            for (var i = a[0].length - 1; i >= 0; i--) {
                switch (k) {
                    case 0:
                        re = BB[7] + re;
                        break;
                    case 4:
                        if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
                            re = BB[4] + re;
                        break;
                    case 8:
                        re = BB[5] + re;
                        BB[7] = BB[5];
                        k = 0;
                        break;
                }
                if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
                if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
                k++;
            }
            if (a.length > 1) //加上小数部分(如果有小数部分)
            {
                re += BB[6];
                for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
            }
            return re;
        }
    });
    clazz.getInstance = function (view) {
        null === GM && (GM = new clazz(view));
        GM['view'] || (GM.view = window['mapview']);
        return GM
    };
    return clazz;
});