<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              宿舍楼列表
            </span>
            <div class="header-actions">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                新 增
              </el-button>
              <right-toolbar  
                class="ml10"
                @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>
          </div>
        </template>

        <!-- 表格 -->
        <el-table 
          :data="state.dataList" 
          v-loading="state.loading" 
          stripe
          :cell-style="tableStyle.cellStyle" 
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table"
          @sort-change="sortChangeHandle"
          show-summary
          :summary-method="getSummaries">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <template v-for="col in visibleColumnsSorted" :key="col.prop || col.label">
            <el-table-column 
              v-if="checkColumnVisible(col.prop || '') && col.prop !== '操作'"
              :prop="col.prop" 
              :label="col.label" 
              :width="col.width"
              :min-width="col.minWidth"
              :show-overflow-tooltip="col.showOverflowTooltip !== false"
              :align="col.align || 'center'">
              <template #header>
                <el-icon v-if="col.icon"><component :is="col.icon" /></el-icon>
                <span :style="{ marginLeft: col.icon ? '4px' : '0' }">{{ 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" 
                link
                type="primary" 
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link
                type="danger" 
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" :image-size="120" />
          </template>
        </el-table>

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

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

<script setup lang="ts" name="DormBuilding">
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
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, Document } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

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

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

// 使用表格列控制 Hook
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns)

// 搜索表单
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(() => {
  // Hook 会自动加载配置
})
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>
