function  CityLandAction(context, id){
    this.context = context
    this.id = id
    this.selected = {}
    this.tempVectorLayer = null
    this.popup = null
    this.obj = new CityLand({
        url : context.local_wmts_path
    })
}

CityLandAction.prototype = {
    clickLock:false,
    startStatus : false,
    createStatus : false,
    create(){
        let that = this
        this.obj.createTileLayer()
        this.tempVectorLayer = this.loadTempVectorLayer()
        this.drawMultiPolygon = new DrawMultiPolygon({vector: this.tempVectorLayer, map: this.context.currentMap,wkt: this.context.wkt})
        this.selectStatusGroup = new SelectStatusGroup({vector: this.tempVectorLayer, cityLandAction : this})

        this.popup = new Popup({map: this.context.currentMap,
            close(){
                that.clickLock = false
            },
            buttons:[
                {"name":"发布任务","click":"pubTask"},{"name":"缩放","click":"fit"}
            ],
            listener: {
                info(){
                    window.location = "/field_point/info"
                },
                fit(popup, event, ext){
                    that.context.currentView.fit(ext.getGeometry(),{duration:1000})
                },
                pubTask(popup, event, ext){
                    that.saveTask(that, ext)
                }
            }
        });
        this.createStatus = true;
    },
    start(){
        if(this.startStatus){
            console.log("startStatus is true")
            return
        }
        // this.context.clicks[this.id] = this
        this.obj.addTileLayer(this.context.currentMap)
        this.context.currentMap.addLayer(this.tempVectorLayer)
        this.drawMultiPolygon.show()
        this.selectStatusGroup.show()
        this.context.landFilter()
        this.context.getSldStyleSign(this.obj.wmsData.params.STYLE)
        this.startStatus = true;

        // this.showBuffer();
    },
    stop(){
        if(!this.startStatus){
            console.log("startStatus is false")
            return
        }
        this.context.currentMap.removeLayer(this.tempVectorLayer)
        this.obj.removeTileLayer(this.context.currentMap)
        console.log("drawMultiPolygon close")
        this.drawMultiPolygon.close()
        this.selectStatusGroup.close()
        console.log("tempVectorLayer cleared")
        this.context.clicks[this.id] = null
        console.log("remove click")
        this.popup._close()
        console.log("close popup")
        this.startStatus = false;
    },
    click(event, that){
        if(that.clickLock){
            console.log("clickLock", that.clickLock)
            return
        }
        that.clickLock = true
        let layerName = that.obj.wmsData.params.LAYER.substring(that.obj.wmsData.params.LAYER.indexOf(":") + 1)
        that.context.getInfo(layerName, event.coordinate, function(res){
            try {
                if(res.code == -1){
                    return;
                }
                console.log(res.data)
                let geometry = that.context.wkt.readGeometry(res.data.wkt)
                let area = geometry.getArea()
                area = (area + area / 2) / 1000
                res.data["area"] = area.toFixed(2)
                let feature = new ol.Feature({
                    geometry: geometry
                });
                for(let key in res.data){
                    if(key != "wkt"){
                        feature.set(key, res.data[key])
                    }
                }
                that.tempVectorLayer.getSource().clear()
                that.tempVectorLayer.getSource().addFeature(feature)
                if(res.data.status > 0){
                    that.addFieldPointOfTempLayer(res.data)
                }
                that.popup.show(ol.extent.getCenter(feature.getGeometry().getExtent()), that.getInfoHtml(feature), feature)
            }catch (e){
                console.log(e)
            }finally {
                that.clickLock = false
            }

        },function(){
            that.clickLock = false
        })
    },
    showBuffer(){
        let that = this
        that.context.getBuffer([113.26962951874916,23.126323245095218],5000, function(res){
            try {
                if(res.code == -1){
                    return;
                }
                let geometry = that.context.wkt.readGeometry(res.msg)
                let feature = new ol.Feature({
                    geometry: geometry
                });
                that.tempVectorLayer.getSource().addFeature(feature)
            }catch (e){
                console.log(e)
            }finally {
            }
        })
    },
    addFieldPointOfTempLayer(cityLand){
        let geometry = this.context.wkt.readGeometry(cityLand.wkt)
        let extent = ol.extent.getCenter(geometry.getExtent());
        let point = new ol.Feature({
            geometry: new ol.geom.Point(extent)
        });
        point.set("isPoint",1)
        point.setId(cityLand.id)
        point.set("status",cityLand.status)
        let source = this.tempVectorLayer.getSource();
        source.addFeature(point)
    },
    newFieldPoint(data){
        let geom = this.context.geojson.readGeometry(data["geojson"])
        let point = new ol.Feature({
            geometry: geom
        });
        for(let key in data){
            if(key != "geojson"){
                point.set(key,data[key])
            }
        }
        point.set("isPoint",1)
        point.setId(data["id"])
        return point;
    }
    ,loadTempVectorLayer(){
        let that = this
        let map = this.context.currentMap
        const vectorSource = new ol.source.Vector({
            loader: function(extent, resolution, projection, success, failure) {
                if(!that.context.vectorSwitch){
                    return;
                }
                let typeNames = that.obj.getVisibleLayers()
                let statusGroupString = that.selectStatusGroup.getStatusGroupString();
                console.log("typeNames",typeNames)
                console.log("statusGroup",statusGroupString)
                const xhr = new XMLHttpRequest();
                xhr.open('GET', "/crop/getGeoJson?tableNames="+typeNames + "&x1=" + extent[0] + "&y1=" + extent[1]+"&x2=" + extent[2] + "&y2="+extent[3] + "&status="+statusGroupString);
                const onError = function() {
                    vectorSource.removeLoadedExtent(extent);
                    failure();
                }
                xhr.onerror = onError;
                xhr.onload = function() {
                    if (xhr.status == 200) {
                        let res = JSON.parse(xhr.responseText);
                        if(res.code == 0){
                            let features = []
                            let datas = res.data;
                            for(let data of datas){
                                let feature = that.newFieldPoint(data)
                                vectorSource.addFeature(feature)
                                features.push(feature)
                            }
                            success(features);
                            if(datas.length > 0){
                                that.context.cacheBbox(extent)
                                that.context.vectorSwitch = false
                            }
                        }
                    } else {
                        onError();
                    }
                }
                xhr.send();
            },
            strategy: ol.loadingstrategy.bbox,
        });

        let vector = new ol.layer.Vector({
            source:vectorSource,
            style: globalStyle.cropStyle,
            minZoom:14,
            maxZoom:22,
            zIndex: 3,
            visible: true
        });

        that.select = new ol.interaction.Select({
            condition: ol.events.condition.singleClick,
            layers:[vector],
            style: globalStyle.selectedCropStyle
        })
        map.addInteraction(that.select)
        that.select.on("select",function(e){
            if(e.selected.length > 0){
                that.popup.show(ol.extent.getCenter(e.selected[0].getGeometry().getExtent()), that.getInfoHtml(e.selected[0]), e.selected[0])
            }
        })
        return vector;
    },getInfoHtml(feature){
        let html = ""
        console.log(feature.getKeys())
        let data = {
            "地块类别":this.landType[feature.get("gridcode")],
            "名称":feature.get("name"),
            "地址":feature.get("address"),
            "作物":cropTypes[feature.get("crop_type")],
            "地块图斑编号":feature.get("id") || feature.getId(),
            "地块状态":this.taskStatus[feature.get("status")],
            "生长期":cropPeriods[feature.get("growing_period")],
            "图片信息":"<a style='color: whitesmoke;' href='javascript:layui.tool.open(!,!,!,!)'>点击查看</a>"
                .format('"/crop_image/view?id='+feature.get("id")+'"','"60%"','"图片信息"','{area:["90%","90%"],shade:0.1}'),
        }

        for(let key in data){
            html += "<div class='layui-row'><div class='lab' >"+key+"</div><div class='val' >"+data[key]+"</div></div>"
        }
        return html
    },
    taskStatus:["未发布","已发布","已领取","已完成"],
    landType:{0:"其他", 1:"湿地", 2:"耕地", 3:"种植", 4:"林地", 5:"草地", 6:"水域"}
    ,
    saveTask(that, feature){
        let id = feature.getId()
        layui.tool.submit("/crop/publish",{"id":feature.get("id") || id.substring(id.indexOf(".") + 1)},function(res){
            if(res.code == 0){
                that.addFieldPointOfTempLayer(res.data)
            }
        })
    }
}

function CityLand(opt){

    this.name = "CityLand"
    var gridsetName = 'EPSG:4326';
    var gridNames = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10', 'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'];

    this.wmsData = {
        url: opt.url,
        projection: new ol.proj.Projection({
            code: 'EPSG:4326',
            units: 'degrees',
            axisOrientation: 'neu'
        }),
        params:{
            'VERSION': '1.0.0',
            'STYLE': "wuhan:city_land",
            'TILEMATRIX': gridNames,
            'TILEMATRIXSET': gridsetName,
            'SERVICE': 'WMTS',
            'FORMAT': "image/png"
        }
    }
    this.layerData = {
        layer : [],
        source : [],
        always : true
    }
}

CityLand.prototype = {
    visibleLayers:[],
    getVisibleLayers(){
        let names = "";
        let i = 0;
        for(let layerName of this.visibleLayers){
            if(i > 0){
                names += ","
            }
            names += layerName
            i++;
        }
        return names;
    },
    layerNames:['wuhan:p_land_banan','wuhan:p_land_beibei','wuhan:p_land_bishan','wuhan:p_land_changshou','wuhan:p_land_chengkou','wuhan:p_land_dadukou','wuhan:p_land_dazu','wuhan:p_land_dianjiang','wuhan:p_land_fengdu','wuhan:p_land_fengjie','wuhan:p_land_fuling','wuhan:p_land_hechuan','wuhan:p_land_jiangbei','wuhan:p_land_jiangjin','wuhan:p_land_jiulongpo','wuhan:p_land_kaizhou','wuhan:p_land_liangping','wuhan:p_land_nanan','wuhan:p_land_nanchuan','wuhan:p_land_pengshui','wuhan:p_land_qianjiang','wuhan:p_land_qijiang','wuhan:p_land_qiuyang','wuhan:p_land_rongchang','wuhan:p_land_shapingba','wuhan:p_land_shizhu','wuhan:p_land_tongliang','wuhan:p_land_tongnan','wuhan:p_land_wanzhou','wuhan:p_land_wulong','wuhan:p_land_wushan','wuhan:p_land_wuxi','wuhan:p_land_xiushan','wuhan:p_land_yongchuan','wuhan:p_land_yubei','wuhan:p_land_yunyang','wuhan:p_land_yuzhong','wuhan:p_land_zhong','wuhan:p_crop'],
    createTileLayer(){
        for(let layer of this.layerNames){
            this.getWMTS(layer)
        }
    },
    addTileLayer(map){
        for(let layer of this.layerData.layer){
            map.addLayer(layer)
        }
    },
    removeTileLayer(map){
        for(let layer of this.layerData.layer){
            map.removeLayer(layer)
        }
    }
    ,getWMS(typeName){
        var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570312E-5, 5.364418029785156E-6, 2.682209014892578E-6, 1.341104507446289E-6, 6.705522537231445E-7, 3.3527612686157227E-7];
        let source = new ol.source.ImageWMS({
            url: 'http://change.zylfsm.com/geoserver/gwc/service/wms?SERVICE=WMS&',
            layer: typeName,
            matrixSet: this.wmsData.params['TILEMATRIXSET'],
            format: this.wmsData.params['FORMAT'],
            projection: this.wmsData.projection,
            tileGrid: new ol.tilegrid.WMS({
                tileSize: [256,256],
                extent: [-180.0,-90.0,180.0,90.0],
                origin: [-180.0, 90.0],
                resolutions: resolutions,
                matrixIds: this.wmsData.params['TILEMATRIX']
            }),
            style: this.wmsData.params['STYLE'],
            wrapX: true
        })
        this.layerData.source.push(source)
        let layer = new ol.layer.Image({
            source: source,
            zIndex: 2,
            minZoom: 7,
            maxZoom: 30,
            visible: true,
        });
        this.layerData.layer.push(layer)
    },getWMTS(typeName){
        var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570312E-5, 5.364418029785156E-6, 2.682209014892578E-6, 1.341104507446289E-6, 6.705522537231445E-7, 3.3527612686157227E-7];
        var baseUrl = this.wmsData.url;
        var baseParams = ['VERSION','STYLE','TILEMATRIX','TILEMATRIXSET','SERVICE','FORMAT'];
        var url = baseUrl+'?LAYER='+ typeName +'&'
        for (var param in this.wmsData.params) {
            if (baseParams.indexOf(param.toUpperCase()) < 0) {
                url = url + param + '=' + this.wmsData.params[param] + '&';
            }
        }
        url = url.slice(0, -1);
        let source = new ol.source.WMTS({
            url: url,
            layer: typeName,
            matrixSet: this.wmsData.params['TILEMATRIXSET'],
            format: this.wmsData.params['FORMAT'],
            projection: this.wmsData.projection,
            tileGrid: new ol.tilegrid.WMTS({
                tileSize: [256,256],
                extent: [-180.0,-90.0,180.0,90.0],
                origin: [-180.0, 90.0],
                resolutions: resolutions,
                matrixIds: this.wmsData.params['TILEMATRIX']
            }),
            style: this.wmsData.params['STYLE'],
            wrapX: true
        })
        this.layerData.source.push(source);
        let tile = new ol.layer.Tile({
            source: source,
            zIndex: 2,
            minZoom: 7,
            maxZoom: 30,
            visible: false,
            properties:{"name":typeName.substring(typeName.indexOf(":") + 1)}
        })
        this.layerData.layer.push(tile);
        return tile;
    },
    visibleWMTS(tableNames){
        this.visibleLayers = tableNames
        for(let layer of this.layerData.layer){
            if(tableNames.includes(layer.get("name"))){
                layer.setVisible(true)
            }else{
                layer.setVisible(false)
            }
        }
    }
}


function DrawMultiPolygon(option){
    this.vector = option.vector
    this.map = option.map
    this.wkt = option.wkt
    let that = this
    let html = "<div class='item'><a href='javascript:void(0)' id='drawMultiPolygon' class='yse-events' >绘制多边形</a></div>";
    $("#menu-pop-list").append(html)
    this.initDraw()
    $("#drawMultiPolygon").on("click",function(){
        that.vector.getSource().clear()
        that.draw.setActive(true)
    })

}

DrawMultiPolygon.prototype = {
    initDraw(){
        let that = this
        that.draw = new ol.interaction.Draw({
            source : that.vector.getSource(),
            type: "MultiPolygon",
            freehand: false,//自由绘制
            stopClick: true
        })
        that.draw.setActive(false)
        that.draw.on("drawend", function(e){
            that.draw.setActive(false)
            that.submit(e.feature)
        })
        that.map.addInteraction(that.draw)
    },
    show(){
        $("#drawMultiPolygon").show()
    },
    close(){
        this.draw.setActive(false)
        $("#drawMultiPolygon").hide()
    },
    submit(feature){
        let geometry = feature.getGeometry()
        layui.tool.post("/crop/addTest",{"wkt":this.wkt.writeGeometry(geometry)})
    }
}

function SelectStatusGroup(option){
    this.vector = option.vector
    this.cityLandAction = option.cityLandAction
    let that = this
    this.statusGroup = [0,1,2,3]
    let html = "<div class='item'><input type='checkbox' value='0'  name='layerStatus'  checked=''>未发布的</div>";
    html += "<div class='item'><input type='checkbox' value='1' name='layerStatus'  checked=''>已发布的</div>";
    html += "<div class='item'><input type='checkbox' value='3' name='layerStatus'  checked=''>已完成的</div>";
    $("#menu-pop-list").append(html)
    $("input[name='layerStatus']").on("click",function(item){
        that.updateStatusGroup()
    })
}

SelectStatusGroup.prototype = {
    updateStatusGroup(){
        this.statusGroup = [2]
        let objs = $("input[name='layerStatus']");
        for(let obj of objs){
            if(obj.checked){
                this.statusGroup.push(obj.value)
            }
        }
        if(this.statusGroup.length == 1){
            this.vector.setVisible(false)
        }else{
            this.vector.setVisible(true)
            this.cityLandAction.context.landFilter(true)
        }
    },
    getStatusGroupString(){
        let res = "";
        for(let i=0;i<this.statusGroup.length;i++){
            if(i != 0){
                res+=","
            }
            res += this.statusGroup[i];
        }
        return res;
    },
    show(){
        $("#menu-pop-list").show()
    },
    close(){
        $("#menu-pop-list").hide()
    }
}









