<template>
    <div>
        <!--暂态事件统计 -->
        <TableHeader :showReset="false" @selectChange="selectChange" datePicker v-if="fullscreen"></TableHeader>
        <my-echart
            class="tall"
            :options="echartList"
            :style="{
                width: prop.width,
                height: `calc(${prop.height} / 2 - ${headerHeight / 2}px + ${fullscreen ? 0 : 28}px )`
            }"
        />
        <Table
            ref="tableRef"
            @cell-click="cellClickEvent"
            :height="`calc(${prop.height} / 2 - ${headerHeight / 2}px + ${fullscreen ? 0 : 28}px )`"
            isGroup
        ></Table>
        <TransientStatisticsDetail ref="transientStatisticsDetailRef"></TransientStatisticsDetail>
    </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 MyEchart from '@/components/echarts/MyEchart.vue'
import { getTimeOfTheMonth } from '@/utils/formatTime'
import { useConfig } from '@/stores/config'
import TransientStatisticsDetail from './components/transientStatisticsDetail.vue'
import TableHeader from '@/components/table/header/index.vue'
import { useRoute } from 'vue-router'
import { useTimeCacheStore } from '@/stores/timeCache'

const prop = defineProps({
    w: { type: String },
    h: { type: String },
    width: { type: String },
    height: { type: String },
    timeKey: { type: String },
    timeValue: { type: Object }
})

const headerHeight = ref(57)

const route = useRoute()
const timeCacheStore = useTimeCacheStore()

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

    // 如果有传入 datePicker 的值
    if (datePickerValue) {
        // 更新表格参数
        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 config = useConfig()

const data = [
    {
        name: '电压中断',
        value: 4
    },
    {
        name: '电压暂降',
        value: 41
    },
    {
        name: '电压暂升',
        value: 46
    }
]
const echartList = ref({
    title: {},

    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        top: 'center',
        right: '5%',
        formatter: function (e: any) {
            return e + '   ' + data.filter(item => item.name == e)[0].value + '次'
        }
    },
    xAxis: {
        show: false
    },
    yAxis: {
        show: false
    },
    grid: {
        left: '10px',
        right: '20px'
    },
    color: ['#FF9100', '#FFBF00', config.layout.elementUiPrimary[0]],
    options: {
        dataZoom: null,
        title: [
            {
                text: '暂态事件统计',
                left: 'center'
            },
            {
                text: data[0].value + data[1].value + data[2].value + '次',
                left: 'center',
                top: 'center'
            }
        ],
        series: [
            {
                type: 'pie',
                center: 'center',
                radius: ['50%', '70%'],
                label: {
                    show: false,
                    position: 'outside',
                    textStyle: {
                        //数值样式
                    }
                },
                name: '事件统计',
                data: data
            }
        ]
    }
})
const transientStatisticsDetailRef = ref()
const tableStore: any = new TableStore({
    url: '/user-boot/dept/deptTree',
    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: 'type',
            minWidth: '70',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='cursor: pointer;text-decoration: underline;'>${row.type}</span>`
            }
        },
        {
            title: '电压暂降(次)',
            field: 'type1',
            minWidth: '80',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='cursor: pointer;text-decoration: underline;'>${row.type1}</span>`
            }
        },
        {
            title: '电压暂升(次)',
            field: 'type2',
            minWidth: '80',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='cursor: pointer;text-decoration: underline;'>${row.type2}</span>`
            }
        }
    ],
    beforeSearchFun: () => {
        // 尝试从缓存获取时间值
        let beginTime, endTime

        if (fullscreen.value) {
            const cached = timeCacheStore.getCache(route.path)
            if (cached && cached.timeValue) {
                beginTime = cached.timeValue[0]
                endTime = cached.timeValue[1]
            }
        }

        // 如果缓存中没有则使用默认值
        tableStore.table.params.searchBeginTime = beginTime || prop.timeValue?.[0] || getTimeOfTheMonth(prop.timeKey)[0]
        tableStore.table.params.searchEndTime = endTime || prop.timeValue?.[1] || getTimeOfTheMonth(prop.timeKey)[1]
    },
    loadCallback: () => {
        tableStore.table.data = [
            {
                name: '35kV1进线',
                type: '2',
                type1: '38',
                type2: '35'
            },
            {
                name: '35kV1变压器',
                type: '2',
                type1: '1',
                type2: '3'
            },
            {
                name: '35kV1母线',
                type: '0',
                type1: '1',
                type2: '4'
            },
            {
                name: '35kV2母线',
                type: '0',
                type1: '1',
                type2: '4'
            }
        ]
    }
})

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

provide('tableStore', tableStore)

// 点击行
const cellClickEvent = ({ row, column }: any) => {
    if (column.field != 'name') {
        transientStatisticsDetailRef.value.open(row)
    }
}

onMounted(() => {
    setTimeout(() => {
        tableStore.index()
    }, 200)
})
watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
watch(
    () => prop.timeValue, // 监听的目标（函数形式避免直接传递 props 导致的警告）
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true // 若 timeValue 是对象/数组，需开启深度监听
    }
)

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