<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 搜索表单卡片 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              筛选条件
            </span>
          </div>
        </template>
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch" class="search-form">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="searchForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable 
              style="width: 200px">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼号" prop="buildingNo">
            <el-select 
              v-model="searchForm.buildingNo" 
              placeholder="请选择楼号" 
              clearable
              filterable 
              style="width: 200px">
              <el-option
                v-for="item in buildingList"
                :key="item.buildingNo"
                :label="item.buildingNo"
                :value="item.buildingNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间号" prop="roomNo">
            <el-input 
              v-model="searchForm.roomNo" 
              placeholder="请输入房间号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="几人间" prop="bedNum">
            <el-select 
              v-model="searchForm.bedNum" 
              placeholder="请选择几人间" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in bedNumList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="已住人数" prop="livedNum">
            <el-input 
              v-model="searchForm.livedNum" 
              placeholder="请输入已住人数" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 内容卡片 -->
      <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>
              <el-button 
                icon="OfficeBuilding" 
                type="success" 
                class="ml10" 
                @click="handleDeptAssign">
                学院安排
              </el-button>
              <el-button 
                icon="Download" 
                type="warning" 
                class="ml10" 
                @click="handleExport">
                导出
              </el-button>
              <right-toolbar  
                v-model:showSearch="showSearch" 
                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"
          @sort-change="sortChangeHandle"
          @selection-change="handleSelectionChange"
          class="modern-table">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index }">
              {{ $index + 1 + ((state.pagination?.current || 1) - 1) * (state.pagination?.size || 10) }}
            </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" 
              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 === 'bedNum'" #default="scope">
              <el-tag v-if="scope.row.bedNum" size="small" type="info" effect="plain">
                {{ scope.row.bedNum }}人间
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 已住人数列特殊模板-->
            <template v-else-if="col.prop === 'livedNum'" #default="scope">
              <el-tag v-if="scope.row.livedNum !== undefined && scope.row.livedNum !== null" size="small" type="success" effect="plain">
                {{ scope.row.livedNum }}
              </el-tag>
              <span v-else>-</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>
        </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)" />
    
    <!-- 学院安排对话框-->
    <el-dialog 
      v-model="deptAssignDialogVisible" 
      title="学院安排" 
      :width="500" 
      :close-on-click-modal="false">
      <el-form :model="deptAssignForm" label-width="100px">
        <el-form-item label="学院" required>
          <el-select 
            v-model="deptAssignForm.deptCode" 
            placeholder="请选择学院" 
            filterable
            style="width: 100%">
            <el-option
              v-for="item in deptList"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deptAssignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeptAssign" :loading="deptAssignLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="DormRoom">
import { ref, reactive, defineAsyncComponent, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, editDept } from "/@/api/stuwork/dormroom";
import { getDeptList } from "/@/api/basic/basicclass";
import { getBuildingList } from "/@/api/stuwork/dormbuilding";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { downBlobFile, adaptationUrl } from "/@/utils/other";
import { getDicts } from "/@/api/admin/dict";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
import { List, OfficeBuilding, House, UserFilled, EditPen, Setting, Menu, Calendar, Search, Document } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'


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

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院' },
  { prop: 'buildingNo', label: '楼号' },
  { prop: 'roomNo', label: '房间号' },
  { prop: 'bedNum', label: '几人间' },
  { prop: 'livedNum', label: '已住人数' },
  { prop: 'remarks', label: '备注' }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  deptName: { icon: OfficeBuilding },
  buildingNo: { icon: OfficeBuilding },
  roomNo: { icon: House },
  bedNum: { icon: UserFilled },
  livedNum: { icon: UserFilled },
  remarks: { icon: EditPen }
}

// 使用表格列控制hook
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns)
const searchFormRef = ref()
const showSearch = ref(true)
const deptList = ref<any[]>([])
const buildingList = ref<any[]>([])
const bedNumList = ref<any[]>([])
const selectedRows = ref<any[]>([])
const deptAssignDialogVisible = ref(false)
const deptAssignLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  deptCode: '',
  buildingNo: '',
  roomNo: '',
  bedNum: '',
  livedNum: ''
})

// 学院安排表单
const deptAssignForm = reactive({
  deptCode: ''
})

// 配置 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 handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 查询
const handleSearch = () => {
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.formRef?.resetFields()
  searchForm.deptCode = ''
  searchForm.buildingNo = ''
  searchForm.roomNo = ''
  searchForm.bedNum = ''
  searchForm.livedNum = ''
  getDataList()
}

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

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

// 学院安排
const handleDeptAssign = () => {
  if (selectedRows.value.length === 0) {
    useMessage().warning('请先选择要安排的宿舍房间')
    return
  }
  deptAssignDialogVisible.value = true
  deptAssignForm.deptCode = ''
}

// 确认学院安排
const confirmDeptAssign = async () => {
  if (!deptAssignForm.deptCode) {
    useMessage().warning('请选择学院')
    return
  }
  
  try {
    deptAssignLoading.value = true
    const ids = selectedRows.value.map((row: any) => row.id)
    await editDept({
      deptCode: deptAssignForm.deptCode,
      ids
    })
    useMessage().success('安排成功')
    deptAssignDialogVisible.value = false
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '安排失败')
  } finally {
    deptAssignLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  try {
    await downBlobFile(
      adaptationUrl('/stuwork/dormroom/export'), 
      searchForm, 
      '宿舍房间.xlsx'
    )
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    deptList.value = []
  }
}

// 获取楼号列表
const getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    if (res.data) {
      buildingList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    buildingList.value = []
  }
}

// 获取几人间字典
const getBedNumDict = async () => {
  try {
    const res = await getDicts('room_stu_num')
    if (res.data) {
      bedNumList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    bedNumList.value = []
  }
}

// 初始化
onMounted(() => {
  getDeptListData()
  getBuildingListData()
  getBedNumDict()
})
</script>

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