function GeoServerContext(opt,geoserver_path){
    this.local_wms_path = geoserver_path+"/wuhan/wms"
    this.local_wmts_path = geoserver_path+"/gwc/service/wmts"
    this.local_wfs_path = geoserver_path + "/wuhan/ows"
    this.actions = {}
    this.clicks = {}
    this.currentMap = opt.currentMap || window.map
    this.currentView = opt.currentView || window.view
    this.projection = opt.projection || window.projection
    this.wkt = new ol.format.WKT()
    this.geojson = new ol.format.GeoJSON()
    this.jstsParser = new jsts.io.OL3Parser()
    this.jstsParser.inject(ol.geom.Point, ol.geom.LineString, ol.geom.LinearRing, ol.geom.Polygon, ol.geom.MultiPoint, ol.geom.MultiLineString, ol.geom.MultiPolygon);

    let that = this
    this.currentMap.on("click", function(event){
        for(let id in that.clicks){
            let action = that.clicks[id]
            if(action && action.click){
                action.click(event, action)
            }
        }
    })

    this.currentMap.on("movestart", function(){
        for(let key in that.actions){
            let action = that.actions[key]
            if(action && action.movestart){
                action.movestart()
            }
        }
    })

    this.currentMap.on("moveend", function(){
        that.landFilter()
    })



    //初始化鼠标位置控件
    var mousePositionControl = new ol.control.MousePosition({
        //样式类名称
        projection: this.projection,
        className:"coord-box",
        //投影坐标格式，显示小数点后边多少位
        coordinateFormat: ol.coordinate.createStringXY(4),
        //目标容器
        target:document.getElementById("coord-box")
    });
    //将鼠标位置坐标控件加入到map中
    this.currentMap.addControl(mousePositionControl);

}

GeoServerContext.prototype = {
    createAction(key, Action, ext){
        if(!this.actions[key]){
            this.actions[key] = new Action(this, key, ext)
            this.actions[key].create()
        }
        return this.actions[key]
    },
    stopActions(currentKey){
        for(let key in this.actions){
            let always = false;
            if(this.actions[key].obj && this.actions[key].obj.layerData){
                always = this.actions[key].obj.layerData["always"]
            }
            if(!always && currentKey != key){
                this.actions[key].stop()
            }
        }
    },
    getInfo(layerName , coordinate, callback, error) {
        // coordinate = ol.proj.transform([coordinate[0],coordinate[1]],"EPSG:4326","EPSG:4526")
        console.log(layerName, coordinate)
        $.ajax({
            type : 'POST',
            url : "/crop/getInfo",
            data : {layerName: layerName, x : coordinate[0], y : coordinate[1]},
            dataType : 'json',
            success : function(res){
                callback(res)
            },error: function(req){
                if(error)
                    error(req)
            }
        });
    },getBuffer(coordinate,m, callback, error) {
        // coordinate = ol.proj.transform([coordinate[0],coordinate[1]],"EPSG:4326","EPSG:4526")
        $.ajax({
            type : 'POST',
            url : "/crop/getBuffer",
            data : { x : coordinate[0], y : coordinate[1], m:m},
            dataType : 'json',
            success : function(res){
                callback(res)
            },error: function(req){
                if(error)
                    error(req)
            }
        });
    },
    //获取图例
    getSldStyleSign(styleName){
        $.ajax({
            type : 'POST',
            url : "/sld_style/sign",
            data : {styleName: styleName},
            dataType : 'json',
            success : function(res){
                let html = ""
                let data = JSON.parse(res.msg)
                for(let item of data){
                    html += '<div class="cutline-item">'
                    html += '<div class="item-color" style="background-color: '+item.fill+'"></div>'
                    html += '<div class="item-name">'+item.title+'</div>'
                    html += '</div>'
                }
                $("#cutline-items").html(html)
            }
        });
    },
    landFilter(must){
        let that = this
        let bbox = that.currentView.calculateExtent(that.currentMap.getSize());
        $.ajax({
            type : 'POST',
            url : "/range_index/getTableNames",
            data : {x1:bbox[0],y1:bbox[1],x2:bbox[2],y2:bbox[3]},
            dataType : 'json',
            success : function(res){
                for(let key in that.actions){
                    let action = that.actions[key]
                    if(action && action.obj && action.obj.visibleWMTS){
                        let tableNames = res.data;
                        action.obj.visibleWMTS(tableNames)
                        if(must || that.changeBbox(bbox)){
                            that.vectorSwitch = true
                            action.tempVectorLayer.getSource().refresh()
                        }else{
                            console.log("bbox以内不需要加载")
                        }
                    }
                }
            }
        });
    },
    bbox:undefined,
    vectorSwitch: false,
    cacheBbox(bbox){
        this.bbox = bbox
    },changeBbox(bbox){
        if(this.bbox){
            let oldBbox = this.bboxToGeom(this.bbox);
            let newBbpx = this.bboxToGeom(bbox);
            let jstsBbox1 = this.jstsParser.read(oldBbox)
            let jstsBbox2 = this.jstsParser.read(newBbpx)
            if(jstsBbox1.contains(jstsBbox2)){
                return false
            }else{
                return true
            }
        }else{
            return true
        }
    },
    bboxToGeom(bbox){
        let x1 = bbox[0]
        let y1 = bbox[1]
        let x2 = bbox[2]
        let y2 = bbox[3]
        let wktStr = "POLYGON (("+x1+" "+y1+", "+x1+" "+y2+", "+x2+" "+y2+", "+x2+" "+y1+", "+x1+" "+y1+"))";
        return this.wkt.readGeometry(wktStr);
    }
}


function MyGeoJsonLayer(option){
    this.url = option.url;
    this.zIndex = option.zIndex || 0
    this.style = option.style
    this.source = new ol.source.Vector({
        projection: 'EPSG:4326',
        url: this.url, //GeoJSON的文件路径，用户可以根据需求而改变
        format: new ol.format.GeoJSON()
    })
    this.vector = new ol.layer.Vector({
        style: this.style,
        zIndex: this.zIndex,
        source: this.source
    });
}

MyGeoJsonLayer.prototype = {
}

function TipLayer(option){
    this.features = option.features || [];
    this.style = option.style
    this.zIndex = option.zIndex || 0
    this.source = new ol.source.Vector({
        projection: 'EPSG:4326'
    })
    for(let feature of this.features){
        let point = new ol.geom.Point(ol.extent.getCenter(feature.getGeometry().getExtent()))
        let pointFeature = new ol.Feature({geometry:point})
        pointFeature.setId(feature.getId().substring(feature.getId().indexOf(".") + 1))
        let keys = feature.getKeys();
        for(let key of keys){
            if(key === "geometry"){
                continue
            }
            pointFeature.set(key,feature.get(key))
        }
        this.source.addFeature(pointFeature)
    }
    this.vector = new ol.layer.Vector({
        style: this.style,
        zIndex: this.zIndex,
        source: this.source,
        maxZoom: 14
    });
}


String.prototype.format = function(){
    let str = this;
    if(arguments.length == 0){
        return str;
    }else{
        Object.keys(arguments).forEach((item,index)=>{
            str = str.replace(/\!/,arguments[item])
        })
        return str
    }
}











