<template>
     <div id="searchDiv" style="position:absolute;top:50px;left:80px;width:320px;height:50px;
                                background:rgba(2, 84, 167, 0.1);z-index:99999;border: 1px solid #ccc; padding: 1em;display: none">  
        <ul id="controls">         
            <!--<li style="list-style-type:none;">  
                <label for="pointToggle">关键字:</label>  
                <input name="searchkey" id="searchkey"  type="text" v-model="searchValue">             
                <input name="type" value="搜索" id="polygonToggle" @click="filterKey" type="button">  
            </li>-->
            <form id="optionsform" ref="optionsform" automplete="off">
                <span class="form-group">
                    <label>图形选择 &nbsp;</label>
                    <select name="draw-type" id="draw-type" @change="typeChoice" v-model="optValue">
                        <option value="Polygon">多边形</option>
                        <option value="Circle">圆</option>
                    </select>
                </span>
                <input name="type" value="查询"  @click="geoQuery" type="button">
                 <input name="type" value="地名获取"  @click="districtQuery" type="button">
            </form>
        </ul>       
     </div>          
</template>
<script>
import { Circle as CircleStyle,Fill, Stroke, Style, Text, Icon} from 'ol/style'
import View from 'ol/View.js';
import WFS from 'ol/format/WFS'
import BingMaps from 'ol/source/BingMaps.js';
import VectorSource from 'ol/source/Vector'
import GeoJSON from 'ol/format/GeoJSON'
import  Feature  from 'ol/Feature'
import { Point } from 'ol/geom'
import WKT from 'ol/format/WKT'
import {transform} from 'ol/proj'
import Circle from 'ol/geom/Circle'
import Snap from 'ol/interaction/Snap'
import {fromLonLat,getTransform} from 'ol/proj'
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import {circular as circularPolygon, fromCircle as fromCirclePolygon} from 'ol/geom/Polygon.js';
import Draw, {createRegularPolygon, createBox} from 'ol/interaction/Draw.js';
import { and, isNull, not, bbox, between, contains, during, equalTo, greaterThan, 
    greaterThanOrEqualTo, intersects, lessThan, lessThanOrEqualTo, like, or, within } from 'ol/format/filter'
import {equalTo as equalToFilter,like as likeFilter,and as andFilter,within as withinFilter} from 'ol/format/filter.js';
import Polygon from 'ol/geom/Polygon'
export default{
    name:'poi-query',
    render () { },
    data() {
       return {
           searchValue:'',
           selectValue:'100',
           point:{},
           LineString:{},
           Polygon:{},
           Circle:{},
           optValue:'Polygon',
           ExampleDraw:{}
       } 
    },
    props:{
        geometryFeatures: {
            type: Array 
        },
        markslayer: {
            type: Object
        }
        ,
        map:{
            type: Object
        }
    },
    computed: {
      spatialQuery () {
        return this.$store.state.spatialQuery
      }
    },
    watch:{

    },
    //mixins: [commonMixin('overlay')],
    methods:{
        typeChoice(e){
            var type = e.target.getAttribute('name');
            var value = e.target.value;
            // this.map.getLayers().array_.length;
            this.clearSpatial("spatialQuery",this.map);
            this.clearLayer('nearbySearch')
            if (type == 'draw-type') {
                 this.ExampleDraw.getActive() && this.ExampleDraw.setActive(true);
            } else if (type == 'interaction') {
                if (value == 'modify') {
                    this.ExampleDraw.setActive(false);
                    this.ExampleModify.setActive(true);
                } else if (value == 'draw') {
                    this.ExampleDraw.setActive(true);
                    this.ExampleModify.setActive(false);
                }
            }         
        },
        filterKey() {
            if (this.searchValue == null || this.searchValue == "") {  
                alert("请输入搜索关键字！");  
                return;  
            } 
            var _this = this;
            var featureRequest = new WFS().writeGetFeature({
                srsName: 'EPSG:4326',//坐标系
                featureNS: 'http://openstreemap.org',//注意这个值必须为创建工作区时的命名空间URI
                featurePrefix: 'osm',//工作区的名称
                featureTypes: ['osm:pass'],
                outputFormat: 'application/json',
                filter:likeFilter('SBBH', this.searchValue+'*')
            });
            fetch('http://192.168.10.19:8080/geoserver/osm/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=osm:pass&maxFeatures=2000', {
                method: 'POST',
                body: new XMLSerializer().serializeToString(featureRequest)
            }).then(function(response) {
                return response.json();  
            }).then(function(json) {
                var features = new GeoJSON().readFeatures(json);
                _this.addVector(features);
            });
        },
        addVector(features,map){
            // let features = this.geometry;
            var vectorSource = new VectorSource({id:"poi"});//Vector
            let iconStyle = new Style({
                    image: new Icon({
                        imgSize: [30, 30],
                        src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXM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XgpRPIfiPZUS5VSBbGo0Ry8xEOJfm0IXooNnqL4C1TaUEEPhdLqtrQVl/irxsNsMYTZ/e5+a+nnts8887xndp55ZqZvbm7O/6G3mjqmnaIP72EjtuJDrMQDXMVFTCPPs6TrbPqazDjtFIuxE0MluK/C9RpGMZZnyey/Aqed4l18gn1dR/haX2J/niWPewKnnaIfn2FPC+g/OoK9eZY8aQUu13QQX2NRD2DYhTOxNa8LuATDNT7fYxK3a2IMYyDWUAdej00R+xMcFP7Gx9iBT1FEfDfgg1jwuu20GW9H7F/gQJ4lz8rv39JO8Tme4sAC335swbcLg9TNeF3Edhfj86Agz5LnOIc7kT7rY8HrwMsjtl/xZ4X/X/glYl/WFvwgYlsjVKuYVmBtxJ63BV+P2FZhKO0US+cb004xICTa6kify7Hgdcl1CY+EbTVfu7E07RQjeIhUKKUfRWLM4ru24B/KTtsjbYPYhp/xPt6piDGFW7GGyl9dFvnjwqhjWiyseRX0GY5V1etupXAKp7v4VGlMOCqjqgXnWfISxzDTEnoPX5X7uz241AxOtgSPqljbxuDyZJnElYbQm/im2y2k0XGXZ8l9jAgJU6cXOJlnyY/dYrY5Z8/jbBefCYw3CdYYnGfJIyHRYqUUfhe2zx9vFFzCp4VZxdbvglDtGqmXK81h3F9g+wmHmlxrewbnWXIXJ4REgr8xmmdJ7Cx+c+BSI8IlHm7gaNsAPYHzLCmEWRc4VSZeKzV+wkQ0KTxpJnrp3OgJ81/oFRAisUp17bv8AAAAAElFTkSuQmCC"
                    })
            });
            for(var i=0;i<features.length;i++){
                let iconFeature = new Feature({
                    id:features[i].id_,
                    geometry: new Point([features[i].X, features[i].Y])
                    //geometry: new Point([features[i].values_.X, features[i].values_.Y])
                });
                vectorSource.addFeature(iconFeature);
            }
            this.clearLayer("poi",map);
            let vectorLayerPoi = new VectorLayer({
                    id:'poi',
                    source: vectorSource,
                    style: iconStyle
            });
            map.getView().fit(vectorSource.getExtent());
            map.addLayer(vectorLayerPoi);
        },
        clearSpatial(layerId,map){
            if(map.getLayers()!=undefined&&map!=undefined){
                if(map.getLayers().array_.length!=0){
                    var newarr = map.getLayers().array_.filter((item, index, self)=>{
                        const obj = {}
                        for(let i = index; i < self.length; i++){
                            if(self[i].values_.id === item.values_.id){
                                return true
                            }
                        }
                        return false
                    })
                    //debugger
                    for(var i = 0;i<newarr.length;i++){
                            if(newarr[i].values_.id===layerId){
                                map.removeLayer(newarr[i]);//删除后数组的length改变了
                            }
                    }
                }
            } 
        },
        clearLayer(layerId,map){
            //清除第一次添加的矢量图层
            // let layerLens = this.map.getLayers().array_.length-1;
            if(map.getLayers()!=undefined&&map!=undefined){
                if(map.getLayers().array_.length!=0){
                    for(var i = 0;i<map.getLayers().array_.length;i++){
                        if(map.getLayers().array_[i].type==="VECTOR"){
                            if(map.getLayers().array_[i].values_.id===layerId){
                                map.removeLayer(map.getLayers().array_[i]);//删除后数组的length改变了
                            }
                        }
                    }
                }
            } 
        },
        districtQuery(results,districtName,map){
                let districtGeometry;
                for (var value of results) {
                    if(value.features[0].properties.name===districtName){
                        districtGeometry = value.features[0].geometry.coordinates[0];
                        break;
                    }
                }   
                let polygonPoly = new Polygon([districtGeometry]);
                let featurePoly = new Feature({
                    geometry:polygonPoly
                })
                let vectorSourcePoly = new VectorSource({
                    features:[featurePoly],
                    projection:'EPSG:4326'
                });
                this.clearLayer("districtQuery",map);
                let vectorLayerPoly = new VectorLayer({
                    id:'districtQuery',
                    source: vectorSourcePoly,
                    style: new Style({
                            stroke: new Stroke({
                                color: '#ff3100',
                                width: 1
                            }),
                            fill: new Fill({
                                color: 'rgba(0, 0, 255, 0.3)'
                            })
                    })
                });
                localStorage.setItem("districtQuery","");//每次进来清空一次
                let wkt = new WKT();
                map.addLayer(vectorLayerPoly);
                map.getView().fit(vectorSourcePoly.getExtent(),15);
                let geometry = featurePoly.getGeometry();//获取圆转为多边形后的范围
                let wktgeometry = wkt.writeGeometry(geometry);
                localStorage.setItem("districtQuery",wktgeometry)
        },
        geoQuery(type){
                    // this.clearLayer("spatialQuery");
                    // this.clearLayer('nearbySearch')
                    var vector = new VectorLayer({
                        id:'spatialQuery',
                        source: new VectorSource(),
                        style: new Style({
                        fill: new Fill({
                        color:"rgba(0,255,0,0.2)"
                        }),
                        stroke: new Stroke({
                            color:"red",
                            width:2
                        }),
                        image: new CircleStyle({
                            radius: 7,
                            fill:new Fill({
                            color:"yellow"
                            }),
                            stroke:new Stroke({
                                red:"red",
                                width:2
                            })
                        })
                        })
                    });
                    var snap = new Snap({
                        source: vector.getSource()
                    });
                    this.map.addLayer(vector);
                    var _this = this;
                    _this.point = new Draw({source: vector.getSource(), type: 'Point'})
                    _this.LineString = new Draw({source: vector.getSource(),type: 'LineString'})
                    _this.Polygon = new Draw({source: vector.getSource(), type: 'Polygon'})
                    _this.Circle = new Draw({source: vector.getSource(),type: 'Circle'})
                    _this.ExampleDraw = {
                        init: function() {
                            _this.map.addInteraction( _this.point);
                            _this.point.setActive(false);
                            _this.map.addInteraction( _this.LineString);
                            _this.LineString.setActive(false);
                            _this.map.addInteraction( _this.Polygon);
                            _this.Polygon.setActive(false);
                            _this.map.addInteraction( _this.Circle);
                            _this.Circle.setActive(false);
                        },
                        getActive: function() {
                            return _this.activeType ? _this[_this.activeType].getActive() : false;
                        },
                        setActive: function(active) {
                            //let type = _this.$refs.optionsform[0].value;
                            if (active) {
                                _this.activeType && _this[_this.activeType].setActive(false);
                                _this[type].setActive(true);
                                _this.activeType = type;
                            } else {
                                _this.activeType && _this[_this.activeType].setActive(false);
                                _this.activeType = null;
                            }
                        }
                    };
                    _this.ExampleDraw.init();//初始化时候设置所有的激活状态为false
                    _this.ExampleDraw.getActive()
                    _this.ExampleDraw.setActive(true);  
                    this.map.addInteraction(snap);
                    // _this.LineString.on('draw')
                    if(_this.activeType==="Circle"){
                        _this.paintQuery(_this.Circle,_this.ExampleDraw,snap)
                    }else if(_this.activeType==="LineString"){
                        _this.paintQuery(_this.LineString,_this.ExampleDraw,snap)
                    }else if(_this.activeType==="Polygon"){
                        _this.paintQuery(_this.Polygon,_this.ExampleDraw,snap)
                    }             
        },
        paintQuery(typeName,ExampleDraw,snap){
            var _this=this;
            typeName.on("drawend",function (e) {
                    ExampleDraw.setActive(false);
                    //this.map.removeInteraction(snap);
                    //let geometry=e.feature.getGeometry();//此时为Circle
                    let geometry;
                    let wkt = new WKT();
                    let wktgeometry;
                    let geoJson;
                    if(typeName.type_==="Circle"){
                        localStorage.setItem("circleQuery",'')
                         let changeGeometry = fromCirclePolygon(e.feature.getGeometry());
                         e.feature.values_.geometry = changeGeometry;
                         geometry = e.feature.getGeometry();
                         wktgeometry = wkt.writeGeometry(geometry);
                         localStorage.setItem("circleQuery",wktgeometry)
                         //geoJson = _this.wktToGeoJson(wktgeometry)
                        // debugger
                         
                    }else{
                         localStorage.setItem("polygonQuery",'')
                         geometry=e.feature.getGeometry();
                         wktgeometry = wkt.writeGeometry(geometry);
                         localStorage.setItem("polygonQuery",wktgeometry)
                         //geoJson = _this.wktToGeoJson(wktgeometry)
                        // debugger
                    } 
              });
        },
        flyTo(pos){  
            var lon = geometry.lon;
            var lat = geometry.lat;
            this.map.getView().setCenter([lon,lat]);
            this.map.getView().setZoom(10);
        }
    }
}
</script>