import * as KMap from '@/utils/ol-map/KMap';
import {newPoint} from "../../zhgl/map";
import Style from "ol/style/Style";
import {deepClone} from '@/common/commonFun'
import {Cluster, Vector as VectorSource} from 'ol/source.js';
import { Vector as VectorLayer} from 'ol/layer.js';
import {boundingExtent} from 'ol/extent.js';
import {
    Circle as CircleStyle,
    Fill,
    Text,
  } from 'ol/style.js';
  import {unByKey} from 'ol/Observable';
import ImageLayer from 'ol/layer/Image';
import ImageStatic from 'ol/source/ImageStatic';

/**
 * @description 全景化地图层对象
 */
class PlotLayer {
    constructor(kmap){
        this.kmap = kmap
        let vectorStyle = new KMap.VectorStyle()
        this.vectorStyle = vectorStyle
        this.imgStyleCache = {};
        this.treeListData = null
        this.treeClusterLayer = null
        this.gardenImgLayer = null
        this.listenKey = null
    }

    // handleLayerColor(legend) {
    //     const result = this.addColorToArr1(deepClone(this.subAreaData), legend, legend.key)
    //     const hasColorKey = result.some(item => 'color' in item);
    //     if (!hasColorKey) {return}
    //     for(let item of result){
    //         this.subAreaLayer.addFeature(newPolymerFeature(item))
    //     }
    //     this.fit(this.subAreaLayer.source.getExtent())
    // }

    // 切换不同类型
    switchType(type) {
        if (type == 1) {
            // 数据变化
            this.subAreaLayer.layer.setVisible(true)
            this.clearImgLayer()
        } else if(type==2) {
            // 切换显示隐藏
            this.subAreaLayer.layer.setVisible(false)
        }else{
            this.clearImgLayer()
            this.clearCluster()
        }
    }

    // 果园级图片叠加
    async addGargendImg(gardenId, legend) {
        let that = this
        this.clearImgLayer()
        this.clearCluster()
        await VE_API.regionalInformation.aPictureGrid({gardenId, key: legend.key}).then(({data}) => {
            if (data) {
                const extent = JSON.parse(data.extent)
                const imgSource = new ImageStatic({
                    url: data.filename,
                    projection: 'EPSG:4326',
                    imageExtent: extent,
                })
                this.gardenImgLayer = new ImageLayer({
                    source: imgSource,
                    // opacity: 0.6,
                    zIndex: 9999
                })
                that.kmap.addLayer(this.gardenImgLayer)
                that.kmap.getView().fit(extent,{ duration: 1000, padding: [250, 350, 250, 350] });
            }
        })
    }

    // 果树级图例切换
    async switchTreeLegend(gardenId, legend) {
        this.clearImgLayer()
        this.clearCluster()
        if (!this.treeListData) {
            await VE_API.regionalInformation.aPictureTreeList({gardenId}).then(({data,code})=>{
                this.treeListData = data
            })
        }
        this.addCluster(legend)
    }

    addCluster(legend) {
        let that = this
        let features = []
        let result = this.addColorToArr1(deepClone(that.treeListData), legend, legend.key)
        const hasColorKey = result.some(item => 'color' in item);
        if (!hasColorKey) { return }
        for (let item of result) {
            if (item.color) {
                let point = newPoint(item);
                features.push(point)
            }
        }
        const source = new VectorSource({
            features: features,
        });

        const clusterSource = new Cluster({
            distance: 5,
            source: source,
        });


        const styleCache = {};
        this.treeClusterLayer = new VectorLayer({
            source: clusterSource,
            style: function (feature) {
                const size = feature.get('features').length;
                if (size == 1) {
                    const color = feature.get('features')[0].get('color')
                    return that.vectorStyle.getPointSimpleStyle(5, color, color, "2")
                }
                let style = styleCache[size];
                if (!style) {
                    style = [
                        new Style({
                            image: new CircleStyle({
                                radius: 15,
                                fill: new Fill({
                                    color: 'rgba(255, 152, 102, 0.4)'
                                })
                            })
                        }),
                        new Style({
                            image: new CircleStyle({
                                radius: 10,
                                fill: new Fill({
                                    color: 'rgba(255, 165, 0, 0.7)',
                                }),
                            }),
                            text: new Text({
                                text: size.toString(),
                                fill: new Fill({
                                    color: '#fff',
                                }),
                            }),
                        }),
                    ];
                    styleCache[size] = style;
                }
                return style;
            },
            zIndex: 999
        });
        that.kmap.addLayer(this.treeClusterLayer)
        this.fit(this.treeClusterLayer.getSource().getSource().getExtent())
        this.listenKey = that.kmap.on('click', (e) => {
            if (that.treeClusterLayer) {
                that.treeClusterLayer.getFeatures(e.pixel).then((clickedFeatures) => {
                    if (clickedFeatures.length) {
                        const features = clickedFeatures[0].get('features');
                        if (features.length > 1) {
                            const extent = boundingExtent(
                                features.map((r) => r.getGeometry().getCoordinates()),
                            );
                            that.kmap.getView().fit(extent,{ duration: 1000, padding: [50, 50, 50, 50] });
                        }
                    }
                });
            }
        });
    }

    clearCluster() {
        if (this.treeClusterLayer) {
            this.treeClusterLayer.getSource().getSource().clear()
            this.treeClusterLayer = null
            unByKey(this.listenKey)
        }
    }

    clearImgLayer() {
        if (this.gardenImgLayer) {
            this.kmap.removeLayer(this.gardenImgLayer)
            this.gardenImgLayer = null
        }
    }
    
    fit(geomOrExtent){
        this.kmap.fit(geomOrExtent)
    }
    
    // 根据图例对应的值加上color属性
    addColorToArr1(arr1, obj, key) {
        if (arr1 && arr1.length&&obj.type!=3) {
            arr1.forEach(item1 => {
                // 遍历obj.items来找到与item1[key]匹配的color
                obj.items.forEach(item => {
                    // if (item.minVal == item1[key]) {
                    if (item1[key] >= item.minVal && item1[key] <= item.maxVal) {
                        // 将找到的color添加到item1中
                        item1.color = item.color;
                        return;
                    }
                });
            });
            return arr1;
        } else {
            return []
        }
    }
}

export default PlotLayer
