<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="classNo">
            <el-input 
              v-model="searchForm.classNo" 
              placeholder="请输入班号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="异动类型" prop="changeType">
            <el-select 
              v-model="searchForm.changeType" 
              placeholder="请选择异动类型" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in changeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </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%">
          <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">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="createTime" label="变动时间" show-overflow-tooltip align="center">
          <template #default="scope">
            <span>{{ scope.row.createTime ? scope.row.createTime.split(' ')[0] + ' ' + scope.row.createTime.split(' ')[1] : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip align="center" />
        <el-table-column prop="classNo" label="班号" show-overflow-tooltip align="center" />
        <el-table-column prop="stuNo" label="学号" show-overflow-tooltip align="center" />
        <el-table-column prop="realName" label="姓名" show-overflow-tooltip align="center" />
        <el-table-column prop="changeType" label="异动类型" show-overflow-tooltip align="center">
          <template #default="scope">
            <span>{{ formatChangeType(scope.row.changeType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="roomNo" label="原房间号" show-overflow-tooltip align="center" />
        <el-table-column prop="bedNo" label="原床位号" show-overflow-tooltip align="center" />
        <el-table-column prop="newRoomNo" label="新房间号" show-overflow-tooltip align="center" />
        <el-table-column prop="newBedNo" label="新床位号" show-overflow-tooltip align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleView(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts" name="DormRoomStudentChange">
import { reactive, ref, onMounted, computed } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { queryStudentAbnormal } from "/@/api/stuwork/dormroomstudent";
import { getDeptList } from "/@/api/basic/basicclass";
import { useMessage } from "/@/hooks/message";
import { getDicts } from "/@/api/admin/dict";

// 定义变量内容
const searchFormRef = ref()
const showSearch = ref(true)
const deptList = ref<any[]>([])
const changeTypeList = ref<any[]>([])
const allDataList = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  deptCode: '',
  classNo: '',
  changeType: ''
})

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  isPage: false, // 接口不支持分页
  pageList: async () => {
    try {
      const res = await queryStudentAbnormal()
      let dataList = []
      if (Array.isArray(res.data)) {
        dataList = res.data
      } else if (res.data && Array.isArray(res.data.records)) {
        dataList = res.data.records
      } else if (res.data && Array.isArray(res.data.list)) {
        dataList = res.data.list
      }
      allDataList.value = dataList
      return {
        ...res,
        data: filterData(dataList)
      }
    } catch (err: any) {
      useMessage().error(err.msg || '获取数据失败')
      return {
        data: []
      }
    }
  },
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

// 过滤数据
const filterData = (data: any[]) => {
  let filtered = data
  if (searchForm.deptCode) {
    filtered = filtered.filter(item => item.deptCode === searchForm.deptCode)
  }
  if (searchForm.classNo) {
    filtered = filtered.filter(item => item.classNo && item.classNo.includes(searchForm.classNo))
  }
  if (searchForm.changeType) {
    filtered = filtered.filter(item => item.changeType === searchForm.changeType)
  }
  return filtered
}

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

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

// 重置
const handleReset = () => {
  searchFormRef.value?.formRef?.resetFields()
  searchForm.deptCode = ''
  searchForm.classNo = ''
  searchForm.changeType = ''
  getDataList()
}

// 查看详情
const handleView = (row: any) => {
  // TODO: 实现查看详情功能
  console.log('查看详情', row)
}

// 格式化异动类型
const formatChangeType = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = changeTypeList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 获取学院列表
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 getChangeTypeDict = async () => {
  try {
    const res = await getDicts('change_type')
    if (res.data) {
      changeTypeList.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)
    changeTypeList.value = []
  }
}

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

