<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" @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" :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>
            <!-- 点 -->
            <BmlMarkerClusterer 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.lineName"
                        :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>
            </BmlMarkerClusterer>
            <!-- 详情 -->
            <bm-marker :position='infoWindowPoint' :icon="{ url: '1', size: { width: 0, height: 0 } }">
                <bm-info-window :show='infoWindowPoint.show' @close='infoWindowPoint.show = false'>
                    <el-descriptions :title='infoWindowPoint.lineName' :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.voltageName }}</el-descriptions-item>
                        <el-descriptions-item label='网络参数'>
                            {{ infoWindowPoint.ip }}
                        </el-descriptions-item>
                        <el-descriptions-item label='PT变化'>{{ infoWindowPoint.pt2 }}</el-descriptions-item>
                        <el-descriptions-item label='CT变化'>{{ infoWindowPoint.ct2 }}</el-descriptions-item>
                        <el-descriptions-item label='生产厂家'>
                            {{ infoWindowPoint.manufacturer }}
                        </el-descriptions-item>
                        <el-descriptions-item label='终端状态'>
                            {{
                                infoWindowPoint.runFlag == 0 ? '投运' : infoWindowPoint.runFlag == 1 ? '热备用' : '停运'
                            }}
                        </el-descriptions-item>
                        <el-descriptions-item label='通讯状态'>
                            {{ infoWindowPoint.comFlag == 0 ? '中断' : '正常' }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <el-button type='primary' size='small' @click='lookPoint(infoWindowPoint)'>查看详情</el-button>

                        </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>
            <!-- 行政区划 -->
            <!-- <bm-boundary v-for="item in boundaryList" :name="item.name" :strokeWeight="2" strokeColor="#0e8780"
                fillColor="#0e8780" fillOpacity="0.05"></bm-boundary> -->


        </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, BmBoundary, BmPolygon } from 'vue-baidu-map-3x'
const emit = defineEmits(['changeValue', 'drop', 'show'])

const datePickerRef = ref()
const height = mainHeight(20)
// 页面中直接引入就可以
const dictData = useDictData()
const inputQuery: any = ref('')
const QueryList: any = ref([])
const activeName: any = ref(0)
const zoomMap = ref(9)
const colorKey = ref('')
const showCollapse: any = ref(true)
const showWrap: any = ref(false)
const deptIndex = ref(dictData.state.area[0].id)

const boundaryList = ref([
    { name: '张家口市' },
    { name: '唐山市' },
    { name: '秦皇岛市' },
    { name: '承德市' },
    { name: '廊坊市' },
])

const zoom = ref(13)
const areaLineInfo = ref<any>([])
const siteList = ref<any>([])
const polyline = ref<any>([])
const lineId = ref('')
const center = ref({
    lng: 116.403765, lat: 39.914850
})
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: 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)
    polyline.value = []
    areaLineInfo.value = []
    let r = 0.0035
    let list = 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: 40,
                    height: 40
                }
            }
            switch (val.runFlag) {
                case 0:
                    // 投运
                    if (val.comFlag == 0) {
                        // 异常
                        if (val.noDealCount > 0) {
                            // 异常有暂降
                            val.icon.url = new URL('@/assets/txycyzj.gif', import.meta.url).href
                        } else if (val.noDealCount == 0) {
                            // 异常无暂降
                            val.icon.url = new URL('@/assets/txzdwzj.png', import.meta.url).href
                        }
                    } else if (val.comFlag == 1) {
                        // 正常
                        if (val.noDealCount > 0) {
                            // 正常有暂降
                            val.icon.url = new URL('@/assets/txzcyzj.gif', import.meta.url).href
                        } else if (val.noDealCount == 0) {
                            // 正常无暂降
                            val.icon.url = new URL('@/assets/txzcwzj.png', import.meta.url).href
                        }
                    }
                    break
                case 1:
                    val.icon.url = new URL('@/assets/rby.png', import.meta.url).href
                    break
                case 2:
                    val.icon.url = new URL('@/assets/ty.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


}
// 获取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.lineName))
        .map((item: any) => {
            return {

                psrName: item.lineName,
                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) => {
    console.log("🚀 ~ flyTo ~ e:", e)
    let regex = new RegExp(e.psrName, 'i')
    center.value.lng = e.coordinate[0]
    center.value.lat = e.coordinate[1]
    zoomMap.value = 15
    let data = areaLineInfo.value.filter((item: any) => regex.test(item.lineName))[0]
    if (data) {
        markerClick(data)
    }


}
// 重置
const reset = () => {
    inputQuery.value = ''
    showWrap.value = false
}
onMounted(() => {
})
defineExpose({ addMarkers, locatePositions, reset })
</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;
}

// @use '@/views/pqs/panorama/components/style/map.scss';</style>
