<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="FolderAdd" 
            type="primary" 
            class="ml10" 
            @click="formDialogRef.openDialog()">
            新 增
          </el-button>
          <right-toolbar  
            class="ml10"
            style="float: right;"
            @queryTable="getDataList">
            <TableColumnControl
              ref="columnControlRef"
              :columns="tableColumns"
              v-model="visibleColumns"
              trigger-type="default"
              trigger-circle
              @change="handleColumnChange"
              @order-change="handleColumnOrderChange"
            >
              <template #trigger>
                <el-tooltip class="item" effect="dark" content="列设置" placement="top">
                  <el-button circle style="margin-left: 0;">
                    <el-icon><Menu /></el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </TableColumnControl>
          </right-toolbar>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-table 
        :data="state.dataList" 
        v-loading="state.loading" 
        border 
        :cell-style="tableStyle.cellStyle" 
        :header-cell-style="tableStyle.headerCellStyle"
        @sort-change="sortChangeHandle"
        show-summary
        :summary-method="getSummaries">
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #header>
            <el-icon><List /></el-icon>
          </template>
        </el-table-column>
        <template v-for="col in sortedTableColumns" :key="col.prop || col.label">
          <el-table-column 
            v-if="checkColumnVisible(col.prop || '') && col.prop !== '操作'"
            :prop="col.prop" 
            :label="col.label" 
            show-overflow-tooltip
            align="center">
            <template #header>
              <el-icon><component :is="columnConfigMap[col.prop]?.icon || Calendar" /></el-icon>
              <span style="margin-left: 4px">{{ col.label }}</span>
            </template>
            <!-- 层数列特殊模板 -->
            <template v-if="col.prop === 'layers'" #default="scope">
              <el-tag v-if="scope.row.layers" size="small" type="info" effect="plain">
                {{ scope.row.layers }}层
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 已住人数列特殊模板 -->
            <template v-else-if="col.prop === 'allAlreadyNum'" #default="scope">
              <el-tag v-if="scope.row.allAlreadyNum !== undefined && scope.row.allAlreadyNum !== null" size="small" type="success" effect="plain">
                {{ scope.row.allAlreadyNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 现住人数列特殊模板 -->
            <template v-else-if="col.prop === 'nowNum'" #default="scope">
              <el-tag v-if="scope.row.nowNum !== undefined && scope.row.nowNum !== null" size="small" type="primary" effect="plain">
                {{ scope.row.nowNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 剩余可住人数列特殊模板 -->
            <template v-else-if="col.prop === 'surplusNum'" #default="scope">
              <el-tag v-if="scope.row.surplusNum !== undefined && scope.row.surplusNum !== null" size="small" type="warning" effect="plain">
                {{ scope.row.surplusNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 空宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, 'all')">
                {{ scope.row.roomEmptyNum }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum || 0 }}</span>
            </template>
            <!-- 空5人宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum5'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum5 > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, '5')">
                {{ scope.row.roomEmptyNum5 }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum5 || 0 }}</span>
            </template>
            <!-- 空4人宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum4'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum4 > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, '4')">
                {{ scope.row.roomEmptyNum4 }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum4 || 0 }}</span>
            </template>
            <!-- 空3人宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum3'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum3 > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, '3')">
                {{ scope.row.roomEmptyNum3 }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum3 || 0 }}</span>
            </template>
            <!-- 空2人宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum2'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum2 > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, '2')">
                {{ scope.row.roomEmptyNum2 }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum2 || 0 }}</span>
            </template>
            <!-- 空1人宿舍数列特殊模板 -->
            <template v-else-if="col.prop === 'roomEmptyNum1'" #default="scope">
              <el-link 
                v-if="scope.row.roomEmptyNum1 > 0"
                type="primary" 
                :underline="false"
                @click="handleViewEmptyRoom(scope.row, '1')">
                {{ scope.row.roomEmptyNum1 }}
              </el-link>
              <span v-else>{{ scope.row.roomEmptyNum1 || 0 }}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #header>
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 4px">操作</span>
          </template>
          <template #default="scope">
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button 
              icon="Delete" 
              text 
              type="danger" 
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination 
        @size-change="sizeChangeHandle" 
        @current-change="currentChangeHandle" 
        v-bind="state.pagination" />
    </div>

    <!-- 编辑、新增  -->
    <FormDialog ref="formDialogRef" @refresh="getDataList(false)" />
    
    <!-- 空宿舍详情对话框 -->
    <EmptyRoomDialog ref="emptyRoomDialogRef" />
  </div>
</template>

<script setup lang="ts" name="DormBuilding">
import { ref, reactive, defineAsyncComponent, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/stuwork/dormbuilding";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const EmptyRoomDialog = defineAsyncComponent(() => import('./emptyRoomDialog.vue'));
import { List, OfficeBuilding, Grid, UserFilled, Setting, Menu, Calendar } from '@element-plus/icons-vue'
import { getTableConfigFromLocal, saveTableConfigToLocal, updateUserTableConfig } from '/@/api/admin/usertable'

// 定义变量内容
const route = useRoute()
const formDialogRef = ref()
const emptyRoomDialogRef = ref()
const columnControlRef = ref<any>()

// 表格列配置
const tableColumns = [
  { prop: 'buildingNo', label: '楼号' },
  { prop: 'layers', label: '层数' },
  { prop: 'allAlreadyNum', label: '已住人数' },
  { prop: 'nowNum', label: '现住人数' },
  { prop: 'surplusNum', label: '剩余可住人数' },
  { prop: 'roomEmptyNum', label: '空宿舍数' },
  { prop: 'roomEmptyNum5', label: '空5人宿舍数' },
  { prop: 'roomEmptyNum4', label: '空4人宿舍数' },
  { prop: 'roomEmptyNum3', label: '空3人宿舍数' },
  { prop: 'roomEmptyNum2', label: '空2人宿舍数' },
  { prop: 'roomEmptyNum1', label: '空1人宿舍数' },
  { prop: 'phone', label: '电话' }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  buildingNo: { icon: OfficeBuilding },
  layers: { icon: Grid },
  allAlreadyNum: { icon: UserFilled },
  nowNum: { icon: UserFilled },
  surplusNum: { icon: UserFilled },
  roomEmptyNum: { icon: UserFilled },
  roomEmptyNum5: { icon: UserFilled },
  roomEmptyNum4: { icon: UserFilled },
  roomEmptyNum3: { icon: UserFilled },
  roomEmptyNum2: { icon: UserFilled },
  roomEmptyNum1: { icon: UserFilled },
  phone: { icon: Calendar }
}

// 当前显示的列
const visibleColumns = ref<string[]>([])
// 列排序顺序
const columnOrder = ref<string[]>([])

// 从本地统一存储加载配置
const loadSavedConfig = () => {
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const savedConfig = getTableConfigFromLocal(storageKey)
  
  if (savedConfig && savedConfig.visibleColumns) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    const filteredSaved = savedConfig.visibleColumns.filter((col: string) => validColumns.includes(col))
    visibleColumns.value = filteredSaved.length > 0 ? filteredSaved : validColumns
  } else {
    visibleColumns.value = tableColumns.map(col => col.prop || col.label)
  }
  
  if (savedConfig && savedConfig.columnOrder) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    columnOrder.value = savedConfig.columnOrder.filter((key: string) => validColumns.includes(key))
    validColumns.forEach(key => {
      if (!columnOrder.value.includes(key)) {
        columnOrder.value.push(key)
      }
    })
  } else {
    columnOrder.value = tableColumns.map(col => col.prop || col.label)
  }
}

loadSavedConfig()

// 排序后的表格列
const sortedTableColumns = computed(() => {
  const columns = tableColumns.filter(col => {
    const key = col.prop || col.label
    return visibleColumns.value.includes(key)
  })
  
  if (columnOrder.value.length > 0) {
    const orderedColumns: typeof tableColumns = []
    const unorderedColumns: typeof tableColumns = []
    
    columnOrder.value.forEach(key => {
      const col = columns.find(c => (c.prop || c.label) === key)
      if (col) {
        orderedColumns.push(col)
      }
    })
    
    columns.forEach(col => {
      const key = col.prop || col.label
      if (!columnOrder.value.includes(key)) {
        unorderedColumns.push(col)
      }
    })
    
    return [...orderedColumns, ...unorderedColumns]
  }
  
  return columns
})

// 列显示控制函数
const checkColumnVisible = (prop: string): boolean => {
  if (visibleColumns.value.length === 0) {
    return true
  }
  return visibleColumns.value.includes(prop)
}

// 监听列变化
const handleColumnChange = (columns: string[]) => {
  visibleColumns.value = columns
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const selectableColumns = columns.filter(col => {
    const column = tableColumns.find(c => (c.prop || c.label) === col)
    return column && !column.alwaysShow && !column.fixed
  })
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { visibleColumns: selectableColumns })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { visibleColumns: selectableColumns }).catch(() => {})
}

// 监听列排序变化
const handleColumnOrderChange = (order: string[]) => {
  columnOrder.value = order
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { columnOrder: order })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { columnOrder: order }).catch(() => {})
}

// 搜索表单
const searchForm = reactive({
})

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  }
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)


// 编辑
const handleEdit = (row: any) => {
  if (formDialogRef.value) {
    formDialogRef.value.openDialog('edit', row)
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除该宿舍楼吗？')
    await delObjs([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 合计行统计
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      // 序号列显示"合计"
      sums[index] = '合计'
      return
    }
    
    // 跳过序号、楼号、层数、电话、操作列
    const prop = column.property
    if (!prop || prop === 'buildingNo' || prop === 'layers' || prop === 'phone') {
      sums[index] = ''
      return
    }
    
    // 统计数值字段
    const values = data.map((item: any) => Number(item[prop]))
    if (!values.every((value: any) => isNaN(value))) {
      const sum = values.reduce((prev: number, curr: number) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = sum.toString()
    } else {
      sums[index] = ''
    }
  })
  
  return sums
}

// 查看空宿舍详情
const handleViewEmptyRoom = (row: any, roomType: string) => {
  if (emptyRoomDialogRef.value) {
    emptyRoomDialogRef.value.openDialog(row.buildingNo, roomType)
  }
}

// 初始化
onMounted(() => {
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
      loadSavedConfig()
    }
  })
})
</script>
