<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>
        <!-- 指标日趋势图 -->
        <HarmonicRatio‌ ref="harmonicRatio‌Ref" v-if="dialogFlag" @close="onHarmonicRatioClose" :showIndex="false" />
        <!-- <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 { ElMessage, ElMessageBox } from 'element-plus'
import DailyTrendChart from '@/components/cockpit/exceedanceLevel/components/dailyTrendChart.vue'
import { getTime } from '@/utils/formatTime'
import HarmonicRatio‌ from '@/components/cockpit/overLimitStatistics/components/harmonicRatio‌.vue'
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 harmonicRatio‌Ref: any = ref(null)
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: 120
        }, {
            title: '越限时间',
            field: 'time',
            minWidth: 100,
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '越限最高监测点名称',
            field: 'lineName',
            minWidth: 140,
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '越限程度(%)',
            field: 'extent',
            minWidth: 100,
            formatter: (row: any) => {
                return row.cellValue ? Math.floor(row.cellValue * 100) / 100 : '/'
            }
        },
        {
            title: '越限最大值',
            field: 'maxValue',
            minWidth: 100,
            render: 'customTemplate',
            customTemplate: (row: any) => {
                const extentValue =
                    row.maxValue !== null && row.maxValue !== undefined && row.maxValue !== ''
                        ? Math.floor(row.maxValue * 100) / 100
                        : '/'
                return extentValue == '/' ? '/' : `<span style='cursor: pointer;text-decoration: underline;'>${extentValue}</span>`
            }
        },
        {
            title: '国标限值',
            field: 'internationalValue',
            minWidth: 100, formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '设备名称', field: 'devName', minWidth: 130, align: 'center', formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '项目名称', field: 'projectName', minWidth: 130, align: 'center', formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '工程名称', field: 'engineeringName', minWidth: 130, align: 'center', formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },




    ],
    beforeSearchFun: () => {
        setTime()
    },
    loadCallback: () => {
        // 定义 x 轴标签顺序

        echartList.value = {
            title: {
                text: '指标越限程度'
            },

            xAxis: {
                data: tableStore.table.data.map((item: any) => item.name)
            },

            yAxis: {
                name: '%' // 给X轴加单位
                // interval: 20
            },
            grid: {
                left: '10px',
                right: '20px'
            },
            options: {
                series: [
                    {
                        type: 'bar',
                        name: '指标越限程度',
                        data: tableStore.table.data.map((item: any) => Math.floor(item.extent * 100) / 100),
                        barMaxWidth: 30
                    }
                ]
            }
        }
    }
})

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

provide('tableStore', tableStore)
const codeMap = [
    { key: '闪变', code: 'flickerOvertime' },
    { key: '电压偏差', code: 'voltageDevOvertime' },
    { key: '三相', code: 'ubalanceOvertime' },
    { key: '谐波电压', code: 'uharm' },
    { key: '谐波电流', code: 'iharm' },
];
// 点击行
const cellClickEvent = ({ row, column }: any) => {
    dialogTrendChart.value = true

    if (column.field == 'maxValue') {
        if (row.lineId == null) {
            ElMessage.info('暂无越限监测点！')
        } else {
            nextTick(() => {
                // dailyTrendChartRef.value.open(row)
                dialogFlag.value = true
                nextTick(() => {

                    const code = codeMap.find(item => row.name.includes(item.key))?.code || '';
                    harmonicRatio‌Ref.value.openDialog(row, code, column.title.replace(/次/g, ""))
                })
            })
        }

    }
}

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 不是一个有效数组')
    }
}
const dialogFlag = ref(false)
// 谐波弹窗关闭时的回调
const onHarmonicRatioClose = () => {
    dialogFlag.value = false
    // 重新打开指标越限详情弹窗

}


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>
