<template>
    <div class="distribution-page" :style="pageHeight" v-loading="tableStore.table.loading">
        <TableHeader ref="TableHeaderRef" :showReset="false" :timeKeyList="timeKeyList" datePicker
            @selectChange="selectChange">
            <template v-slot:operation>
                <el-button icon="el-icon-Back" @click="handleBack">返回</el-button>
            </template>
        </TableHeader>
        <p class="note">注：暂降类型仅统计暂降原因为短路故障事件</p>
        <div class="statistics-main" v-if="renderFlag">
            <div class="chart-cell">
                <my-echart :options="reasonChart" class="chart-box" />
            </div>
            <div class="table-cell">
                <vxe-table height="auto" auto-resize :data="reasonData" v-bind="defaultAttribute">
                    <vxe-column field="name" title="暂降原因" />
                    <vxe-column field="value" title="暂降次数" sortable />
                </vxe-table>
            </div>
            <div class="chart-cell">
                <my-echart :options="typeChart" class="chart-box" />
            </div>
            <div class="table-cell">
                <vxe-table height="auto" auto-resize :data="typeData" v-bind="defaultAttribute">
                    <vxe-column field="name" title="暂降类型" />
                    <vxe-column field="value" title="暂降次数" sortable />
                </vxe-table>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, inject } from 'vue'
import TableStore from '@/utils/tableStore'
import MyEchart from '@/components/echarts/MyEchart.vue'
import TableHeader from '@/components/table/header/index.vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { getTime } from '@/utils/formatTime'
import { useDictData } from '@/stores/dictData'

import { mainHeight } from '@/utils/layout'
import { color1 } from '@/components/echarts/color'
const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const EventTypeList: any = dictData.getBasicData('Event_Type')
const pageHeight = mainHeight(106)
const eventStatisticsBack = inject<() => void>('eventStatisticsBack', () => {})
const handleBack = () => eventStatisticsBack()
const timeKeyList = ['1', '2', '3', '4', '5']
const defaultInterval = 3

const TableHeaderRef = ref()
const renderFlag = ref(true)
const reasonChart = ref({})
const typeChart = ref({})
const reasonData = ref<any[]>([])
const typeData = ref<any[]>([])

const sortDistributionList = (list: any[]) => {
    const totalRow = list.find((item: any) => item.name === '总计')
    const total = totalRow?.value ?? list.reduce((sum, item) => sum + (item.value ?? 0), 0)
    const sorted = list
        .filter((item: any) => item.name !== '总计')
        .sort((a, b) => (b.value ?? 0) - (a.value ?? 0))
    return [{ name: '总计', value: total }, ...sorted]
}

const transformReasonData = (eventReason: any[] = []) => {
    const list = ReasonList.map((item: any) => {
        const matched = eventReason.find((row: any) => row.eventReasonId === item.id)
        return {
            name: item.name,
            value: matched?.eventReasonCount ?? 0
        }
    })
    return sortDistributionList(list)
}

const transformTypeData = (eventType: any[] = []) => {
    const list = EventTypeList.map((item: any) => {
        const matched = eventType.find((row: any) => row.eventTypeId === item.id)
        return {
            name: item.name,
            value: matched?.eventTypeCount ?? 0
        }
    })
    return sortDistributionList(list)
}

const parseDistributionData = (raw: any) => {
    if (raw?.eventReason || raw?.eventType) {
        return {
            reason: transformReasonData(raw.eventReason || []),
            type: transformTypeData(raw.eventType || [])
        }
    }
    if (raw?.reason?.length || raw?.type?.length) {
        return {
            reason: sortDistributionList(raw.reason || []),
            type: sortDistributionList(raw.type || [])
        }
    }
    return {
        reason: transformReasonData([]),
        type: transformTypeData([])
    }
}

const buildPieOptions = (title: string, seriesName: string, data: any[], exportFileName: string) => ({
    title: { text: title },
    exportFileName,
    legend: {
        type: 'scroll',
        orient: 'vertical',
        left: 10,
        top: '5%',
        tooltip: { show: true }
    },
    color: color1,
    xAxis: { show: false },
    yAxis: { show: false },
    dataZoom: { show: false },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} (次)',
        confine: true
    },
    options: {
        series: [
            {
                name: seriesName,
                type: 'pie',
                center: ['50%', '50%'],
                selectedOffset: 30,
                clockwise: true,
                label: { show: false, position: 'outside' },
                data: data.filter((item: any) => item.name !== '总计')
            }
        ]
    }
})

const updateCharts = (res: any) => {
    renderFlag.value = false
    reasonData.value = res?.reason || []
    typeData.value = res?.type || []
    reasonChart.value = buildPieOptions('暂降原因', '暂降原因', reasonData.value, '暂降原因')
    typeChart.value = buildPieOptions('暂降类型', '暂降类型', typeData.value, '暂降类型')
    renderFlag.value = true
}

const tableStore: any = new TableStore({
    url: '/cs-harmonic-boot/event/eventReasonAndTypeStatistics',
    method: 'POST',
    showPage: false,
    column: [],
    beforeSearchFun: () => {
        setTime()
    },
    loadCallback: () => {
        updateCharts(parseDistributionData(tableStore.table.data))
    }
})

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

const selectChange = (_showSelect: any, _height: any, datePickerValue?: any) => {
    if (datePickerValue?.timeValue) {
        tableStore.table.params.searchBeginTime = datePickerValue.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerValue.timeValue[1]
    }
}

const setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || defaultInterval) ?? 0,
        timeKeyList,
        [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
    )

    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(() => {
    updateCharts(parseDistributionData(null))
    setTimeout(() => {
        tableStore.index()
    }, 100)
})
</script>

<style scoped>
.distribution-page {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 0;
    box-sizing: border-box;
}

.note {
    margin: 8px 0 0;
    flex-shrink: 0;
    color: #f56c6c;
    font-size: 12px;
}

.statistics-main {
    flex: 1;
    min-height: 0;
    display: grid;
    grid-template-columns: 1fr 420px;
    grid-template-rows: 1fr 1fr;
    gap: 20px;
    margin-top: 8px;
}

.chart-cell,
.table-cell {
    min-height: 0;
    overflow: hidden;
}

.chart-cell {
    display: flex;
}

.chart-box {
    flex: 1;
    min-height: 0;
    width: 100%;
}

.chart-box :deep(.chart),
.chart-box :deep(.my-chart) {
    height: 100%;
}
</style>
