import * as KMap from "@/utils/ol-map/KMap";
import * as util from "@/common/ol_common.js";
import Style from "ol/style/Style";
import { Point } from "ol/geom";
import Feature from "ol/Feature";
import { ElMessage } from "element-plus";
import eventBus from "@/api/eventBus";
import VectorLayer from "ol/layer/Vector.js";
import config from "@/api/config.js";
import { Fill, Circle, Stroke } from "ol/style.js";
import WKT from "ol/format/WKT.js";
import { getArea } from "ol/sphere.js";
import * as turf from "@turf/turf";
import * as proj from "ol/proj";
import proj4 from "proj4";
import { register } from "ol/proj/proj4";
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 IndexMap {
    constructor() {
        let that = this;
        let vectorStyle = new KMap.VectorStyle();
        this.vectorStyle = vectorStyle;
        this.curPoint = null;
        this.selectPoint = null;
        this.isPoint = false;
        this.pointIndex = null;

        this.selectPointLayer = new KMap.VectorLayer("selectPointLayer", 10000, {
            style: () => {
                return new Style({
                    image: new Circle({
                        radius: 6,
                        fill: new Fill({
                            color: "red",
                        }),
                        stroke: new Stroke({
                            color: "#fff",
                            width: 1,
                        }),
                    }),
                });
            },
        });
    }

    //获取地块信息
    getAreaGeometry() {
        let features = this.kmap.getLayerFeatures();
        let geometryArr = [];
        let area = 0;
        // 获取图层上的Polygon，转成geoJson用于回显
        features.forEach((item) => {
            geometryArr.push({ featureWkt: new WKT().writeFeature(item) });
            let geom = item.getGeometry().clone();
            geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
            let areaItem = getArea(geom);
            area = (areaItem + areaItem / 2) / 1000;
        });
        return { geometryArr, area: area.toFixed(2) };
    }

    initMap(location, target) {
        // 先销毁旧地图实例
        if (this.kmap) {
            this.kmap.destroy(); // 确保 KMap 有 destroy 方法
            this.kmap = null;
        }
        let level = 16;
        let coordinate = util.wktCastGeom(location).getFirstCoordinate();
        this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 12.5, 23);
        let xyz2 = config.base_img_url3 + 'map/lby/{z}/{x}/{y}.png';
        this.kmap.addXYZLayer(xyz2,{minZoom:12.5,maxZoom:23});
        this.kmap.addLayer(this.selectPointLayer.layer);
        this.kmap.initDraw((e) => {
            if (e.type === "drawend") {
                this.curPoint = e.feature;
                this.curPoint.set("icon", "point");
                this.startModify();
            }
        });
        this.kmap.modifyDraw((e) => {});
        this.addMapSingerClick();
    }

    // 开始编辑
    startModify(isFit = false) {
        this.kmap.startModify();
        const features = this.kmap.getLayerFeatures();
        if (features.length) {
            this.curPoint = features[0];
        }
        if (isFit) {
            this.fitMap();
        }
        this.curPoint.set("icon", "point-act");
    }

    clearSelectPoint(isMsg = true) {
        if (this.isPoint) {
            if (isMsg) {
                ElMessage.warning("Uncheck the point position");
            }
            this.selectPointLayer.source.clear();
            this.kmap.startModify();
            this.isPoint = false;
        }
    }

    // 地图点击事件
    addMapSingerClick() {
        let that = this;
        that.kmap.on("singleclick", (evt) => {
            that.selectPonitFun(that.kmap.map, evt);
        });
    }

    //选中点位方法
    selectPonitFun(map, evt) {
        let that = this;
        map.forEachFeatureAtPixel(evt.pixel, function (f, layer) {
            let d = 0.0002;
            if (layer instanceof VectorLayer && layer.get("name") === "defaultPolygonLayer") {
                const fs = map.getFeaturesAtPixel(evt.pixel);
                let lonlat = map.getCoordinateFromPixel(evt.pixel);
                if (fs.length > 0) {
                    const feature = fs[0];
                    const geometry = feature.getGeometry();
                    let coordinates = geometry.getCoordinates()[0]; // 获取多边形的顶点坐标
                    ElMessage.success("This point has been selected");
                    let list = that.curPoint.getGeometry().getCoordinates();
                    if (list[0].length === 1) {
                        coordinates = list[0][0];
                    } else {
                        coordinates = list[0];
                    }
                    let arr = [];
                    let i = 0;
                    let curDistance = 0;
                    for (let subArray of coordinates) {
                        let from = turf.point(subArray);
                        let to = turf.point(lonlat);
                        let options = { units: "miles" };
                        let distance = turf.distance(from, to, options);
                        if (distance < 0.1) {
                            if (curDistance == 0) {
                                arr = subArray;
                                curDistance = distance;
                                that.pointIndex = i;
                            } else if (curDistance > distance) {
                                arr = subArray;
                                curDistance = distance;
                                that.pointIndex = i;
                            }
                        }
                        i++;
                    }
                    that.selectPointLayer.refresh();
                    let point = new Feature(new Point(arr));
                    that.selectPointLayer.addFeature(point);
                    that.selectPoint = coordinates;
                    that.kmap.endModify();
                    that.isPoint = true;
                    eventBus.emit("map:point");
                }
            }
        });
    }

    // 移除点的功能
    removePoint() {
        const coordinates = this.curPoint.getGeometry().getCoordinates();
        let array = coordinates[0];
        if (coordinates[0].length === 1) {
            array = coordinates[0][0];
        }
        // 如果点存在，则删除它
        if (this.pointIndex > -1) {
            array.splice(this.pointIndex, 1); // 删除点
            // 更新多边形的坐标
            this.curPoint.getGeometry().setCoordinates(coordinates); // 更新几何形状
            this.pointIndex = -1;
        } else {
            ElMessage.warning("Please choose a point");
        }
        this.clearSelectPoint(false);
    }

    fitMap() {
        const extent = this.curPoint.getGeometry().getExtent();
        this.kmap.getView().fit(extent, { duration: 500, padding: [50, 50, 50, 50] });
    }

    setAreaGeometry(geometryArr) {
        let that = this;
        geometryArr.map((item) => {
            that.kmap.setLayerWkt(item.featureWkt);
        });
        this.startModify(true);
    }

    zoomMap(type) {
        const finalZoom = this.kmap.getView().getZoom();
        if (type === "add") {
            this.kmap.getView().setZoom(finalZoom + 1);
        } else {
            this.kmap.getView().setZoom(finalZoom - 1);
        }
    }

    clearLayer() {
        this.kmap.polygonLayer && this.kmap.polygonLayer.source.clear();
        this.kmap.selectPointLayer && this.kmap.selectPointLayer.source.clear();
    }
}

export default IndexMap;
