let map = null // 地图实例
let graphicLayer = null // 图形图层
let graphicLayerList = [] // 图形图层列表
let treeData = [] // 组织机构树数据
let nodeId = '' // 当前选中的节点ID
let cablewayList = [] // 索道列表
let towerList = [] // 塔列表
let crossingList = [] // 跨越列表
let crossingListNew = [] // 跨越列表
let crossingLineListNew = [] // 跨越线列表
let highwayList = [] // 公路列表
let aThousandFieldsList = [] // 牵张场地
let intLng = 116.254 // 初始经度
let intLat = 39.965 // 初始纬度
let isMap = true // 是否是地图模式
let projectOverview = '' // 工程概况
let projectTitle = '' // 项目名称
let centerTitle = '' // 中间标题
let polylines1 = []
let polylines2 = []
let polylines3 = []

// 转换函数
function dmsToDecimal(dmsString) {
    // 替换所有可能的符号变体
    const cleaned = dmsString
        .replace(/[°′″]/g, ' ') // 替换° ′ ″为空格
        .replace(/'/g, ' ') // 替换单引号
        .replace(/"/g, ' ') // 替换双引号
        .replace(/\s+/g, ' ') // 合并多个空格
        .trim()

    const parts = cleaned.split(' ')

    const degrees = parseFloat(parts[0])
    const minutes = parseFloat(parts[1] || 0)
    const seconds = parseFloat(parts[2] || 0)

    return degrees + minutes / 60 + seconds / 3600
}

/**
 * 根据经纬度获取海拔高度
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米），如果获取失败则返回0
 */
async function getAltitude(lng, lat) {
    try {
        // 确保 map 实例已初始化
        if (!map || !map.scene) {
            console.warn('地图未初始化，无法获取海拔高度')
            return 0
        }

        const Cesium = window.mars3d.Cesium

        // 将经纬度转换为 Cartographic 对象（弧度）
        const cartographic = Cesium.Cartographic.fromDegrees(lng, lat)

        // 方法1: 使用 sampleTerrainMostDetailed 获取精确的地形高度（推荐）
        const terrainProvider = map.scene.terrainProvider
        if (terrainProvider) {
            try {
                // 检查地形提供者是否支持采样
                if (terrainProvider.availability || terrainProvider.ready) {
                    const positions = [cartographic]
                    const updatedPositions = await Cesium.sampleTerrainMostDetailed(
                        terrainProvider,
                        positions,
                    )
                    if (
                        updatedPositions &&
                        updatedPositions.length > 0 &&
                        updatedPositions[0].height !== undefined &&
                        updatedPositions[0].height !== null
                    ) {
                        return updatedPositions[0].height
                    }
                }
            } catch (error) {
                console.warn('使用 sampleTerrainMostDetailed 获取海拔失败:', error)
            }
        }

        // 方法2: 使用 sampleTerrain 作为备选方案（精度较低但更兼容）
        if (terrainProvider && Cesium.sampleTerrain) {
            try {
                const level = 11 // 地形级别，可以根据需要调整
                const positions = [cartographic]
                const updatedPositions = await Cesium.sampleTerrain(
                    terrainProvider,
                    level,
                    positions,
                )
                if (
                    updatedPositions &&
                    updatedPositions.length > 0 &&
                    updatedPositions[0].height !== undefined &&
                    updatedPositions[0].height !== null
                ) {
                    return updatedPositions[0].height
                }
            } catch (error) {
                console.warn('使用 sampleTerrain 获取海拔失败:', error)
            }
        }

        // 方法3: 如果以上方法都失败，返回0作为默认值
        console.warn(`无法获取坐标(${lng}, ${lat})的海拔高度，返回默认值0`)
        return 0
    } catch (error) {
        console.error('获取海拔高度时发生错误:', error)
        return 0
    }
}

/**
 * 方案1: 使用第三方 OpenElevation API 获取海拔（推荐，不依赖地形服务）
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByAPI(lng, lat) {
    try {
        // 使用 OpenElevation API（免费，无需API密钥）
        const response = await fetch(
            `https://api.open-elevation.com/api/v1/lookup?locations=${lat},${lng}`,
        )
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
        const data = await response.json()
        if (data.results && data.results.length > 0) {
            const elevation = data.results[0].elevation
            console.log(`API获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
            return elevation
        }
        return 0
    } catch (error) {
        console.warn('OpenElevation API 获取海拔失败:', error)
        // 尝试备用API
        return await getElevationByBackupAPI(lng, lat)
    }
}

/**
 * 备用API方案: 使用其他高程API服务
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByBackupAPI(lng, lat) {
    try {
        // 备用方案1: 使用 elevation-api.io（需要注册但免费额度较大）
        // const response = await fetch(
        //     `https://api.elevation-api.io/api/v1/lookup?locations=${lat},${lng}`
        // );

        // 备用方案2: 使用 Google Elevation API（需要API密钥）
        // const response = await fetch(
        //     `https://maps.googleapis.com/maps/api/elevation/json?locations=${lat},${lng}&key=YOUR_API_KEY`
        // );

        // 备用方案3: 使用 MapBox Elevation API（需要API密钥）
        // const response = await fetch(
        //     `https://api.mapbox.com/v4/mapbox.terrain-rgb/${lng},${lat}.json?access_token=YOUR_ACCESS_TOKEN`
        // );

        // 如果以上API都不可用，返回0
        return 0
    } catch (error) {
        console.warn('备用API获取海拔失败:', error)
        return 0
    }
}

/**
 * 方案2: 使用 mars3d/Cesium 的地形采样（需要地形服务已加载）
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByTerrain(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        const Cesium = window.mars3d.Cesium
        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
        ) {
            const elevation = updatedPositions[0].height
            console.log(`地形采样获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
            return elevation
        }

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

/**
 * 方案3: 使用 Cesium 的 pickPosition 方法（需要场景已渲染）
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByPickPosition(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        const Cesium = window.mars3d.Cesium
        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
            console.log(`pickPosition获取海拔成功: ${elevation}米 (${lng}, ${lat})`)
            return elevation
        }

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

/**
 * 方案4: 使用 mars3d 的工具方法（如果可用）
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByMars3dUtil(lng, lat) {
    try {
        if (!map || !map.scene) {
            console.warn('地图未初始化')
            return 0
        }

        const mars3d = window.mars3d
        const Cesium = window.mars3d.Cesium

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

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

/**
 * 综合方案: 按优先级尝试多种方法获取海拔
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<number>} 返回海拔高度（米）
 */
async function getElevationByLngLat(lng, lat) {
    // 方案1: 优先使用第三方 API（最可靠，不依赖地形服务）
    let elevation = await getElevationByAPI(lng, lat)
    if (elevation > 0) {
        return elevation
    }

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

    // 方案3: 尝试使用地形采样
    elevation = await getElevationByTerrain(lng, lat)
    if (elevation > 0) {
        return elevation
    }

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

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

const mapConfig = {
    scene: {
        center: {
            lat: 31.686288,
            lng: 117.229619,
            // alt: 11333.9,
            // heading: 359.2,
            // pitch: -39.5,
            alt: 12000, // 高度≈缩放级别
            heading: 30, // 旋转30度
            pitch: -45, // 俯视角45度
        },

        highDynamicRange: false, // 关闭HDR（可减少模糊）

        scene3DOnly: false,
        shadows: false,
        removeDblClick: true,
        sceneMode: 3,
        showSun: true,
        showMoon: true,
        showSkyBox: true,
        showSkyAtmosphere: true,
        fog: true,
        fxaa: false,
        requestRenderMode: false,
        globe: {
            depthTestAgainstTerrain: false,
            baseColor: '#546a53',
            showGroundAtmosphere: true,
            enableLighting: false,
        },
        cameraController: {
            zoomFactor: 3.0,
            minimumZoomDistance: 1,
            maximumZoomDistance: 50000000,
            enableRotate: true,
            enableTranslate: true,
            enableTilt: true,
            enableZoom: true,
            enableCollisionDetection: true,
            minimumCollisionTerrainHeight: 15000,
        },
    },
    control: {
        homeButton: true,
        baseLayerPicker: true,
        sceneModePicker: true,
        vrButton: false,
        fullscreenButton: true,
        navigationHelpButton: true,
        animation: false,
        timeline: false,
        infoBox: false,
        geocoder: false,
        selectionIndicator: false,
        contextmenu: { hasDefault: false },
        mouseDownView: true,
        zoom: { insertIndex: 1 },
        compass: { bottom: 'toolbar', left: '5px' },
        distanceLegend: { left: '10px', bottom: '2px' },
        locationBar: {
            fps: true,
            crs: 'CGCS2000_GK_Zone_3',
            crsDecimal: 0,
            template:
                "<div>经度:{lng}</div> <div>纬度:{lat}</div> <div class='hide1000'>横{crsx}  纵{crsy}</div> <div>海拔：{alt}米</div> <div class='hide700'>层级：{level}</div><div>方向：{heading}°</div> <div>俯仰角：{pitch}°</div><div class='hide700'>视高：{cameraHeight}米</div>",
        },
    },
    templateValues: {
        dataServer: '//data.mars3d.cn',
        gltfServerUrl: '//data.mars3d.cn/gltf',
    },
    terrain: {
        url: '//data.mars3d.cn/terrain',
        show: true,
    },
    basemaps: [
        { id: 10, name: '地图底图', type: 'group' },
        {
            id: 2021,
            pid: 10,
            name: '天地图影像',
            icon: '../../img/mars-map-img/tdt_img.png',
            type: 'group',
            layers: [
                { name: '底图', type: 'tdt', layer: 'img_d' },
                { name: '注记', type: 'tdt', layer: 'img_z' },
            ],
            show: true,
        },
        {
            pid: 10,
            name: '天地图电子',
            icon: '../../img/mars-map-img/tdt_vec.png',
            type: 'group',
            layers: [
                { name: '底图', type: 'tdt', layer: 'vec_d' },
                { name: '注记', type: 'tdt', layer: 'vec_z' },
            ],
        },
        {
            pid: 10,
            name: '高德影像',
            type: 'group',
            icon: '../../img/mars-map-img/gaode_img.png',
            layers: [
                { name: '底图', type: 'gaode', layer: 'img_d' },
                { name: '注记', type: 'gaode', layer: 'img_z' },
            ],
        },
        {
            pid: 10,
            name: '高德电子',
            type: 'gaode',
            icon: '../../img/mars-map-img/gaode_vec.png',
            layer: 'vec',
        },
        {
            pid: 10,
            name: '百度影像',
            type: 'group',
            icon: '../../img/mars-map-img/bd-img.png',
            layers: [
                { name: '底图', type: 'baidu', layer: 'img_d' },
                { name: '注记', type: 'baidu', layer: 'img_z' },
            ],
        },
        {
            pid: 10,
            name: '百度电子',
            icon: '../../img/mars-map-img/bd-vec.png',
            type: 'baidu',
            layer: 'vec',
        },
        {
            pid: 10,
            name: '腾讯影像',
            icon: '../../img/mars-map-img/tencent_img.png',
            type: 'group',
            layers: [
                { name: '底图', type: 'tencent', layer: 'img_d' },
                { name: '注记', type: 'tencent', layer: 'img_z' },
            ],
        },
        {
            pid: 10,
            name: '腾讯电子',
            icon: '../../img/mars-map-img/tencent_vec.png',
            type: 'tencent',
            layer: 'vec',
        },
        {
            pid: 10,
            name: 'ArcGIS影像',
            icon: '../../img/mars-map-img/esriWorldImagery.png',
            type: 'xyz',
            url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            enablePickFeatures: false,
        },
    ],
}

// 图例数据
const legendData = [
    {
        name: '协调完成',
        value: 0,
        // icon: "../../img/digitalSignage/icon_three.png",
        icon: '../../img/digitalSignage/icon_three_new.png',
    },
    {
        name: '基础开挖',
        value: 0,
        // icon: "../../img/digitalSignage/icon_two.png",
        icon: '../../img/digitalSignage/icon_two_new.png',
    },
    {
        name: '基础开挖完成',
        value: 0,
        // icon: "../../img/digitalSignage/icon_five.png",
        icon: '../../img/digitalSignage/icon_five_new.png',
    },
    {
        name: '基础浇筑',
        value: 0,
        // icon: "../../img/digitalSignage/icon_seven.png",
        icon: '../../img/digitalSignage/icon_seven_new.png',
    },
    {
        name: '基础浇筑完成',
        value: 0,
        // icon: "../../img/digitalSignage/icon_four.png",
        icon: '../../img/digitalSignage/icon_four_new.png',
    },
    {
        name: '铁塔组立',
        value: 0,
        // icon: "../../img/digitalSignage/icon_six.png",
        icon: '../../img/digitalSignage/zt_orange.png',
    },
    {
        name: '铁塔组立完成',
        value: 0,
        icon: '../../img/digitalSignage/zt_red.png',
    },
    {
        name: '架线施工',
        value: 0,
        icon: '../../img/digitalSignage/line_y.png',
    },
    // {
    //     name: "架线施工完成",
    //     value: 0,
    //     icon: "../../img/digitalSignage/zt_purple.png",
    // },
    {
        name: '架线施工完成',
        value: 0,
        icon: '../../img/digitalSignage/line_r.png',
    },
    {
        name: '附件安装完成',
        value: 0,
        icon: '../../img/digitalSignage/zt_green.png',
    },
    {
        name: '未  开  始',
        value: 0,
        icon: '../../img/digitalSignage/icon_one_new.png',
    },
    {
        name: '索道运输',
        value: 0,
        icon: '../../img/digitalSignage/sd.png',
    },
    // {
    //     name: "项  目  部",
    //     value: 0,
    //     icon: "../../img/digitalSignage/project.png",
    // },
]

// 地图配置项
const config = {
    polyline: {
        strokeWeight: 3, // 线条宽度
        strokeOpacity: 0.9, // 透明度
        strokeStyle: 'dashed', // solid(实线)或dashed(虚线)
        enableEditing: false, // 是否可编辑
        enableClicking: true, // 是否可点击
    },
}

// 获取位置信息
function getLocationInfo(id) {
    const params = {
        encryptedData: encryptCBC(JSON.stringify({ id })),
    }
    ajaxRequest(
        dataUrl + '/backstage/digitalSignage/getTowersInfo',
        'POST',
        params,
        true,
        function () {},
        function (result) {
            console.log(result, '获取位置信息---')
            const { data } = result

            crossingList = []
            crossingListNew = []
            crossingLineListNew = []
            cablewayList = []
            towerList = []

            if (data.cablewaTransVos.length > 0) {
                cablewayList = data.cablewaTransVos
            } else {
                cablewayList = []
            }
            if (data.towerInfoVos.length > 0) {
                towerList = data.towerInfoVos
            } else {
                towerList = []
            }
            if (data.spanInfoVos.length > 0) {
                crossingList = data.spanInfoVos
            } else {
                crossingList = []
                crossingListNew = []
                crossingLineListNew = []
            }

            if (data.highwayList.length > 0) {
                highwayList = data.highwayList
            } else {
                highwayList = []
            }

            if (data.aThousandFieldsList.length > 0) {
                aThousandFieldsList = data.aThousandFieldsList
            } else {
                aThousandFieldsList = []
            }

            // 处理一下交叉信息
            if (crossingList && crossingList.length > 0) {
                crossingList.forEach((item) => {
                    let lineList = []
                    if (item.lonAndLat && item.lonAndLat.indexOf(',') > -1) {
                        const lonAndLatList = item.lonAndLat.split(',')

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

                            lineList.push({
                                baiduLon: lonAndLatItem[0],
                                baiduLat: lonAndLatItem[1],
                                ...item,
                            })
                        })
                    }

                    crossingLineListNew.push({ lineList })
                })
            }
            initMap()
        },
        function (xhr) {
            error(xhr)
        },
    )
}

async function initMap() {
    const mars3d = window.mars3d // 静态资源引入时，对象都是挂载在window中
    const Cesium = window.mars3d.Cesium
    try {
        if (map) {
            // 移除所有自定义图层
            if (graphicLayer) {
                graphicLayerList.forEach((e) => {
                    graphicLayer.removeGraphic(e)
                })

                polylines1.forEach((e) => {
                    graphicLayer.removeGraphic(e)
                })
                polylines2.forEach((e) => {
                    graphicLayer.removeGraphic(e)
                })
                polylines3.forEach((e) => {
                    graphicLayer.removeGraphic(e)
                })

                polylines1 = []
                polylines2 = []
                polylines3 = []
            }
            const centerPoint = [intLng, intLat]

            // 方式1：直接飞向目标点
            map.flyToPoint(centerPoint, {
                radius: 5000, // 可视范围半径（米）
                duration: 2, // 飞行时间（秒）
                heading: 0, // 视角方向（0-360度）
                pitch: -45, // 俯仰角度（-90俯视，0平视，90仰视）
            })
            await addAllMapPoints(graphicLayer, mars3d, Cesium)
            await addMapLine(graphicLayer, mars3d, Cesium)
            await addMapAThousandFields(graphicLayer, mars3d, Cesium)
        } else {
            // 2. WebGL兼容性检查
            if (!mars3d.Util.webglreport()) {
                mars3d.Util.webglerror()
                return
            }

            // 3. 初始化新地图
            mapConfig.scene.center.lat = intLat || 31.686288
            mapConfig.scene.center.lng = intLng || 117.229619
            map = new mars3d.Map('map-box', mapConfig)

            // 4. 创建新的图形图层
            graphicLayer = new mars3d.layer.GraphicLayer()

            const centerPoint = [intLng, intLat]

            map.flyToPoint(centerPoint, {
                radius: 5000, // 可视范围半径（米）
                duration: 5, // 飞行时间（秒）
                heading: 0, // 视角方向（0-360度）
                pitch: -45, // 俯仰角度（-90俯视，0平视，90仰视）
            })

            map.addLayer(graphicLayer)

            // 5. 添加内容
            await addAllMapPoints(graphicLayer, mars3d, Cesium)
            await addMapLine(graphicLayer, mars3d, Cesium)
            await addMapAThousandFields(graphicLayer, mars3d, Cesium)
        }
    } catch (error) {
        // 失败时也清理残留
        if (map) {
            map.destroy()
            map = null
        }
    }
}

// 添加标点
async function addAllMapPoints(graphicLayer, mars3d, Cesium) {
    const iconTypeList = {
        // 1: "../../img/digitalSignage/icon_three.png",
        1: '../../img/digitalSignage/icon_three_new.png',
        // 2: "../../img/digitalSignage/icon_two.png",
        2: '../../img/digitalSignage/icon_two_new.png',
        // 3: "../../img/digitalSignage/icon_five.png",
        3: '../../img/digitalSignage/icon_five_new.png',
        // 4: "../../img/digitalSignage/icon_seven.png",
        // 4: "../../img/digitalSignage/icon_purple.png",
        4: '../../img/digitalSignage/icon_seven_new.png',
        // 5: "../../img/digitalSignage/icon_four.png",
        5: '../../img/digitalSignage/icon_four_new.png',
        // 6: "../../img/digitalSignage/icon_six.png",
        6: '../../img/digitalSignage/zt_orange.png',
        7: '../../img/digitalSignage/zt_red.png',
        8: '../../img/digitalSignage/zt_red.png', // 新增的工序
        9: '../../img/digitalSignage/zt_red.png',
        10: '../../img/digitalSignage/zt_green.png',
        // 0: "../../img/digitalSignage/icon_one.png",
        0: '../../img/digitalSignage/icon_one_new.png',
        12: '../../img/digitalSignage/sd.png',
        20: '../../img/digitalSignage/project.png',
        // 21: "../../img/digitalSignage/zt_white.png",
        21: '../../img/digitalSignage/zt_gary.png',
    }

    // 绘制索道标点
    if (cablewayList && cablewayList.length > 0) {
        cablewayList.forEach((pointData, index) => {
            if (pointData.cablewaTransPointVoList && pointData.cablewaTransPointVoList.length > 0) {
                // const positionNew = mars3d.PointTrans.bd2wgs([
                //     pointData.cablewaTransPointVoList[0].lng,
                //     pointData.cablewaTransPointVoList[0].lat,
                // ]);
                const billboard = new mars3d.graphic.BillboardEntity({
                    position: [
                        pointData.cablewaTransPointVoList[0].lng,
                        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,
                    },
                })

                // 添加点击事件
                billboard.on(mars3d.EventType.click, function (event) {
                    // console.log("点击了标点", event.graphic.attr);
                    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)

                graphicLayerList.push(billboard)
            }
        })
    }

    // 绘制项目部
    if (intLng && intLat) {
        // const positionNew = mars3d.PointTrans.bd2wgs([intLng, intLat]);
        const billboard = new mars3d.graphic.BillboardEntity({
            position: [intLng, intLat, 1000],
            style: {
                image: iconTypeList[20],
                width: 30,
                height: 30,

                scale: 1,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                clampToGround: true,
            },
        })

        // 添加点击事件
        billboard.on(mars3d.EventType.click, function (event) {
            // console.log("点击了标点", event.graphic.attr);
            const graphic = event.graphic
            const infoContent = `
            <div class="map-container">
                    <h4>
                        ${projectTitle}
                    </h4>
            </div>`
            // 创建自定义信息窗体
            graphicLayer.bindPopup(infoContent, {
                position: graphic.position,
            })
        })

        graphicLayer.addGraphic(billboard)
        graphicLayerList.push(billboard)
    }

    // 绘制杆塔
    if (towerList && towerList.length > 0) {
        // showData(towerList, graphicLayer);

        const towerList1 = towerList

        // 异步获取所有点的海拔高度
        // const hList = [
        //     1719.018, 1692.086, 1603.903, 1613.565, 1766.005, 1731.971, 1740.48,
        //     1751.94, 1762.712, 1711.249,
        // ];

        const newTowerList2D = towerList1.filter(
            (item) =>
                item.towerProgress != 6 &&
                item.towerProgress != 7 &&
                item.towerProgress != 8 &&
                item.towerProgress != 9 &&
                item.towerProgress != 10,
        )
        const newTowerList3D = towerList1.filter(
            (item) =>
                item.towerProgress == 6 ||
                item.towerProgress == 7 ||
                item.towerProgress == 8 ||
                item.towerProgress == 9 ||
                item.towerProgress == 10,
        )
        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,
                }
            }),
        )

        // 过滤出需要绘制3D塔的数据

        showData(newTowerList3DData, graphicLayer)

        newTowerList2D.forEach((pointData, index) => {
            const isEven = index % 2 === 0
            // 标点垂直方向设置
            const billboardVerticalOrigin = Cesium.VerticalOrigin.BOTTOM // 标点固定底部对齐

            // 标签位置设置
            const labelVerticalOrigin = isEven
                ? Cesium.VerticalOrigin.BOTTOM
                : Cesium.VerticalOrigin.TOP
            const pixelOffsetY = isEven ? 40 : -70 // 调整偏移量（根据标点大小适当调整）

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

            // const wgsPoint = mars3d.PointTrans.bd2wgs([
            //     pointData.baiduLon,
            //     pointData.baiduLat,
            // ]);

            // const wgsPoint = [
            //     dmsToDecimal(pointData.baiduLon),
            //     dmsToDecimal(pointData.baiduLat),
            // ];

            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) {
                // console.log("点击了标点", event.graphic.attr);
                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,
                })
            })

            graphicLayerList.push(billboard)
            graphicLayerList.push(label2)
        })
    }

    // 绘制交叉跨越
    if (crossingListNew.length > 0) {
        crossingListNew.forEach((pointData, index) => {
            // const positionNew = mars3d.PointTrans.bd2wgs([
            //     pointData.baiduLon,
            //     pointData.baiduLat,
            // ]);
            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) {
                // console.log("点击了标点", event.graphic.attr);

                console.log(event, 'pointData点击了----')

                //     <div class="map-container-1 map-container">
                //     <h4>
                //         ${pointData.towerInfoVo.towerName}
                //     </h4>
                //      <div class="map-container-item">
                //         <span>协调完成</span>
                //         <span>${
                //             pointData.towerInfoVo.time1 || "/"
                //         }</span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>基础开挖</span>
                //         <span>
                //         ${pointData.towerInfoVo.time2 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>基础开挖完成</span>
                //         <span>
                //         ${pointData.towerInfoVo.time3 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>基础浇筑</span>
                //         <span>
                //         ${pointData.towerInfoVo.time4 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>基础浇筑完成</span>
                //         <span>
                //         ${pointData.towerInfoVo.time5 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>铁塔组立</span>
                //         <span>
                //         ${pointData.towerInfoVo.time6 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>铁塔组立完成</span>
                //         <span>
                //         ${pointData.towerInfoVo.time7 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>架线施工</span>
                //         <span>
                //         ${pointData.towerInfoVo.time8 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>架线施工完成</span>
                //         <span>
                //         ${pointData.towerInfoVo.time9 || "/"}
                //         </span>
                //     </div>
                //     <div class="map-container-item">
                //         <span>附件安装完成</span>
                //         <span>
                //         ${pointData.towerInfoVo.time10 || "/"}
                //         </span>
                //     </div>
                // </div>
                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)
            graphicLayerList.push(billboard)
        })
    }
}

// 添加标点折线（智能绘制虚实线）
async function addMapLine(graphicLayer, mars3d, Cesium) {
    const newTowerList1 = towerList.filter(
        (item) =>
            item.towerProgress != 6 &&
            item.towerProgress != 7 &&
            item.towerProgress != 8 &&
            item.towerProgress != 9 &&
            item.towerProgress != 10,
    )

    console.log(newTowerList1, 'newTowerList1----')
    // 存储所有线段
    const segments = []
    // 绘制杆塔线
    for (let i = 0; i < newTowerList1.length - 1; i++) {
        const startPoint = newTowerList1[i]
        const endPoint = newTowerList1[i + 1]

        let lineColor = ''
        let lineMaterial = null // 用于存储线材质

        // 判断条件部分保持不变
        if (
            (startPoint.towerProgress == 8 && endPoint.towerProgress == 8) ||
            startPoint.towerProgress == 8
        ) {
            // lineColor = "#FFFF00";
            // lineMaterial = new Cesium.ColorMaterialProperty({
            //     // 实线
            //     color: Cesium.Color.fromCssColorString("#FFFF00"),
            // });

            // 创建线段点数组
            const positions = [
                [startPoint.baiduLon, startPoint.baiduLat, 500],
                [endPoint.baiduLon, endPoint.baiduLat, 500],
            ]
            const polyline = new mars3d.graphic.PolylineEntity({
                positions: positions,
                eventParent: false,
                style: {
                    width: 2, // 线宽（像素）
                    color: '#FFFF00', // 使用动态设置的材质
                    clampToGround: true, // 是否贴地（山区建议设为true）
                },
            })
            graphicLayer.addGraphic(polyline)
            graphicLayerList.push(polyline)
        } else if (
            endPoint.existSpan === 1 &&
            startPoint.existSpan === 1 &&
            startPoint.towerProgress != 9 &&
            endPoint.towerProgress != 9 &&
            startPoint.towerProgress != 8 &&
            endPoint.towerProgress != 8 &&
            startPoint.towerProgress != 10 &&
            endPoint.towerProgress != 10
        ) {
            // lineColor = "#d81e06";
            // lineMaterial = new Cesium.PolylineDashMaterialProperty({
            //     // 虚线
            //     color: Cesium.Color.fromCssColorString(lineColor),
            //     dashLength: 16.0, // 可调整虚线长度
            // });
            // // 创建线段点数组
            // const positions = [
            //     [startPoint.baiduLon, startPoint.baiduLat, 500],
            //     [endPoint.baiduLon, endPoint.baiduLat, 500],
            // ];
            // const polyline = new mars3d.graphic.PolylineEntity({
            //     positions: positions,
            //     eventParent: false,
            //     style: {
            //         width: 2, // 线宽（像素）
            //         material: lineMaterial, // 使用动态设置的材质
            //         clampToGround: true, // 是否贴地（山区建议设为true）
            //     },
            // });
            // graphicLayer.addGraphic(polyline);
            // graphicLayerList.push(polyline);
        } else if (
            (startPoint.towerProgress === 9 && endPoint.towerProgress === 9) ||
            (startPoint.towerProgress === 10 && endPoint.towerProgress === 10) ||
            startPoint.towerProgress === 9
        ) {
            // lineColor = "#d81e06";
            // lineMaterial = new Cesium.ColorMaterialProperty({
            //     // 实线
            //     color: Cesium.Color.fromCssColorString(lineColor),
            // });

            // 创建线段点数组
            const positions = [
                [startPoint.baiduLon, startPoint.baiduLat],
                [endPoint.baiduLon, endPoint.baiduLat],
            ]
            const polyline = new mars3d.graphic.PolylineEntity({
                positions: positions,
                eventParent: false,
                style: {
                    width: 2, // 线宽（像素）
                    color: '#d81e06', // 使用动态设置的材质
                    clampToGround: true, // 是否贴地（山区建议设为true）
                },
            })
            graphicLayer.addGraphic(polyline)
            graphicLayerList.push(polyline)
        } else {
            lineColor = '#fff'
            lineMaterial = new Cesium.PolylineDashMaterialProperty({
                // 虚线
                // color: Cesium.Color.fromCssColorString(lineColor),
                color: Cesium.Color.TRANSPARENT,
                dashLength: 16.0, // 可调整虚线长度
            })
        }
    }

    // 绘制交叉线路
    if (crossingLineListNew.length > 0) {
        for (let i = 0; i < crossingLineListNew.length; i++) {
            for (let j = 0; j < crossingLineListNew[i].lineList.length - 1; j++) {
                const startPoint = crossingLineListNew[i].lineList[j]
                const endPoint = crossingLineListNew[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)
                graphicLayerList.push(polyline)
            }
        }
    }

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

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

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

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

    // 绘制公路线
    if (highwayList.length > 0) {
        for (let i = 0; i < highwayList.length; i++) {
            if (highwayList[i].cablewaTransPointVoList.length > 0) {
                for (let j = 0; j < highwayList[i].cablewaTransPointVoList.length - 1; j++) {
                    const startPoint = highwayList[i].cablewaTransPointVoList[j]
                    const endPoint = highwayList[i].cablewaTransPointVoList[j + 1]

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

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

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

                    // 添加点击事件
                    polyline.on(mars3d.EventType.click, function (event) {
                        // console.log("点击了标点", event.graphic.attr);
                        const graphic = event.graphic
                        let infoContent = `
                <div class="map-container-2 map-container">
                    <h4>公路所在杆塔：${highwayList[i].towerName}</h4>
                    <div class="map-container-item">
                        <span>宽度</span>
                        <span>${highwayList[i].cablewayWidth || '/'}</span>
                    </div>
                    <div class="map-container-item">
                        <span>长度</span>
                        <span>${highwayList[i].cablewayLength || '/'}</span>
                    </div>     
                </div>`
                        // 创建自定义信息窗体
                        // graphicLayer.bindPopup(infoContent, {
                        //     position: graphic.position,
                        // });

                        graphic.bindPopup(infoContent)
                        graphic.openPopup()
                    })
                    graphicLayer.addGraphic(polyline)
                    graphicLayerList.push(polyline)
                }
            }
        }
    }

    // 将所有线段添加到地图
    segments.forEach((segment) => map.addOverlay(segment))
}

// 绘制牵张场地区域图
async function addMapAThousandFields(graphicLayer, mars3d, Cesium) {
    if (aThousandFieldsList.length > 0) {
        aThousandFieldsList.forEach((item) => {
            if (item.cablewaTransPointVoList && item.cablewaTransPointVoList.length > 0) {
                let points = []
                // 根据sort字段排序 防止点位顺序不一致
                item.cablewaTransPointVoList.forEach((j) => {
                    points.push([j.lng, j.lat])
                })

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

                if (points.length > 0) {
                    const graphic = new mars3d.graphic.PolygonEntity({
                        positions: points,
                        // eventParent: false,
                        style: {
                            color: '#00FFFF', // 区域填充颜色
                            opacity: 0.5, // 透明度(0-1)
                            outline: true, // 是否显示边框
                            outlineWidth: 2, // 边框宽度(像素)
                            outlineColor: '#00FFFF', // 边框颜色
                            clampToGround: true,
                        },
                        attr: { remark: '示例区域' },
                    })

                    // 添加点击事件
                    graphic.on(mars3d.EventType.click, function (event) {
                        // console.log("点击了标点", event.graphic.attr);
                        const graphic = event.graphic
                        let 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>`
                        // 创建自定义信息窗体
                        // graphicLayer.bindPopup(infoContent, {
                        //     position: graphic.position,
                        // });

                        graphic.bindPopup(infoContent)
                        graphic.openPopup()
                    })
                    graphicLayer.addGraphic(graphic)
                    graphicLayerList.push(graphic)
                }
            }
        })
    }
}

function showData(arrdata, graphicLayer) {
    const polylinesTB = [] // 图标显示的点

    // 预处理坐标及角度
    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.scale = item.height / (item.type === '1' ? 69 : 80.5)

        // 测试塔顶高度与实际高度是否一致
        // const positionTop = mars3d.PointUtil.addPositionsHeight(position, item.height) // 顶部点
        // const graphic2 = new mars3d.graphic.PointPrimitive({
        //   position: positionTop,
        //   style: {
        //     color: "#ff0000",
        //     pixelSize: 8,
        //     outlineColor: "#ffffff",
        //     outlineWidth: 2
        //   }
        // })
        // graphicLayer.addGraphic(graphic2)

        // 计算电线塔转角角度
        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(polylines2, "#cccccc", graphicLayer);
    drawGuideLine(polylines3, '#ff0000', graphicLayer)

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

// 绘制电线塔模型
function drawWireTowerModel(graphicLayer, position, degree, scale, item) {
    const item1 = {
        alt: 488.28,
        heading: -2.2333,
        headingStr: '-2°14′',
        height: 52,
        lat: item.baiduLat,
        lon: item.baiduLon,
    }

    const graphic = new mars3d.graphic.ModelPrimitive({
        position,
        style: {
            url:
                item.type === '1'
                    ? '../../img/3d-model/tower_1.glb'
                    : '../../img/3d-model/tower_2.glb',
            heading: degree,
            scale: scale,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 4000.0),
        },
        // popup: html,
    })

    // 添加点击事件
    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)
    graphicLayerList.push(graphic)
}

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, // 模型本身不是竖直，需要加pitch纠正
            scale: 1,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 4000.0),
        },
    })
    graphicLayer.addGraphic(graphic2)
    graphicLayerList.push(graphic2)
}

function drawGuideLine(positions, color, graphicLayer) {
    const graphic = new mars3d.graphic.PolylinePrimitive({
        positions,
        style: {
            width: 4,
            color,
        },
    })
    graphicLayer.addGraphic(graphic)
    graphicLayerList.push(graphic)
}
