/**
 * openlayer工具类
 * 2021-4-20
 */
import "ol/ol.css";
import { Map, View, Overlay } from "ol";
import TileGrid from 'ol/tilegrid/TileGrid';
import * as olControl from 'ol/control';
import { get as getProjection, transform, fromLonLat, Projection } from 'ol/proj';
import { ImageArcGISRest, Vector as VectorSource, XYZ, ImageStatic} from 'ol/source';
import { Image as ImageLayer, Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import GeoJSON from 'ol/format/GeoJSON'
import * as olRender from 'ol/render';
import WKT from 'ol/format/WKT'
import { Style as olStyle, Stroke as olStroke, Circle as olCircle, Fill as olFill, Icon as olIcon, RegularShape as olRegularShape } from 'ol/style'
import Feature from "ol/Feature"
import { Point, LineString } from 'ol/geom'
import { defaults as defaultControls, OverviewMap, FullScreen, ScaleLine, ZoomSlider, MousePosition, ZoomToExtent } from 'ol/control'

import polylineJSON from '../constant/polyline.json'
import { getTurfArcFeatures, degreesToRadians, lineChunk } from './turf_util'
import arrowPNG from "../assets/img/visualizing/arrow.png";
import mapPNG from "../assets/img/visualizing/map.png";

// 地图投影
 
var turfFormat = new GeoJSON()

function initImageMap(Id, options = {}){
    options.extent = options.extent || [-180, -90, 180, 90]
    options.level = options.level || 4;
    options.center = options.center || [120, 27];
 
    //地图设置中心，设置到成都，在本地离线地图offlineMapTiles刚好有一张zoom为4的成都瓦片
    var center = transform(options.center, 'EPSG:4326', 'EPSG:3857');
    var extent = [
        center[0] - 1920 * 1000 / 2,
        center[1] - 1080 * 1000 / 2,
        center[0] + 1920 * 1000 / 2,
        center[1] + 1080 * 1000 / 2
    ];
 
    let layer = new ImageLayer({
        source: new ImageStatic({
            url: mapPNG,
            imageExtent: extent,
          
        })
    });

    let map = new Map({
        layers: [
            layer
        ],
        target: Id,
        view: new View({
            // extent: options.extent,
            center: center,
            zoom: 6,
          
        }),
        controls: defaultControls().extend([
            new ZoomSlider(),// 往地图增加滑块缩放控件
            new FullScreen({ tipLabel: '全屏' }),// 全屏控件
            new ScaleLine(),//比例尺
           
        ])
    });
    listenPostRender(layer, map);
    return map;
}

let overlay = null;

function getOverlay(titleStr, bodyStr) {
    if (!document.getElementById("popup")) {
        let dom_str = `<div id="popup" class="ol-popup">
                            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
                            <div id="popup-title" class="popup-title">${titleStr}</div>
                            <div id="popup-content" class="popup-content"></div>
                       </div>`;
        let popup_parent = document.createElement("div");
        popup_parent.innerHTML = dom_str;
        let popup = popup_parent.firstElementChild;
        let popup_close = popup.firstElementChild;
        popup_close.addEventListener("click", function () {
            overlay.setPosition(undefined);
        })
        let popup_content = popup.lastElementChild;
        popup_content.innerHTML = bodyStr;
        overlay = new Overlay({
            element: popup,
            // autoPan: true,
            // autoPanAnimation: {
            //     duration: 250   //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度.
            // }
        });
    } else {
        document.getElementById("popup-title").innerHTML = titleStr;
        document.getElementById("popup").lastElementChild.innerHTML = bodyStr;
    }
    return overlay;
}

//创建图层
function createVectorLayer(options = {}) {
    let layer = new VectorLayer({
        source: new VectorSource({
            features: []
        }),
    });
    layer.setProperties(options);
    return layer;
}

//创建要素
function createFeature(cordination, properties, iconStyleOption) {
    const dotStyle = new olStyle({
        image: new olRegularShape({
            stroke: new olStroke({
                color: 'red',
                width: 6.0
            }),
            radius: 5,
            radius2: 2,
            points: 5
        })
    });
    //图标放大或缩小比例
    iconStyleOption.scale = iconStyleOption.scale || 0.1;
    //图标锚点位置
    // iconStyleOption.anchor = iconStyleOption.anchor || [0.5, 0.5];
    //方位角
    iconStyleOption.rotation = iconStyleOption.rotation || 0;
    //图标图标地址，webpack中需要import引用
    // iconStyleOption.src = iconStyleOption.src || "";
    let feature = new Feature({
        geometry: new Point(transform(cordination, 'EPSG:4326', 'EPSG:3857'))
    });
    feature.setProperties(properties);
    if (iconStyleOption.src) {
        feature.setStyle(new olStyle({
            image: new olIcon(iconStyleOption)
        }));
    } else {
        feature.setStyle(dotStyle);
    }
    return feature;
}

/**
 * 动态航线图
 * @param {*} layer 
 * @param {*} map 
 */
function listenPostRender(layer, map) {
    let arcStyle = new olStyle({
        stroke: new olStroke({
            color: [0, 186, 107, 0.7],
            width: 3
        })
    });
    let dotStyle = new olStyle({
        image: new olRegularShape({
            stroke: new olStroke({
                color: 'red',
                width: 6.0
            }),
            radius: 5,
            radius2: 2,
            points: 5
        })
    });

    let arcLinesFeature = [];
    let e = polylineJSON.data;
    for (let i = 0; i < e.length; i++) {
        if (e[i].wkt) {
            let tempF = getTurfArcFeatures(new WKT().readFeature(e[i]["wkt"]).getGeometry().getCoordinates(), {
                'from': e[i].name,
                'to': e[i].name,
                'resolution': multiple_x > 2 ? 80000 : null
            });
            arcLinesFeature.push(tempF);
        }
    }
    let multiple_x = window.screen.width / 1920;
    layer.on('postrender', (evt) => {
        let veContext = olRender.getVectorContext(evt);
        arcLinesFeature.forEach((item, index) => {
            //线
            veContext.drawFeature(item, arcStyle);
            let time = (evt.frameState.time - item.get('start')) / (multiple_x > 2 ? 50000 : 5000);
            let frac = time / 5 - index / arcLinesFeature.length;
            if (!item.get('start')) item.set('start', new Date().getTime());
            if (frac >= 1) {
                item.set('start', new Date().getTime());
                frac = 0;
            }
            // console.log(frac)
            // 动点
            let along = item.getGeometry().getCoordinateAt(frac);

            //设置动点的方位角
            let point1 = item.getGeometry().getCoordinateAt(frac - 0.01);
            let point2 = item.getGeometry().getCoordinateAt(frac + 0.01);
            // let pF = new Feature(new Point(along));
            // veContext.drawFeature(pF, dotStyle);
            let myImage = new Image(128, 128);
            myImage.src = arrowPNG;
            veContext.setStyle(new olStyle({
                image: new olIcon({
                    img: myImage,
                    imgSize: [128, 128],
                    scale: map.getView().getZoom() / 50,
                    rotation: degreesToRadians(point1, point2)
                })
            }));
            // console.log(map.getView().getZoom());
            veContext.drawGeometry(new Point(transform(along, 'EPSG:4326', 'EPSG:3857')));

        })
        map.render();
    });
}

/**
 * 动态箭头图
 * @param {*} layer 
 * @param {*} map 
 */
function arrow(layer, map) {
    let buttomPathStyle = new olStyle({
        stroke: new olStroke({
            color: [4, 110, 74],
            width: 28
        }),
    })
    let upperPathStyle = new olStyle({
        stroke: new olStroke({
            color: [0, 186, 107],
            width: 20
        }),
    })

    let street = new Feature({
        name: 'Null Island',
        population: 4000,
        rainfall: 500,
        geometry: new LineString(
            // [[113.136955877820221, 23.03567],[113.126955877820221, 23.13567],[112.93695587721, 23.13557] ]
            [[50.93695587721, 23.13557], [123.136955877820221, 23.03567]]
        )
    });

    let n = 0;
    //初始偏移量
    let offset = 0.01;
    layer.on('postrender', (evt) => {
        let vct = olRender.getVectorContext(evt);
        // 线边界
        vct.drawFeature(street, buttomPathStyle);
        vct.drawFeature(street, upperPathStyle);

        //最大层级下，150效果是最多2个点
        let numArr = Math.ceil((street.getGeometry().getLength() / map.getView().getResolution()) / 400);
        let points = [];
        //设置每个点的坐标
        for (let i = 0; i <= numArr; i++) {
            let fracPos = (i / numArr) + offset;
            if (fracPos > 1) fracPos -= 1;
            let pf = new Feature(new Point(street.getGeometry().getCoordinateAt(fracPos)));
            points.push(pf);
        }

        // n++;
        //确定方向并绘制
        street.getGeometry().forEachSegment((start, end) => {
            let line = new LineString([start, end]);
            points.forEach((item) => {
                let coord = item.getGeometry().getFirstCoordinate();
                let cPoint = line.getClosestPoint(coord);
                // if (Math.abs(cPoint[0] - coord[0]) < 1 && Math.abs(cPoint[1] - coord[1]) < 1) {
                if (line.intersectsCoordinate(coord)) {
                    let myImage = new Image(117, 71);
                    // myImage.src = '/static/img/arrow.png';
                    myImage.src = arrowPNG;
                    let dx = end[0] - start[0];
                    let dy = end[1] - start[1];
                    let rotation = Math.atan(dx / dy);
                    rotation = dy > 0 ? rotation : (Math.PI + rotation);
                    vct.setStyle(new olStyle({
                        image: new olIcon({
                            img: myImage,
                            imgSize: [117, 71],
                            scale: 0.15,
                            rotation: rotation
                        })
                    }))
                    vct.drawGeometry(item.getGeometry());
                }
            });
        })

        //每个点的每次移动量
        offset = offset + 0.001;
        //复位
        if (offset >= 1) {
            offset = 0.001
        }
        map.render()
    });
}

/**
 * 将指定的线段根据距离打断成多个线
 * @param {} map 
 */
function showLineChunk(map) {
    let data = [[111.93695587721, 23.13557], [113.126955877820221, 23.13567], [113.136955877820221, 22.03567]];
    var textLayer = new VectorLayer(
        {
            source: new VectorSource()
        }
    )
    map.addLayer(textLayer);

    var buttomPathStyle = new olStyle({
        stroke: new olStroke({
            color: [255, 255, 0],
            width: 20
        }),
    })
    var upperPathStyle = new olStyle({
        stroke: new olStroke({
            color: [220, 20, 60],
            width: 10
        }),
    })

    var upperPathStyle1 = new olStyle({
        stroke: new olStroke({
            color: [0, 0, 255],
            width: 10
        }),
    })

    let street = new Feature({
        geometry: new LineString(
            data
        )
    });
    street.setStyle(buttomPathStyle);

    textLayer.getSource().addFeature(street);

    let chunk = lineChunk(data);

    let features = turfFormat.readFeatures(chunk);
    for (let i in features) {
        if (i % 2 == 0) {
            features[i].setStyle(upperPathStyle);
        } else {
            features[i].setStyle(upperPathStyle1);
        }
        textLayer.getSource().addFeature(features[i]);
    }



}


export { createVectorLayer, getOverlay, createFeature, initImageMap }