import { fetchEmergencyForceList } from '@/views/cockpit/api/emergencyForce'
import { getAllYHZList } from '@/views/cockpit/api/commonHttp'

import ImageMarkData from './ImageMarkData'
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'


import serviceFacilityMarkerIcon from '../assets/legendTool/服务设施icon定位.png'
import riskRoadMarkerIcon from '../assets/legendTool/风险路段icon定位.png'
import blockEventMarkerIcon from '../assets/legendTool/阻断事件icon定位.png'
import emergencyForceMarkerIcon from '../assets/legendTool/应急力量icon定位.png'
import weatherAlertMarkerIcon from '../assets/legendTool/气象预警icon定位.png'
import { ElMessage } from 'element-plus'


/**
 *  当前业务下的地图服务
 *  主要是涉及需要调用后端服务获得地图数据
 * */

export const useMapImageMark = (mapStore) => {

    // mapStore准备就绪进行初始化
    mapStore.onReady(() => init())

    // 接口服务映射
    const imageMarkMap = {
        // 养护站 legend
        serviceFacility: new ImageMarkData({
            key: 'serviceFacility',
            api: getAllYHZList,
            markerIcon: serviceFacilityMarkerIcon,
            onResponse: function (res) {
                if (res?.success) {
                    res.data = res.data.filter((item) => {
                        if (isNaN(item.jd) || isNaN(item.wd)) {
                            return false
                        }
                        return true
                    })
                    const dataList = res.data.map((item) => {
                        item.mapData = {
                            id: this.key + '-' + item.id,
                            layerId: this.key,
                            position: [Number(item.jd), Number(item.wd), 0],
                            image: this.markerIcon
                        }
                        return item
                    })
                    return dataList
                }
                return []
            }
        }),
        blockEvent: new ImageMarkData({
            key: 'blockEvent',
            markerIcon: blockEventMarkerIcon,
            api: fetchEmergencyForceList,
        }),
        weatherAlert: new ImageMarkData({
            key: 'weatherAlert',
            markerIcon: weatherAlertMarkerIcon,
            api: fetchEmergencyForceList,
        })
    }

    let entityService
    let viewer
    let handler

    const init = () => {
        entityService = mapStore.services().entity
        viewer = mapStore.getViewer()

        // 事件注册
        handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

        // 点击事件
        handler.setInputAction(function (event) {
            const pickedFeature = viewer.scene.pick(event.position);
            if (pickedFeature?.id) {
                const entity = pickedFeature.id
                const data = entity.properties.originalData.getValue()
                const imageMarkData = imageMarkMap[data.mapData.layerId]
                imageMarkData.tooltip.show({
                    data,
                    entity,
                    position: getScreenPosition(entity)
                })
            }

        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 帧渲染函数，也就是显示器的每一帧都会执行
        // 地图拖动与放大的监控，需要更新各个tooltips的位置, 通过消息来通知
        viewer.scene.postRender.addEventListener(() => {
            for (const key in imageMarkMap) {
                const imageMarkData = imageMarkMap[key]
                const entity = imageMarkData.tooltip.entity
                if (!entity) continue
                imageMarkData.tooltip.updatePosition(getScreenPosition(entity))
            }
        })
    }



    /**
     * 绘制各个地图标，例如点击LengendItem的某一项，就会显示对应的图标列表
     */
    const drawImageEntities = async (dataList) => {
        for (const item of dataList) {
            const mapData = item.mapData
            entityService.addBillboard({
                id: mapData.id,
                layerId: mapData.layerId,
                position: mapData.position,
                image: mapData.image,
                width: mapData.width || 44,
                height: mapData.height || 44,
                clampToGround: true,
                properties: { originalData: item }
            })
        }
    }

    /*
    * 清除某个图层里的实体
    */
    const clearLayerEntity = (layerId) => {
        entityService.clearLayerEntities(layerId)
        const imageMarkData = imageMarkMap[layerId]
        if (!imageMarkData) return
        imageMarkData.tooltip.close()
    }

    /**
     * 聚焦到图片实例的中心点
     */
    const focusOnMarkers = (dataList) => {
        if (!dataList || dataList.length === 0) return
        const positions = dataList.map((item) => {
            return [item.mapData.position[0], item.mapData.position[1]]
        })
        const features = turf.points(positions)
        const center = turf.center(features)
        const position = center.geometry.coordinates
        mapStore.viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(position[0], position[1], 160000),
            orientation: {
                heading: Cesium.Math.toRadians(0), // 方向角
                pitch: Cesium.Math.toRadians(-90), // 俯仰角（-90 为垂直向下看）
                roll: 0 // 翻滚角
            }
        })
    }


    /**
     * 根据图标名称请求后台服务，动态加载图标列表
     */
    const loadDynamicMark = async ({ key, params }) => {
        const imageMarkData = imageMarkMap[key]
        if (!imageMarkData) return
        // 取消上一次请求
        imageMarkData.cancelRequest()
        const dataList = await imageMarkData.request(params)
        clearLayerEntity(key)
        drawImageEntities(dataList)
    }

    /**
     * 显示/隐藏地图标
     */
    const toggleMark = async ({ key, active, params }) => {
        const imageMarkData = imageMarkMap[key]

        if (!active) {
            clearLayerEntity(key)
            if (imageMarkData) imageMarkData.cancelRequest()
            return
        }

        loadDynamicMark({ key, params })
    }

    /**
     * 过滤养护站图标
     */
    const filterYHZMark = async (key, filterFn, focusFn) => {
        const imageMarkData = imageMarkMap[key]
        if (!imageMarkData) return
        // 取消上一次请求
        imageMarkData.cancelRequest()
        let dataList = await imageMarkData.request()
        dataList = dataList.filter((item) => {
            return filterFn(item)
        })
        clearLayerEntity(key)
        // 绘制过滤出来的点
        drawImageEntities(dataList)
        // 聚焦聚焦函数过滤出来的点
        const focusDataList = dataList.filter((item)=>{
            return focusFn(item)
        })
        if(focusDataList) {
            focusOnMarkers(focusDataList)
        }
    }

    /**
     * 获得该实体位于屏幕的位置，用于html元素进行定位使用
     */
    const getScreenPosition = (entity) => {

        try {
            const position = entity.position?.getValue(Cesium.JulianDate.now())
            if (!position) return

            // 处理 clampToGround 实体
            // 对于使用 CLAMP_TO_GROUND 的 billboard，需要获取实际的地形高度
            let clampedPosition = position

            // 转换为地理坐标
            const cartographic = Cesium.Cartographic.fromCartesian(position)

            // 尝试获取地形高度
            if (viewer.scene.globe) {
                const height = viewer.scene.globe.getHeight(cartographic)

                // 如果成功获取地形高度，使用地形高度重建位置
                if (Cesium.defined(height)) {
                    cartographic.height = height
                    clampedPosition = Cesium.Cartographic.toCartesian(cartographic)
                } else {
                    // 备用方案：尝试使用 clampToHeight
                    const clampedCartesian = viewer.scene.clampToHeight(position)
                    if (clampedCartesian) {
                        clampedPosition = clampedCartesian
                    }
                }
            }

            // 使用修正后的位置进行屏幕坐标转换
            const screenPosition = viewer.scene.cartesianToCanvasCoordinates(clampedPosition)
            if (screenPosition) {
                return screenPosition
            }
        } catch (error) {
            console.error('更新 Tooltip 位置失败:', error)
        }
    }

    return {
        toggleMark,
        filterYHZMark
    }

}