<template>
    <div>
        <!--指标越限程度 -->
        <TableHeader
            ref="TableHeaderRef"
            :showReset="false"
            @selectChange="selectChange"
            datePicker
            :timeKeyList="prop.timeKey"
            v-if="fullscreen"
        ></TableHeader>
        <my-echart
            class="tall"
            :options="echartList"
            :style="{ width: prop.width, height: `calc(${prop.height} / 2 )` }"
        />
        <Table
            ref="tableRef"
            @cell-click="cellClickEvent"
            :height="`calc(${prop.height} / 2 - ${headerHeight}px + ${fullscreen ? 0 : 56}px )`"
            isGroup
        ></Table>
        <!-- 指标日趋势图 -->
        <DailyTrendChart v-if="dialogTrendChart" ref="dailyTrendChartRef" @close="dialogTrendChart = false" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { getTimeOfTheMonth } from '@/utils/formatTime'
import DailyTrendChart from '@/components/cockpit/exceedanceLevel/components/dailyTrendChart.vue'
import { getTime } from '@/utils/formatTime'

const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: Array as () => string[] },
    timeValue: { type: Object },
    interval: { type: Number }
})

const TableHeaderRef = ref()

const headerHeight = ref(57)

const dialogTrendChart = ref(false)

const selectChange = (showSelect: any, height: any, datePickerValue?: any) => {
    headerHeight.value = height

    if (datePickerValue && datePickerValue.timeValue) {
        // 更新时间参数
        tableStore.table.params.searchBeginTime = datePickerValue.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerValue.timeValue[1]
    }
}
// 计算是否全屏展示
const fullscreen = computed(() => {
    const w = Number(prop.w)
    const h = Number(prop.h)
    if (!isNaN(w) && !isNaN(h) && w === 12 && h === 6) {
        // 执行相应逻辑
        return true
    } else {
        return false
    }
})

const echartList = ref()

const dailyTrendChartRef = ref()
const tableStore: any = new TableStore({
    url: '/cs-harmonic-boot/limitRateDetailD/limitExtentData',
    method: 'POST',

    showPage: false,

    column: [
        {
            field: 'index',
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        {
            title: '指标名称',
            field: 'name',
            minWidth: '90'
        },

        {
            title: '越限最大值',
            field: 'maxValue',
            minWidth: '70',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                const extentValue =
                    row.maxValue !== null && row.maxValue !== undefined && row.maxValue !== ''
                        ? Math.floor(row.maxValue * 100) / 100
                        : '/'
                return `<span style='cursor: pointer;text-decoration: underline;'>${extentValue}</span>`
            }
        },
        {
            title: '国标限值',
            field: 'internationalValue',
            minWidth: '60'
        },
        {
            title: '越限程度(%)',
            field: 'extent',
            minWidth: '70',
            formatter: (row: any) => {
                return Math.floor(row.cellValue * 100) / 100 
            }
        },
        {
            title: '越限时间',
            field: 'time',
            minWidth: '60',
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '越限最高监测点',
            field: 'lineName',
            minWidth: '90',
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        }
    ],
    beforeSearchFun: () => {
        setTime()
    },
    loadCallback: () => {
        // 定义 x 轴标签顺序
        const xAxisLabels = ['长时闪变', '谐波电压', '谐波电流', '电压偏差', '三相不平衡']

        // 根据指标名称顺序提取对应的 extent 数据
        const chartData = xAxisLabels.map(label => {
            // 在表格数据中查找对应指标名称的数据项
            const item = tableStore.table.data.find((row: any) => row.name === label)
            // 如果找到对应项，则返回 extent 值，否则返回 0，并保留两位小数
            const extentValue = item ? item.extent || 0 : 0
            return Math.round(extentValue * 100) / 100
        })
        echartList.value = {
            title: {
                text: '指标越限严重度'
            },

            xAxis: {
                data: xAxisLabels
            },

            yAxis: {
                name: '%' // 给X轴加单位
                // interval: 20
            },
            grid: {
                left: '10px',
                right: '20px'
            },
            options: {
                series: [
                    {
                        type: 'bar',
                        name: '越限占比',
                        data: chartData,
                        barMaxWidth: 30
                    }
                ]
            }
        }
    }
})

const tableRef = ref()
provide('tableRef', tableRef)

provide('tableStore', tableStore)

// 点击行
const cellClickEvent = ({ row, column }: any) => {
    dialogTrendChart.value = true

    if (column.field == 'maxValue' && row.lineId) {
        nextTick(() => {
            dailyTrendChartRef.value.open(row)
        })
    }
}

const setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || prop.interval) ?? 0,
        prop.timeKey,
        fullscreen.value
            ? [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
            : prop.timeValue
    )

    if (Array.isArray(time)) {
        tableStore.table.params.searchBeginTime = time[0]
        tableStore.table.params.searchEndTime = time[1]
        TableHeaderRef.value?.setInterval(time[2] - 0)
        TableHeaderRef.value?.setTimeInterval([time[0], time[1]])
    } else {
        console.warn('获取时间失败，time 不是一个有效数组')
    }
}

onMounted(() => {
    tableStore.index()
})
watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
watch(
    () => prop.timeValue,
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true
    }
)

const addMenu = () => {}
</script>
<style lang="scss" scoped></style>
