import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style'
import qs from 'qs'
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 axios from 'axios'
import Circle from 'ol/geom/Circle'
import Snap from 'ol/interaction/Snap'
import Modify from 'ol/interaction/Modify'
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 Polygon from 'ol/geom/Polygon'
import Overlay from 'ol/Overlay'
var styles = null;
export function typeChoice(e) {
    var type = e.target.getAttribute('name')
    var value = e.target.value
        // this.map.getLayers().array_.length
    clearSpatial("spatialQuery", this.map)
    clearLayer('nearbySearch', this.map)
    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)
        }
    }
}
export function filterKey(name, map, config) {
    var _this = this;
    if (name == null || name == "") {
        alert("请输入搜索关键字！")
        return
    }
    let domArr = document.getElementsByClassName("popup");
    if (domArr != undefined || domArr != null) {
        for (var i = 0; i < domArr.length; i++) {
            if (domArr[i].innerHTML.indexOf("地址") > -1) {
                domArr[i].style.display = "none"
            }
        }
    }
    document.getElementsByClassName("popup")[2].innerHTML.indexOf("地址")
    document.getElementById("qingpuPoi").style.display = "none"
    var initData = {
        "posArray": [{
            "name": name,
            "tableName": config.tableName
        }]
    }
    axios.post(config.serurl, qs.stringify(initData), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }).then(res => {
        let data = res.data

        addVector(data, map, config);
    })
}
//添加POI功能接口
export function addVector(features, map, obj) {
    var vectorSource = new VectorSource({ id: obj.id })
    let iconStyle = new Style({
        image: new Icon({
            scale: obj.scale,
            src: obj.img
        })
    })
    for (var i = 0; i < features.length; i++) {
        let iconFeature;
        if (obj.id == 'poi' || obj.id == 'poiExtent') {
            iconFeature = new Feature({
                id: features[i].id,
                attributes: { "address": features[i].address, "name": features[i].name },
                geometry: new Point([features[i].geom.coordinates[0], features[i].geom.coordinates[1]])
            })
        } else {
            iconFeature = new Feature({
                id: features[i].id,
                geometry: new Point([features[i].X, features[i].Y])
            })
        }
        vectorSource.addFeature(iconFeature)
    }
    if (obj.id == 'poi') {
        map.getView().fit(vectorSource.getExtent())
        map.getView().setZoom(13)
    }
    let vectorLayerPoi = new VectorLayer({
        id: obj.id,
        source: vectorSource,
        style: iconStyle
    })
    vectorLayerPoi.setZIndex(obj.zIndex)
    map.addLayer(vectorLayerPoi)
}

function addVector(features, map, obj) {
    var vectorSource = new VectorSource({ id: obj.id })
    let iconStyle = new Style({
        image: new Icon({
            scale: obj.scale,
            src: obj.img
        })
    })
    for (var i = 0; i < features.length; i++) {
        let iconFeature;
        if (obj.id == 'poi' || obj.id == 'poiExtent') {
            iconFeature = new Feature({
                id: features[i].id,
                attributes: { "address": features[i].address, "name": features[i].name },
                geometry: new Point([parseFloat(features[i].gaodelon), parseFloat(features[i].gaodelat)])
            })
        } else if (obj.id == 'intersectPoi') {
            iconFeature = new Feature({
                // id:features[i].id,
                geometry: new Point([features[i].geometry.coordinates[0], features[i].geometry.coordinates[1]])
            })
        } else {
            iconFeature = new Feature({
                id: features[i].id,
                attributes: features[i].attributes,
                geometry: new Point([features[i].X, features[i].Y])
            })
        }

        vectorSource.addFeature(iconFeature)
    }
    if (obj.id == 'poi') {
        map.getView().fit(vectorSource.getExtent())
        map.getView().setZoom(13)
    }
    let vectorLayerPoi = new VectorLayer({
        id: obj.id,
        source: vectorSource,
        style: iconStyle
    })
    vectorLayerPoi.setZIndex(obj.zIndex)
    map.addLayer(vectorLayerPoi)
}
export function clearMap(map) {
    let config = {
        drawLine: 'drawLineQuery',
        line: 'lineBuffer',
        nearby: 'nearbySearch',
        spatialRect: 'spatialQueryRect',
        spatialPolygon: 'spatialQueryPolygon',
        spatialCircle: 'spatialQueryCircle',
        car: 'carLayer',
        poi: 'poi'
    }
    for (var i in config) {
        clearSpatial(config[i], map)
    }
}
//清除图层接口
export function 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
            })
            for (var i = 0; i < newarr.length; i++) {
                if (newarr[i].values_.id === layerId) {
                    map.removeLayer(newarr[i]) //删除后数组的length改变了
                }
            }
        }
    }
}

function 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改变了
                    }
                }
            }
        }
    }
}

function styleFunction(feature) {
    return styles[feature.getGeometry().getType()];
};
export function addExtent(id, pointArray, obj, map) {
    styles = {
        'MultiPolygon': new Style({
            stroke: new Stroke({
                color: obj.color,
                width: 1
            }),
            fill: new Fill({
                color: obj.fill
            })
        }),
    };
    var geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
            'type': 'name',
            'properties': {
                'name': 'EPSG:4326'
            }
        },
        'features': [{
            'type': 'Feature',
            'geometry': {
                'type': 'MultiPolygon',
                'coordinates': [
                    [pointArray]
                ]
            }
        }]
    };
    var vectorSource = new VectorSource({
        features: (new GeoJSON()).readFeatures(geojsonObject)
    });
    var vectorLayer = new VectorLayer({
        id: id,
        source: vectorSource,
        style: styleFunction
    });
    map.getView().fit(vectorSource.getExtent())
    map.addLayer(vectorLayer);
}
//行政区边界显示接口
export function districtQuery(results, districtName, map, districtQueryObj) {
    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'
    })
    clearLayer("districtQuery", map)
    let vectorLayerPoly = new VectorLayer({
        id: 'districtQuery',
        source: vectorSourcePoly,
        style: new Style({
            stroke: new Stroke({
                //color: '#ff3100',
                color: districtQueryObj.color,
                width: districtQueryObj.width
            }),
            fill: new Fill({
                color: districtQueryObj.colorFill
            })
        })
    })
    vectorLayerPoly.setZIndex(districtQueryObj.nodeIndex)
    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)
}
//地图几何查询接口
export function geoQuery(type, map) {
    var _this = this;
    return new Promise(function(resolve) {
        var source = new VectorSource();
        var vector = new VectorLayer({
            id: 'spatialQuery' + type,
            source: source,
            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: source
        })
        var modify = new Modify({
            source: source
        });
        clearSpatial("spatialQueryCircle", map)
        clearSpatial("nearbySearch", map)
            //clearInteraction(map)
        map.addInteraction(modify);
        map.addInteraction(snap)
        map.addLayer(vector);
        modify.on("modifyend", function(e) {
            //map.removeInteraction(modify);
            var features = e.features.array_;
            var wktformat = new WKT();
            console.log(wktformat.writeGeometry(features[0].getGeometry()))
                // alert(wktformat.writeGeometry(features[0].getGeometry()));
        });
        if (type === "Circle") {
            _this.Circle = new Draw({ source: vector.getSource(), type: 'Circle' })
                // map.removeInteraction(_this.Circle);
                // map.removeInteraction(snap);
            map.addInteraction(_this.Circle)
            _this.Circle.setActive(true)
            paintQuery(_this.Circle, _this.ExampleDraw, type, resolve, map, vector, modify, snap)
        } else if (type === "Rect") {
            _this.Rect = new Draw({ source: vector.getSource(), type: 'Circle', geometryFunction: createBox() })

            map.addInteraction(_this.Rect)
            _this.Rect.setActive(true)
            paintQuery(_this.Rect, _this.ExampleDraw, type, resolve, map, vector, modify, snap)
        } else if (type === "Polygon") {
            _this.Polygon = new Draw({ source: vector.getSource(), type: 'Polygon' })

            map.addInteraction(_this.Polygon)
            _this.Polygon.setActive(true)
            paintQuery(_this.Polygon, _this.ExampleDraw, type, resolve, map, vector, modify, snap)
        }
    })
}
export function radarChart(map, pos, dom) {
    dom.style.display = "block"
    this.overlayToShowSelectedInfo = new Overlay({
        element: dom,
        position: "bottom-center",
        offset: [0, -10],
        position: pos
    })
    map.addOverlay(this.overlayToShowSelectedInfo)
}

function clearInteraction(map) {
    if (map.getInteractions() != null || map.getInteractions() != undefined) {
        let len = map.getInteractions().array_.length
        for (var i = 0; i < len; i++) {
            let type = map.getInteractions().array_[i].type_
            if (type === "LineString" || type === "Polygon" || type === "Circle") {
                map.getInteractions().array_[i].setActive(false)
            }

        }

    }
}

function drawCircle1000(center, radius, map, resolve, modify) {
    clearSpatial("spatialQueryCircle", map)
    clearSpatial("nearbySearch", map)
    map.removeInteraction(modify);
    if (radius != undefined && radius != '') {
        let circle = new Circle(center, radius / 100000)
        let feature = new Feature({
            position: center,
            radius: radius / 100000,
            type: 'circle',
            id: 'N',
            geometry: fromCirclePolygon(circle)
        })
        let vectorSource = new VectorSource({
            features: [feature],
            projection: 'EPSG:4326'
        })
        let vectorLayer = new VectorLayer({
            id: 'nearbySearch',
            source: vectorSource,
            style: new Style({
                stroke: new Stroke({
                    color: '#ff3100',
                    width: 1
                }),
                fill: new Fill({
                    color: 'rgba(0, 0, 255, 0.1)'
                })
            })
        })
        map.addLayer(vectorLayer)
        let geometry = feature.getGeometry() //获取圆转为多边形后的范围
            //   let wkt = new WKT
        let wktgeometry = wkt.writeGeometry(geometry)
        resolve(wktgeometry)
            //this.$emit('drawend1000', "半径"+wktgeometry)
            // var initData = {
            // "posArray": [{
            //         "extent":wktgeometry,
            //         "tableName": config.tableName
            //     }]
            // }
            // axios.post(config.serurl, qs.stringify(initData), {
            //     headers: {
            //         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            // }
            // }).then(res => {
            //     let data = res.data
            //     addVector(data,this.poiMap,config);
            // })
            // FROM qingpupoi
            // where ST_Contains(st_geomfromtext('POLYGON((121.38837585449218 31.19121551513672,121.3864543825325 31.21072454733833,121.3807638077433 31.229483858373225,121.37152281572244 31.246772538438677,121.35908653261083 31.26192619325537,121.34393287779415 31.274362476366967,121.3266441977287 31.28360346838784,121.3078848866938 31.289294043177037,121.28837585449219 31.291215515136713,121.26886682229058 31.289294043177037,121.25010751125568 31.28360346838784,121.23281883119023 31.274362476366967,121.21766517637354 31.26192619325537,121.20522889326193 31.246772538438677,121.19598790124107 31.229483858373225,121.19029732645187 31.21072454733833,121.1883758544922 31.19121551513672,121.19029732645187 31.171706482935107,121.19598790124107 31.152947171900212,121.20522889326193 31.13565849183476,121.21766517637354 31.120504837018068,121.23281883119023 31.10806855390647,121.25010751125568 31.098827561885596,121.26886682229058 31.0931369870964,121.28837585449219 31.091215515136724,121.3078848866938 31.0931369870964,121.3266441977287 31.098827561885596,121.34393287779415 31.10806855390647,121.35908653261083 31.120504837018068,121.37152281572244 31.13565849183476,121.3807638077433 31.152947171900212,121.3864543825325 31.171706482935107,121.38837585449218 31.19121551513672))',4326),geom)
    }
}

function paintQuery(typeName, ExampleDraw, type, resolve, map, vector, modify, snap) {
    var _this = this
    typeName.on("drawend", function(e) { //每次点击一次添加了drawend事件
        //map.removeInteraction(typeName);
        //map.removeInteraction(snap);
        //clearSpatial("nearbySearch",map)//1000米
        // vector.getSource().clear()
        let geometry, wktgeometry
        let wkt = new WKT()
        typeName.setActive(false)
        if (type === "Circle") {
            if (e.feature.getGeometry().setCenter != undefined) {
                let radius = e.feature.values_.geometry.getRadius() * 100000;
                let lon = e.feature.values_.geometry.getCenter()[0];
                let lat = e.feature.values_.geometry.getCenter()[1];
                if (radius > 1000) {
                    drawCircle1000([lon, lat], 1000, map, resolve, modify)
                    return false;
                } else {
                    let changeGeometry = fromCirclePolygon(e.feature.getGeometry())
                    e.feature.values_.geometry = changeGeometry
                    geometry = e.feature.getGeometry()
                    wktgeometry = wkt.writeGeometry(geometry)
                    resolve(wktgeometry)
                }
            }
        } else if (type === "Polygon") {
            geometry = e.feature.getGeometry()
            wktgeometry = wkt.writeGeometry(geometry)
            resolve(wktgeometry)
        } else {
            geometry = e.feature.getGeometry()
            wktgeometry = wkt.writeGeometry(geometry)
            resolve(wktgeometry)
        }
    })
}
// export function flyTo(map,pos,zoom){  
//     map.getView().setCenter(pos)
//     map.getView().setZoom(zoom)
// }