<template>
    <div class="map-center">
        <div class="map-container" ref="mapContainer" />
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { getBaseMapLayer } from '../../api'
import * as Cesium from 'cesium'
import { useMapStore } from '../../../../map/index.js'

const emit = defineEmits()
const mapStore = useMapStore()

Cesium.Ion.defaultAccessToken = import.meta.env.VITE_CESIUM_ION_TOKEN || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyMGE2MTYzOS02OTA3LTRhZDEtYmFmYi01YWZmNDJmZGRlODgiLCJpZCI6MTEwNDE2LCJpYXQiOjE3NjY3MTE5MzR9.MtiUq510xS8C3Wm1rgHCloJqv0dlxIL0CfOIHj4uHBY'

const mapContainer = ref(null);
const viewerRef = ref(null);

const initCesium = () => {
    if (!mapContainer.value) return;
    if (viewerRef.value) return

    try {
        viewerRef.value = new Cesium.Viewer(mapContainer.value, {
            // 基本配置
            timeline: false,
            animation: false,
            fullscreenButton: false,
            vrButton: false,
            geocoder: false,
            homeButton: false,
            infoBox: false,
            sceneModePicker: true,
            selectionIndicator: false,
            shadows: true,
            shouldAnimate: true,
            navigationHelpButton: false,
            imageryProvider: false,
            baseLayerPicker: false,
            sceneModePicker: false,

            // 使用高分辨率渲染
            useBrowserRecommendedResolution: false,
            maximumScreenSpaceError: 2,

            // 添加基础图层
            // imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
            //     url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
            // })
        })

        viewerRef.value.cesiumWidget.creditContainer.style.display = 'none'
        mapStore.destroy()
        mapStore.init(viewerRef.value)

        loadBaseMap()


    } catch (e) {
        console.error('初始化 Cesium 失败:', e)
    }
}

const setViewToCoordinates = (longitude, latitude, height) => {
    if (!viewerRef.value) return
    viewerRef.value.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
        orientation: {
            heading: Cesium.Math.toRadians(0), // 方向角
            pitch: Cesium.Math.toRadians(-90), // 俯仰角（-90 为垂直向下看）
            roll: 0 // 翻滚角
        }
    })

    clearAllEntities()

    // addDeviceMarker(longitude, latitude, 0, {
    //     label: device.value.DName
    // })
}


// 添加设备图标标记
// const addDeviceMarker = (longitude, latitude, height = 0, options = {}) => {
//     if (!viewerRef.value) return null;

//     const entity = viewerRef.value.entities.add({
//         id: options.id || `device-${Date.now()}`,
//         position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
//         billboard: {
//             image: '/src/assets/images/device.png',
//             width: 42,
//             height: 42,
//             horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
//             verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
//             heightReference: options.clampToGround
//                 ? Cesium.HeightReference.CLAMP_TO_GROUND
//                 : Cesium.HeightReference.NONE,
//             disableDepthTestDistance: Number.POSITIVE_INFINITY, // 始终显示在最上层
//             color: options.color ? Cesium.Color.fromCssColorString(options.color) : Cesium.Color.WHITE
//         },
//         label: options.label ? {
//             text: options.label,
//             font: options.font || '14px sans-serif',
//             fillColor: Cesium.Color.BLACK,
//             outlineWidth: 0,
//             style: Cesium.LabelStyle.FILL_AND_OUTLINE,
//             verticalOrigin: Cesium.VerticalOrigin.TOP,
//             pixelOffset: new Cesium.Cartesian2(0, 2),
//             showBackground: true,
//             backgroundColor: Cesium.Color.WHITE,
//             backgroundPadding: new Cesium.Cartesian2(5, 8),
//             distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000.0) // 距离显示条件
//         } : undefined
//     });

//     return entity;
// };

// 清除所有设备标记
const clearAllEntities = () => {
    if (!viewerRef.value) return;
    entityMap = {}
    // 移除所有实体或只移除设备标记
    viewerRef.value.entities.removeAll();
};

const setDevice = (_device) => {
    device.value = _device
    const { Lng, Lat } = _device
    setViewToCoordinates(Lng, Lat, 1600)
};

// 加载天地图，也就是最基础的图层，如果没有该图层，就只会看到一个蓝色球体
async function loadBaseMap() {
    const { layer } = mapStore.services()
    try {
        const currentGroupId = mapStore.getCurrentBaseMapGroupId()
        console.log('当前底图组ID：', currentGroupId)
        if (!currentGroupId) return
        for (const group of mapStore.baseMapGroups) {
            const groupId = group.Attribute?.rid || group.Rid
            const visible = groupId === currentGroupId
            const layers = mapStore.getBaseMapLayersForGroup(groupId)
            for (const cfg of layers) {
                await layer.addLayer({
                    id: cfg.id,
                    type: cfg.type,
                    url: cfg.url,
                    options: { visible },
                    meta: cfg.meta
                })
            }
        }
    } catch (e) {
        console.warn('底图加载失败', e)
    }
}

onMounted(async () => {
    await fetchBaseMapLayers()
    initCesium()
})

const fetchBaseMapLayers = async () => {
    try {
        const params = {
            pcatalog: 'DDT'
        }
        const res = await getBaseMapLayer(params)

        // const response = await axiosApi('/api/v1/DataDirectory/QueryCatalog', 'GET', {
        //     pcatalog: 'DDT'
        // })

        // if (!response?.data) {
        //     console.error('获取底图服务失败：无效的响应数据结构。')
        //     return createDefaultResult()
        // }

        // const loadBaseMap = response.data.length > 0 ? response.data : defaultBaseMapLayers
        // const layerConfigs = processLayerConfigs(collectLayerConfigs(loadBaseMap))

        // return { layerConfigs, rawBaseMapData: loadBaseMap }
    } catch (error) {
        console.error('获取底图图层时出错:', error)
        // return createDefaultResult()
    }
}


</script>
<style scoped lang="scss">
.map-center {
    width: 100%;
    height: 100%;

    .map-container {
        overflow: hidden;
        border-radius: 6px;
        width: 100%;
        height: 100%;
    }
}
</style>
