import { Map, View, Feature } from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Cluster, XYZ, Vector as VectorSource } from "ol/source";
import * as olProj from "ol/proj";
import { Point } from "ol/geom";
import { Style, Fill, Stroke as Stroke, Circle as sCircle, Icon, Text, Circle as CircleStyle } from "ol/style";
import GeoJSON from 'ol/format/GeoJSON';
import { createEmpty, extend, getWidth } from 'ol/extent';
import Overlay from 'ol/Overlay';
//---------------------------------------------添加标记----------------------------------------
//总和
const outerCircleFill = new Fill({
    color: 'rgba(255, 153, 102, 0.3)',
});
const innerCircleFill = new Fill({
    color: 'rgba(255, 165, 0, 0.7)',
});

const innerCircle = new CircleStyle({
    radius: 14,
    fill: innerCircleFill,
});
const outerCircle = new CircleStyle({
    radius: 20,
    fill: outerCircleFill,
});

//单个
const outerSonCircleFill = new Fill({
    color: 'rgba(230,103,126, 0.3)',
});
const innerSonCircleFill = new Fill({
    color: 'rgba(255,0,47, 0.7)',
});

//单个
const outerSonCircleFillGreen = new Fill({
    color: 'rgba(124, 252, 0, 0.3)',
});
const innerSonCircleFillGreen = new Fill({
    color: 'rgba(0, 255, 0, 0.7)',
});

const innerSonCircle = new CircleStyle({
    radius: 14,
    fill: innerSonCircleFill,
});
const outerSonCircle = new CircleStyle({
    radius: 20,
    fill: outerSonCircleFill,
});

const innerSonCircleGreen = new CircleStyle({
    radius: 14,
    fill: innerSonCircleFillGreen,
});
const outerSonCircleGreen = new CircleStyle({
    radius: 20,
    fill: outerSonCircleFillGreen,
});
// 区域样式
const convexHullFill = new Fill({
    color: 'rgba(255, 153, 0, 0.4)',
});
const convexHullStroke = new Stroke({
    color: 'rgba(204, 85, 0, 1)',
    width: 1.5,
});
/**
 * 设置样式
 * @returns 
 */
export function setStyle() {
    const styleCache = {};
    const _style = (feature) => {
        let size = 0;
        for (let item of feature.get("features")) {
            let data = item.get('data')
            if (data) {
                if (!data.engineerCompletionTime) {
                    size++
                }
            }
        }
        if (size > 1) {
            return [new Style({
                image: outerCircle,
            }),
            new Style({
                image: innerCircle,
                text: new Text({
                    text: size.toString(),
                    fill: new Fill({
                        color: '#fff',
                    }),
                    stroke: new Stroke({
                        color: 'rgba(0, 0, 0, 0.6)',
                        width: 3,
                    }),
                }),
            })]

        } else {
            let data = feature.get("features")[0].get('data')
            
            if (data) {
                let text=""
                if(data.engineer){
                    text =data.factoryName+" \r\n "+ data.engineer
                }else{
                    text =data.factoryName+" \r\n "
                }
                
                if (data.engineerCompletionTime) {
                    return [new Style({
                        image: outerSonCircleGreen,
                    }),
                    new Style({
                        
                        image: innerSonCircleGreen,
                        text: new Text({
                            offsetY: 10,
                            text: text,
                            fill: new Fill({
                                color: '#fff',
                            }),
                            stroke: new Stroke({
                                color: 'rgba(0, 0, 0, 0.6)',
                                width: 3,
                            }),
                        }),
                    })]

                } else {
                    return [new Style({
                        image: outerSonCircle,
                    }),
                    new Style({
                        
                        image: innerSonCircle,
                        text: new Text({
                            offsetY: 10,
                            text: text,
                            fill: new Fill({
                                color: '#fff',
                            }),
                            stroke: new Stroke({
                                color: 'rgba(0, 0, 0, 0.6)',
                                width: 3,
                            }),
                        }),
                    })]
                }
            }
        }
    };
    return _style;
}
/**
 * 设置feature
 * @param {*} points 
 * @returns 
 */
export function setMarkerSource(points) {
    const _features = points.map((item) => {
        let arr = [item.longitude, item.latitude]
        const _feature = new Feature({
            geometry: new Point(olProj.fromLonLat(arr)),
            data: item
        });
        return _feature;
    });
    return new Cluster({
        distance: 100,
        source: new VectorSource({
            features: _features,
        }),
    });
}
/**
 * 添加点标记
 * @returns 
 */
export function addMarkers(points) {
    let _style = setStyle();
    let clusters = new VectorLayer({
        source: setMarkerSource(points),
        style: _style,
    });
    return clusters
}

//-------------------------------------------添加点位标记及事件-------------------------------------
let hoverFeature;
export function pointermoveMarkers(map, clusters) {
    map.on('pointermove', (event) => {
        clusters.getFeatures(event.pixel).then((features) => {
            if (features[0] !== hoverFeature) {
                // Display the convex hull on hover.
                hoverFeature = features[0];
                clusterHulls.setStyle(clusterHullStyle);
                // Change the cursor style to indicate that the cluster is clickable.
                map.getTargetElement().style.cursor =
                    hoverFeature && hoverFeature.get('features').length > 1
                        ? 'pointer'
                        : '';
            }
        })
    })
}

export function dblclickMarkers(map, clusters, object) {
    if (object) {
        object.popupClose()
    }
    map.on('dblclick', (event) => {
        clusters.getFeatures(event.pixel).then((features) => {
            if (features.length > 0) {
                const clusterMembers = features[0].get('features');
                if (clusterMembers.length > 1) {
                    // Calculate the extent of the cluster members.
                    const extent = createEmpty();
                    clusterMembers.forEach((feature) =>
                        extend(extent, feature.getGeometry().getExtent())
                    );
                    const view = map.getView();
                    const resolution = map.getView().getResolution();
                    if (
                        view.getZoom() === view.getMaxZoom() ||
                        (getWidth(extent) < resolution && getWidth(extent) < resolution)
                    ) {
                        // Show an expanded view of the cluster members.
                        clickFeature = features[0];
                        clickResolution = resolution;
                        clusterCircles.setStyle(clusterCircleStyle);
                    } else {
                        // Zoom to the extent of the cluster members.
                        view.fit(extent, { duration: 500, padding: [50, 50, 50, 50] });
                    }
                }
            }
        });
    });
}
export function addPopup(ref) {
    let overlay = new Overlay({  // 创建一个图层
        element: ref.$el,   // 图层绑定我们上边的弹窗
        autoPan: true,
        autoPanAnimation: {
            duration: 250,
        }
    })
    overlay.setPosition(undefined)
    return overlay;
}
/**
 * 单击事件
 * @param {*} map 
 * @param {*} clusters 
 * @param {*} ref 
 */
export function clickMarkers(map, clusters, overlay, ref) {
    map.on('singleclick', (event) => {
        let coodinate = event.coordinate;
        let feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
            return feature   // 查找出点击的哪个坐标
        })
        if (feature) {
            if (feature.get("features").length <= 1) {
                ref.init(feature.get("features")[0].get('data'), 'single')
                overlay.setPosition(coodinate)
            } else {
                let clusterMembers = feature.get("features");
                let data = []
                for (let item of clusterMembers) {
                    let data1 = item.get('data')
                    if (data1) {
                        if (!data1.engineerCompletionTime) {
                            data.push(data1)
                        }
                    }
                    
                }
                ref.init(data, 'region', "汇总信息")
                overlay.setPosition(coodinate)
            }
        }


    });
}

const clusterHulls = new VectorLayer({
    source: clusterSource,
    style: clusterHullStyle,
});

const clusterSource = new Cluster({
    attributions:
        'Data: <a href="https://www.data.gv.at/auftritte/?organisation=stadt-wien">Stadt Wien</a>',
    distance: 35,
    source: vectorSource,
});

const vectorSource = new VectorSource({
    format: new GeoJSON(),
    url: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=210105',
});

function clusterHullStyle(cluster) {
    if (cluster !== hoverFeature) {
        return;
    }
    const originalFeatures = cluster.get('features');
    const points = originalFeatures.map((feature) =>
        feature.getGeometry().getCoordinates()
    );
    return new Style({
        geometry: new Polygon([monotoneChainConvexHull(points)]),
        fill: convexHullFill,
        stroke: convexHullStroke,
    });
}
