import Layer from "ol/layer/Vector";
import config from "@/api/config.js";
import * as KMap from "@/utils/ol-map/KMap";
import Stroke from "ol/style/Stroke";
import * as util from "@/common/ol_common.js";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import { Point } from 'ol/geom';
import Feature from "ol/Feature";
import VectorLayer from "ol/layer/Vector.js";
import WKT from "ol/format/WKT";
import { Cluster, Vector as VectorSource } from "ol/source";
import { newAreaFeature, newAreaPoint, newPolymerFeature, newPoint } from "@/utils/map.js";
import { GARDEN_STATUS_ENUM as STATUS_ENUM } from "@/api/enum.js"
import { getArea } from 'ol/sphere.js';
import * as proj from "ol/proj";
import { register } from "ol/proj/proj4";
import proj4 from "proj4"
import eventBus from "@/api/eventBus";
proj4.defs("EPSG:38572", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs");
register(proj4);

/**
 * @description 智能巡园地图层对象
 */
class FarmMap {
    constructor() {
        let that = this;
        let vectorStyle = new KMap.VectorStyle();
        this.vectorStyle = vectorStyle;

        this.treeClusterLayer = new KMap.VectorLayer("tree-cluster", 999, {
            minZoom: 15,
            style: (f) => this.getStyle(f)
        })

        this.areaLayer = new KMap.VectorLayer("areaLayer", 999, { style: (f) => that.vectorStyle.getPolygonStyle("#00000010", "#000000", 3) })
        this.subAreaLayer = new KMap.VectorLayer("subAreaLayer", 1000, {
            style: (f) => {
                return that.vectorStyle.getPolygonStyle(f.get("fillColor"), f.get("strokeColor"), 2)
            }
        })
        that.areaVal = 0

        this.treeCacheStyle = {}
        this.treeStyle = (f) => {
            let key = f.get("imgSrc");
            if (that.treeCacheStyle[key]) {
                return that.treeCacheStyle[key]
            }
            let style = new Style({
                image: new Icon({
                    src: f.get("imgSrc"),
                    scale: 1,
                    anchor: [0.5, 1],
                })
            });
            that.treeCacheStyle[key] = style
            return style
        }
        this.treeLayer = new KMap.VectorLayer("statusPointLayer", 999, { style: that.treeStyle })



        this.blueRegionLayer = new KMap.VectorLayer("blueRegionLayer", 99, {
            minZoom: 1,
            maxZoom: 22,
            style: function (f) {
                const selected = f.get('selected');
                if (selected) {
                    return that.vectorStyle.getPolygonStyle("rgba(23, 99, 110, 0.43)", "rgba(37, 227, 255, 0.7)", 2)
                }
                return that.vectorStyle.getPolygonStyle("rgba(0, 0, 0, 0.5)", "rgba(255, 255, 255, 0.2)", 1)
            }
        });
    }

    initMap(location, target) {
        let level = 16;
        let coordinate = util.wktCastGeom(location).getFirstCoordinate();
        this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 1, 22, "vec", true, true);
        this.kmap.addLayer(this.areaLayer.layer)
        this.kmap.addLayer(this.subAreaLayer.layer)
        this.kmap.addLayer(this.treeLayer.layer)
        this.kmap.addLayer(this.blueRegionLayer.layer)
        this.kmap.addLayer(this.treeClusterLayer.layer)

        this.addMapSingerClick()
    }

    initData(farmId, regionId) {
        let that = this
        VE_API.image.pointByRegionId({ farmId, regionId }).then(({ data }) => {
            let features = []
            for (let item of data) {
                item.iconName = 'defalut'
                that.getIcon(item)
                let point = newPoint(item);
                features.push(point)
            }

            if (this.treeClusterLayer &&  this.treeClusterLayer.layer.getSource()) {
                // this.treeClusterLayer.layer.getSource().getSource().clear()
            }
            that.clusterSource = new Cluster({
                distance: 15,
                minDistance: 60,
                source: new VectorSource({
                    features: features,
                }),
            });
            that.treeClusterLayer.layer.setSource(that.clusterSource)
            setTimeout(()=>{
                that.kmap.fit(that.clusterSource.source.getExtent(), {padding:[100,100,100,100]})
            },100)
        })
    }
    //多点的过滤方法
    manyFeatureFilter(features) {
        let res = features[0]
        if (features.length == 1) {
            return res
        }
        for (let item of features) {
            res = res.get('status') > item.get('status') ? res : item
        }
        return res;
    }
    //得到点样式
    getStyle(feature) {
        feature = this.manyFeatureFilter(feature.get('features'))
        return this.getIconStyle(feature)
    }
    getIconStyle(feature) {
        let style = new Style({
            image: new Icon({
                src: feature.get('icon'),
                // src: `/src/assets/images/map/${feature.get('iconName')}-icon.png`,
                scale: feature.get('scale'),
            })
        });
        return style
    }
    getIcon(item) {
        // let imgSrc = require(`@/assets/images/map/${item.iconName}-icon.png`)
        let imgSrc = '/src/assets/images/map/status/status-zc.png'
        let scale = 0.8
        if (item.status == 1) {
            imgSrc = '/src/assets/images/map/status/status-szyc.png'
        }
        if (item.status == 2) {
            imgSrc = '/src/assets/images/map/status/status-bh.png'
        }
        if (item.status == 3) {
            imgSrc = '/src/assets/images/map/status/status-ch.png'
        }
        item["icon"] = imgSrc
        item["scale"] = scale
    }

    // 重新渲染地图
    updateMap() {
        setTimeout(() => {
            this.kmap.map.updateSize()
        }, 1000);
    }

    fit(geomOrExtent, padding) {
        this.kmap.fit(geomOrExtent, padding);
    }
    addMapSingerClick() {
        let that = this
        this.kmap.on("singleclick", (evt) => {
            that.kmap.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
                if (layer instanceof VectorLayer && layer.get("name") === "blueRegionLayer") {
                    feature.set('selected', feature.get("selected") ? false : true);

                    let geom = feature.getGeometry().clone()
                    geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"))
                    let areaItem = getArea(geom)
                    areaItem = (areaItem + areaItem / 2) / 1000;
                    if (feature.get('selected') === true) {
                        that.areaVal += areaItem
                    } else {
                        that.areaVal -= areaItem
                    }
                    eventBus.emit("editNsMap:areaVal", that.areaVal)
                }
            })
        })
    }


    // 状态图例
    handleStatusIcon(obj) {
        let key = this.afterDayNum == 3 ? "ycStatus" : this.afterDayNum == 5 ? "ycStatus5d" : "ycStatus7d"
        let hasStatus = false
        let imgSrc = null
        if (obj[key] == 3) {
            hasStatus = true
            imgSrc = '/src/assets/status/status_bcyc.png'
            return { hasStatus, imgSrc }
        }
        if (obj[key] == 2) {
            hasStatus = true
            imgSrc = '/src/assets/status/status_szyc.png'
            return { hasStatus, imgSrc }
        }
        // if (obj[key] == 1) {
        //     hasStatus = true
        //     imgSrc = require('@/assets/status/status_dfh.png')
        //     return { hasStatus, imgSrc }
        // }
        // if (obj[key] == 0) {
        //     hasStatus = true
        //     imgSrc = require('@/assets/status/status_xfdw.png')
        //     return { hasStatus, imgSrc }
        // }
        return { hasStatus, imgSrc }
    }

    // 区级颜色
    handleStatusColor(key) {
        let fillColor = '#ffffff00'
        let strokeColor = '#ffffff'
        switch (key) {
            case STATUS_ENUM.DONE:
                fillColor = 'rgba(95,255,197,0)'
                strokeColor = '#ffffff'
                break;
            case STATUS_ENUM.ABNORMAL_GROWTH:
                fillColor = 'rgba(255,189,5,0.2)'
                strokeColor = '#FFE44E'
                break;
            case STATUS_ENUM.ABNORMAL_Pest:
                fillColor = 'rgba(51,11,3,0.52)'
                strokeColor = '#F55A5A'
                break;
            case STATUS_ENUM.PENDING_REVIEW:
                fillColor = 'rgba(3,40,51,0.2)'
                strokeColor = '#032833'
                break;
            case STATUS_ENUM.REVIEWED:
                fillColor = 'rgba(95,255,197,0.1)'
                strokeColor = '#5FFFC5'
                break;
            default:
                break;
        }
        return { fillColor, strokeColor }
    }

    initArea(data, callback) {
        let that = this
        this.areaLayer.refresh()
        for (let item of data) {
            that.areaLayer.addFeature(newAreaFeature(item))
            that.areaPointLayer.addFeature(newAreaPoint(item))
        }
        callback && callback()
    }

    initSubArea(organId, callback) {
        let that = this
        this.subAreaLayer.refresh()
        VE_API.sub_area.list({ organId }).then(({ data, code }) => {
            for (let item of data) {
                item.fillColor = that.handleStatusColor(item.status).fillColor
                item.strokeColor = that.handleStatusColor(item.status).strokeColor
                that.subAreaLayer.addFeature(newPolymerFeature(item))
            }
            callback && callback()
        })
    }

    toggleLegend(val) {
        // this.treeLayer.layer.setVisible(val)
        this.treeClusterLayer.layer.setVisible(val)
    }


    getBlueRegion({ gardenId, regionId }, callback) {
        this.blueRegionLayer.source && this.blueRegionLayer.source.clear()
        VE_API.farm.blueRegionList({ farmId: gardenId, regionId }).then(({ data, code }) => {
            for (let item of data) {
                item.wkt = item.geom
                item.id = item.blueZoneCode
                let feature = newAreaFeature(item);
                this.blueRegionLayer.addFeature(feature)
            }
            this.kmap.fit(this.blueRegionLayer.source.getExtent(), [0, 0, 0, 0])
            callback && callback(data.length)
        })
    }

    setBlueRegion(data) {
        this.blueRegionLayer.source.getFeatures().forEach(feature => {
            // 检查 feature 的属性中是否有 selected 属性且为 true
            data.map(item => {
                if (item.id === feature.get('id')) {
                    feature.set('selected', true)
                }
            })
        });
    }

    toggleAllArea(val) {
        let that = this
        that.areaVal = 0
        this.blueRegionLayer.source.getFeatures().forEach(feature => {
            feature.set('selected', val)
            if (val === true) {
                let geom = feature.getGeometry().clone()
                geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"))
                let areaItem = getArea(geom)
                areaItem = (areaItem + areaItem / 2) / 1000;
                that.areaVal += areaItem
            }
            eventBus.emit("editNsMap:areaVal", that.areaVal)
        });

    }
    getSelectedBlueRegion() {
        // 用于存储 selected 为 true 的 feature 的 id
        const selectedFeatureIds = [];
        // 遍历所有 features
        this.blueRegionLayer.source.getFeatures().forEach(feature => {
            // 检查 feature 的属性中是否有 selected 属性且为 true
            if (feature.get('selected') === true) {
                // 获取 feature 的 id
                const id = feature.get('id');
                // 将 id 添加到数组中
                selectedFeatureIds.push({ id });
            }
        });
        return selectedFeatureIds;
    }
}

export default FarmMap;
