<template>
    <page-container>
        <div ref="mapRef" :style="{ width: '100%', height: 'calc(100vh - 118px)' }" id="map"></div>
    </page-container>
</template>
<script lang="ts" setup name="gisHome">
import bg from '/images/bind/bdt.png';
import "leaflet/dist/leaflet.css";
import * as L from 'leaflet';
import { LatLngBoundsExpression, Layer, LayerGroup, Map } from 'leaflet';
import { treeList, monitorTypeOptions, RealTimeData, monitorNode, AlarmData } from '@/views/gis/data.ts';
import { deviceIcons, stateIcons } from '@/assets/diviceIcon';
import { message, notification, List, ListItem, ListItemMeta, Avatar, Button, Row, Col, Table, Badge } from 'jetlinks-ui-components';
import { useResizeObserver } from '@/components/Metadata/Table/hooks/useResizeObserver.ts'

import { useMenuStore } from 'store/menu';
const menuStory = useMenuStore();
const url = ref<string>(bg)
const mapRef = ref();
const map = ref<Map>()
const markers = ref<LayerGroup>()
const mapMonitorList = ref<monitorNode[]>(RealTimeData)
const checkMonitorList = ref<{ id: string, monitorName: string, monitorType: number }[]>([]);

//初始化画板
const loadMap = () => {
    const element = mapRef.value;
    const width = element.offsetWidth;
    const height = element.offsetHeight;
    const imageBounds: LatLngBoundsExpression = [[0, 0], [height, width]];
    if (map.value) {

    } else {
        map.value = L.map('map', {
            crs: L.CRS.Simple,
            minZoom: -1,
            maxZoom: 3,
            center: [-1, -1],
            zoom: -1,
            //zoomSnap: 0.1,
            maxBounds: [[-20, 10], [height, width]],
            attributionControl: false,//默认情况下，是否将 attribution 版权控件添加到地图中。
            zoomControl: false,//默认情况下，是否将 zoom 缩放控件添加到地图中。
            doubleClickZoom: false,//禁用双击放大
        });
        L.imageOverlay(url.value, imageBounds,).addTo(map.value);
        map.value.setMaxBounds(imageBounds);
        markers.value = L.layerGroup();
        map.value.addLayer(markers.value);
        map.value.on('dblclick', () => {
            map.value?.setZoom(-1)
        })
    }
}
// 定义 renderItem 函数
const renderItem = ({ item }:{ item: {id: string;
    monitorName: string;} }) => {
    return h(ListItem, null, {
        default: () => h(ListItemMeta, { description: '' }, {
            title: () => h('p', {}, item.monitorName),
            avatar: () => h(Avatar, { src: deviceIcons[item.monitorType] })
        })
    });
};
const createAlarmTable = () => {
    if (AlarmData.length) {
        notification.open({
            key: 2,
            message: '报警列表',
            placement: 'topRight',
            duration: null,
            description: alarmTableRender(),
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    }
};
const alarmTableRender = () => {
    const slotProps = (record) => ({
        state: record.state,
    });
    return h(Table, {
        size: 'small',
        bordered: true,
        columns: [
            { title: '监测点', dataIndex: 'monitorName' },
            { title: '告警详情', dataIndex: 'info', ellipsis: true, },
            { title: '状态', width: 60, scopedSlots: true, dataIndex: 'state', key: 'state', },
        ],
        dataSource: AlarmData,
    }, {
        state: (scope) => {
            const { record } = scope;
            const props = slotProps(record);
            return h(Badge, {
                status: 'error',
            });
        },
    })
};
const notificationRender = () => {
    return h('div', [
        h(List, {
            itemLayout: 'horizontal',
            size: 'small',
            dataSource: checkMonitorList.value,
            class: 'map-tree-content-card-list'
        }, {
            renderItem: ({ item }) => renderItem({ item }),//() => h(Button, { type: 'primary', onClick: () => { notification.close(1) } }, { default: () => '关闭' })
            footer: () => h(Row, { gutter: 20 }, [
                h(Col, { span: 12 }, [h(Button, {
                    type: 'primary', style: { width: '100%' }, onClick: () => {
                        notification.close(1);
                        menuStory.jumpPage('gis/RealTime/Graph', { id: ':id' });
                    }
                }, '实时图谱'),]),
                h(Col, { span: 12 }, [h(Button, {
                    type: 'primary', style: { width: '100%' }, onClick: () => {
                        notification.close(1);
                        menuStory.jumpPage('gis/History', { id: ':id' });
                    }
                }, '历史趋势'),])
            ])
        }),
    ])
};
//渲染监测点
const createMarkers = (info: monitorType): MarkerType => {
    let { id, name, monitorType, deviceNum, deviceIp, devicePort, positionX, positionY, monitorName, value, state } = info

    const x = parseFloat(positionX as string);
    const y = parseFloat(positionY as string);
    let text = Object.keys(value).map(key => `<p>${key}:${value[key]}</p>`);
    text.unshift(`<p>${monitorName}</p>`);
    text = text.join('');
    const marker: MarkerType = L.marker(
        [y, x], {
        icon: L.icon({
            iconUrl: deviceIcons[monitorType],
            iconSize: [30, 30],
            shadowUrl: stateIcons[state.value],
            shadowSize: [15, 15],
            shadowAnchor: [-12, 24]
        }),
        draggable: true,//开启拖拽
    })
    marker.markerId = id
    marker.bindTooltip(text, {
        permanent: true, // 永久显示提示
        direction: 'top',// 提示显示的方向
        offset: L.point(0, -10)
    });


    // 添加 click 事件监听器
    marker.on('click', (event) => {
        if (event.originalEvent.ctrlKey) {
            console.log(List, ListItem, Button)
            const index = checkMonitorList.value.findIndex(i => i == id)
            if (index === -1) {
                if (checkMonitorList.value.length == 4) {
                    message.warning('最多选择6个监测点');
                    return
                } else {
                    checkMonitorList.value.push({ id, monitorName, monitorType })
                    marker.setIcon(L.icon({ ...marker.getIcon().options, shadowUrl: stateIcons['selected'], shadowSize: [20, 20], }));
                    notification.open({
                        key: 1,
                        message: '快捷操作',
                        placement: 'bottomLeft',
                        duration: null,
                        description: notificationRender(),
                        onClick: () => {
                            console.log('Notification Clicked!');
                        },
                    });
                }

            } else {
                checkMonitorList.value.splice(index, 1)
                marker.setIcon(L.icon({ ...marker.getIcon().options, shadowUrl: stateIcons[state.value], shadowSize: [15, 15], }))
            }

            // 在这里添加你需要执行的操作
        }
    });
    return marker
}
//窗口变化跟踪
const handleResize = (rect, e) => {
    //map.value.invalidateSize()
    //map.value.setMaxBounds([-100, -100],[ rect.height,rect.width]);
    console.log(rect, e)
}
useResizeObserver(mapRef, handleResize)
onMounted(() => {
    loadMap();
    window.addEventListener('resize', handleResize);
    createAlarmTable();
    mapMonitorList.value.forEach((i: monitorType) => {
        if (i.positionX) {
            markers.value?.addLayer(createMarkers(i))
        }
    })
})
onBeforeUnmount(() => {
    notification.close(2);
    window.removeEventListener('resize', handleResize)
})

</script>

<style lang="less">
.leaflet-container {
    background-color: #fff;
}
</style>
