<template>
    <DatePicker ref="datePickerRef" style="display: none" />
    <div id="map" style="width: 100%; height: 100%" v-show="prop.lineInfo"></div>
    <div id="nrDeviceCard"></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 '@/assets/panorama/narimap.css'
import '@/assets/panorama/nrgisCommon.css'
const emit = defineEmits(['changeValue', 'drop', 'show'])
const prop = defineProps({
    lineInfo: {
        type: Boolean
    }
})
const narimap = window?.narimap
const dictData = useDictData()
const datePickerRef = ref()
const map: any = ref(null)
const deviceCard: any = ref(null)
const popup: any = ref(null)
const powerManageGridMap: any = ref(null)
const orgId = ref(dictData.state.area[0].code)
const deptIndex = ref(dictData.state.area[0].id)
narimap.Require(
    ['PSRMap', 'Thematic', 'Components.Query', 'Components.RegionSelector', 'Components.DeviceTreeGW'],
    () => {
        if (narimap.Config.examples.notlogin) {
            initMap(narimap.Config.styles.sjDark)
        } else {
            //电网GIS地图服务登录
            narimap.SGAuth.login()
                .then((result: any) => {
                    if (result.success) {
                        console.log('登录成功')
                    } else {
                        console.log('登录失败', result)
                    }
                    //默认打开电网GIS影像图
                    initMap(narimap.Config.styles.sjDark)
                })
                .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: false,
        country: true,
        // 地图默认字体
        localIdeographFontFamily: 'Microsoft YoHei'
    })
    map.value.on('load', () => {
        addLayer()

        nextTick(() => {
            // 添加图层

            Query()
        })
    })
}

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

    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 addLine = () => {
    //添加电网图层
    let psrmap = new narimap.PSRMap(map.value, {
        orgId: orgId.value == '1100F3DE20806FADE050007F01006CBE' ? '' : orgId.value
    })
    psrmap.addPSR()
    initDeviceCard()
    const devTree = new narimap.Components.DeviceTreeGW(map.value)

    devTree.init({ orgId: orgId.value })

    //添加电网要素点击事件
    // device-tree-gw__button
    document.querySelectorAll('.device-tree-gw__button')[0].onclick = function (v: any) {
        emit('show', true)
    }
    //添加电网要素点击事件
    psrmap.on('click', (features: any) => {
        console.log(features)
    })
}
// 添加变电站弹框
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 nrgisCommon.EquipmentAccount.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 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': true,
                    'icon-allow-overlap': true
                }
            })
            map.value.addLayer({
                id: 'spotName',
                type: 'symbol',
                minzoom: 10,
                source: {
                    type: 'geojson',
                    data: {
                        type: 'FeatureCollection',
                        features: []
                    }
                },
                layout: {
                    // 为图层设置引用的图片ID

                    'text-field': '{name}',
                    'icon-ignore-placement': true,
                    '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': true,
                    'icon-allow-overlap': true
                    // 'text-ignore-placement': false,
                    // 'text-size': 12,
                    // 'text-max-width': 8,
                    // 'text-offset': [0, 2],
                    // 'text-font': ['Microsoft YaHei Regular']
                }
                // paint: {
                //     'text-color': '#ccc',
                //     // 'text-halo-color': '#FFFFFF',
                //     'text-halo-width': 1.33333
                // }
            })
        }
    )
    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': true,
                    'icon-allow-overlap': true
                },
                Paint: {
                    'icon-opacity': 10
                }
            })
        }
    )
    // 添加地图弹框
    map.value.on('click', (e: any) => {
        const features = map.value.queryRenderedFeatures(e.point, {
            layers: ['spotImg-ZY', 'spotImg-TY', 'spotImg-GJ']
        })

        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)
            let markerHeight = 20
            let markerRadius = 10
            let linearOffset = 25
            let popupOffsets = {
                top: [0, 0],
                'top-left': [0, 0],
                'top-right': [0, 0],
                bottom: [0, -markerHeight + 10],
                'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
                'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
                left: [markerRadius, (markerHeight - markerRadius) * -1],
                right: [-markerRadius, (markerHeight - markerRadius) * -1]
            }

            popup.value = new narimap.Popup({ offset: popupOffsets, 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)
            document.getElementById('ids').onclick = function (v: any) {
                // console.log(e.target.dataset.sid)
                emit('drop', v.target.dataset.sid)
            }
        }
    })
}
//添加多个监测点
const addMarkers = async (row?: any, key?: any) => {
    console.log('🚀 ~ addMarkers ~ key:', key)
    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',
        statisticalType: {},
        ...row
    }
    let { data } = await getAreaLineInfo(params)
    let r = 0.0035
    let tempFeatureZ: any = []
    let tempFeatureT: any = []
    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 == 0) {
                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
                }
            }
        })
    })

    map.value.getSource('spotImg-ZY').setData({
        type: 'FeatureCollection',
        features: tempFeatureZ
    })
  
    map.value.setLayerZoomRange('spotImg-GJ', key != undefined ? 0 : 8)
    map.value.setLayerZoomRange('spotImg-TY', key != undefined ? 0 : 8)
    map.value.setLayerZoomRange('spotImg-ZY', key != undefined ? 0 : 8)
    if (key == 0) {
        map.value.getSource('spotImg-GJ').setData({
            type: 'FeatureCollection',
            features: tempFeatureT
        })
        map.value.getSource('spotImg-TY').setData({
            type: 'FeatureCollection',
            features: []
        })
    } else {
        map.value.getSource('spotImg-GJ').setData({
            type: 'FeatureCollection',
            features: []
        })
        map.value.getSource('spotImg-TY').setData({
            type: 'FeatureCollection',
            features: tempFeatureT
        })
    }

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

onMounted(() => {
    // 监听地图初始化完成事件
})

const locatePositions = (e: any) => {
    // let mapList = [
    //     {
    //         code: '1100F3DE20806FADE050007F01006CBE', //冀北
    //         centralCoordinate: [117.14740482, 40.5478448705],
    //         zoom: 6
    //     },
    //     {
    //         code: '1100F3DE246A6FADE050007F01006CBE', //超高压
    //         centralCoordinate: [117.14740482, 40.5478448705],
    //         zoom: 6
    //     },

    //     {
    //         code: '1100F3DE22316FADE050007F01006CBE', //"唐山"
    //         centralCoordinate: [118.335849137, 39.7213593355],
    //         zoom: 7
    //     },
    //     {
    //         code: '1100F3DE20816FADE050007F01006CBE', //张家口
    //         centralCoordinate: [115.032504679, 40.8651549951],
    //         zoom: 7
    //     },
    //     {
    //         code: '1100F3DE23F96FADE050007F01006CBE', //秦皇岛
    //         centralCoordinate: [119.185113833, 40.0879119754],
    //         zoom: 7
    //     },
    //     {
    //         code: '1100F3DE23466FADE050007F01006CBE', //承德
    //         centralCoordinate: [117.548498365, 41.3475890632],
    //         zoom: 7
    //     },
    //     {
    //         code: '1100F3DE218D6FADE050007F01006CBE', //廊坊
    //         centralCoordinate: [116.628004129, 39.2589378611],
    //         zoom: 7
    //     }
    // ]
    // let data: any = []
    // data = mapList.filter(item => item.code == e.data.code) || []

    if (map.value != null) {
        deptIndex.value = e.data.id
        // 加载点
        addMarkers()
        powerManageGridMap.value.drillDown({
            // 判断超高压
            orgId: e.data.code == '1100F3DE246A6FADE050007F01006CBE' ? '1100F3DE20806FADE050007F01006CBE' : e.data.code,
            onlyDisplay: true
        })
    }
}
defineExpose({ locatePositions, addMarkers })
const height = mainHeight(20)
</script>

<style lang="scss" scoped>
:deep(.query-box-wrap) {
    position: absolute;
    top: 10px;
    left: calc(50% - 345px);
    .query-box {
        border-radius: 8px 0 0 8px;
    }
}
:deep(.device-tree-gw__button) {
    position: absolute;
    top: 10px;
    border-radius: 0 8px 8px 0;
    left: calc(50% - 15px);
    z-index: 0 !important;
}

:deep(.province-selector) {
    position: absolute;
    top: 10px;
    left: 50%;
    .distribution__body {
        height: auto;
    }
    .province-selector__options {
        height: auto;
    }
    .province-op {
        width: 48%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .province-selector__button {
        width: 100px;
        padding: 4px 12px;
        span {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
    .province-selector__options {
        z-index: 1;
    }
}
:deep(.sgmap-canvas) {
    width: 100% !important;
}
:deep(.my-popup) {
    max-width: 400px !important;
    .popup-box {
        width: 300px;
        height: 70px;
        .popup_content {
            display: grid;
            grid-template-columns: 50px 1fr;
            img {
                width: 42px;
                height: 42px;
            }
            .title {
                font-weight: 550;
            }
            .state {
                width: 45px;
                margin-left: 5px;
                text-align: center;
                border-radius: 3px;
                color: #fff;
            }
            .info {
                color: #18181b99;
                margin: 5px 0;
                span {
                    display: inline-block;
                    width: 120px;
                    height: 14px;
                    line-height: 14px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    -webkit-box-orient: vertical;
                    &::after {
                        display: inline-block;
                        margin: 0 3px;
                        content: ' ';
                        width: 2px;
                        height: 11px;
                        background: #e5e6eb73;
                        vertical-align: middle;
                    }
                }
            }
        }
        .popup_footer {
            padding: 5px 5px;
            border-top: 1px solid #e5e6eb;
            color: var(--el-color-primary);
            span {
                margin-right: 8px;
                cursor: pointer;
            }
        }
    }
    .sgmap-popup-content {
        padding: 15px 10px 10px !important;
    }
    .sgmap-popup-close-button {
        position: absolute;
        right: 5px;
        top: 5px;
        font-size: 16px;
    }
}
#nrDeviceCard {
    position: absolute;
    top: 11px;
    right: 70px;
    width: 450px;
    z-index: 0;
}
</style>
