<template>
    <MarsMap :options="configJson" map-key="test" @onload="marsOnload" />
</template>

<script setup>
import * as mars3d from 'mars3d'
import MarsMap from '@/components/ComMap/index.vue'
import configJson from './config.json'
import mapData from './data.js'

// 导入所有图标图片
import iconThreeNew from '@/assets/images/map/icon_three_new.png'
import iconTwoNew from '@/assets/images/map/icon_two_new.png'
import iconFiveNew from '@/assets/images/map/icon_five_new.png'
import iconSevenNew from '@/assets/images/map/icon_seven_new.png'
import iconFourNew from '@/assets/images/map/icon_four_new.png'
import ztOrange from '@/assets/images/map/zt_orange.png'
import ztRed from '@/assets/images/map/zt_red.png'
import ztGreen from '@/assets/images/map/zt_green.png'
import iconOneNew from '@/assets/images/map/icon_one_new.png'
import sdIcon from '@/assets/images/map/sd.png'
import projectIcon from '@/assets/images/map/project.png'
import ztGary from '@/assets/images/map/zt_gary.png'

// 导入 3D 杆塔模型（替换 demo.js 中的 ../../img/3d-model 路径）
import towerModel1 from '@/assets/3d/tower_1.glb'
import towerModel2 from '@/assets/3d/tower_2.glb'

const Cesium = mars3d.Cesium

// 对应 demo.js 顶部的全局变量（保留原有流程）
let map = null // 地图实例（由 MarsMap 传入）
let graphicLayerGlobal = null // 当前使用的图形图层
let graphicLayerList = [] // 记录所有绘制的图形
let polylines1 = [] // 导线曲线1
let polylines2 = [] // 导线曲线2
let polylines3 = [] // 导线曲线3

// 图标类型映射
const iconTypeList = {
    1: iconThreeNew,
    2: iconTwoNew,
    3: iconFiveNew,
    4: iconSevenNew,
    5: iconFourNew,
    6: ztOrange,
    7: ztRed,
    8: ztRed,
    9: ztRed,
    10: ztGreen,
    0: iconOneNew,
    12: sdIcon,
    20: projectIcon,
    21: ztGary,
}

const marsOnload = (marsMap) => {
    // 保存地图实例到全局变量，供海拔计算等函数使用（对应 demo.js 中的 map）
    map = marsMap

    const graphicLayer = new mars3d.layer.GraphicLayer()
    marsMap.addLayer(graphicLayer)

    graphicLayerGlobal = graphicLayer
    graphicLayerList = []
    polylines1 = []
    polylines2 = []
    polylines3 = []

    // 绘制五个地图覆盖物
    drawFields(graphicLayer) // 场地
    drawCableway(graphicLayer) // 索道
    drawHighway(graphicLayer) // 公路线
    drawSpanTowers(graphicLayer) // 跨越杆塔
    drawNormalTowers(graphicLayer) // 正常杆塔
}

// 绘制场地（牵张场地）
function drawFields(graphicLayer) {
    const aThousandFieldsList = mapData.aThousandFieldsList || []
    if (aThousandFieldsList.length === 0) return

    aThousandFieldsList.forEach((item) => {
        if (item.cablewaTransPointVoList && item.cablewaTransPointVoList.length > 0) {
            // 根据sort字段排序，防止点位顺序不一致
            const sortedPoints = [...item.cablewaTransPointVoList].sort((a, b) => a.sort - b.sort)
            const points = sortedPoints.map((p) => [parseFloat(p.lng), parseFloat(p.lat)])

            if (points.length > 0) {
                const graphic = new mars3d.graphic.PolygonEntity({
                    positions: points,
                    style: {
                        color: '#00FFFF',
                        opacity: 0.5,
                        outline: true,
                        outlineWidth: 2,
                        outlineColor: '#00FFFF',
                        clampToGround: true,
                    },
                    attr: { remark: item.name || '场地' },
                })

                // 添加点击事件
                graphic.on(mars3d.EventType.click, function (event) {
                    const graphic = event.graphic
                    const infoContent = `
                        <div class="map-container-2 map-container">
                            <h4>名称：${item.name || '/'}</h4>
                            <div class="map-container-item">
                                <span>宽度</span>
                                <span>${item.cablewayWidth || '/'}</span>
                            </div>
                            <div class="map-container-item">
                                <span>长度</span>
                                <span>${item.cablewayLength || '/'}</span>
                            </div>
                        </div>`
                    graphic.bindPopup(infoContent)
                    graphic.openPopup()
                })

                graphicLayer.addGraphic(graphic)
            }
        }
    })
}

// 绘制索道
function drawCableway(graphicLayer) {
    const cablewaTransVos = mapData.cablewaTransVos || []
    if (cablewaTransVos.length === 0) return

    cablewaTransVos.forEach((pointData) => {
        if (pointData.cablewaTransPointVoList && pointData.cablewaTransPointVoList.length > 0) {
            // 绘制索道起点标点
            const billboard = new mars3d.graphic.BillboardEntity({
                position: [
                    parseFloat(pointData.cablewaTransPointVoList[0].lng),
                    parseFloat(pointData.cablewaTransPointVoList[0].lat),
                    1000,
                ],
                style: {
                    image: iconTypeList[12],
                    width: 30,
                    height: 30,
                    scale: 1,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    clampToGround: true,
                },
                attr: { remark: '索道运输' },
            })

            // 添加点击事件
            billboard.on(mars3d.EventType.click, function (event) {
                const graphic = event.graphic
                const infoContent = `
                    <div class="map-container">
                        <h4>索道运输</h4>
                        <div class="map-container-item-ropeway">
                            <span>索道位置</span>
                            <span>${pointData.towerName || '/'}</span>
                        </div>
                        <div class="map-container-item-ropeway">
                            <span>索道长度</span>
                            <span>${pointData.cablewayLength || '/'} KM</span>
                        </div>
                        <div class="map-container-item-ropeway">
                            <span>最大载重</span>
                            <span>${pointData.maxHeight || '/'} kg</span>
                        </div>
                        <div class="map-container-item-ropeway">
                            <span>安全距离</span>
                            <span>${pointData.safetyDistance || '/'} m</span>
                        </div>
                        <div class="map-container-item-ropeway">
                            <span>最大坡度</span>
                            <span>${pointData.maxSlope || '/'} °</span>
                        </div>
                        <div class="map-container-item-ropeway">
                            <span>索道宽度</span>
                            <span>${pointData.cablewayWidth || '/'} m</span>
                        </div>
                    </div>`
                graphicLayer.bindPopup(infoContent, {
                    position: graphic.position,
                })
            })

            graphicLayer.addGraphic(billboard)

            // 绘制索道线
            for (let j = 0; j < pointData.cablewaTransPointVoList.length - 1; j++) {
                const startPoint = pointData.cablewaTransPointVoList[j]
                const endPoint = pointData.cablewaTransPointVoList[j + 1]

                const positions = [
                    [parseFloat(startPoint.lng), parseFloat(startPoint.lat)],
                    [parseFloat(endPoint.lng), parseFloat(endPoint.lat)],
                ]

                const polyline = new mars3d.graphic.PolylineEntity({
                    positions: positions,
                    eventParent: false,
                    style: {
                        width: 2,
                        color: '#262fc9',
                        clampToGround: true,
                    },
                })

                graphicLayer.addGraphic(polyline)
            }
        }
    })
}

// 绘制公路线
function drawHighway(graphicLayer) {
    const highwayList = mapData.highwayList || []
    if (highwayList.length === 0) return

    highwayList.forEach((item) => {
        if (item.cablewaTransPointVoList && item.cablewaTransPointVoList.length > 0) {
            for (let j = 0; j < item.cablewaTransPointVoList.length - 1; j++) {
                const startPoint = item.cablewaTransPointVoList[j]
                const endPoint = item.cablewaTransPointVoList[j + 1]

                const positions = [
                    [parseFloat(startPoint.lng), parseFloat(startPoint.lat)],
                    [parseFloat(endPoint.lng), parseFloat(endPoint.lat)],
                ]

                const polyline = new mars3d.graphic.PolylineEntity({
                    positions: positions,
                    style: {
                        width: 2,
                        color: '#FFFF00',
                        clampToGround: true,
                    },
                })

                // 添加点击事件
                polyline.on(mars3d.EventType.click, function (event) {
                    const graphic = event.graphic
                    const infoContent = `
                        <div class="map-container-2 map-container">
                            <h4>公路所在杆塔：${item.towerName || '/'}</h4>
                            <div class="map-container-item">
                                <span>宽度</span>
                                <span>${item.cablewayWidth || '/'}</span>
                            </div>
                            <div class="map-container-item">
                                <span>长度</span>
                                <span>${item.cablewayLength || '/'}</span>
                            </div>
                        </div>`
                    graphic.bindPopup(infoContent)
                    graphic.openPopup()
                })

                graphicLayer.addGraphic(polyline)
            }
        }
    })
}

// 绘制跨越杆塔
function drawSpanTowers(graphicLayer) {
    const spanInfoVos = mapData.spanInfoVos || []
    let spanInfoVosNew = []
    let spanInfoVosLineNew = []
    spanInfoVos.forEach((item) => {
        let lineList = []
        if (item.lonAndLat && item.lonAndLat.indexOf(',') > -1) {
            const lonAndLatList = item.lonAndLat.split(',')

            lonAndLatList.forEach((lonAndLat, index) => {
                const lonAndLatItem = lonAndLat.split('@')
                spanInfoVosNew.push({
                    baiduLon: lonAndLatItem[0],
                    baiduLat: lonAndLatItem[1],
                    ...item,
                })
                lineList.push({
                    baiduLon: lonAndLatItem[0],
                    baiduLat: lonAndLatItem[1],
                    ...item,
                })
            })

            spanInfoVosLineNew.push({ lineList })
        }
    })

    spanInfoVosNew.forEach((pointData, index) => {
        const billboard = new mars3d.graphic.BillboardEntity({
            position: [pointData.baiduLon, pointData.baiduLat, 1000],
            style: {
                image: iconTypeList[21],
                width: 30,
                height: 30,
                scale: 1,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                clampToGround: true,
            },
        })

        // 添加点击事件
        billboard.on(mars3d.EventType.click, function (event) {
            const graphic = event.graphic
            const infoContent = `
                    <div class="map-container-cross">
                      
                        <div  class="map-container-2 map-container">
                            <h4>
                                交叉跨越信息 ( ${pointData.spanTowerName} )
                            </h4>
                            <div class="map-container-item-ropeway">
                                <span>上层线路</span>
                                <span>${pointData.upperLine}</span>
                            </div>
                            <div class="map-container-item-ropeway">
                                <span>下层线路</span>
                                <span>${pointData.lowerLine}</span>
                            </div>
                            <div class="map-container-item-ropeway">
                                <span>交叉角度</span>
                                <span>${pointData.intersectionAngle} °</span>
                            </div>
                            <div class="map-container-item-ropeway">
                                <span>垂直距离</span>
                                <span>${pointData.verticalDistance} m</span>
                            </div>
                            <div class="map-container-item-ropeway">
                                <span>安全裕度</span>
                                <span>${pointData.safetyMargin} m</span>
                            </div>
                        </div>
                    </div>`
            // 创建自定义信息窗体
            graphicLayer.bindPopup(infoContent, {
                position: graphic.position,
            })
        })

        graphicLayer.addGraphic(billboard)
    })

    for (let i = 0; i < spanInfoVosLineNew.length; i++) {
        for (let j = 0; j < spanInfoVosLineNew[i].lineList.length - 1; j++) {
            const startPoint = spanInfoVosLineNew[i].lineList[j]
            const endPoint = spanInfoVosLineNew[i].lineList[j + 1]

            // 创建线段点数组
            const positions = [
                [startPoint.baiduLon, startPoint.baiduLat],
                [endPoint.baiduLon, endPoint.baiduLat],
            ]

            // const positions2 = positions.map((item) => {
            //     return mars3d.PointTrans.bd2wgs(item);
            // });

            const polyline = new mars3d.graphic.PolylineEntity({
                positions: positions,
                eventParent: false,
                style: {
                    width: 2, // 线宽（像素）
                    color: '#800080', // 线颜色
                    clampToGround: true, // 是否贴地（山区建议设为true）
                },
            })
            graphicLayer.addGraphic(polyline)
        }
    }
}

// 绘制正常杆塔
async function drawNormalTowers(graphicLayer) {
    const towerInfoVos = mapData.towerInfoVos || []
    const towerList3D = mapData.towerList3D || []
    if (towerInfoVos.length === 0) return

    const newTowerList2D = towerInfoVos.filter(
        (item) =>
            item.towerProgress != 6 &&
            item.towerProgress != 7 &&
            item.towerProgress != 8 &&
            item.towerProgress != 9 &&
            item.towerProgress != 10,
    )
    const newTowerList3D = towerInfoVos.filter(
        (item) =>
            item.towerProgress == 6 ||
            item.towerProgress == 7 ||
            item.towerProgress == 8 ||
            item.towerProgress == 9 ||
            item.towerProgress == 10,
    )

    newTowerList2D.forEach((pointData, index) => {
        console.log(pointData, 'pointData----123')
        const isEven = index % 2 === 0

        // 标签位置设置
        const labelVerticalOrigin = isEven
            ? Cesium.VerticalOrigin.BOTTOM
            : Cesium.VerticalOrigin.TOP

        const iconUrl = iconTypeList[parseInt(pointData.towerProgress)]

        const billboard = new mars3d.graphic.BillboardEntity({
            position: [pointData.baiduLon, pointData.baiduLat],
            style: {
                image: iconUrl,
                width: 30,
                height: 30,
                scale: 1,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                clampToGround: true,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 必须设置
                disableDepthTestDistance: Number.POSITIVE_INFINITY, // 防止被地形遮挡
            },
            // 其他属性
            attr: {
                id: index,
                name: pointData.towerName,
            },
        })

        const label2 = new mars3d.graphic.DivGraphic({
            position: [pointData.baiduLon, pointData.baiduLat],
            style: {
                html: `<div class="tower-label">${pointData.towerName}</div>`,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: labelVerticalOrigin,
                scaleByDistance: true,
                offsetY: isEven ? -40 : 10,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
            },
        })

        graphicLayer.addGraphic(billboard)
        graphicLayer.addGraphic(label2)

        // 添加点击事件
        billboard.on(mars3d.EventType.click, function (event) {
            const graphic = event.graphic
            let infoContent = `
                <div class="map-container">
                    <h4>${pointData.towerName}</h4>
                    <div class="map-container-item">
                        <span>协调完成</span>
                        <span>${pointData.time1 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>基础开挖</span>
                        <span>${pointData.time2 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>基础开挖完成</span>
                        <span>${pointData.time3 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>基础浇筑</span>
                        <span>${pointData.time4 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>基础浇筑完成</span>
                        <span>${pointData.time5 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>铁塔组立</span>
                        <span>${pointData.time6 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>铁塔组立完成</span>
                        <span>${pointData.time7 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>架线施工</span>
                        <span>${pointData.time8 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>架线施工完成</span>
                        <span>${pointData.time9 || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>附件安装完成</span>
                        <span>${pointData.time10 || '/'}</span>
                    </div>
                </div>`
            // 创建自定义信息窗体
            graphicLayer.bindPopup(infoContent, {
                position: graphic.position,
            })
        })
    })

    const newTowerList3DData = await Promise.all(
        newTowerList3D.map(async (item, index) => {
            const altitude = await getElevationByLngLat(item.baiduLon, item.baiduLat)

            const heightInit = item.towerType == 1 ? 68.5 : 80
            return {
                alt: altitude - heightInit, // 海拔高度 根据经纬度计算
                heading: 23.0667, // 方向
                headingStr: '23°4′', // 方向字符串
                height: heightInit, // 杆塔高度
                lat: item.baiduLat, // 纬度
                lon: item.baiduLon, // 经度
                ...item,
                type: item.towerType,
            }
        }),
    )

    // console.log(newTowerList3DData, 'newTowerList3DData----123')

    showData(newTowerList3DData, graphicLayer)
}

async function getElevationByLngLat(lng, lat) {
    // 方案1: 优先使用高德地图API（需要后端代理或签名，这里先尝试，失败后降级）
    try {
        const amapKey = '707f79ea9a9d6ec1b55fc932465352f8'
        // 注意：高德地图的WebService API需要签名，不能直接在前端调用
        // 如果您的后端有代理接口，请使用后端接口
        // 这里先尝试，如果失败会自动降级到其他方案
        const response = await fetch(
            `https://restapi.amap.com/v3/elevation/geo?locations=${lng},${lat}&key=${amapKey}`,
            { method: 'GET' },
        )

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }

        const data = await response.json()

        // 检查高德API返回结果
        if (data.status === '1' && data.elevation && data.elevation.length > 0) {
            const elevation = parseFloat(data.elevation[0])
            if (!isNaN(elevation) && elevation > 0) {
                console.log(`高德地图获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
                return elevation
            }
        }

        // 如果返回了错误信息，记录日志
        if (data.status === '0') {
            console.warn(`高德地图API返回错误: ${data.info || '未知错误'}, 降级使用其他方案`)
        }
    } catch (error) {
        console.warn('高德地图API调用失败，降级使用其他方案:', error.message)
    }

    // 方案2: 优先使用 mars3d 地形服务（无CORS问题，最可靠）
    let elevation = await getElevationByTerrain(lng, lat)
    if (elevation > 0) {
        return elevation
    }

    // 方案3: 尝试使用 mars3d 工具方法
    elevation = await getElevationByMars3dUtil(lng, lat)
    if (elevation > 0) {
        return elevation
    }

    // 方案4: 尝试使用 pickPosition
    elevation = await getElevationByPickPosition(lng, lat)
    if (elevation > 0) {
        return elevation
    }

    // 方案5: 尝试使用外部API（可能有CORS问题）
    elevation = await getElevationByAPI(lng, lat)
    if (elevation > 0) {
        return elevation
    }

    // 所有方法都失败，返回0
    console.warn(`所有方法都无法获取坐标(${lng}, ${lat})的海拔高度，返回默认值0`)
    return 0
}

async function getElevationByAPI(lng, lat) {
    // 方案1: 优先使用 mars3d 地形服务（无CORS问题，最可靠）
    if (map && map.scene && Cesium) {
        try {
            const cartographic = Cesium.Cartographic.fromDegrees(lng, lat)
            const terrainProvider = map.scene.terrainProvider

            if (terrainProvider) {
                // 等待地形提供者准备就绪
                if (terrainProvider.readyPromise) {
                    await terrainProvider.readyPromise
                }

                const positions = [cartographic]
                const updatedPositions = await Cesium.sampleTerrainMostDetailed(
                    terrainProvider,
                    positions,
                )

                if (
                    updatedPositions &&
                    updatedPositions.length > 0 &&
                    updatedPositions[0].height !== undefined &&
                    updatedPositions[0].height !== null &&
                    !isNaN(updatedPositions[0].height)
                ) {
                    const elevation = updatedPositions[0].height
                    console.log(`mars3d地形服务获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
                    return elevation
                }
            }
        } catch (error) {
            console.warn('mars3d地形服务获取海拔失败，尝试其他方案:', error)
        }
    }

    // 方案2: 使用 JSONP 方式调用 OpenElevation（绕过CORS）
    try {
        const elevation = await getElevationByJSONP(lng, lat)
        if (elevation > 0) {
            return elevation
        }
    } catch (error) {
        console.warn('JSONP方式获取海拔失败:', error)
    }

    // 方案3: 尝试备用API
    return await getElevationByBackupAPI(lng, lat)
}

// 使用 JSONP 方式调用 OpenElevation API（绕过CORS限制）
// 注意：OpenElevation API 可能不支持 JSONP，此方法作为备选
function getElevationByJSONP(lng, lat) {
    return new Promise((resolve, reject) => {
        const callbackName = `elevationCallback_${Date.now()}_${Math.random()
            .toString(36)
            .substr(2, 9)}`

        // 创建脚本标签
        const script = document.createElement('script')
        let timeout = null

        // 清理函数
        const cleanup = () => {
            try {
                if (window[callbackName]) {
                    delete window[callbackName]
                }
                if (script.parentNode) {
                    document.head.removeChild(script)
                }
                if (timeout) {
                    clearTimeout(timeout)
                }
            } catch (e) {
                // 忽略清理错误
            }
        }

        // 创建回调函数
        window[callbackName] = function (data) {
            cleanup()
            try {
                if (data && data.results && data.results.length > 0) {
                    const elevation = data.results[0].elevation
                    if (elevation !== undefined && elevation !== null && !isNaN(elevation)) {
                        console.log(`JSONP方式获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
                        resolve(elevation)
                        return
                    }
                }
                resolve(0)
            } catch (error) {
                reject(error)
            }
        }

        script.src = `https://api.open-elevation.com/api/v1/lookup?locations=${lat},${lng}&callback=${callbackName}`
        script.onerror = () => {
            cleanup()
            reject(new Error('JSONP请求失败'))
        }

        // 设置超时
        timeout = setTimeout(() => {
            cleanup()
            reject(new Error('JSONP请求超时'))
        }, 10000) // 10秒超时

        document.head.appendChild(script)
    })
}

async function getElevationByMars3dUtil(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        // 使用文件顶部导入的 mars3d 和 Cesium
        if (!mars3d || !mars3d.Cesium) {
            console.warn('mars3d 或 Cesium 未加载')
            return 0
        }

        // 尝试使用 mars3d 的工具方法
        if (mars3d.PointUtil && mars3d.PointUtil.getTerrainHeight) {
            const height = await mars3d.PointUtil.getTerrainHeight(map.scene, lng, lat)
            if (height !== undefined && height !== null && !isNaN(height)) {
                console.log(`mars3d工具获取海拔成功: ${height}米 (${lng}, ${lat})`)
                return height
            }
        }

        return 0
    } catch (error) {
        console.warn('mars3d工具获取海拔失败:', error)
        return 0
    }
}

async function getElevationByTerrain(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        // 使用文件顶部导入的 Cesium
        if (!Cesium) {
            console.warn('Cesium 未加载')
            return 0
        }

        const cartographic = Cesium.Cartographic.fromDegrees(lng, lat)
        const terrainProvider = map.scene.terrainProvider

        if (!terrainProvider) {
            console.warn('地形提供者未加载')
            return 0
        }

        // 等待地形提供者准备就绪
        if (terrainProvider.readyPromise) {
            await terrainProvider.readyPromise
        }

        // 使用 sampleTerrainMostDetailed
        const positions = [cartographic]
        const updatedPositions = await Cesium.sampleTerrainMostDetailed(terrainProvider, positions)

        if (
            updatedPositions &&
            updatedPositions.length > 0 &&
            updatedPositions[0].height !== undefined &&
            updatedPositions[0].height !== null &&
            !isNaN(updatedPositions[0].height)
        ) {
            const elevation = updatedPositions[0].height
            console.log(`地形采样获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
            return elevation
        }

        return 0
    } catch (error) {
        console.warn('地形采样获取海拔失败:', error)
        return 0
    }
}

async function getElevationByPickPosition(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        // 使用文件顶部导入的 Cesium
        if (!Cesium) {
            console.warn('Cesium 未加载')
            return 0
        }

        const cartesian = Cesium.Cartesian3.fromDegrees(lng, lat, 10000)
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian)

        // 使用 pickPosition 获取地形高度
        const pickedPosition = map.scene.pickPosition(cartesian)
        if (pickedPosition) {
            const pickedCartographic = Cesium.Cartographic.fromCartesian(pickedPosition)
            const elevation = pickedCartographic.height
            if (elevation !== undefined && elevation !== null && !isNaN(elevation)) {
                console.log(`pickPosition获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
                return elevation
            }
        }

        return 0
    } catch (error) {
        console.warn('pickPosition获取海拔失败:', error)
        return 0
    }
}

async function getElevationByBackupAPI(lng, lat) {
    // 如果 mars3d 地形服务可用，优先使用（最可靠，无CORS问题）
    if (map && map.scene && Cesium) {
        try {
            const terrainProvider = map.scene.terrainProvider
            if (terrainProvider) {
                const cartographic = Cesium.Cartographic.fromDegrees(lng, lat)

                if (terrainProvider.readyPromise) {
                    await terrainProvider.readyPromise
                }

                const positions = [cartographic]
                const updatedPositions = await Cesium.sampleTerrainMostDetailed(
                    terrainProvider,
                    positions,
                )

                if (
                    updatedPositions &&
                    updatedPositions.length > 0 &&
                    updatedPositions[0].height !== undefined &&
                    updatedPositions[0].height !== null &&
                    !isNaN(updatedPositions[0].height)
                ) {
                    return updatedPositions[0].height
                }
            }
        } catch (error) {
            // 忽略错误，继续尝试其他方案
        }
    }

    // 所有备用方案都不可用时，返回0
    return 0
}

function showData(arrdata, graphicLayer) {
    // 预处理坐标及角度
    for (let i = 0, len = arrdata.length; i < len; i++) {
        const item = arrdata[i]
        const position = Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.alt)
        item.position = position
        item.index = i + 1

        // 模型比例，根据塔高换算
        item.height = 68.5
        item.scale = item.height / 69

        // 计算电线塔转角角度
        if (i !== 0) {
            const priorPt = arrdata[i - 1].position
            item.lineHeading = mars3d.MeasureUtil.getAngle(priorPt, position) // 线的角度
        }
    }

    // 计算各坐标及路线坐标，并渲染矢量对象
    for (let i = 0, len = arrdata.length; i < len; i++) {
        const item = arrdata[i]
        const position = item.position

        // 计算电线塔转角角度
        let degree = -2.2333
        // if (degree) {
        //   item.degree = item.lineHeading - item.heading
        // } else {
        if (i === 0) {
            degree = arrdata[i + 1].lineHeading
        } else if (i === len - 1) {
            degree = arrdata[i].lineHeading
        } else {
            const nextTower = arrdata[i + 1]
            let stepAngle = (nextTower.lineHeading - item.lineHeading) / 2
            if (stepAngle > 90) {
                stepAngle = 180 - stepAngle
            } else if (stepAngle < -90) {
                stepAngle = stepAngle + 180
            }
            degree = item.lineHeading + stepAngle
        }
        item.degree = degree
        // }

        const hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(degree), 0, 0)

        // 3个悬垂串的位置
        const offsetLineZ = item.height - 3.9
        let newPoint1 = mars3d.PointUtil.getPositionByHprAndOffset(
            position,
            new Cesium.Cartesian3(0, 10.6, offsetLineZ),
            hpr,
        ) // 左边挂线
        let newPoint2 = mars3d.PointUtil.getPositionByHprAndOffset(
            position,
            new Cesium.Cartesian3(0, 0, offsetLineZ),
            hpr,
        ) // 中间线
        let newPoint3 = mars3d.PointUtil.getPositionByHprAndOffset(
            position,
            new Cesium.Cartesian3(0, -10.6, offsetLineZ),
            hpr,
        ) // 右边挂线

        // polylinesTB.push(newPoint2); // 图标显示的点

        drawWireTowerModel(graphicLayer, position, degree, item.scale, item)
        drawWireTowerJYZModel(newPoint1, degree, graphicLayer) // 3个悬垂串模型
        // // drawWireTowerJYZModel(newPoint2, degree, graphicLayer);
        drawWireTowerJYZModel(newPoint3, degree, graphicLayer)

        // 计算路线点
        const jyzHeight = -5
        newPoint1 = mars3d.PointUtil.addPositionsHeight(newPoint1, jyzHeight)
        // newPoint2 = mars3d.PointUtil.addPositionsHeight(newPoint2, jyzHeight);
        newPoint3 = mars3d.PointUtil.addPositionsHeight(newPoint3, jyzHeight)

        if (i === 0) {
            polylines1.push(newPoint1)
            polylines2.push(newPoint2)
            polylines3.push(newPoint3)
        } else {
            const angularityFactor = -5000
            const num = 50
            let positions = mars3d.PolyUtil.getLinkedPointList(
                polylines1[polylines1.length - 1],
                newPoint1,
                angularityFactor,
                num,
            ) // 计算曲线点
            polylines1 = polylines1.concat(positions)

            positions = mars3d.PolyUtil.getLinkedPointList(
                polylines2[polylines2.length - 1],
                newPoint2,
                angularityFactor,
                num,
            ) // 计算曲线点
            polylines2 = polylines2.concat(positions)

            positions = mars3d.PolyUtil.getLinkedPointList(
                polylines3[polylines3.length - 1],
                newPoint3,
                angularityFactor,
                num,
            ) // 计算曲线点
            polylines3 = polylines3.concat(positions)
        }
    }

    // 绘制路线
    drawGuideLine(polylines1, '#0000ff', graphicLayer)
    drawGuideLine(polylines3, '#ff0000', graphicLayer)

    // polylines1 = mars3d.LngLatArray.toArray(polylines1)
    // polylines3 = mars3d.LngLatArray.toArray(polylines3)
}

// 绘制电线塔 3D 模型（使用本地 glb 模型，逻辑与 demo.js 一致）
function drawWireTowerModel(graphicLayer, position, degree, scale, item) {
    const graphic = new mars3d.graphic.ModelPrimitive({
        position,
        style: {
            url: towerModel1,
            heading: degree,
            scale: scale,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 4000.0),
        },
    })

    // 添加点击事件
    graphic.on(mars3d.EventType.click, function (event) {
        // console.log("点击了标点", event.graphic.attr);
        const graphic = event.graphic
        let infoContent = `
        <div class="map-container">
            <h4>${item.towerName}</h4>
            <div class="map-container-item">
                <span>协调完成</span>
                <span>${item.time1 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>基础开挖</span>
                <span>${item.time2 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>基础开挖完成</span>
                <span>${item.time3 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>基础浇筑</span>
                <span>${item.time4 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>基础浇筑完成</span>
                <span>${item.time5 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>铁塔组立</span>
                <span>${item.time6 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>铁塔组立完成</span>
                <span>${item.time7 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>架线施工</span>
                <span>${item.time8 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>架线施工完成</span>
                <span>${item.time9 || '/'}</span>
            </div>
            <div class="map-container-item">
                <span>附件安装完成</span>
                <span>${item.time10 || '/'}</span>
            </div>
        </div>`
        // 创建自定义信息窗体
        graphicLayer.bindPopup(infoContent, {
            position: graphic.position,
        })
    })
    graphicLayer.addGraphic(graphic)
}

// 绘制悬垂串模型（沿用 demo.js 的远程模型）
function drawWireTowerJYZModel(position, degree, graphicLayer) {
    const graphic2 = new mars3d.graphic.ModelPrimitive({
        position,
        style: {
            url: 'https://data.mars3d.cn/gltf/mars/tower/tower-jyz.glb',
            heading: degree,
            pitch: 90,
            scale: 1,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 4000.0),
        },
    })
    graphicLayer.addGraphic(graphic2)
    graphicLayerList.push(graphic2)
}

// 绘制导线（与 demo.js 保持一致）
function drawGuideLine(positions, color, graphicLayer) {
    const graphic = new mars3d.graphic.PolylinePrimitive({
        positions,
        style: {
            width: 4,
            color,
        },
    })
    graphicLayer.addGraphic(graphic)
    graphicLayerList.push(graphic)
}
</script>

<style>
.tower-label {
    color: #fff;
    padding: 1px;
    background: rgba(0, 0, 0, 0.7);
    font-size: 10px;
}
</style>
