import config from "@/api/config.js"
import * as KMap from '@/utils/ol-map/KMap';
import * as util from "@/common/ol_common.js"
import {newAreaFeature, newAreaPoint, newPoint,newPolymerFeature} from "../zhgl/map";
import {base_img_url2} from "../../api/config";
import Stroke from "ol/style/Stroke";
import Style from "ol/style/Style";
import Photo from "ol-ext/style/Photo";
import {deepClone} from '@/common/commonFun'

import WKT from 'ol/format/WKT.js';
import Feature from 'ol/Feature.js';
import Map from 'ol/Map.js';
import Point from 'ol/geom/Point.js';
import View from 'ol/View.js';
import {Cluster, OSM, 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 RegionalInformationMap {
    getRadius(zoom){
        if(zoom >= 20){
            return 70;
        }
        if(zoom >= 19){
            return 30;
        }
        if(zoom >= 18){
            return 15;
        }
        if(zoom >= 17){
            return 10;
        }
        return 5;
    }

    constructor(){
        let that = this
        let vectorStyle = new KMap.VectorStyle()
        this.vectorStyle = vectorStyle
        this.areaLayer = new KMap.VectorLayer("areaLayer",999,{style:(f)=> vectorStyle.getPolygonStyle("#032833" + "80", "#0BFDF2",3)})
        this.subAreaLayer = new KMap.VectorLayer("subAreaLayer",999,{style:(f)=> {
            const color = f.get("color")
            const fillColor = color.length === 9 ? color : color + "80"
            const strokeColor = color.length === 9 ? '#ffffff' : color
            return vectorStyle.getPolygonStyle(fillColor, strokeColor, 2)
        }})
        this.areaPointLayer =  new KMap.VectorLayer("areaPointLayer",1000,{style:(f)=> vectorStyle.getPointTextStyle(f.get("name"), "#120046","#FFFFFF",2, 30)})
        this.treeLayer = new KMap.VectorLayer("treeLayer",999)
        this.imgStyleCache = {};
        this.imgTreeLayer = new KMap.VectorLayer("imgTreeLayer",999,{minZoom:15,maxZoom:22,
            style:(feature)=> {
                let zoom = that.kmap.view.getZoom();
                let r = that.getRadius(zoom);
                let img = feature.get("img");
                let k = img+r;
                if(img && img != ""){
                    let style = that.imgStyleCache[k];
                    if(!style){
                        style = new Style ({
                            image: new Photo ({
                                src: base_img_url2 + img,
                                radius: r,
                                shadow: 0,
                                crop:true,
                                kind:"circle",
                                onload: function() { that.imgTreeLayer.layer.changed(); },
                                displacement: [0, 30 + 15],
                                stroke: new Stroke({
                                    width: 3,
                                    color: '#fdfcfc'
                                })
                            })
                        });
                        that.imgStyleCache[k] = style
                    }
                    return style
                }else{
                    return vectorStyle.getPointSimpleStyle(10,"#00000000","#00000000",1)
                }

            }})
        // 果树级图例点标记
        // this.treePointLayer = new KMap.VectorLayer("treePointLayer",999,{style:(f)=> {
        //     let colorValue = f.get("color")
        //     return vectorStyle.getPointSimpleStyle(5,colorValue,colorValue,"2")
        // }})
        this.imgTreeLayer.layer.setVisible(false)
        this.subAreaLayer.layer.setVisible(true)
        this.subAreaData = []
        this.treeListData = null
        this.treeClusterLayer = null
        this.gardenImgLayer = null
        this.listenKey = null
    }

    initMap(location,target)  {
        let level = 18
        let coordinate = util.wktCastGeom(location).getFirstCoordinate()
        this.kmap = new KMap.Map(target,level,coordinate[0], coordinate[1],null,10,22);
        let xyz = config.base_img_url + 'map/lby/{z}/{x}/{y}.png';
        this.kmap.addXYZLayer(xyz,{minZoom:15,maxZoom:22});
        let xyz2 = config.base_img_url3 + 'map/lby/{z}/{x}/{y}.png';
        this.kmap.addXYZLayer(xyz2,{minZoom:12,maxZoom:22});
        this.kmap.addLayer(this.areaLayer.layer)
        this.kmap.addLayer(this.subAreaLayer.layer)
        this.kmap.addLayer(this.treeLayer.layer)
        this.kmap.addLayer(this.areaPointLayer.layer)
        this.kmap.addLayer(this.imgTreeLayer.layer)
        // this.kmap.addLayer(this.treePointLayer.layer)
    }

    initArea(organId){
        let that = this
        this.areaLayer.refresh()
        VE_API.area.list({organId}).then(({data,code})=>{
            for(let item of data){
                that.areaLayer.addFeature(newAreaFeature(item))
                that.areaPointLayer.addFeature(newAreaPoint(item))
            }
        })
    }

    initSubArea(organId){
        let that = this
        this.subAreaLayer.refresh()
        VE_API.sub_area.list({organId}).then(({data,code})=>{
            this.subAreaData = data
        })
    }

    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) {
        console.log('type', type);
        if (type == 1) {
            // 数据变化
            this.subAreaLayer.layer.setVisible(true)
            this.clearImgLayer()
        } else {
            // 切换显示隐藏
            this.subAreaLayer.layer.setVisible(false)
        }
    }

    // 果园级图片叠加
    async addGargendImg(gardenId, legend) {
        let that = this
        this.clearImgLayer()
        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: 999
                })
                that.kmap.addLayer(this.gardenImgLayer)
                that.fit(extent)
            }
        })
    }

    // 果树级图例切换
    async switchTreeLegend(gardenId, legend) {
        // this.treePointLayer.source.clear()
        this.clearImgLayer()
        this.clearCluster()
        if (!this.treeListData) {
            await VE_API.regionalInformation.aPictureTreeList({gardenId}).then(({data,code})=>{
                // for(let item of data){
                //     let point = newPoint(item);
                //     that.treeLayer.addFeature(point)
                //     that.imgTreeLayer.addFeature(point)
                // }
                this.treeListData = data
            })
        }
        // 果树级
        // this.treePointLayer.refresh()
        // 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, "wkt","polymer");
        //         that.treePointLayer.addFeature(point)
        //     }
        // }
        // this.fit(this.treePointLayer.source.getExtent())
        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,
            // minDistance: 60,
            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
        }
    }

    initTree(organId){
        let that = this
        this.treeLayer.refresh()
        this.imgTreeLayer.refresh()
        VE_API.tree.treeListAndGrowData({organId,areaId:-1}).then(({data,code})=>{
            for(let item of data){
                let point = newPoint(item);
                that.treeLayer.addFeature(point)
                that.imgTreeLayer.addFeature(point)
            }
        })
    }
    addSingleSelect(listener){
        this.treeLayer.addSingleSelect(function(e){
            if(e.selected.length > 0){
                listener(e.selected[0])
            }
        },this.kmap.map)
    }

    setTreeStyle(style){
        this.treeLayer.layer.setStyle(style)
        this.treeLayer.layer.changed()
    }
    fit(geomOrExtent){
        this.kmap.fit(geomOrExtent)
    }
    openCloseImg(){
        this.imgTreeLayer.layer.setVisible(!this.imgTreeLayer.layer.getVisible())
    }
    openClosePolymer(){
        this.subAreaLayer.layer.setVisible(!this.subAreaLayer.layer.getVisible())
    }
    // 根据图例对应的值加上color属性
    addColorToArr1(arr1, obj, key) {
        if (arr1 && arr1.length) {
            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 RegionalInformationMap
