import { Fill, Stroke, Style, Text, Icon, Circle } from 'ol/style'
import ol from 'ol'
import WKT from 'ol/format/WKT'
import Overlay from 'ol/Overlay'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import GeoJSON from 'ol/format/GeoJSON'
import turf_linestring from 'turf-linestring'
import turf_distance from '@turf/distance'
import turf_destination from '@turf/Destination'
import turf_point from 'turf-point'
import Snap from 'ol/interaction/Snap'
import turf_buffer from '@turf/buffer'
import Draw, { createRegularPolygon, createBox } from 'ol/interaction/Draw'
export function trackBuffer(map, featuresArray, radius, trackBuffer) {
    //线的缓冲区分析----传入radius,返回bufferGeometry;
    let linestring = turf_linestring(featuresArray, { name: 'line 1' })
    bufferCommon(map, linestring, radius, trackBuffer)
}
export function insertfun(id, map) {
    /******插值计算开始*********/
    let insertFinalArr = [];
    //获取地图中所有线图层
    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 === id) {
                    let lineLayer = map.getLayers().array_[i];
                    var trackLine = lineLayer.getSource().getFeatures()[0].getGeometry(); //轨迹线图形
                    if (trackLine.getType() != 'Point') {
                        //轨迹地理长度
                        let length = trackLine.getLength();
                        let stpes = 0.01; //像素步长间隔
                        let geo_steps = stpes * 0.00034332275390625;
                        let arrowsNum = parseInt(length / geo_steps);
                        insertFinalArr.push([trackLine.flatCoordinates[0], trackLine.flatCoordinates[1]]) //起始点
                        for (let i = 1; i < arrowsNum; i++) { //箭头总数
                            let arraw_coor = trackLine.getCoordinateAt(i * 1.0 / arrowsNum);
                            insertFinalArr.push(arraw_coor);
                        }
                        insertFinalArr.push([trackLine.flatCoordinates[trackLine.flatCoordinates.length - 2],
                                trackLine.flatCoordinates[trackLine.flatCoordinates.length - 1]
                            ]) //终止点
                    }
                }
            }
        }
        return insertFinalArr
    }
    /******插值计算结束*********/
    // let insertFinalArr = [];
    // for(var i = 0;i<initArr.length-1;i++){
    //     let startPOS = initArr[i];
    //     let endPOS = initArr[i+1];
    //     let from = turf_point(startPOS);
    //     let to = turf_point(endPOS);
    //     let dx = endPOS[0] - startPOS[0];
    //     let dy = endPOS[1] - startPOS[1];
    //     //计算每个segment的方向，即箭头旋转方向
    //     let rotation = Math.atan2(dy, dx);
    //     //两点之间得把角度算出来
    //     let options = {units: 'kilometers'};
    //     let distance = turf_distance(from, to, options)*1000;//单位为米
    //     let stpeNumber = parseInt(distance/step);
    //     let perDistance = distance/8
    //     insertFinalArr.push(startPOS);
    //     for(var j = 0;j<stpeNumber;j++){
    //         //核心：此处应该根据起点以及后面的长度求出另外一些坐标
    //         let point = turf_point(startPOS);
    //         let distance1;
    //         if(j == 0){
    //              distance1 = perDistance;
    //         }else{
    //              distance1 = perDistance*stpeNumber;
    //         }
    //         let options = {units: 'kilometers'};
    //         let destination = turf_destination(point, distance1/1000, rotation, options);
    //         insertFinalArr.push(destination.geometry.coordinates);
    //     }
    //     insertFinalArr.push(endPOS);
    // }
    // return insertFinalArr;
}

function bufferCommon(map, linestring, radius, trackBuffer) {
    let featureOrigin = turf_buffer(linestring, radius)
    let geojsonFormat = new GeoJSON({ defaultDataProjection: "EPSG:4326" })
    let features = geojsonFormat.readFeatures(featureOrigin)
    let bufferLine = features[0]
    let bufferGeometry = bufferLine.getGeometry()
    let source = new VectorSource({
        features: [bufferLine],
        projection: 'EPSG:4326'
    })
    let bufferLayer = new VectorLayer({
        id: 'lineBuffer',
        source: source,
        style: new Style({
            stroke: new Stroke({
                color: '#ff3100',
                width: 1
            }),
            fill: new Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
        })
    })
    map.addLayer(bufferLayer)
    let wkt = new WKT()
    let wktgeometry = wkt.writeGeometry(bufferGeometry)
    return wktgeometry;
}

function wktToGeoJson(wktgeometry) {
    {
        var geoJson = {}
            // 面，其中有可能有环
        geoJson["type"] = "Polygon"
        var firstLeftIndex = wktgeometry.indexOf('(')
        var lastRightIndex = wktgeometry.indexOf(')')
            // 去掉首尾括号    
        var str = wktgeometry.substring(firstLeftIndex + 1, wktgeometry.length - 1)
        var rArray = new Array()
        var ringsArray = str.split("),(")
        for (var j = 0; j < ringsArray.length; j++) {
            var ringStr = ringsArray[j]
            if (ringsArray.length === 1) {
                // 去掉第一个(   去掉结尾  )
                ringStr = ringStr.substring(1, ringStr.length - 1)
            } else if (j === 0) { // 如果是第一个
                // 去掉第一个(
                ringStr = ringStr.substring(1, ringStr.length)
            } else if (j === ringsArray.length - 1) { // 最后一个 
                // 去掉结尾 )
                ringStr = ringStr.substring(0, ringStr.length - 1)
            }
            // 再按逗号分割就是点集合
            var ptsArray = new Array()
            var pointArr = ringStr.split(",")
            for (var k = 0; k < pointArr.length; k++) {
                var pt_arr = pointArr[k].split(" ")
                ptsArray.push(pt_arr)
            }
            rArray.push(ptsArray)
        }
        geoJson["coordinates"] = rArray
    }
    return geoJson
}
export function drawLine(map, radius) {
    // localStorage.setItem("myLine",'')
    return new Promise(function(resolve) {
        var vector = new VectorLayer({
            id: 'drawLineQuery',
            source: new VectorSource(),
            style: new Style({
                fill: new Fill({
                    color: "rgba(0,255,0,0.2)"
                }),
                stroke: new Stroke({
                    color: "red",
                    width: 2
                })
            })
        })
        var snap = new Snap({
            source: vector.getSource()
        })
        map.addLayer(vector)
        var lineString = {}
        clearInteraction(map)
        lineString = new Draw({ source: vector.getSource(), type: 'LineString' })
        map.addInteraction(lineString)
        lineString.setActive(true)
        lineString.on("drawend", function(e) {
            lineString.setActive(false)
            let myLine = null;
            lineString.setActive(false)
            let geometry
            geometry = e.feature.getGeometry()
            let line = turf_linestring(geometry.getCoordinates())
            myLine = bufferCommon(map, line, radius)
            resolve(myLine)
                // localStorage.setItem("myLine",myLine)
        })
    })

}

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)
            }
        }
    }
}