<template>
    <j-spin :spinning="loading">
        <div class="dash-board">
            <div class="header">
                <div class="left">
                    <j-tree-select showSearch v-model:value="monitorIds" placeholder="请选择监测点" :tree-data="treeList"
                        @change="valueChange" allow-clear :max-tag-count="2" :height="233" multiple
                        :style="{ width: '400px' }" :fieldNames="{
                            label: 'name',
                            value: 'id',
                            children: 'children',
                        }" :filterTreeNode="(v: string, option: any) => filterSelectNode(v, option, 'name')
                            ">
                        <template #tagRender="{ label, closable, onClose, option }">
                            <a-tag :closable="closable" style="margin-right: 3px" @close="onClose">
                                <j-tooltip placement="top" :title="label">
                                    {{ label }}
                                </j-tooltip>
                            </a-tag>
                        </template>
                    </j-tree-select>
                </div>
                <div class="right">
                    <j-radio-group default-value="a" button-style="solid" style="margin-right: 10px"
                        v-model:value="data.time.type">
                        <j-radio-button value="hour">
                            最近1小时
                        </j-radio-button>
                        <j-radio-button value="day">
                            最近24小时
                        </j-radio-button>
                        <j-radio-button value="week"> 近一周 </j-radio-button>
                    </j-radio-group>
                    <j-range-picker :allowClear="false" :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss"
                        v-model:value="data.time.time" @change="pickerTimeChange">
                        <template #suffixIcon>
                            <AIcon type="CalendarOutlined" />
                        </template>
                    </j-range-picker>
                </div>
            </div>
            <div>
                <j-empty v-if="isEmpty" style="margin-top: 100px" />
                <template v-else>
                    <div style="height: calc(100vh - 232px)" :style="{ minHeight: `${echartsMinHeight * 200}px` }">
                        <Echarts :options="echartsOptions" />
                    </div>
                </template>
            </div>
        </div>
    </j-spin>
</template>

<script lang="ts" setup name="Network">
import { filterSelectNode, onlyMessage } from '@/utils/comm';
import { dashboard } from '@/api/link/dashboard';
import {
    getTimeByType,
    typeDataLine,
    areaStyle,
    colorNetwork,
    networkParams,
    arrayReverse,
} from './tool.ts';
import dayjs from 'dayjs';
import { DataType } from '../typings.d';
import ServerList from './ServerList.vue';
import Echarts from './echarts.vue';
import { TreeNode } from '../../Site/type.d.ts';
import { Ref } from 'vue';
import { minHeight } from '../data.js';
import { method } from 'lodash-es';
const props = defineProps({
    serviceId: {
        type: String,
        default: undefined,
    },
});
const innerWidth = ref<number>(window.innerWidth)
const monitorIds = ref<string[]>(['GIS1-1-1-1', 'TX1-1-1-1', 'GIS1-1', 'GIS1-6', 'GIS2-1-1-1', 'TX2-1-1-1-s']);
const monitorNames = ref<string[]>(['GIS东1站监测', '铁芯东1站监测', 'GIS东站监测', 'GIS西站监测', 'GIS东2站监测', '铁芯东2站监测']);
const treeList: Ref<TreeNode[]> = ref([
    {
        name: '站点1',
        id: 'global_role',
        disabled: true,
        children: [
            {
                name: '站点1-1',
                disabled: true,
                id: 'global_role1-1',
                children: [
                    {
                        name: 'GIS监测',
                        id: 'GIS1-1-1',
                        disabled: true,
                        children: [
                            {
                                name: 'GIS东1站监测',
                                id: 'GIS1-1-1-1',
                                children: [],
                                level: 2,
                                positionX: 53.968072270519315,
                                positionY: 835.9531405092218
                            },
                        ],
                        level: 1,
                    },
                    {
                        name: '铁芯监测',
                        id: 'GIS1-1-2',
                        disabled: true,
                        children: [
                            {
                                name: '铁芯东1站监测',
                                id: 'TX1-1-1-1',
                                children: [],
                                level: 2,
                            },
                        ],
                        level: 1,
                    },
                ],
                level: 1,
            },
            {
                name: 'GIS东站监测',
                id: 'GIS1-1',
                children: [],
                level: 2,
                positionX: 193.968072270519315,
                positionY: 835.9531405092218
            },
            {
                name: 'GIS西站监测',
                id: 'GIS1-6',
                children: [],
                level: 2,
                positionX: 193.968072270519315,
                positionY: 735.9531405092218
            },
        ],
        type: 'root',
        level: 1,
    },
    {
        name: '站点2',
        disabled: true,
        id: 'global_role1sss',
        children: [
            {
                name: '站点2-1',
                disabled: true,
                id: 'global_role1-2',
                children: [
                    {
                        name: 'GIS监测',
                        id: 'GIS1-2-1',
                        disabled: true,
                        children: [
                            {
                                name: 'GIS东2站监测',
                                id: 'GIS2-1-1-1',
                                children: [],
                                level: 2,
                            },
                        ],
                        level: 1,
                    },
                    {
                        name: '铁芯监测',
                        id: 'GIS1-2-2-2',
                        disabled: true,
                        children: [
                            {
                                name: '铁芯东2站监测',
                                id: 'TX2-1-1-1-s',
                                children: [],
                                level: 2,
                            },
                        ],
                        level: 1,
                    },
                ],
                level: 1,
            },
        ],
        type: 'root',
        level: 1,
    },
]);

const valueChange = (value: string, label: string[]) => {
    monitorNames.value = label;
};

const loading = ref(false);
const data = ref<DataType>({
    type: 'bytesRead',
    time: {
        type: 'hour',
        time: [null, null],
    },
});
const isEmpty = ref(false);

const pickerTimeChange = (value: any) => {
    data.value.time.type = undefined;
    //getNetworkEcharts(data.value);
};

const handleNetworkOptions = (optionsData: any, xAxis: any) => {
    // const dataKeys = Object.keys(optionsData);
    // serverActive.value = dataKeys;
    // serverOptions.value = dataKeys;
    // serverData.xAxis = xAxis;
    // serverData.data = optionsData;
};
const echartsMinHeight = computed(() => {
    return monitorIds.value.length || 1
})
const calculateGridPercentages = (rows: number, cols: number, elementsCount: number) => {
    let percentages: { height: number; top: number; left: number; width: number; }[] = [];
    let currentRow = 0;
    let top = 0;
    const left = 0;
    let height = 100;
    const width = 100;
    let index = 1;
    for (let i = 0; i < elementsCount; i++) {
        percentages.push({
            top,
            left,
            width,
            height
        });
        // Move to the next row as needed
        currentRow++;
        if (currentRow >= rows) {
            top = (index / cols) * 100;
            height = (1 / cols) * 100;
            percentages = percentages.map(i => ({ ...i, height }))
            currentRow = 0;
            index++;
        }
    }
    console.log(percentages)
    return percentages;
};
const getRandomInt = (min: number, max: number): number => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
const setOptions = (): any => {
    const legend = ['脉冲平均值', '噪声平均值', '最大值', '脉冲频次', '放电相位', '事件数'];

    const initOptions: any = {
        title: {
            show:false,
            text: '监测点',   //获取间隔名称
            subtextStyle: {
                color: '#92A3A8'
            },
            left: '10%',
            top: 0,
            textStyle: {
                fontSize: 12,
                color: '#92A3A8'
            }
        },

        grid: {
            id: 0,
            // top: '50px',
            // left: '180px',
            right: '0',
            bottom: '0',
            containLabel: true,
            // show: true,
            // shadowColor: 'rgba(0, 0, 0, 0.5)',
            // shadowBlur: 10
        },
        xAxis: {
            type: 'category',
            name: 'time',
            axisLine: {
                show: false,
            },
            axisLabel: { //调整x轴的lable
                textStyle: {
                    color: '#92A3A8'
                }
            },
        },
        yAxis: [
            {
                boundaryGap: [0, '50%'],
                axisLine: {
                    lineStyle: {
                        color: '#fff',
                    }
                },
                splitLine: {
                    show: false
                },
                type: 'value',
                name: '脉冲频次(次)',
                position: 'right',
                offset: -80,
                // axisTick: {
                //     inside: 'false',
                //     length: 10
                // },
                axisLine: {
                    lineStyle: {
                        color: '#92A3A8'
                    }
                },
                axisPointer: {
                    label: {
                        formatter: function (param) { return parseInt(param.value) }
                    }
                },
            },
            {
                boundaryGap: [0, '0%'],
                axisLine: {
                    lineStyle: {
                        color: '#92A3A8'
                    }
                },
                type: 'value',
                name: '相位(度)',
                position: 'right',
                offset: -22,
                splitNumber: 10,
                axisLabel: {
                    formatter: '{value}',
                    textStyle: {
                        color: '#92A3A8'
                    }
                },
                splitLine: {
                    show: false
                },
                axisPointer: {
                    label: {
                        formatter: function (param) { return parseInt(param.value) }
                    }
                },
            },
            {
                boundaryGap: [0, 0],
                axisLine: {
                    lineStyle: {
                        color: '#92A3A8'
                    }
                },
                splitLine: {
                    show: false,
                },

                type: 'value',
                name: '幅值(dBm)',
                position: 'left',
                offset: -3,
                axisLabel: {
                    formatter: '{value}'
                },
                min: -80,
                max: 0,
                axisPointer: {
                    label: {
                        formatter: function (param) { return parseInt(param.value) }
                    },
                },
            },
            {
                boundaryGap: [0, 0],
                axisLine: {
                    lineStyle: {
                        color: '#92A3A8'
                    }
                },
                splitLine: {
                    show: false,
                },
                type: 'value',
                name: '事件数(次)',
                position: 'left',
                offset: -60,
                axisLabel: {
                    formatter: '{value}'
                },
                axisPointer: {
                    label: {
                        formatter: function (param) { return parseInt(param.value) }
                    }
                },
            }
        ],
        legend: {
            left: '0',
            top: '50px',
            type: 'scroll',
            //orient: 'vertical',
            data: legend,
            textStyle: {
                color: "#92A3A8",
                fontsize: 5
            },
            selected: {

            },
            type: 'scroll',
            width: '100%'
        },
        series: [
            {
                name: '脉冲平均值',
                type: 'line',
                showSymbol: false,
                method:()=>getRandomInt(-80,0),
                data: [],
                yAxisIndex: 2,
                xAxisIndex: 0,
                smooth: true,
                lineStyle: {
                    width: 1,
                }
            },
            {
                name: '噪声平均值',
                type: 'line',
                showSymbol: false,
                method:()=>getRandomInt(-80,0),
                data: [],
                yAxisIndex: 2,
                xAxisIndex: 0,
                smooth: true,
                lineStyle: {
                    width: 1,
                }
            },
            {
                name: '最大值',
                type: 'line',
                showSymbol: false,
                method:()=>getRandomInt(-80,0),
                data: [],
                yAxisIndex: 2,
                xAxisIndex: 0,
                smooth: true,
                lineStyle: {
                    width: 1,
                }
            },
            {
                name: '脉冲频次',
                type: 'line',
                showSymbol: false,
                method:()=>getRandomInt(1000,3000),
                data: [],
                yAxisIndex: 0,
                xAxisIndex: 0,
                smooth: true,
                lineStyle: {
                    width: 1,
                }
            },
            {
                name: '放电相位',
                type: 'line',
                showSymbol: false,
                method:()=>getRandomInt(0,256),
                data: [],
                yAxisIndex: 1,
                xAxisIndex: 0,
                smooth: true,
                lineStyle: {
                    width: 1,
                }
            },
            {
                name: '事件数',
                type: 'line',
                smooth: true,
                showSymbol: false,
                method:()=>getRandomInt(10,60),
                data: [],
                yAxisIndex: 3,
                xAxisIndex: 0,
                lineStyle: {
                    width: 1,
                }
            }
        ],
        toolbox: {
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        axisPointer: {
            link: [
                {
                    xAxisIndex: 'all',
                }
            ],
            label:{
                formatter: ()=>{}
            }
        },
    }
    if (monitorIds.value.length > 0) {
        // >=1200 ,一行最多3个  >=768,一行最多2个 小于768 一行一个echarts
        const maxColumns = 1//innerWidth.value >= 1200 ? 3 : (innerWidth.value >= 768 ? 2 : 1);
        const length = monitorIds.value.length;
        const hCount = echartsMinHeight.value;
        const gridOptions = calculateGridPercentages(maxColumns, hCount, length)
        initOptions['title'] = monitorNames.value.map((text, index) => ({
            ...initOptions.title,
            text,
            left:'10%',
            top: gridOptions[index].top +  + '%',
        }));
        initOptions['grid'] = monitorIds.value.map((item, index) => ({
            left: '0%',
            top: gridOptions[index].top + 5 + '%',
            width: gridOptions[index].width + '%',
            height: gridOptions[index].height - 4 + '%',
            containLabel: true,
            show: true,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
            shadowBlur: 10
        }))
        initOptions['xAxis'] = monitorIds.value.map((item, index) => ({
            ...initOptions.xAxis,
            gridIndex: index,
        })); 
        initOptions['toolbox'] = monitorIds.value.map((item, index) => ({
            ...initOptions.toolbox,
            top: gridOptions[index].top +  + '%',
            gridIndex: index,
        })); 
        initOptions['legend'] = monitorIds.value.map((item, index) => ({
            ...initOptions.legend,
            left: 'center',
            top: gridOptions[index].top+ 5 + '%',
            width: '80%',
            gridIndex: index,
        }))
        initOptions['axisPointer'].label.formatter = (param) =>  monitorNames.value[param.axisIndex] + '\n' + param.value
        const yAxis: any[] = []
        const series: any[] = []
        const timeData = [
            ["2024-03-01 13:59:21",-75.525],
            ["2024-03-01 13:59:22",-72.525],
            ["2024-03-01 13:59:23",-76.525],
            ["2024-03-01 13:59:24",-71.525],
            ["2024-03-01 13:59:25",-74.525],
            ["2024-03-01 13:59:26",-72.525],
            ["2024-03-01 13:59:27",-76.525],
            ["2024-03-01 13:59:28",-72.525],
            ["2024-03-01 13:59:29",-79.525],
            ["2024-03-01 13:59:30",-76.525],
            ["2024-03-01 13:59:31",-74.525],
            ["2024-03-01 13:59:32",-78.525],
        ];
        monitorIds.value.map((item, index) => {
            const arr = initOptions.yAxis.map((i: any) => ({ ...i, gridIndex: index }))
            yAxis.push(...arr)
        })
        initOptions['yAxis'] = yAxis
        monitorNames.value.map((text, index) => {
            const arr = initOptions.series.map((i: any,id) => ({
                ...i,
                xAxisIndex: index,
                yAxisIndex: index*4 + i.yAxisIndex,
                data: timeData.map((it: any[]) => ([it[0],i.method()]) )
            }))
            series.push(...arr)
        })
        initOptions['series'] = series;
    }
    else if (monitorIds.value.length == 1) {
        initOptions['title'].text = monitorNames.value[0]
    }
    return initOptions
};

const echartsOptions = computed(() => {
    const { title, grid, xAxis, yAxis, series, legend,axisPointer,toolbox } = setOptions();

    return {
        title,
        backgroundColor: '#fff',
        color: ['#FF7D00', '#FFC300', '#37E2E2', '#165DFF', '#722ED1','#313CA9', '#21CCFF', '#249EFF', '#86DF6C', '#979AFF','#246EFF', '#00B2FF', '#81E2FF', '#2CAB40', '#8D4EDA'],
        tooltip: {
            trigger: 'axis',
            //trigger: 'item',
            position:function (point, params, dom, rect, size) {
                // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
                // 提示框位置
                var x = 0; // x坐标位置
                var y = 0; // y坐标位置
                
                // 当前鼠标位置
                var pointX = point[0];
                var pointY = point[1];
                
                // 外层div大小
                // var viewWidth = size.viewSize[0];
                // var viewHeight = size.viewSize[1];
                
                // 提示框大小
                var boxWidth = size.contentSize[0];
                var boxHeight = size.contentSize[1];
                
                // boxWidth > pointX 说明鼠标左边放不下提示框
                if (boxWidth > pointX) {
                    x = 5;
                } else { // 左边放的下
                    x = pointX - boxWidth;
                }
                
                // boxHeight > pointY 说明鼠标上边放不下提示框
                if (boxHeight > pointY) {
                    y = 5;
                } else { // 上边放得下
                    y = pointY - boxHeight;
                }
                
                return [x, y];
            },
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#92A3A8'
                }
            }
        },
        toolbox,
        legend,
        dataZoom: [{
            show: false,
            realtime: true,
            start: 0,
            end: 100,
            // backgroundColor:'#d'
            textStyle: {
                color: "#92A3A8"
            },
        }, {
            type: 'inside',
            realtime: true,
            start: 5,
            end: 85
        }],
        axisPointer,
        grid,
        xAxis,
        yAxis,
        series
    };
});

onMounted(() => {
    window.addEventListener('resize', () => { innerWidth.value = window.innerWidth })
})

onUnmounted(() => {
    window.removeEventListener('resize', () => { })
})

watch(
    () => data.value.time.type,
    (value) => {
        if (value === undefined) return;
        const date = getTimeByType(value);
        data.value.time.time = [dayjs(date), dayjs(new Date())];

        //getNetworkEcharts(data.value);
    },
    { immediate: true, deep: true },
);
</script>

<style lang="less" scoped>
.dash-board {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 24px;
    background-color: #fff;
    // box-shadow: 0px 2.73036px 5.46071px rgba(31, 89, 245, 0.2);
    border-radius: 2px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left h3 {
        width: 200px;
        margin-top: 8px;
    }
}

.left,
.right {
    display: flex;
    align-items: center;
}
</style>: { value: string; }: { value: string; }: { value: string; }: { value: string; }(: any): { value: string; }: {
value: string; }: { value: string; }: { value: string; }(: any)
