<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch">
          <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-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="FolderAdd" 
            type="primary" 
            class="ml10" 
            @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 mr20"
            style="float: right;"
            @queryTable="getDataList">
          </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"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #header>
            <el-icon><List /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><OfficeBuilding /></el-icon>
            <span style="margin-left: 4px">学院</span>
          </template>
        </el-table-column>
        <el-table-column prop="buildingNo" label="楼号" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><OfficeBuilding /></el-icon>
            <span style="margin-left: 4px">楼号</span>
          </template>
        </el-table-column>
        <el-table-column prop="roomNo" label="房间号" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><House /></el-icon>
            <span style="margin-left: 4px">房间号</span>
          </template>
        </el-table-column>
        <el-table-column prop="bedNum" label="几人间" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><UserFilled /></el-icon>
            <span style="margin-left: 4px">几人间</span>
          </template>
          <template #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>
        </el-table-column>
        <el-table-column prop="livedNum" label="已住人数" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><UserFilled /></el-icon>
            <span style="margin-left: 4px">已住人数</span>
          </template>
          <template #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>
        <el-table-column prop="remarks" label="备注" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><EditPen /></el-icon>
            <span style="margin-left: 4px">备注</span>
          </template>
        </el-table-column>
        <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)" />
    
    <!-- 学院安排对话框 -->
    <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 } from 'vue'
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";

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

// 定义变量内容
const formDialogRef = ref()
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) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

// 获取楼号列表
const getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    if (res.data) {
      buildingList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取楼号列表失败', 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) {
    console.error('获取几人间字典失败', err)
    bedNumList.value = []
  }
}

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