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';
import XYZLayer from "../../utils/ol-map/XYZLayer";
import GeoJsonLayer from "../../utils/ol-map/GeoJsonLayer";
import eventBus from "@/api/eventBus";
import {VectorStyle} from "../../utils/ol-map/KMap";
import StaticImgLayer from "../../utils/ol-map/StaticImgLayer";

function getColorByVal(val, legendData) {
    for (let i = 0; i < legendData.level.length; i++) {
        if(legendData.level[i] instanceof Array){
            let [min, max] = legendData.level[i];
            if (val >= min && val <= max) {
                return legendData.colors[i];
            }
        }else{
            if(val === legendData.level[i]){
                return legendData.colors[i];
            }
        }
    }
    return undefined; // 如果 val 不在任何区间内，返回 undefined
}

/**
 * @description 全景化地图层对象
 */
class StaticMapLayers {
    constructor(map, data){
        this.vectorStyle = new VectorStyle()
        this.layerData = {}
        this.cacheStyle = {}
        this.timeIndex = 0
        this.layerName = ""
        this.initStaticMapLayers(map,data)
    }
    initStaticMapLayers(map,data){
        let that = this
        if(data){
            that.initStaticMapLayer(map,data)
        }else{
            VE_API.warning.fetchWarningLayer({
                k: "static_map",
                resultType: "json",
            }).then(({data}) => {
                that.initStaticMapLayer(map,data)
                // that.autoTest()
                // 时间轴
                // eventBus.on("weatherTime:changeTime", ({index}) => {
                //     this.timeIndex = index
                //     this.show(this.layerName)
                // })
            })
        }
    }

    initStaticMapLayer(map,data){
        for(let key in data){
            let item = data[key]
            if(item.type === "xyz"){
                this.layerData[key] = {legend:item.legend, layer:this.addXyzLayer(map, item)}
            }else if(item.type === "geojson"){
                this.layerData[key] = {legend:item.legend, legendData:item.legendData, layer:this.addGeoJsonLayer(map, item, key)}
            }else if(item.type === "img"){
                this.layerData[key] = {legend:item.legend, layer:this.addStaticImgLayer(map, item)}
            }
        }
    }

    show(key,isFit = false){
        if (isFit) {
            this.timeIndex = 0
        }
        this.layerName = key
        this.hideAll()
        let keyText = key+this.timeIndex
        let layer = this.layerData[keyText].layer
        eventBus.emit("alarmList:changeMapLayer", {legendUrl:layer.layer.get("legend"),
            colors:layer.layer.get("colors"), labels:layer.layer.get("labels")});
        layer.show()
        if(isFit && layer.layer.getExtent){
            let extent = layer.layer.getExtent();
            if(extent && extent[0] != Infinity){
                layer.mapInstance.fit(extent,{padding:[-200,-200,-200,-200]})
            }
        }
    }

    showSingle(key,isFit = false,hideOther = true){
        console.log('layerData', key, this.layerData,);
        if(!this.layerData[key]){
            return;
        }
        this.layerName = key
        hideOther && this.hideAll()
        let layer = this.layerData[key].layer
        eventBus.emit("alarmList:changeMapLayer", {legendUrl:layer.layer.get("legend"),
            colors:layer.layer.get("colors"), labels:layer.layer.get("labels")});
        layer.show()
        if(isFit && layer.layer.getExtent){
            let extent = layer.layer.getExtent();
            if(extent && extent[0] != Infinity){
                layer.mapInstance.fit(extent,{padding:layer.layer.get("padding") || [200,400,200,200]})
            }
        }
    }

    hideByKey(key){
        let layer = this.layerData[key].layer
        layer.hide()
    }
    hideAll(){
        for(let key in this.layerData){
            this.hideByKey(key)
        }
    }
    removeLayers(map){
        for(let key in this.layerData){
            let layer = this.layerData[key].layer
            map.removeLayer(layer)
        }
        this.layerData = {}
    }

    addStaticImgLayer(map, item){
        if(!item["opacity"]){
            item["opacity"] = 0.5
        }
        let imgLayer = new StaticImgLayer(item.url, item, 5, map);
        imgLayer.hide()
        if(item.legendData){
            imgLayer.layer.set("colors", item.legendData.colors)
            imgLayer.layer.set("labels", item.legendData.label)
        }
        imgLayer.layer.set("legend", item.legend)
        return imgLayer
    }

    addXyzLayer(map, item){
        let xyz = new XYZLayer(item.url, item, 3, map);
        xyz.hide()
        return xyz
    }

    addGeoJsonLayer(map, item, key){
        let that = this
        item["style"] = function(feature){
            let val = feature.get(item.legendData.paramKey)
            let cacheKey = `${key}_${item.legendData.paramKey}_${val}`
            let style = that.cacheStyle[cacheKey]
            if(!style){
                let color = getColorByVal(val, item.legendData)
                let fillColor = color
                let strokeColor = color
                style = that.vectorStyle.getPolygonStyle(fillColor, "#000000", 1)
                that.cacheStyle[cacheKey] = style
            }
            return style
        }
        let geoJsonLayer = new GeoJsonLayer(item.url, item, 3, map);
        geoJsonLayer.layer.set("colors", item.legendData.colors)
        geoJsonLayer.layer.set("labels", item.legendData.label)
        geoJsonLayer.hide()
        return geoJsonLayer
    }



    autoTest(){
        let that = this
        let keys = []
        for(let key in that.layerData){
            keys.push(key)
        }
        let index = 0
        setTimeout(() => {
            that.showSingle("从化地块日温",true)
            index = (index + 1) % keys.length

        }, 2000);
    }
}

export default StaticMapLayers
