<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"
          >
            <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"
          >
            <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>
      </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"
        :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="subVStationValue" :title="harmonicValueTitle" align="center" min-width="150"></vxe-column>
        <vxe-column field="subVoltage" title="变电站电压等级" align="center" min-width="150"></vxe-column>
        <vxe-column title="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="showDetailDialog(row)">监测点详情</el-button>
          </template>
        </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]"
          background
          layout="sizes, total, prev, pager, next, jumper"
          :total="tableStore.table.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="custom-pagination"/>
    </div>

     <!-- 添加弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      :title="detailDialogTitle" 
      width="80%"
    >
      <div v-loading="detailLoading">
        <div style="margin-bottom: 10px; text-align: right;">
          <el-button icon="el-icon-Download" type="primary" @click="exportDetailEvent">导出</el-button>
        </div>
        <vxe-table
          ref="detailTableRef"
          :data="detailData"
          auto-resize
          resizable
          show-overflow
          height="400px"
        >
          <vxe-column title="序号" width="60" type="seq" align="center"></vxe-column>
         
          <vxe-column field="lineName" title="监测点名称" align="center" min-width="120"></vxe-column>
          <vxe-column field="devName" title="终端名称" align="center" min-width="120"></vxe-column>
          <vxe-column field="devType" title="终端型号" align="center" min-width="100"></vxe-column>
          <vxe-column field="manufacturer" title="终端厂家" align="center" min-width="120"></vxe-column>
          <vxe-column field="loginTime" title="投运时间" align="center" min-width="120"></vxe-column>
          <vxe-column field="interval" title="统计间隔" align="center" min-width="100"></vxe-column>
          <vxe-column field="powerFlag" title="监测位置" align="center" min-width="100"></vxe-column>
          <vxe-column field="vharmonicValue" title="监测点污染值" align="center" min-width="120"></vxe-column>
        </vxe-table>
      </div>
    </el-dialog>
  </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 detailTableRef = ref()
const selectedArea = ref()
const areOptions: any = dictData.state.area
const allData = ref<PollutionItem[]>([])
const searchKeyword = ref('')
const harmonicValueTitle = ref('电站谐波电压污染值')
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('')
const detailLoading = ref(false)
const detailData = ref<PollutionItem[]>([])
const originalTableData = ref<any[]>([])

// 方法
const showDetailDialog = (row) => {
  detailDialogTitle.value = `${row.subStationName} - 监测点详情`
  loadDetailData(row)
  detailDialogVisible.value = true
}


const loadDetailData = async (row) => {
  detailLoading.value = true
  try {
    // 从原始数据中查找该变电站的详细信息
    const originalItem = originalTableData.value.find(
      item => item.subStationName === row.subStationName
    )
    
    if (originalItem && originalItem.powerFlagPollutionList) {
      const detailList: PollutionItem[] = []
      originalItem.powerFlagPollutionList.forEach((point: any) => {
        detailList.push({
        
          lineName: processNullValue(point.lineName),
          devName: processNullValue(point.devName),
          devType: processNullValue(point.devType),
          manufacturer: processNullValue(point.manufacturer),
          loginTime: processNullValue(point.loginTime),
          interval: processNullValue(point.interval),
          powerFlag: processNullValue(point.powerFlag),
          vharmonicValue: processNullValue(point.vharmonicValue)
        })
      })
      detailData.value = detailList
    } else {
      detailData.value = []
    }
  } catch (error) {
    console.error('加载详情数据失败:', error)
    detailData.value = []
  } finally {
    detailLoading.value = false
  }
}

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

interface PollutionItem {
  gdName?: string
  subStationName?: string
  subVStationValue?: string
  subVoltage?: string
  devName?: string
  lineName?: string
  powerFlag?: string
  devType?: string
  manufacturer?: string
  loginTime?: string
  interval?: string
  vharmonicValue?: string
}

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 processNullValue = (value: any) => {
  return value === null || value === undefined || value === '' || value === 'null'? '/' : value
}

const tableStore = new TableStore({
  url: '/harmonic-boot/PollutionSubstation/downPollutionSubCalc',
  method: 'POST',
  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: () => {
    // 保存原始数据以便后续查询
    originalTableData.value = [...(tableStore.table.data || [])]
    
    const expandedData: PollutionItem[] = [];
    
    (tableStore.table.data || []).forEach((item: any) => {
      expandedData.push({
        gdName: processNullValue(item.gdName),
        subStationName: processNullValue(item.subStationName),
        subVStationValue: processNullValue(item.subVStationValue),
        subVoltage: processNullValue(item.subVoltage)
        
      });
    });
    
    allData.value = expandedData;
    tableStore.table.total = updateTotal.value;
    tableStore.table.data = currentPageData.value;
  }
})

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: any) {
            return !(
                column.column.title === '操作'
            )
        }
  })
}

// 导出详情数据的方法
const exportDetailEvent = () => {
  detailTableRef.value.exportData({
    filename: detailDialogTitle.value,
    sheetName: 'Sheet1',
    type: 'xlsx',
    useStyle: true,
    data: detailData.value,
    columnFilterMethod({ column }) {
      // 导出所有列，包括隐藏列
      return true;
    }
  })
}

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

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

defineExpose({
  refresh: () => {
    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>