<template>
    <DatePicker ref="datePickerRef" theCurrentTime style="display: none" />
    <div id="map" style="width: 100%; height: 100%" v-show="prop.lineInfo"></div>
    <div id="nrDeviceCard"></div>
    <!-- 搜索框 -->
    <div class="query-box-wrap">
        <el-input
            v-model.trim="inputQuery"
            style="height: 46px; width: 334px"
            @keyup.enter="DeviceQ"
            placeholder="请输入终端名称"
        >
            <template #prefix>
                <div class="Icon"></div>
            </template>

            <template #suffix>
                <el-icon @click="DeviceQ" class="el-input__icon"><Search /></el-icon>
            </template>
        </el-input>
    </div>
    <!-- 搜索内容展示 -->
    <div class="query-box-wrap collapse" v-show="showWrap">
        <div v-if="QueryList.length == 0" class="collapse_none">查询无结果</div>
        <el-collapse v-if="QueryList.length > 0 && showCollapse" v-model="activeName" accordion>
            <el-collapse-item v-for="(item, i) in QueryList" :name="i">
                <template #title>
                    {{ item.psrName }}
                    <span class="ml10" style="color: #0d867f">{{ item.count }}</span>
                </template>
                <div class="collapseBox">
                    <div
                        class="group-list__item"
                        :style="colorKey == k.coordinate ? 'background-color: #009ea81a;' : ''"
                        v-for="k in item.psrList"
                        @click="flyTo(k)"
                    >
                        <p>{{ k.psrName }}</p>
                        <p>{{ k.vlevelName }}|{{ k.maintOrgName }}</p>
                    </div>
                </div>
            </el-collapse-item>
        </el-collapse>
        <div
            v-if="QueryList.length > 0 && !showCollapse"
            class="collapse_none"
            style="color: #009ea8"
            @click="showCollapse = true"
        >
            展开搜索结果
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import { mainHeight } from '@/utils/layout'
import { useDictData } from '@/stores/dictData'
// import { devicesDemo } from '@/assets/panorama/devicesDemo.js'
import { getAreaLineInfo } from '@/api/event-boot/areaInfo'
import DatePicker from '@/components/form/datePicker/index.vue'
import { getGridDiagramAreaData } from '@/api/device-boot/panorama'
import { Search } from '@element-plus/icons-vue'
import '@/assets/panorama/narimap.css'
import '@/assets/panorama/nrgisCommon.css'
const emit = defineEmits(['changeValue', 'drop', 'show'])
const prop = defineProps({
    lineInfo: {
        type: Boolean
    }
})
const inputQuery: any = ref('')
const activeName: any = ref(0)
const narimap = window?.narimap
const dictData = useDictData()
const datePickerRef = ref()
const form: any = ref({})
const colorKey = ref('')
const PopKey = ref(2)
const assessList: any = ref([])
const linList: any = ref([])
const QueryList: any = ref([])
const AreaData: any = ref([])
const map: any = ref(null)
const showCollapse: any = ref(true)
const showWrap: any = ref(false)
const deviceCard: any = ref(null)
const popup: any = ref(null)
const DeviceQuery: any = ref(null)
const rPopList: any = ref([])
const powerManageGridMap: any = ref(null)
const orgId = ref(dictData.state.area[0].code)
const deptIndex = ref(dictData.state.area[0].id)
const popupOffsets = ref({
    top: [0, 0],
    'top-left': [0, 0],
    'top-right': [0, 0],
    bottom: [0, -10],
    'bottom-left': [25, -35],
    'bottom-right': [-25, -35],
    left: [10, -10],
    right: [-10, -10]
})
const mapList: any = ref([])
const flag = ref(true)
const LngLat = [
    {
        name: '唐山',
        LngLat: [118.335849137, 39.7513593355]
    },
    {
        name: '张家口',
        LngLat: [115.032504679, 40.8951549951]
    },
    {
        name: '秦皇岛',
        LngLat: [119.185113833, 40.1179119754]
    },
    {
        name: '承德',
        LngLat: [117.548498365, 41.3775890632]
    },
    {
        name: '廊坊',
        LngLat: [116.628004129, 39.0589378611]
    }
]
import { getAssessOverview } from '@/api/device-boot/panorama'
// narimap.publicKey =
//     'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRYFEiMdZVgY8+jIjx4GR1QbN7qVgCE0istwPZN8xRqdSV+hePUPIW1k9eCVh9gxIIWHAw2TfNZLb8l0Tmk9OH3XnZ009TNBjzZ2zWLrbjFQzgutKKI2JRLK+CaJbOZ0LiD78QnTo5Zk+ZuQBKgtyFJdp4T5gQS+Mnbj/c4EnK0QIDAQAB'
narimap.publicKey = 'JBb74325ae94dc49358b7d699660b692'

narimap.Require(
    [
        'PSRMap',
        'ManageGrid',
        'Components.Query',
        'Components.DeviceCard',
        'Popup',
        'Components.MapSelector',
        'Components.RegionSelector',
        'Marker'
    ],
    // ['PSRMap', 'Components.Query', 'Marker'],
    () => {
        if (narimap.Config.examples.notlogin) {
            initMap(narimap.Config.styles.sjRaster)
        } else {
            //电网GIS地图服务登录
            narimap.SGAuth.login()
                .then((result: any) => {
                    if (result.success) {
                        console.log('登录成功')
                    } else {
                        console.log('登录失败', result)
                    }

                    //默认打开电网GIS影像图
                    initMap(narimap.Config.styles.sjRaster)
                })
                .catch((err: any) => {
                    console.log('错误', err)
                })
        }
    }
)
function initMap(styleurl: any) {
    map.value = new narimap.Map({
        container: 'map',
        style: styleurl,
        zoom: 6,
        center: [116.478935, 39.997761],
        controls: ['attribute', 'navigation', 'geolocate', 'scale'],
        country: true,
        // 地图默认字体
        localIdeographFontFamily: 'Microsoft YoHei',
        fullExtent: narimap.Config.examples.fullExtent
    })

    map.value.on('load', () => {
        createMapSelectorComponent()
        DeviceQuery.value = new narimap.ResourceQuery.DeviceQuery()
        addLayer()
        //testAddLayer()
        nextTick(() => {
            // 添加图层
            Query()
        })
    })
}

const Query = () => {
    // 添加行政区划
    powerManageGridMap.value = new narimap.ManageGrid.PowerManageGridMap(map.value)
    powerManageGridMap.value.init(
        {
            base: {
                outline: {
                    paint: {
                        'line-color': '#fff',
                        'line-width': 2,
                        'line-opacity': 1
                    }
                },
                fill: {
                    paint: {
                        'fill-color': '#0D867F',
                        // 'fill-opacity': 0.3
                        'fill-opacity': 0
                    }
                },
                label: {
                    paint: {
                        'text-color': '#063094',
                        'text-halo-color': '#ffffff',
                        'text-halo-width': 1
                    }
                },
                hover: {
                    type: 'all',
                    fill: {
                        paint: {
                            'fill-color': 'rgba(1,1,1,0)',
                            'fill-opacity': 0
                        }
                    },
                    outline: {
                        paint: {
                            'line-color': '#fff',
                            'line-width': 4,
                            'line-opacity': 1
                        }
                    }
                }
            },
            levels: {
                city: {
                    // minzoom: 10,
                    maxzoom: 9
                }
            }
        },
        {
            initOrgIds: [orgId.value],
            //是否联级，包含下属全部子部门，即同样显示编码对应的所属下级
            cascade: true
        }
    )

    powerManageGridMap.value.on('load', function () {
        // 区分区域颜色
        // powerLoad()
    })

    setTimeout(() => {
        addLine()
        // const query = new narimap.Components.Query(map.value)
        // query.init(map.value.getContainer())
        // query.setQueryOrgId(orgId.value)

        setTimeout(() => {
            locatePositions({ data: dictData.state.area[0] })
        }, 500)
    }, 500)
}
// 添加热力图
const sourceList: any = ref([])
const addSource = async () => {
    // const features = [
    // {
    //     type: 'Feature',
    //     geometry: {
    //         type: 'Point',
    //         coordinates: [117.651148, 41.121061]
    //     },
    //     properties: {
    //         value: 64
    //     }
    // }
    // ]
    console.log('🚀 ~ sourceList:', sourceList.value)

    if (map.value.getSource('themeData')) {
        map.value.getSource('themeData').setData({
            type: 'FeatureCollection',
            features: sourceList.value
        })
    } else {
        map.value.addSource('themeData', {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: sourceList.value
            }
        })
    }
    if (map.value.getLayer('earthquakes-paint')) {
    } else {
        map.value.addLayer({
            id: 'earthquakes-paint',
            type: 'heatmap',
            source: 'themeData',
            paint: {
                /**
                 * 数据点的影响力，weight=10的点相当于十个weight=1的点
                 * 下述为插值表达式，输入是点geojson的properties的mag，输出随mag线性增大
                 */
                'heatmap-weight': [
                    'interpolate',
                    ['linear'],
                    ['get', 'value'],
                    0,
                    0.1,
                    1,
                    0.3,
                    101,
                    0.5,
                    1001,
                    0.7,
                    10001,
                    1
                ],
                'heatmap-color': [
                    'interpolate',
                    ['linear'],
                    ['heatmap-density'],
                    0,
                    'rgba(255, 0, 0, 0)',
                    0.1,
                    'rgba(7, 91, 243, .8)',
                    0.3,
                    'rgba(7, 208, 255, .6)',

                    0.5,
                    'rgba(213, 251, 12, .8)',

                    0.7,
                    'rgba(255, 191, 0, .8)',

                    1,
                    'rgba(255, 0, 0, .8)'
                ],

                'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 0, 1, 12, 3],
                /**
                 * 该值越大，热力图越平滑，信息越不详细。
                 * 下述为插值表达式，输出随zoom线性变化，zoom为0时值为8，zoom为9时值为20
                 */
                'heatmap-radius': 30,
                /**
                 * 透明度，输出为1则不透明
                 * 下述为插值表达式，输出随zoom线性变化，zoom为5时值为0.8，zoom为12时值为0.4
                 */
                'heatmap-opacity': 1
            },
            maxzoom: 12
        })
    }
}
// 添加变电站线路
const addLine = () => {
    //添加电网图层
    let psrmap = new narimap.PSRMap(map.value, {
        orgId: orgId.value == '1100F3DE20806FADE050007F01006CBE' ? '' : orgId.value
    })
    psrmap.addPSR()

    initDeviceCard()
    setTimeout(() => {
        psrmap.filterByDomain(1)
    }, 0)
    //添加电网要素点击事件
    psrmap.on('click', (features: any) => {
        console.log(features)
        showCollapse.value = false
        if (inputQuery.value.length == 0) showWrap.value = false
    })
}

// 添加变电站弹框
const initDeviceCard = () => {
    deviceCard.value && deviceCard.value.close()

    let options = {
        map: map.value, // map实例
        container: 'nrDeviceCard', // details容器id，为用户自定义的容器名
        narimap: narimap, //nariMap实例
        //用户自定义功能
        customButtons: {
            popupButtons: {
                buttons: []
            },
            detailsButtons: {
                buttons: []
            }
        }
    }

    deviceCard.value = new narimap.Components.DeviceCard(options)

    deviceCard.value.on('click', (res: any) => {
        if (res.button.id == 'nariPopupViewDetail') {
            emit('show', true)
        }
        setTimeout(() => {
            document.querySelectorAll('.nari-tabs__close')[0].onclick = function (v: any) {
                emit('show', false)
            }
        }, 10)
    })
    //
}

const grids = (row: any) => {
    form.value = {
        ...row,
        id: row.orgNo,
        deptIndex: row.orgNo,
        orgId: row.orgNo,
        ids: [],
        statisticalType: dictData.getBasicData('Statistical_Type', ['Report_Type'])[0],
        isUpToGrid: row.isUpToGrid,
        monitorFlag: row.isUpToGrid == 0 ? null : row.isUpToGrid
    }

    // 综合评估
    getAssessOverview(form.value).then(res => {
        assessList.value = res.data?.children

        getGridDiagramAreaData({ ...form.value, deptIndex: deptIndex.value }).then((res: any) => {
            AreaData.value = res.data
            GridDiagramArea()
        })
        if (powerManageGridMap.value) powerLoad()
    })
}

// 加载行政区划
const powerLoad = () => {
    // dictData.state.area[0]

    let colors: any = [
        {
            orgIds: [],
            outline: {
                color: '#fff'
            },
            fill: {
                color: '#00b07d'
            }
        },
        {
            orgIds: [],
            outline: {
                color: '#fff'
            },
            fill: {
                color: '#3399ff'
            }
        },
        {
            orgIds: [],
            outline: {
                color: '#fff'
            },
            fill: {
                color: '#ffcc33'
            }
        },
        {
            orgIds: [],
            outline: {
                color: '#fff'
            },
            fill: {
                color: '#db0887'
            }
        },
        {
            orgIds: [],
            outline: {
                color: '#fff'
            },
            fill: {
                color: '#ff0000'
            }
        }
    ]

    assessList.value.forEach((item: any) => {
        if (item.score == 3.14159) {
        } else if (item.score > 4.5) {
            colors[0].orgIds.push(item.code)
        } else if (item.score > 4) {
            colors[1].orgIds.push(item.code)
        } else if (item.score > 3) {
            colors[2].orgIds.push(item.code)
        } else if (item.score > 2) {
            colors[3].orgIds.push(item.code)
        } else if (item.score > 0) {
            colors[4].orgIds.push(item.code)
        }
    })

    powerManageGridMap.value.setColorByOrgId({
        orgIdColors: colors
    })
}
// 添加图层
const addLayer = () => {
    map.value.loadImage(
        new URL('@/assets/txzcwzj.png', import.meta.url).href, // 图片地址
        (error: any, image: any) => {
            if (error) throw error

            //添加图片到map，第一个参数为图片设置id
            map.value.addImage('poi1', image)
            map.value.addLayer({
                id: 'spotImg-ZY',
                type: 'symbol',
                minzoom: 8,
                source: {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID
                    'icon-image': 'poi1',
                    'icon-size': 0.7,
                    'icon-ignore-placement': false,
                    'icon-allow-overlap': false
                }
            })
            map.value.addLayer({
                id: 'spotName',
                type: 'symbol',
                minzoom: 10,
                source: {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID

                    'text-field': '{name}',
                    'icon-ignore-placement': false,
                    'text-ignore-placement': true,
                    'text-size': 12,
                    'text-max-width': 8,
                    'text-offset': [0, 2],
                    'text-font': ['Microsoft YaHei Regular']
                },
                paint: {
                    'text-color': '#ccc',

                    'text-halo-width': 1.33333
                }
            })
        }
    )

    map.value.loadImage(
        new URL('@/assets/txzdwzj.png', import.meta.url).href, // 图片地址
        (error: any, image: any) => {
            if (error) throw error

            //添加图片到map，第一个参数为图片设置id
            map.value.addImage('poi2', image)
            map.value.addLayer({
                id: 'spotImg-TY',
                type: 'symbol',
                minzoom: 8,
                source: {
                    type: 'geojson',

                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID
                    'icon-image': 'poi2',
                    'icon-size': 0.7,
                    // 'text-field': '{name}',
                    'icon-ignore-placement': false,
                    'icon-allow-overlap': false
                }
            })
        }
    )
    map.value.loadImage(
        new URL('@/assets/point.png', import.meta.url).href, // 图片地址
        (error: any, image: any) => {
            if (error) throw error

            //添加图片到map，第一个参数为图片设置id
            map.value.addImage('poi3', image)
            map.value.addLayer({
                id: 'spotImg-GJ',
                type: 'symbol',
                minzoom: 8,
                source: {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID
                    'icon-image': 'poi3',
                    'icon-size': 0.6,
                    'icon-ignore-placement': false,
                    'icon-allow-overlap': false
                },
                Paint: {
                    'icon-opacity': 10
                }
            })
        }
    )
    map.value.loadImage(
        new URL('@/assets/dw.png', import.meta.url).href, // 图片地址
        (error: any, image: any) => {
            if (error) throw error

            //添加图片到map，第一个参数为图片设置id
            map.value.addImage('poi4', image)
            map.value.addLayer({
                id: 'spotImg-DW',
                type: 'symbol',
                minzoom: 8,
                zIndex: 9999,
                source: {
                    type: 'geojson',

                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID
                    'icon-image': 'poi4',
                    'icon-size': 0.35,
                    // 'icon-pitch-alignment': 'map', //贴地
                    'icon-ignore-placement': false,
                    'icon-allow-overlap': false
                }
            })
        }
    )

    // 添加地图弹框
    map.value.on('click', (e: any) => {
        const features = map.value.queryRenderedFeatures(e.point, {
            layers: ['spotImg-ZY', 'spotImg-TY', 'spotImg-GJ', 'spotImg-DW']
        })

        if (features.length > 0) {
            popup.value && popup.value.remove()
            setTimeout(() => {
                deviceCard.value.popup && deviceCard.value.popup.remove()
            }, 10)
            let data = JSON.parse(features[0].properties.list)

            popup.value = new narimap.Popup({ offset: popupOffsets.value, className: 'my-popup' })
                .setLngLat([data.lng, data.lat])
                .setHTML(
                    ` <div class="popup-box">
                        <div class="popup_content">
                            <img src="${data.imageUrl}" />
                            <div>
                                <div style="display: flex">
                                    <span class="title">${data.lineName}</span>
                                    <span
                                        class="state"
                                        style="background-color: ${data.comFlag == 0 ? '#ff0000' : '#3ab34a'};"
                                    >
                                        ${data.comFlag == 0 ? '中断' : '在线'}
                                    </span>
                                </div>
                                <div class="info">
                                    <span>${data.subName} </span>
                                    <span>${data.voltageName}</span>
                                </div>
                            </div>
                        </div>
                        <div class="popup_footer">
                            <span id="ids" data-sid="${data.lineId}">
                                查看详情
                            </span>
                        </div>
                    </div>`
                )
                .addTo(map.value)

            let html = document.getElementById('ids')
            if (html)
                html.onclick = function (v: any) {
                    // console.log(e.target.dataset.sid)
                    emit('drop', v.target.dataset.sid)
                }
        }
    })

    // 监听地图缩放完成事件
    map.value.on('zoomend', (e: any) => {
        console.log(123, map.value.getZoom())

        if (map.value.getZoom() > 8.5 || map.value.getZoom() < 6) {
            rPopList.value.map((item: any) => item.remove())
            rPopList.value = []
        } else {
            if (mapList.value.length > 0) radiusPop()
        }
    })
}

const PollutionList = dictData.getBasicData('Pollution_Calc').filter(item => item.name == '谐波电压')
//添加多个监测点
const addMarkers = async (row?: any, key?: any, num?: any) => {
    if (map.value == null) return
    let params = {
        deptIndex: deptIndex.value,
        monitorFlag: 2,
        powerFlag: 2,
        searchBeginTime: datePickerRef.value.timeValue[0],
        searchEndTime: datePickerRef.value.timeValue[1],
        serverName: 'event-boot',
        dicData: [PollutionList[0].id],
        isPollution: 1,
        statisticalType: {},
        ...row
    }

    let { data } = await getAreaLineInfo(params)

    let r = 0.0035
    let tempFeatureZ: any = []
    let tempFeatureT: any = []

    sourceList.value = []
    data.forEach((item: any) => {
        if (item.children.length > 10 && item.children.length < 100) {
            r = 0.0055
        } else if (item.children.length >= 100) {
            r = 0.01055
        }

        item.children.forEach((val: any, i: number) => {
            val.lng = item.lng + r * Math.cos((2 * Math.PI * i) / item.children.length)
            val.lat = item.lat + r * Math.sin((2 * Math.PI * i) / item.children.length)
            val.imageUrl =
                val.comFlag == 0
                    ? new URL('@/assets/txzdwzj.png', import.meta.url).href
                    : new URL('@/assets/txzcwzj.png', import.meta.url).href
            // // 监测点图标

            let tempFeature = {
                type: 'Feature',

                geometry: {
                    type: 'Point',
                    coordinates: [val.lng, val.lat]
                },
                properties: {
                    name: val.lineName,
                    list: val
                }
            }
            if (key == 1) {
                switch (val.type) {
                    case 0:
                        tempFeatureZ.push(tempFeature)

                        break
                    case 1:
                        tempFeatureT.push(tempFeature)
                        break
                }
            } else {
                switch (val.comFlag) {
                    case 0:
                        tempFeatureT.push(tempFeature)
                        break
                    case 1:
                        tempFeatureZ.push(tempFeature)
                        break
                }
            }
            let num = 20
            if (val.vharmonicValue > 10000) {
                num = 100
            } else if (val.vharmonicValue > 1000) {
                num = 80
            } else if (val.vharmonicValue > 100) {
                num = 60
            } else if (val.vharmonicValue > 0) {
                num = 40
            } else {
                num = 20
            }

            sourceList.value.push({
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [val.lng, val.lat]
                },
                properties: {
                    value: val.vharmonicValue || 0
                    // value: num //10 //val.vharmonicValue || 0
                    // value: 0
                }
            })
        })
    })

    if (flag.value) {
        linList.value = [...tempFeatureZ, ...tempFeatureT]

        flag.value = false
    }
    //    清除图层图片
    map.value.getSource('spotImg-ZY').setData({
        type: 'FeatureCollection',
        features: []
    })
    map.value.getSource('spotImg-TY').setData({
        type: 'FeatureCollection',
        features: []
    })
    map.value.getSource('spotImg-GJ').setData({
        type: 'FeatureCollection',
        features: []
    })
    map.value.getSource('spotImg-DW').setData({
        type: 'FeatureCollection',
        features: []
    })
    if (key != undefined && num == undefined) map.value.easeTo({ zoom: 8.1 })

    if (key == undefined) {
        map.value.getSource('spotImg-DW').setData({
            type: 'FeatureCollection',
            features: [...tempFeatureT, ...tempFeatureZ]
        })
    } else if (key == 1) {
        map.value.getSource('spotImg-ZY').setData({
            type: 'FeatureCollection',
            features: tempFeatureZ
        })
        map.value.getSource('spotImg-TY').setData({
            type: 'FeatureCollection',
            features: tempFeatureT
        })
    } else {
        map.value.getSource('spotImg-ZY').setData({
            type: 'FeatureCollection',
            features: [...tempFeatureZ, ...tempFeatureT]
        })
        // map.value.getSource('spotImg-TY').setData({
        //     type: 'FeatureCollection',
        //     features: tempFeatureT
        // })
    }

    // console.log('🚀 ~ addMarkers ~  map.value.getStyle().layers:', map.value.getStyle().layers)
    const layers = map.value.getStyle().layers
    const topLayer = layers[layers.length - 1]
    map.value.moveLayer('spotImg-DW', topLayer.id)
    map.value.moveLayer('spotImg-ZY', topLayer.id)
    map.value.moveLayer('spotImg-TY', topLayer.id)
    map.value.moveLayer('spotImg-GJ', topLayer.id)

    map.value.getSource('spotName').setData({
        type: 'FeatureCollection',
        features: [...tempFeatureT, ...tempFeatureZ]
    })
    addSource()
    //
}

// 统计弹框数据
const GridDiagramArea = () => {
    LngLat.forEach((item: any) => {
        assessList.value.forEach((y: any) => {
            if (item.name == y.name) {
                if (y.score == 3.14159) {
                } else if (y.score > 4.5) {
                    item.background = '#33996699'
                } else if (y.score > 4) {
                    item.background = '#3399ff99'
                } else if (y.score > 3) {
                    item.background = '#ffcc3399'
                } else if (y.score > 2) {
                    item.background = '#db088799'
                } else if (y.score > 0) {
                    item.background = '#ff000099'
                }
            }
        })

        AreaData.value.forEach((k: any, i: any) => {
            if (item.name == k.orgName) {
                k.LngLat = item.LngLat
                k.background = item.background
            }
        })
    })
    mapList.value = AreaData.value.filter((item: any) => item.orgName != '超高压' && item.orgName != '风光储')
    setTimeout(() => {
        radiusPop()
    }, 0)
}
// 添加统计弹框
const radiusPop = (k?: number) => {
    if (k != undefined) PopKey.value = 0
    if (rPopList.value.length > 0) {
        rPopList.value.map((item: any) => item.remove())
        rPopList.value = []
    }

    mapList.value.forEach((item: any, i: number) => {
        let infoText = ''

        if (PopKey.value == 2) {
            // 监测点
            infoText = `<img src="${new URL(`@/assets/img/JCD-ZS.png`, import.meta.url)}" />
                        <div class="infoBox">
                            <div   id="clickZs${i}" data-line="${item.lineList}" data-alarm="${
                item.alarmList
            }" data-key="0" data-LngLat="${item.LngLat}">总数<br/>${item.lineNum}</div>
                            <div id="clickZx${i}"  data-alarm="${item.onlineList}" data-key="0" data-LngLat="${
                item.LngLat
            }">在线<br/>${item.onlineNum}</div>
                            <div id="clickGj${i}" data-line="" data-alarm="${
                item.alarmList
            }" data-key="1" data-LngLat="${item.LngLat}">告警<br/>${item.alarm}</div>
                        </div>`
        } else if (PopKey.value == 0) {
            // 变电站
            infoText = `<img src="${new URL(`@/assets/img/BDZ-ZS.png`, import.meta.url)}" />
                        <div class="infoBox">
                            <div id="clickZs${i}" data-line="${item.lineList}" data-alarm="${
                item.alarmSubList
            }" data-key="1" data-LngLat="${item.LngLat}">总数<br/>${item.subNum}</div>
                            <div id="clickGj${i}" data-line="" data-alarm="${
                item.alarmSubList
            }" data-key="1" data-LngLat="${item.LngLat}">告警<br/>${item.alarmSubNum}</div>
                        </div>`
        } else if (PopKey.value == 1) {
            // 终端
            infoText = `<img src="${new URL(`@/assets/img/ZD-ZS.png`, import.meta.url)}" />
                        <div class="infoBox">
                            <div id="clickZs${i}" data-line="${item.lineList}" data-alarm="${
                item.onlineList
            }" data-key="2" data-LngLat="${item.LngLat}">总数<br/>${item.deviceNum}</div>
                            <div id="clickGj${i}" data-line="" data-alarm="${
                item.onlineList
            }" data-key="2" data-LngLat="${item.LngLat}">在运<br/>${item.onDevice}</div>
                        </div>`
        }

        let pop = new narimap.Popup({
            offset: popupOffsets.value,
            className: 'my-radiusPop',
            closeButton: false,
            closeOnClick: false
        })
            .setLngLat(item.LngLat)
            .setHTML(
                `<div class="sgmap-popup-content" style="background-color: ${item.background};">
                    <div style="display: flex;">` +
                    infoText +
                    ` </div>
                </div>`
            )
            .addTo(map.value)
        rPopList.value.push(pop)
        let html: any = document.getElementById(`clickZs${i}`)
        let html1: any = document.getElementById(`clickZx${i}`)
        let html2: any = document.getElementById(`clickGj${i}`)
        if (html)
            html.onclick = function (v: any) {
                popMarkers(
                    v.target.dataset.line?.split(','),
                    v.target.dataset.alarm?.split(','),
                    v.target.dataset.key,
                    v.target.dataset.lnglat?.split(',')
                )
            }
        if (html1)
            html1.onclick = function (v: any) {
                popMarkers(
                    [],
                    v.target.dataset.alarm?.split(','),
                    v.target.dataset.key,
                    v.target.dataset.lnglat?.split(',')
                )
            }
        if (html2)
            html2.onclick = function (v: any) {
                popMarkers(
                    [],
                    v.target.dataset.alarm?.split(','),
                    v.target.dataset.key,
                    v.target.dataset.lnglat?.split(',')
                )
            }
    })
}
// 点击弹框调用点加载
const popMarkers = (coutList: any, alarmList: any, key: any, LngLat: any) => {
    addMarkers(
        {
            coutList: coutList,
            alarmList: alarmList,
            type: 1
        },
        key,
        0
    )

    flyTo(
        {
            coordinate: LngLat
        },
        8.1
    )
}

const locatePositions = (e: any) => {
    if (map.value != null) {
        deptIndex.value = e.data.id
        // 加载点
        addMarkers()

        powerManageGridMap.value.drillDown({
            // 判断超高压
            orgId: e.data.code == '1100F3DE246A6FADE050007F01006CBE' ? '1100F3DE20806FADE050007F01006CBE' : e.data.code,
            onlyDisplay: true
        })
    }
}
// 电网查询功能
const DeviceQ = () => {
    showCollapse.value = true
    if (inputQuery.value.length == 0) return

    let list = []
    // linList.value
    DeviceQuery.value.queryDeviceByName(
        {
            orgId: orgId.value,
            maxRecord: 9999,
            keyword: inputQuery.value,
            devTypes: [
                {
                    devType: 'zf05',
                    distribution: 1
                },
                {
                    devType: 'zf01',
                    distribution: 1
                },
                {
                    devType: 'zf02',
                    distribution: 1
                },
                {
                    devType: 'zf03',
                    distribution: 1
                },
                {
                    devType: 'zf04',
                    distribution: 1
                }
            ]
        },
        (res: any) => {
            list = res.result.psrDataList.map((item: any) => {
                item.psrName = item.psrList[0].psrTypeName
                return item
            })
            let regex = new RegExp(inputQuery.value, 'i')
            let data = linList.value
                .filter((item: any) => regex.test(item.properties.name))
                .map((item: any) => {
                    return {
                        psrName: item.properties.name,
                        vlevelName: item.properties.list.voltageScale,
                        maintOrgName: item.properties.list.gdName,
                        coordinate: [item.properties.list.lng, item.properties.list.lat]
                    }
                })
            // data.replace(//s/g,',')

            // data
            if (data.length > 0) {
                list.push({
                    count: data.length,
                    psrList: data,
                    psrName: '监测点'
                })
            }
            QueryList.value = list
            showWrap.value = true
        }
    )
}
// 搜索信息定位
const flyTo = (row: any, zoom?: number) => {
    if (!map.value) return
    colorKey.value = row.coordinate
    map.value.flyTo({
        center:
            typeof row.coordinate === 'string'
                ? narimap.Projection.mercatorToWgs84(row.coordinate.split(' ').map(Number))
                : row.coordinate, // 位置，飞行后的地图中心点
        zoom: zoom || 16, // 飞行后的地图缩放级别
        bearing: 0, // 地图的旋转角度，0-360之间的数字，0表示正北，90表示正东
        pitch: 0, // 地图的倾斜角，介于0-60之间的数字，0表示俯视视图，60表示垂直视图
        speed: 2 // 地图视图移动速度
    })
}

// 添加地图选择
const createMapSelectorComponent = () => {
    const mapSelector = new narimap.Components.MapSelector()
    mapSelector.init(
        map.value
        // ['sjBase', 'sjDark'],
        // [
        //     {
        //         styleKey: 'sjRaster',
        //         styleName: '影像图',
        //         styleUrl: narimap.Config.styles.sjRaster,
        //         // styleIcon: WebGIS.Config.apiRoot + 'libs/webgis/images/map/map_sjRasterStyle.png'
        //     }
        // ]
    )
}

defineExpose({ locatePositions, addMarkers, grids, DeviceQ, radiusPop, flyTo })
const height = mainHeight(20)
</script>

<style lang="scss" scoped>
@use '@/views/pqs/qualityInspeection/panorama/components/style/map.scss';
</style>
