<template>
    <div class="tab-content">
        <TableHeader datePicker ref="tableHeaderRef" @selectChange="handleSelectChange">
            <template #select>
                <el-form-item label="区域">
                    <el-cascader
                        v-bind="$attrs"
                        :options="areOptions"
                        :props="cascaderProps"
                        v-model="selectedArea"
                        @change="handleFilterChange"
                    />
                </el-form-item>
                <el-form-item label="统计类型">
                    <el-select
                        v-model="tableStore.table.params.statisticalType"
                        value-key="id"
                        placeholder="请选择统计类型"
                        @change="handleStatisticalTypeChange"
                        filterable
                    >
                        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="电网标志">
                    <el-select
                        v-model="tableStore.table.params.powerFlag"
                        placeholder="请选择电网标志"
                        @change="handleFilterChange"
                        filterable
                    >
                        <el-option label="全部" value="0"></el-option>
                        <el-option label="电网侧" value="1"></el-option>
                        <el-option label="非电网侧" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="筛选数据">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="请输入变电站/终端/监测点"
                        clearable
                        @input="handleFilterChange"
                        :show-word-limit="true"
                        :maxlength="32"
                    />
                </el-form-item>
            </template>
            <template #operation>
                <el-button icon="el-icon-Download" type="primary" @click="exportEvent">导出</el-button>
                <el-button
                    class="ml10"
                    icon="el-icon-Setting"
                    @mousedown="onCustomColumnMousedown"
                    @click="openCustomColumn"
                >
                    列设置
                </el-button>
            </template>
        </TableHeader>

        <div v-loading="tableStore.table.loading" class="main-container">
            <vxe-table
                class="full-height-table"
                ref="tableRef"
                auto-resize
                :data="tableStore.table.data"
                v-bind="defaultAttribute"
                :id="tableId"
                :height="tableHeight"
                resizable
                show-overflow
            >
                <vxe-column title="序号" width="80" type="seq" align="center"></vxe-column>
                <vxe-column field="gdName" title="供电公司" align="center" min-width="120"></vxe-column>
                <vxe-column
                    field="subStationName"
                    :show-overflow="true"
                    title="变电站"
                    align="center"
                    min-width="150"
                ></vxe-column>
                <vxe-column field="devName" title="终端名称" align="center" min-width="120"></vxe-column>
                <vxe-column field="devType" title="终端型号" align="center" min-width="150"></vxe-column>
                <vxe-column
                    field="lineName"
                    title="监测点名称"
                    align="center"
                    min-width="150"
                    :formatter="formatMonitorId"
                ></vxe-column>
                <vxe-column
                    field="objName"
                    title="监测对象名称"
                    align="center"
                    min-width="150"
                    :formatter="formatMonitorId"
                ></vxe-column>
                <vxe-column field="subVoltage" title="变电站电压等级" align="center" min-width="120"></vxe-column>
                <vxe-column field="lineVoltage" title="监测点电压等级" align="center" min-width="120"></vxe-column>
                <vxe-column field="powerFlag" title="用户性质" align="center" min-width="100"></vxe-column>
                <vxe-column field="monitorId" title="一类监测点" align="center" min-width="120" :formatter="formatMonitorId"></vxe-column> 
                <vxe-column field="loadType" title="干扰源类型" align="center" min-width="120"></vxe-column>
               
                <vxe-column field="loginTime" title="投运时间" align="center" min-width="120"></vxe-column>
                
                <vxe-column field="runFlag" title="运行状态" align="center" min-width="100">
                    <template #default="{ row }">
                        <el-tag v-if="row.runFlag === '投运'" type="success" :disable-transitions="true" size="small">
                            投运
                        </el-tag>
                        <el-tag v-if="row.runFlag === '检修'" type="warning" :disable-transitions="true" size="small">
                            检修
                        </el-tag>
                        <el-tag v-if="row.runFlag === '停运'" type="danger" :disable-transitions="true" size="small">
                            停运
                        </el-tag>
                    </template>
                </vxe-column>
                
                <vxe-column
                    field="interval"
                    title="统计间隔"
                    align="center"
                    min-width="100"
                    :formatter="formatMonitorId"
                ></vxe-column>
                <vxe-column
                    field="harmonicValue"
                    :title="harmonicValueTitle"
                    align="center"
                    min-width="120"
                ></vxe-column>
                <vxe-column field="onlineRate" title="在线率(%)" align="center" min-width="100"></vxe-column>
                <vxe-column field="integrity" title="完整率(%)" align="center" min-width="100"></vxe-column>

                <!-- <vxe-column field="upCounts" title="暂升次数(次)" align="center" min-width="100"></vxe-column> -->
                <!-- <vxe-column field="downCounts" title="电压暂降(次)" align="center" min-width="100"></vxe-column> -->
                <!-- <vxe-column field="breakCounts" title="短时中断(次)" align="center" min-width="100"></vxe-column> -->
                
            </vxe-table>
        </div>

        <div class="pagination-container">
            <el-pagination
                :current-page="tableStore.table.params.pageNum"
                :page-size="tableStore.table.params.pageSize"
                :page-sizes="[10, 20, 50, 100, 200]"
                background
                layout="sizes, total, prev, pager, next, jumper"
                :total="tableStore.table.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="custom-pagination"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, onBeforeUnmount, computed, watch } from 'vue'
import TableStore from '@/utils/tableStore'
import TableHeader from '@/components/table/header/index.vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { useDictData } from '@/stores/dictData'
import { debounce } from 'lodash-es'

const props = defineProps({
    active: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['initialized'])

const dictData = useDictData()
const options = dictData.getBasicData('Pollution_Calc')
const tableHeight = ref(500)
const tableRef = ref()
const tableHeaderRef = ref()
const tableId = 'pollution-monitoring-point-report'

const selectedArea = ref()
const areOptions: any = dictData.state.area
const allData = ref<PollutionItem[]>([])
const searchKeyword = ref('')
const harmonicValueTitle = ref('谐波电压污染值')

let customColumnVisibleOnPress = false
const onCustomColumnMousedown = () => {
    const table = tableRef.value as any
    if (!table) return
    customColumnVisibleOnPress = table.getCustomVisible?.() ?? !!table.reactData?.customStore?.visible
    if (table.reactData?.customStore) {
        table.reactData.customStore.activeBtn = true
    }
}
const openCustomColumn = () => {
    const table = tableRef.value as any
    if (!table) return
    if (table.reactData?.customStore) {
        table.reactData.customStore.activeBtn = false
    }
    if (customColumnVisibleOnPress) {
        table.closeCustom?.()
    } else {
        table.openCustom?.()
    }
}

const cascaderProps = {
    label: 'name',
    value: 'id',
    checkStrictly: true,
    emitPath: false
}

interface PollutionItem {
    gdName?: string
    subStationName?: string
    devName?: string
    lineName?: string
    powerFlag?: string
}

const formatMonitorId = (row: any) => {
    return row.cellValue || '/'
}

const handleSelectChange = (isExpanded: boolean) => {
    if (isExpanded) {
        tableHeight.value = tableHeight.value - 55
    } else {
        tableHeight.value = tableHeight.value + 55
    }
}

const calculateTableHeight = () => {
    const windowHeight = window.innerHeight
    const headerHeight = 160
    const paginationHeight = 120
    const padding = 30
    const calculatedHeight = windowHeight - headerHeight - paginationHeight - padding
    tableHeight.value = Math.max(calculatedHeight, 300)
}

const debouncedCalculateTableHeight = debounce(() => {
    calculateTableHeight()
}, 300)

const filteredData = computed(() => {
    let result = [...allData.value]

    if (selectedArea.value) {
        let areaName = ''
        let areaLevel = -1
        const findAreaName = (areas: any[]) => {
            for (const area of areas) {
                if (area.id === selectedArea.value) {
                    areaName = area.name
                    areaLevel = area.level !== undefined ? area.level : -1
                    break
                }
                if (area.children && area.children.length > 0) {
                    findAreaName(area.children)
                }
            }
        }
        findAreaName(areOptions)

        if (areaName && areaLevel > 1) {
            result = result.filter(item => item.gdName && item.gdName.includes(areaName))
        }
    }

    if (tableStore.table.params.powerFlag === '1') {
        result = result.filter(item => item.powerFlag && !item.powerFlag.includes('非'))
    } else if (tableStore.table.params.powerFlag === '2') {
        result = result.filter(item => item.powerFlag && item.powerFlag.includes('非'))
    }

    if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(
            item =>
                (item.subStationName && item.subStationName.toLowerCase().includes(keyword)) ||
                (item.devName && item.devName.toLowerCase().includes(keyword)) ||
                (item.lineName && item.lineName.toLowerCase().includes(keyword))
        )
    }

    return result
})

const currentPageData = computed(() => {
    const pageSize = tableStore.table.params.pageSize
    const pageNum = tableStore.table.params.pageNum
    const start = (pageNum - 1) * pageSize
    const end = start + pageSize
    return filteredData.value.slice(start, end)
})

const updateTotal = computed(() => {
    return filteredData.value.length
})

const tableStore = new TableStore({
    url: '/harmonic-boot/PollutionSubstation/downPollutionLineCalc',
    method: 'POST',
    filename: '监测点评估',
    column: [],
    beforeSearchFun: () => {
        delete tableStore.table.params.deptIndex
        delete tableStore.table.params.interval
        delete tableStore.table.params.searchEndTime
        delete tableStore.table.params.searchBeginTime
        delete tableStore.table.params.timeFlag
    },
    loadCallback: () => {
        allData.value = tableStore.table.data || []
        tableStore.table.total = updateTotal.value
        tableStore.table.data = currentPageData.value
    },
    resetCallback: () => {
        clearQueryParams()
    }
})

provide('tableStore', tableStore)

watch(
    () => areOptions,
    newOptions => {
        if (newOptions && newOptions.length > 0) {
            selectedArea.value = newOptions[0].id
            tableStore.table.params.id = newOptions[0].id
        }
    },
    { immediate: true }
)

watch(
    () => options,
    newOptions => {
        if (newOptions && newOptions.length > 0) {
            if (!tableStore.table.params.statisticalType) {
                tableStore.table.params.statisticalType = newOptions[0]
                tableStore.table.params.ids = [newOptions[0].id]
            }
        }
    },
    { immediate: true }
)

tableStore.table.params.powerFlag = '0'
tableStore.table.params.isUpToGrid = 0
tableStore.table.params.type = 1

const handleStatisticalTypeChange = (newVal: { id: any }) => {
    if (newVal) {
        tableStore.table.params.statisticalType = newVal
        tableStore.table.params.ids = [newVal.id]
        if (newVal.name) {
            harmonicValueTitle.value = newVal.name + '污染值'
        }
    }
    // 重新调用接口
    tableStore.index()
}

const handleFilterChange = () => {
    tableStore.table.params.pageNum = 1
    tableStore.table.data = currentPageData.value
    tableStore.table.total = updateTotal.value
}

const handleSizeChange = (val: number) => {
    tableStore.table.params.pageSize = val
    tableStore.table.params.pageNum = 1
    tableStore.table.data = currentPageData.value
    tableStore.table.total = updateTotal.value
}

const handleCurrentChange = (val: number) => {
    tableStore.table.params.pageNum = val
    tableStore.table.data = currentPageData.value
    tableStore.table.total = updateTotal.value
}

const exportEvent = () => {
    const allFilteredData = filteredData.value
    tableRef.value.exportData({
        filename: '监测点评估-污染值报告',
        sheetName: 'Sheet1',
        type: 'xlsx',
        useStyle: true,
        data: allFilteredData,
        columnFilterMethod: function (column, $columnIndex) {
            return !(column.$columnIndex === 0)
        }
    })
}

onMounted(() => {
    if (props.active) {
        tableStore.index()
        emit('initialized', 'pollutionReport')
    }
    calculateTableHeight()
    window.addEventListener('resize', debouncedCalculateTableHeight)
})

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

const clearQueryParams = () => {
    // 将区域恢复成第一层
    if (areOptions && areOptions.length > 0) {
        selectedArea.value = areOptions[0].id
        tableStore.table.params.id = areOptions[0].id
    }

    // 清空搜索关键词
    searchKeyword.value = ''
}

defineExpose({
    refresh: (name?: any) => {
        // 清空查询参数
        clearQueryParams()
        tableHeaderRef.value.setTheDate(3)
        if (name) {
            searchKeyword.value = name
        }
        tableStore.index()
    }
})
</script>

<style scoped>
.pagination-container {
    border: 1px solid #ebeef5;
    border-top: none;
    padding: 10px;
    margin: 0 0 5px 0;
    background-color: #fff;
}

:deep(.custom-pagination) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}

:deep(.custom-pagination .el-pagination__sizes) {
    margin-right: 10px;
}

:deep(.custom-pagination .el-pagination__total) {
    margin-right: auto;
}

:deep(.custom-pagination .el-pagination__jump) {
    margin-left: 20px;
}

/* 响应式处理 */
@media screen and (max-width: 768px) {
    :deep(.custom-pagination) {
        flex-direction: column;
        align-items: stretch;
    }

    :deep(.custom-pagination .el-pagination__total) {
        margin-right: 0;
        order: 1;
        margin-top: 10px;
    }

    :deep(.custom-pagination .el-pagination__sizes) {
        order: 2;
    }

    :deep(.custom-pagination .btn-prev),
    :deep(.custom-pagination .el-pager),
    :deep(.custom-pagination .btn-next),
    :deep(.custom-pagination .el-pagination__jump) {
        order: 3;
        justify-content: center;
        margin-top: 10px;
    }
}
</style>
