<template>
    <div class="default-main">
        <DatePicker ref="datePickerRef" theCurrentTime style="display: none" />
        <!-- 搜索框 -->
        <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"
                            :key="k"
                            @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 class="collapse_none" style="color: red; cursor: pointer" @click="showWrap = false">关闭</div>
        </div>
        <baidu-map
            class="map pb10"
            :style="height"
            @ready="initMap"
            @zoomend="syncCenterAndZoom"
            :center="center"
            :zoom="zoomMap"
            :scroll-wheel-zoom="true"
        >
            <!--  线-->
            <div v-if="zoom > 13">
                <bm-polyline :path="path" v-for="(path, index) in polyline" :key="index"></bm-polyline>
            </div>
            <!-- 变电站-->
            <template v-if="zoom > 13">
                <bm-marker
                    :position="path"
                    v-for="path in siteList"
                    :key="path.subId"
                    :icon="path.icon"
                    @click="markerClick(path)"
                ></bm-marker>
            </template>
            <!-- 点 -->
            <div :maxZoom="12" v-if="zoom > 9">
                <bm-marker
                    :position="path"
                    v-for="path in areaLineInfo"
                    :key="path.lineId"
                    :icon="path.icon"
                    @click="markerClick(path)"
                    :zIndex="1"
                >
                    <bm-label
                        v-if="zoom > 14"
                        :content="path.deviceName"
                        :labelStyle="{
                            color: '#fff',
                            border: '0px solid #fff',
                            backgroundColor: 'rgba(0, 0, 0, 0.5)',
                            borderRadius: '10px',
                            padding: '2px 5px',
                            fontSize: '12px',
                            lineHeight: '15px',
                            transform: 'translateX(-30%)'
                        }"
                        :offset="{ height: 33 }"
                    />
                </bm-marker>
            </div>
            <!-- 详情 -->
            <bm-marker :position="infoWindowPoint" :icon="{ url: '1', size: { width: 0, height: 0 } }">
                <bm-info-window :show="infoWindowPoint.show" @close="infoWindowPoint.show = false">
                    <el-descriptions
                        style="width: auto"
                        :title="infoWindowPoint.deviceName"
                        :column="1"
                        v-if="infoWindowPoint.lineId"
                    >
                        <el-descriptions-item label="供电公司">{{ infoWindowPoint.gdName }}</el-descriptions-item>
                        <el-descriptions-item label="变电站(场站)">{{ infoWindowPoint.subName }}</el-descriptions-item>
                        <el-descriptions-item label="网络参数">
                            {{ infoWindowPoint.ip }}
                        </el-descriptions-item>

                        <el-descriptions-item label="生产厂家">
                            {{ infoWindowPoint.manufacturer }}
                        </el-descriptions-item>

                        <el-descriptions-item label="通讯状态">
                            {{ infoWindowPoint.comFlag == 0 ? '中断' : '正常' }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions
                        :title="infoWindowPoint.subName"
                        :column="1"
                        v-else-if="infoWindowPoint.subId"
                        style="padding-top: 10px"
                    ></el-descriptions>
                </bm-info-window>
            </bm-marker>
            <!-- 行政区划 -->
            <div v-if="zoom <= 11">
                <div v-for="item in AreaData">
                    <bm-polygon
                        v-for="timeK in item.boundary"
                        :path="timeK"
                        :key="timeK"
                        :strokeWeight="2"
                        strokeColor="#0e8780"
                        :strokeOpacity="1"
                        :fillColor="item.background || ''"
                        :fillOpacity="0.6"
                    ></bm-polygon>
                </div>
            </div>

            <!-- 信息弹框 -->
            <!-- <div v-if="zoom <= 9">
                <bm-overlay
                    v-for="item in AreaData"
                    pane="labelPane"
                    :class="{ sample: true }"
                    @draw="draw($event, item.LngLat)"
                >
                    <div class="my-radiusPop" :style="{ background: item.background }">
                        <img :src="PopKey == 2 ? imgUrl2 : PopKey == 1 ? imgUrl1 : PopKey == 0 ? imgUrl0 : ''" />
                        <div class="infoBox">
                            <div>
                                总数
                                <br />
                                {{
                                    PopKey == 2
                                        ? item.lineNum
                                        : PopKey == 1
                                        ? item.deviceNum
                                        : PopKey == 0
                                        ? item.subNum
                                        : '/'
                                }}
                            </div>
                            <div>
                                {{ PopKey == 2 ? '在线' : PopKey == 1 ? '在运' : '告警' }}
                                <br />
                                {{
                                    PopKey == 2
                                        ? item.onlineNum
                                        : PopKey == 1
                                        ? item.alarmSubNum
                                        : PopKey == 0
                                        ? item.onDevice
                                        : '/'
                                }}
                            </div>
                            <div v-if="PopKey == 2">
                                告警
                                <br />
                                {{ PopKey == 2 ? item.alarm : PopKey == 1 ? item.xx : PopKey == 0 ? item.xx : '/' }}
                            </div>
                        </div>
                    </div>
                </bm-overlay>
            </div> -->
        </baidu-map>
    </div>
</template>

<script setup lang="ts">
import { mainHeight } from '@/utils/layout'
import { getAreaLineInfo } from '@/api/event-boot/areaInfo'
import { ref, reactive, onMounted } from 'vue'
import DatePicker from '@/components/form/datePicker/index.vue'
import { useDictData } from '@/stores/dictData'
import { Search } from '@element-plus/icons-vue'
import { BaiduMap, BmOverlay } from 'vue-baidu-map-3x'
import { getAssessOverview } from '@/api/device-boot/panorama'
import { getRunEvaluate } from '@/api/device-boot/runEvaluate'
import { getGridDiagramAreaData } from '@/api/device-boot/panorama'
const emit = defineEmits(['changeValue', 'drop', 'show'])
const props = defineProps({
    params: {
        type: Object,
        default: () => {}
    }
})
import mapJson from '@/views/pqs/panorama/components/boundary'
import jxMapJson from './jx'
const datePickerRef = ref()
const height = mainHeight(90)
// 页面中直接引入就可以
const dictData = useDictData()
const inputQuery: any = ref('')
const QueryList: any = ref([])
const activeName: any = ref(0)
const zoomMap = ref(8.9)
const colorKey = ref('')
const showCollapse: any = ref(true)
const showWrap: any = ref(false)
const deptIndex = ref(dictData.state.area[0].id)
const assessList: any = ref([])
const AreaData: any = ref([])
const PopKey: any = ref(2)
const imgUrl0 = new URL('@/assets/img/BDZ-ZS.png', import.meta.url).href
const imgUrl1 = new URL('@/assets/img/ZD-ZS.png', import.meta.url).href
const imgUrl2 = new URL('@/assets/img/JCD-ZS.png', import.meta.url).href
const boundaryList: any = ref([
    {
        orgName: '大连',
        LngLat: [122.060077, 39.635794],
        boundary: mapJson['大连']
    },
    {
        orgName: '抚顺',
        LngLat: [124.354599, 41.88962],
        boundary: mapJson['抚顺']
    },
    {
        orgName: '沈阳',
        LngLat: [123.0389, 41.992993],
        boundary: mapJson['沈阳']
    },
    {
        orgName: '丹东',
        LngLat: [124.585661, 40.645967],
        boundary: mapJson['丹东']
    },
    {
        orgName: '营口',
        LngLat: [122.225226, 40.433551],
        boundary: mapJson['营口']
    },
    {
        orgName: '盘锦',
        LngLat: [121.875362, 41.075416],
        boundary: mapJson['盘锦']
    },
    {
        orgName: '铁岭',
        LngLat: [124.229492, 42.731873],
        boundary: mapJson['铁岭']
    },
    {
        orgName: '朝阳',
        LngLat: [119.640944, 41.39657],
        boundary: mapJson['朝阳']
    },
    {
        orgName: '葫芦岛',
        LngLat: [119.850873, 40.728517],
        boundary: mapJson['葫芦岛']
    },
    {
        orgName: '锦州',
        LngLat: [121.42, 41.58],
        boundary: mapJson['锦州']
    },
    {
        orgName: '阜新',
        LngLat: [121.658585, 42.350951],
        boundary: mapJson['阜新']
    },
    {
        orgName: '本溪',
        LngLat: [124.390785, 41.197021],
        boundary: mapJson['本溪']
    },
    {
        orgName: '辽阳',
        LngLat: [123.090785, 41.297021],
        boundary: mapJson['辽阳']
    },
    {
        orgName: '鞍山',
        LngLat: [122.808845, 40.840049],
        boundary: mapJson['鞍山']
    },


    
    {
        orgName: '南昌',
        LngLat: [115.862285, 28.717589],
        boundary: jxMapJson['南昌']
    },
    {
        orgName: '九江',
        LngLat: [115.8287, 29.4315],
        boundary: jxMapJson['九江']
    },
    {
        orgName: '上饶',
        LngLat: [117.9434, 28.4576],
        boundary: jxMapJson['上饶']
    },
    {
        orgName: '抚州',
        LngLat: [116.3587, 27.9835],
        boundary: jxMapJson['抚州']
    },
    {
        orgName: '宜春',
        LngLat: [114.4168, 27.8155],
        boundary: jxMapJson['宜春']
    },
    {
        orgName: '吉安',
        LngLat: [114.9924, 27.1138],
        boundary: jxMapJson['吉安']
    },
    {
        orgName: '赣州',
        LngLat: [114.9359, 25.8458],
        boundary: jxMapJson['赣州']
    },
    { orgName: '景德镇', LngLat: [117.2148, 29.2926], boundary: jxMapJson['景德镇'] },
    {
        orgName: '萍乡',
        LngLat: [113.8547, 27.6228],
        boundary: jxMapJson['萍乡']
    },
    { orgName: '新余', LngLat: [114.9302, 27.8109], boundary: jxMapJson['新余'] },
    {
        orgName: '鹰潭',
        LngLat: [117.0356, 28.2413],
        boundary: jxMapJson['鹰潭']
    }
])

const zoom = ref(13)
const areaLineInfo = ref<any>([])
const siteList = ref<any>([])
const polyline = ref<any>([])
const lineId = ref('')
const center = ref({
    //lng: 115.64636, //江西
    //lat: 27.232634
     lng: 122.42588,//辽宁
     lat: 40.810977
})
const infoWindowPoint = ref<anyObj>({
    lng: 0,
    lat: 0,
    show: false
})
// 地图实例
const initMap = async ({ BMap, map }: any) => {}
// 加载点
const addMarkers = async (row?: any, key?: any, num?: any) => {
    let params = {
        deptIndex: props.params.deptIndex,
        monitorFlag: 2,
        powerFlag: 2,
        searchBeginTime: datePickerRef.value.timeValue[0],
        searchEndTime: datePickerRef.value.timeValue[1],
        serverName: 'event-boot',
        statisticalType: {},
        ...row
    }

    let { data } = await getAreaLineInfo(params)
    polyline.value = []
    areaLineInfo.value = []
    let r = 0.0035
    let list = filterUniqueDeviceNames(data.filter((item: any) => item.lng != 0))
    list.forEach((item: any) => {
        // 变电站图标
        item.icon = {
            url: new URL('@/assets/jcd.png', import.meta.url).href,
            size: {
                width: 40,
                height: 40
            }
        }
        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.icon = {
                url: '',
                size: {
                    width: 35,
                    height: 30
                }
            }
            switch (val.runFlag) {
                case 0:
                    val.icon.url = new URL('@/assets/terminal0.png', import.meta.url).href
                    break
                case 1:
                    val.icon.url = new URL('@/assets/terminal1.png', import.meta.url).href
                    break
                case 2:
                    val.icon.url = new URL('@/assets/terminal2.png', import.meta.url).href
                    break
                default:
                    break
            }
            polyline.value.push([
                {
                    lng: item.lng,
                    lat: item.lat
                },
                {
                    lng: val.lng,
                    lat: val.lat
                }
            ])
        })

        areaLineInfo.value.push(...item.children)
    })
    siteList.value = list
    // center.value.lng = areaLineInfo.value[0].lng
    // center.value.lat = areaLineInfo.value[0].lat
}
// 过滤终端
const filterUniqueDeviceNames = data => {
    return data.map(item => {
        const uniqueChildren = item.children.reduce((acc, curr) => {
            if (!acc.some(child => child.deviceName === curr.deviceName)) {
                acc.push(curr)
            }
            return acc
        }, [])
        return {
            ...item,
            children: uniqueChildren
        }
    })
}
// 获取zoom
const syncCenterAndZoom = (e: any) => {
    zoom.value = e.target.getZoom()
}
const locatePositions = (e: any) => {
    deptIndex.value = e.data.id
    // 加载点
    addMarkers()

    // powerManageGridMap.value.drillDown({
    //     // 判断超高压
    //     orgId: e.data.code == '1100F3DE246A6FADE050007F01006CBE' ? '1100F3DE20806FADE050007F01006CBE' : e.data.code,
    //     onlyDisplay: true
    // })
}
// 点击点
const markerClick = (e: any) => {
    showCollapse.value = false
    infoWindowPoint.value = e
    infoWindowPoint.value.show = true
}
// 查看详情
const lookPoint = (e: any) => {
    emit('drop', e.lineId)
    emit('show', true)
}
// 搜索
const DeviceQ = () => {
    
    showCollapse.value = true
    if (inputQuery.value.length == 0) return

    let list = []
    let regex = new RegExp(inputQuery.value, 'i')
    let data = areaLineInfo.value
        .filter((item: any) => regex.test(item.deviceName))
        .map((item: any) => {
            return {
                psrName: item.deviceName,
                vlevelName: item.voltageScale,
                maintOrgName: item.gdName,
                coordinate: [item.lng, item.lat]
            }
        })
    // data.replace(//s/g,',')

    if (data.length > 0) {
        list.push({
            count: data.length,
            psrList: data,
            psrName: '监测点'
        })
    }
    QueryList.value = list
    showWrap.value = true
}

// 定位
const flyTo = (e: any, zoom?: number) => {
   // console.log('🚀 ~ flyTo ~ e:', e)
    let regex = new RegExp(e.psrName, 'i')
    center.value.lng = e.coordinate[0]
    center.value.lat = e.coordinate[1]
    if (zoom) {
        zoomMap.value = zoom
    } else {
        zoomMap.value = 15
        let data = areaLineInfo.value.filter((item: any) => regex.test(item.deviceName))[0]
        if (data) {
            markerClick(data)
        }
    }
}
// 市级统计数据
const grids = (row: any) => {
    AreaData.value = []
    // 综合评估

    getRunEvaluate({ ...row, deptIndex: props.params.deptIndex }).then((res: any) => {
       // console.log('🚀 ~ getRunEvaluate ~ res:', res)
        AreaData.value = res.data
        GridDiagramArea()
    })
    // if (powerManageGridMap.value) powerLoad()
}
const radiusPop = (k: any) => {
   // console.log('🚀 ~ radiusPop ~ k:', k)
    if (k != undefined) PopKey.value = k
}
const GridDiagramArea = () => {
    boundaryList.value.forEach((item: any) => {
        AreaData.value.forEach((k: any, i: any) => {
            if (item.orgName == k.name) {
                for (let kk in item) {
                    k[kk] = item[kk]
                }
                if (k.evaluate >= 90) {
                    k.background = '#00b07d'
                } else if (k.evaluate >= 80) {
                    k.background = '#2b7fd3'
                } else if (k.evaluate >= 70) {
                    k.background = '#ff8c00'
                } else {
                    k.background = '#c00'
                }
            }
        })
    })
    AreaData.value = AreaData.value.filter((item: any) => item.orgName != '超高压' && item.orgName != '风光储')
    setTimeout(() => {
        // radiusPop()
    }, 0)
}
// 市级统计
const draw = ({ el, BMap, map }, val) => {
    const pixel = map.pointToOverlayPixel(new BMap.Point(val[0], val[1]))
    el.style.left = pixel.x - 60 + 'px'
    el.style.top = pixel.y - 20 + 'px'
}
// 重置
const reset = () => {
    inputQuery.value = ''
    showWrap.value = false
}
onMounted(() => {})
defineExpose({ addMarkers, locatePositions, reset, grids, radiusPop, flyTo })
</script>
<style lang="scss" scoped>
@use '@/views/pqs/qualityInspeection/panorama/components/style/map.scss';

.map {
    width: 100%;
}

.query-box-wrap {
    z-index: 1;
}

:deep(.el-collapse-item__content) {
    padding-bottom: 0px !important;
}

.sample {
    position: absolute;

    .my-radiusPop {
        width: 200px;
        height: 50px;
        border-radius: 5px;
        background: rgba(0, 0, 0, 0.5);
        overflow: hidden;
        // box-shadow: 0 0 5px #000;
        color: #fff;
        text-align: center;
        padding: 5px 5px !important;
        display: flex;

        img {
            height: 40px;
            margin-right: 10px;
        }

        .infoBox {
            flex: 1;
            display: flex;
            justify-content: space-around;
            text-align: center;

            div {
                cursor: pointer;
            }
        }
    }
}
:deep(.el-descriptions__cell) {
    white-space: nowrap;
}
</style>
