<template>
    <div class="bottom-map" ref="areaRef"></div>
</template>

<script setup>
import Layer from "ol/layer/Vector";
import config from "@/api/config.js";
import { newPoint, newAreaFeature } from "@/utils/map";
import * as KMap from "@/utils/ol-map/KMap";
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 { ElMessage } from 'element-plus'
import Feature from "ol/Feature";
import VectorLayer from "ol/layer/Vector.js";
import WKT from "ol/format/WKT";
import { Fill, Text, Circle, Stroke } from "ol/style.js";
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import SampleVectorLayer from "../map/sampleVectorLayer"

const router = useRouter();

const props = defineProps({
    isPopup: {
        type: Boolean,
        default: false,
    },
    locationId:{
      type: [Number,String],
      default: null,
    },
    showOverview: {
        type: Boolean,
        default: true,
    },
    mapData: {
        type: Object,
        default: () => ({}),
    },
});

const areaRef = ref(null);
let polygonLayer = null;
let kmap = null;
let vectorStyle = new KMap.VectorStyle();
let sampleVectorLayer = null;

const isSmallLevel = ref(false)
const initData = async (toSmall = false, locationId) => {
    sampleVectorLayer.setLocationId(locationId)
    // 清除旧的 polygonLayer 图层
    if (polygonLayer) {
        polygonLayer.source.clear();
    }
    isSmallLevel.value = toSmall
    if (!toSmall) {
        let features = []
        const data = props.mapData
        for (let item of data) {
            item.wkt = item.geom;
            item.name = item.locationCode
            features.push(newAreaFeature(item))
            polygonLayer.source.addFeatures(features);
        }
        let extent = polygonLayer.source.getExtent()
        // 地图自适应到区域可视范围
        kmap.getView().fit(extent, { duration: 500, padding: [0, 0, 0, 0] });
        setTimeout(()=>{
            const finalZoom = kmap.getView().getZoom();
            if (finalZoom <= 12) {
                kmap.getView().setZoom(12.1);
            }
        },501)
    }
    if (toSmall) {
        VE_API.home.locationList({id: locationId}).then(({data}) => {
            for (let item of data) {
                item.wkt = item.geom;
                item.name = item.locationCode
                polygonLayer.addFeature(newAreaFeature(item));
            }
            setTimeout(() => {
                let extent = polygonLayer.source.getExtent()
                // 地图自适应到区域可视范围
                kmap.getView().fit(extent, { duration: 500, padding: [10, 10, 10, 10] });
                setTimeout(()=>{
                    const finalZoom = kmap.getView().getZoom();
                    if (finalZoom <= 12) {
                        kmap.getView().setZoom(12.1);
                    }
                },501)
            }, 100)
        })
    }

};

let listenKey;
const parentId = ref(null)
onMounted(() => {
    // 范围
    polygonLayer = new KMap.VectorLayer("areaLayer", 99, {
        minZoom: 5,
        style: (f) => {
            const style = new Style({
                fill: new Fill({
                    color: f.get('sort')?"#00000030":"#53f89300",
                }),
                stroke: new Stroke({
                    color: f.get('sort')?"#53f893":"red", // 边框
                    width: 2,
                }),
                text: new Text({
                    text: f.get("name"), // 显示的文字
                    font: "16px sans-serif",
                    fill: new Fill({
                        color: "black", // 文字颜色
                    }),
                    stroke: new Stroke({
                        color: "white", // 文字描边
                        width: 2,
                    }),
                }),
            });
            return style;
        },
    });
    let level = 16;
    let coordinate = util.wktCastGeom("POINT (105.08041038233972 -4.782851670)").getFirstCoordinate();
    kmap = new KMap.Map(areaRef.value, level, coordinate[0], coordinate[1], null, 12.5, 23, "img", true, true);
    let xyz2 = config.base_img_url3 + 'map/lby/{z}/{x}/{y}.png';
    // kmap.addXYZLayer(xyz2,{minZoom:12,maxZoom:22});
    let xyzLayer = kmap.addXYZLayer(xyz2,{minZoom:12.5,maxZoom:23});
    xyzLayer.show()
    kmap.addLayer(polygonLayer.layer);
    sampleVectorLayer = new SampleVectorLayer(kmap)
    sampleVectorLayer.setLocationId(props.locationId)
    if (props.showOverview) {
        initData(null,props.locationId);
    }

    // 监听聚合点位的点击，点击后缩放到范围内
    listenKey = kmap.on("click", (e) => {
        kmap.map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
            if (layer instanceof VectorLayer && layer.get("name") === "areaLayer") {
                if(feature.get('sort')) return ElMessage.error('暂无数据')
                if (isSmallLevel.value) {
                    router.push({path:'/layout/detail',query:{id:parentId.value,name:feature.get('locationCode')}})
                }
                if (feature.get('id') && !isSmallLevel.value && props.isPopup) {
                    parentId.value = feature.get('id')
                    emit("toSmall", feature.get('name'))
                    initData(true, feature.get('id'))
                }
            }
        })
    });


});

const updateMapDate = (data,name) =>{
    if(polygonLayer){
        polygonLayer.addFeature(newAreaFeature({wkt:data,name}));
        setTimeout(() => {
            let extent = polygonLayer.source.getExtent()
            // 地图自适应到区域可视范围
            kmap.getView().fit(extent, { duration: 500, padding: [10, 10, 10, 10] });
        }, 100)
    }
}

const emit = defineEmits(["toSmall"])
defineExpose({initData,updateMapDate})
</script>

<style scoped>
.bottom-map {
    width: 100%;
    height: 100%;
    clip-path: inset(0px round 8px);
}
</style>
