import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style'
// import View from 'ol/View.js'
// import {Select} from 'ol/interaction'
import Circle from 'ol/geom/Circle'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import WKT from 'ol/format/WKT'
import qs from 'qs'
import turf_linestring from 'turf-linestring'
import turf_length from '@turf/length'
// import turf_bezierSpline from '@turf/bezier'
import bezierSpline from '@turf/bezier-spline'
import GeoJSON from 'ol/format/GeoJSON'
import Feature from 'ol/Feature'
import { Point } from 'ol/geom'
import { transform } from 'ol/proj'
import line_intersect from '@turf/line-intersect'
import axios from 'axios'
import Overlay from 'ol/Overlay'
import Snap from 'ol/interaction/Snap'
import { getDistance } from 'ol/sphere';
import Select from 'ol/interaction/Select'
import Modify from 'ol/interaction/Modify'
import LineString from 'ol/geom/LineString'
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'
var styles = null;
var PI = 3.1415926535897932384626;
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 intersectRoute(allArr, map, intersectImg) {
    let lineStringArr = [];
    for (var i = 0; i < allArr.length; i++) {
        lineStringArr.push(turf_linestring(allArr[i]))
    }
    if (lineStringArr[0] == undefined || lineStringArr[1] == undefined) return;
    let intersects = line_intersect(lineStringArr[0], lineStringArr[1]); //只是判断两条线是否相交
    let insertPoint;
    if (intersects.features != undefined) {
        insertPoint = intersects.features[0].geometry.coordinates
    }
    let ele = document.createElement('div');
    let img = document.createElement('img');
    img.src = intersectImg
    ele.appendChild(img);
    this.addSZPic('shizong', ele, insertPoint, [0, 0], map);
}
export function radarChart(id, map, pos, dom, offset) {
    dom.style.display = "block"
    this.overlayToShowSelectedInfo = new Overlay({
        id: id,
        element: dom,
        position: "bottom-center",
        offset: offset,
        position: pos
    })
    map.addOverlay(this.overlayToShowSelectedInfo)
}
export function Pic(id, dom, center, offset, map) {
    let SZPicOver = new Overlay({
        id: id,
        element: dom,
        position: "bottom-center",
        offset: offset,
        position: center
    })
    map.addOverlay(SZPicOver)
}
export function getSubWayLine(config) {
    return new Promise(function(resolve) {
        var initData = {
            "posArray": [{
                "tableName": config.tableName,
                "name": config.name
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function deleteIndexDBFolder(config) {
    // return new Promise(function(resolve) {
    var initData = {
        "posArray": [{
            "folderPath": config.path
        }]
    }
    axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            //   let data = res.data
            //   resolve(data)
        })
        // })
}
export function findPosByCityName(config) {
    return new Promise(function(resolve) {
        var initData = {
            "posArray": [{
                "tableName": config.tableName,
                "name": config.cityName

            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function filterKey(name, map, config, style) {
    var _this = this;
    if (name == null || name == "") {
        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"
            }
        }
    }
    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;
        if (data.length == 0) return;
        //addVector(data, map, config);//这块可以单独去调用,不用在此处调用,aoi验证完后可注释开
        for (let i = 0; i < data.length; i++) {
            drawGeometry('AOI', map, [JSON.parse(data[i].st_asgeojson).coordinates[0]], style)
        }
        // drawGeometry('AOI', map, [JSON.parse(data[0].st_asgeojson).coordinates[0]], style)
    })
}

function featureSymbol(id, order, type, name, geometry, attributes) {
    return new Feature({
        id: id,
        order: order,
        type: type,
        name: name,
        geometry: geometry,
        attributes: attributes
    })
}
export function findRoadZY(id, map, tablename, name, serverUrl, roadstyle) {
    var _this = this
    return new Promise(function(resolve) {
        var postData = {
            "data": [{
                'name': name,
                "tableName": tablename
            }]
        }
        axios.post(serverUrl, qs.stringify(postData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let linePointArr = res.data;
            if (linePointArr.length == 0) return;
            for (var i = 0; i < linePointArr.length; i++) {
                let x1 = linePointArr[i].y1
                let y1 = linePointArr[i].x1
                let x2 = linePointArr[i].y2
                let y2 = linePointArr[i].x2
                let pos1 = _this.gcj_encrypt(y1, x1);
                let pos2 = _this.gcj_encrypt(y2, x2)
                let route = new LineString([pos1, pos2]);
                // let route = new LineString([[y1,x1],[y2,x2]]);
                let feature = featureSymbol('findroad', '', "route", '', route, '')
                let find_line = new VectorSource()
                find_line.addFeature(feature);
                let lineLayer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                    id: id,
                    source: find_line,
                    style: new Style({ // 线串的样式
                        stroke: new Stroke({
                            color: roadstyle.lineColor,
                            width: roadstyle.lineWidth
                        })
                    })
                })
                map.addLayer(lineLayer)
                resolve(lineLayer);
            }
        }, err => {})
    })
}
export function addPoiVectors(id, attributes, pos, map, config, number) {
    let iconStyle;
    var vectorSource = new VectorSource({ id: id })
    if (attributes.name.indexOf('洗手间') > -1) {
        iconStyle = new Style({
            image: new Icon({
                scale: config.scalewc,
                src: config.imgwc
            })
        })
    } else if (attributes.name.indexOf('门') > -1) {
        iconStyle = new Style({
            image: new Icon({
                scale: config.scaledoor,
                src: config.imgdoor
            })
        })
    } else {
        iconStyle = new Style({
            image: new Icon({
                scale: config.scale,
                src: config.img
            })
        })
    }
    let iconFeature;
    iconFeature = new Feature({
        id: id,
        attributes: attributes,
        geometry: new Point(pos)
    })
    vectorSource.addFeature(iconFeature)
    let vectorLayerPoi = new VectorLayer({
        id: id,
        source: vectorSource,
        style: iconStyle
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    map.addLayer(vectorLayerPoi)
}
// export function addPoiVectors(id, attributes, pos, map, config, number) {
//     var vectorSource = new VectorSource({ id: id })
//     let iconStyle = new Style({
//         image: new Icon({
//             scale: config.scale,
//             src: config.img
//         })
//     })
//     let iconFeature;
//     iconFeature = new Feature({
//         id: id,
//         attributes: attributes,
//         geometry: new Point(pos)
//     })
//     vectorSource.addFeature(iconFeature)
//     let vectorLayerPoi = new VectorLayer({
//         id: id,
//         source: vectorSource,
//         style: iconStyle
//     })
//     vectorLayerPoi.setZIndex(config.zIndex)
//     map.addLayer(vectorLayerPoi)
// }
//添加POI功能接口
// export function addVector(features, map, obj,style) {
//     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') {
//             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,
//                 attributes: 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
//     })
//     console.log("222222")
//     vectorLayerPoi.setZIndex(obj.zIndex)
//     map.addLayer(vectorLayerPoi)
// }
export function addSZPic(id, dom, center, offset, map) {
    let SZPicOver = new Overlay({
        id: id,
        element: dom,
        offset: offset,
        stopEvent: false
    })
    SZPicOver.setPosition(center);
    //解决overlay渲染center时出现偏移的问题
    SZPicOver.setPositioning("bottom-center");
    map.addOverlay(SZPicOver)
}

export function bd09togcj02(bd_lon, bd_lat) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var x = bd_lon - 0.0065;
    var y = bd_lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    var gg_lng = z * Math.cos(theta);
    var gg_lat = z * Math.sin(theta);
    return [gg_lng, gg_lat]
}
export function gcj_encrypt(lng, lat) { //谷歌坐标系WGS-84 to GCJ-02
    //定义一些常量
    var PI = 3.1415926535897932384626;
    var a = 6378245.0;
    var ee = 0.00669342162296594323;
    // if (this.outOfChina(wgsLat, wgsLon))
    //     return {'lat': wgsLat, 'lon': wgsLon};
    // var d = delta(wgslat, wgslon);
    // return {'lat' : wgslat + d.lat,'lon' : wgslon + d.lon};
    if (out_of_china(lng, lat)) {
        return [lng, lat]
    } else {
        var dlat = transformlat(lng - 105.0, lat - 35.0);
        var dlng = transformlng(lng - 105.0, lat - 35.0);
        var radlat = lat / 180.0 * PI;
        var magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        var sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        var mglat = lat + dlat;
        var mglng = lng + dlng;
        return [mglng, mglat]
    }
}

function transformlat(lng, lat) {
    var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
    return ret
}

function transformlng(lng, lat) {
    var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
    return ret
}
/**
 * 判断是否在国内，不在国内则不做偏移
 */
function out_of_china(lng, lat) {
    return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}

function delta(lat, lon) {
    var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
    var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
    var dLat = transformLat(lon - 105.0, lat - 35.0);
    var dLon = transformLon(lon - 105.0, lat - 35.0);
    var radLat = lat / 180.0 * PI;
    var magic = Math.sin(radLat);
    magic = 1 - ee * magic * magic;
    var sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
    dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
    return { 'lat': dLat, 'lon': dLon };
}

function transformLat(x, y) {
    var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
    return ret;
}

function transformLon(x, y) {
    var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
    return ret;
}

function setStyle(obj, config) {
    return new Style({
        image: new Icon({
            anchor: [0.5, 1],
            scale: obj.scale,
            src: obj.img
        }),
        text: new Text({
            font: config.font,
            text: config.text,
            fill: new Fill({
                color: config.fillColor
            }),
            stroke: new Stroke({
                color: config.stroke.strokeColor,
                width: config.stroke.strokeWidth
            }),
            textAlign: "center"
        })
    })
}
export function addVector(features, map, obj, type) {
    var vectorSource = new VectorSource({ id: obj.id })
    let iconStyle
    if (type == 'freeHandStartNode') {
        iconStyle = setStyle(obj, {
            font: "bold 12px 黑体",
            text: "起点",
            fillColor: "#aa3300",
            stroke: { strokeColor: "#fff", strokeWidth: 2 }
        })
    } else if (type == 'freeHandEndNode') {
        iconStyle = setStyle(obj, {
            font: "bold 12px 黑体",
            text: "终点",
            fillColor: "#aa3300",
            stroke: { strokeColor: "#fff", strokeWidth: 2 }
        })
    } else if (type = "freeHandMediumNode") {
        iconStyle = setStyle(obj, {
            font: "bold 10px 黑体",
            text: "途经点",
            fillColor: "#aa3300",
            stroke: { strokeColor: "#fff", strokeWidth: 2 }
        })
    } else {
        iconStyle = setStyle(obj, {
            font: "",
            text: "",
            fillColor: "",
            stroke: { strokeColor: "", strokeWidth: 0 }
        })
    }
    for (var i = 0; i < features.length; i++) {
        let iconFeature;
        if (obj.id == 'poi' || obj.id == 'poiExtent') {
            if (obj.tableName == 'shanghai_sample_poi') {
                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 {
                iconFeature = new Feature({
                    id: features[i].id,
                    attributes: { "address": features[i].address, "name": features[i].name },
                    geometry: new Point([parseFloat(features[i].wgslon), parseFloat(features[i].wgslat)])
                })
            }

        } else if (obj.id == "poiHalfCircle") {
            iconFeature = new Feature({
                id: features[i].id,
                attributes: { "address": features[i].address, "name": features[i].name },
                geometry: new Point([parseFloat(features[i].wgslon), parseFloat(features[i].wgslat)])
            })
        } 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, pos, dom) {
    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 clearLikeSpatial(layerId, map) {
    if (map.getLayers() != undefined && map != undefined) {
        if (map.getLayers().array_.length != 0) {
            var newarr = map.getLayers().array_.filter((item, index, self) => {
                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.includes(layerId)) {
                    map.removeLayer(newarr[i]) //删除后数组的length改变了
                }
            }
        }
    }
}
//清除图层接口
export function visibleLikeSpatial(layerId, map, flag) {
    if (map.getLayers() != undefined && map != undefined) {
        if (map.getLayers().array_.length != 0) {
            var newarr = map.getLayers().array_.filter((item, index, self) => {
                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.includes(layerId)) {
                    newarr[i].setVisible(flag);
                }
            }
        }
    }
}
//清除图层接口
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) => {
                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改变了
                }
            }
        }
    }
}
export function clearInterModifyAndSelect(map) {
    // map.getInteractions().forEach(function (interaction) {
    //     if ((interaction instanceof Modify)||interaction instanceof Select||interaction instanceof Draw) {
    //          map.removeInteraction(interaction);//移除之后数组的个数变化了
    //     }
    // })
    var newArr = [];
    if (map.getInteractions() != undefined && map != undefined) {
        if (map.getInteractions().array_.length != 0) {
            map.getInteractions().array_.filter((item, index, self) => {
                for (let i = index; i < self.length; i++) {
                    if ((self[i] instanceof Modify) || (self[i] instanceof Select) || (self[i] instanceof Draw)) {
                        newArr.push(self[i])
                        return true
                    }
                }
                return false
            })
            for (var i = 0; i < newArr.length; i++) {
                map.removeInteraction(newArr[i]) //删除后数组的length改变了
            }
        }
    }
}
//清除图层接口
export function clearOverLay(layerId, map) {
    if (map.getOverlays() != undefined && map != undefined) {
        if (map.getOverlays().array_.length != 0) {
            var newarr = map.getOverlays().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].id === layerId) {
                    newarr[i].setPosition(undefined);
                    newarr[i] = null;
                }
            }
        }
    }
}
export function findByIdToLayer(layerId, map) {
    // let guizhouLayerId = obj.feature.values_.layerId;
    let findTargetLayer;
    if (map.getLayers() != undefined && map != undefined) {
        if (map.getLayers().array_.length != 0) {
            var newarr = map.getLayers().array_.filter((item, index, self) => {
                if (item.values_.id === layerId) {
                    findTargetLayer = item;
                }
            })
        }
    }
    return findTargetLayer
}
export function removeLayersExceptMap(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_.isBaseMap == undefined) {
                    // if (newarr[i].values_.isBaseMap === false) {
                    map.removeLayer(newarr[i]) //删除后数组的length改变了
                        // }
                }
            }
        }
    }
}
//centre:椭圆中心点,X:横向经度,Y:纵向纬度
export function add_oval(centre, x, y) //画椭圆
{
    var assemble = new Array();
    var angle;
    var dot;
    var tangent = x / y;
    for (var i = 0; i < 36; i++) {
        angle = (2 * Math.PI / 36) * i;
        dot = [centre.lng + Math.sin(angle) * y * tangent, centre.lat + Math.cos(angle) * y];
        assemble.push(dot);
    }
    return assemble;
}

function createLabelStyle(feature, imgSrc, scale, offset, fontStyle, fontColor, imgOffset) {
    //返回一个样式
    if (imgSrc == "") {
        return new Style({
            //文本样式
            text: new Text({
                //对齐方式
                textAlign: 'center',
                //文本基线
                textBaseline: 'middle',
                //字体样式
                font: fontStyle,
                //文本内容
                text: feature.get('name'), //获取到前端传递的name属性值
                //填充样式
                fill: new Fill({
                    color: fontColor.fill
                }),
                offsetX: offset[0],
                offsetY: offset[1],
                //笔触
                stroke: new Stroke({
                    color: fontColor.color,
                    width: fontColor.width
                })
            })
        });
    } else {
        return new Style({
            //把点的样式换成ICON图标
            image: new Icon({
                //控制标注图片和文字之间的距离
                anchor: [0.5, 40],
                //标注样式的起点位置
                anchorOrigin: 'top-right',
                //X方向单位：分数
                anchorXUnits: 'fraction',
                //Y方向单位：像素
                anchorYUnits: 'pixels',
                //偏移起点位置的方向
                offsetOrigin: 'top-right',
                //透明度
                scale: scale,
                offset: imgOffset,
                // opacity: 0.65,
                //图片路径
                src: imgSrc
            }),
            //文本样式
            text: new Text({
                //对齐方式
                textAlign: 'center',
                //文本基线
                textBaseline: 'middle',
                //字体样式
                font: fontStyle,
                //文本内容
                text: feature.get('name'), //获取到前端传递的name属性值
                //填充样式
                fill: new Fill({
                    color: fontColor.fill
                }),
                offsetX: offset[0],
                offsetY: offset[1],
                //笔触
                stroke: new Stroke({
                    color: fontColor.color,
                    width: fontColor.width
                })
            })
        });
    }
}
export function addPicAndText(vectors, config, map) {
    var vectorSource = new VectorSource({});
    let hugePointsArr = [];
    if (vectors.length == 0) return;
    for (var i = 0; i < vectors.length; i++) {
        let iconFeature = new Feature({
            attributes: vectors[i].attributes,
            name: vectors[i].attributes.name,
            geometry: new Point([vectors[i].X, vectors[i].Y]),
            attributes: vectors[i].attributes
        })
        iconFeature.setStyle(createLabelStyle(iconFeature, config.imgSrc, config.scale, config.offset, config.fontStyle, config.fontColor, config.imgOffset)); //这块添加图片
        hugePointsArr.push(iconFeature)
    }
    vectorSource.addFeatures(hugePointsArr)
    var vectorLayer = new VectorLayer({
        id: config.layerId,
        source: vectorSource
    });
    map.addLayer(vectorLayer);
    vectorLayer.setZIndex(config.z_index)
}
export function addVectorLabelJG(map, markerObj, offset) { //添加矢量标签
    //初始化一个新的点要素
    var newFeature = new Feature({ //features中可以放attributes
        geometry: new Point([markerObj.lon, markerObj.lat]),
        name: markerObj.name,
        attributes: markerObj
    });
    //设置点的样式
    newFeature.setStyle(createLabelStyle(newFeature, markerObj.imgSrc, markerObj.scale, offset, markerObj.fontStyle)); //这块添加图片
    //初始化矢量数据源
    var vectorSource = new VectorSource({
        //指定要素
        features: [newFeature]
    });
    //初始化矢量图层
    var vectorLayer = new VectorLayer({
        //数据源
        id: markerObj.vectorId,
        source: vectorSource
    });
    map.addLayer(vectorLayer);
    vectorLayer.setZIndex(markerObj.z_index)
}
export function drawBezierLine(routeArr) {
    let linestring = turf_linestring(routeArr, { name: 'line' });
    let curved = bezierSpline(linestring);
    return curved
}
export function arrToRoute(layerId, routeArr, roadStyle, zIndex, map) {
    let linestring = turf_linestring(routeArr, { name: 'line' });
    let format = new GeoJSON();
    //读取geojson数据
    let a = format.readFeature(linestring);
    let vectorSource = new VectorSource({})
        //将数据添加到数据源的
    vectorSource.addFeature(a);
    let vectorLayer = new VectorLayer({
        id: layerId,
        source: vectorSource,
        style: [
            new Style({ // 线串的样式
                stroke: new Stroke({
                    color: roadStyle.lineColor,
                    width: roadStyle.lineWidth
                })
            })
        ]
    })
    vectorLayer.setZIndex(zIndex)
    map.addLayer(vectorLayer);
}
export function lineShowDistant(layerId, posArr, roadStyle, zIndex, map) { //这样两个点传值对性能影响特别大，可能矢量图层建立的非常多
    let linestring = turf_linestring(posArr, { name: 'line' });
    let format = new GeoJSON();
    //读取geojson数据
    let a = format.readFeature(linestring);
    let vectorSource = new VectorSource({})
        //将数据添加到数据源的
    vectorSource.addFeature(a);
    let vectorLayer = new VectorLayer({
        id: layerId,
        source: vectorSource,
        style: [
            new Style({ // 线串的样式
                stroke: new Stroke({
                    color: roadStyle.lineColor,
                    width: roadStyle.lineWidth
                })
            })
        ]
    })

    vectorLayer.setZIndex(zIndex)
    map.addLayer(vectorLayer);
    let length = turf_length(turf_linestring(posArr), { units: 'kilometers' });
    return 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 vector = new VectorLayer({
            id: 'spatialQuery' + type,
            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()
        })
        map.addLayer(vector);
        clearInteraction(map)
        map.addInteraction(snap)
        if (type === "Circle") {
            _this.Circle = new Draw({ source: vector.getSource(), type: 'Circle' })
            map.addInteraction(_this.Circle)
            _this.Circle.setActive(true)
            paintQuery(_this.Circle, _this.ExampleDraw, type, resolve)
        } 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)
        } 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)
        }
    })
}

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 paintQuery(typeName, ExampleDraw, type, resolve) {
    var _this = this
    typeName.on("drawend", function(e) { //每次点击一次添加了drawend事件
        let geometry
        let wkt = new WKT()
        let wktgeometry
        typeName.setActive(false)
        if (type === "Circle") {
            if (e.feature.getGeometry().setCenter != undefined) {
                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().animate({
        duration: 2000, //持续时间
        center: pos,
        zoom: zoom
    })
}
export function drawGeometry(id, map, geoArr, styleConfig, zIndex, attr) {
    //多边形要素
    var polygonFeature = new Feature({
        id: id,
        attributes: attr,
        geometry: new Polygon(
            geoArr
        )
    });
    //实例化一个矢量图层Vector作为绘制层
    var source = new VectorSource({
        features: [
            polygonFeature
        ]
    });
    var vectorLayer = new VectorLayer({
        id: id,
        source: source,
        style: new Style({
            fill: new Fill({
                color: styleConfig.fillColor
            }),
            stroke: new Stroke({
                color: styleConfig.strokeColor,
                width: styleConfig.strokeWidth
            })
        })
    });
    vectorLayer.setZIndex(zIndex)
        //将绘制层添加到地图容器中
    map.addLayer(vectorLayer);
}
export function drawCircleSymbol(id, map, radius, center, zIndex, styleConfig) {
    if (radius == '' || radius == undefined) {
        return
    } else if (center == '' || center == undefined) {
        return
    }
    let lon = center[0]
    let lat = center[1]
    let circle = new Circle([lon, lat], radius * 0.000001)
    let feature = new Feature({
        position: [
            [lon, lat]
        ],
        type: 'circle',
        id: id,
        geometry: fromCirclePolygon(circle)
    })
    let vectorSource = new VectorSource({
        features: [feature],
        projection: 'EPSG:4326'
    })
    let vectorLayer = new VectorLayer({
        id: id,
        source: vectorSource,
        style: new Style({
            stroke: new Stroke({
                color: styleConfig.strokeColor,
                width: styleConfig.strokeWidth,
                lineDash: styleConfig.lineDash
            }),
            fill: new Fill({
                color: styleConfig.fillColor
            })
        })
    })
    vectorLayer.setZIndex(zIndex)
    map.addLayer(vectorLayer)
        // map.getView().setCenter([lon, lat])
    let geometry = feature.getGeometry() //获取圆转为多边形后的范围
    let wkt = new WKT
    let wktgeometry = wkt.writeGeometry(geometry)
    return wktgeometry;
}
export function getTwoPointsLength(coord1, coord2, opt) {
    return getDistance(coord1, coord2, opt);
}