<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="deptName">
            <el-select 
              v-model="searchForm.deptName" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px">
              <el-option 
                v-for="item in deptList"
                :key="item.deptCode" 
                :label="item.deptName"
                :value="item.deptName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班号" prop="classCode">
            <el-select 
              v-model="searchForm.classCode" 
              placeholder="请选择班号" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级状态" prop="classStatus">
            <el-select 
              v-model="searchForm.classStatus" 
              placeholder="请选择班级状态" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in classStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教室位置" prop="position">
            <el-input 
              v-model="searchForm.position" 
              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="Download" 
                type="success" 
                @click="handleExport">
                导出
              </el-button>
              <el-button 
                icon="Refresh" 
                type="primary" 
                class="ml10" 
                @click="handleSync">
                同步教室安排
              </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
          row-key="id"
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table">
          <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" 
              :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 === 'classStatus'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatClassStatus(scope.row.classStatus) }}
              </el-tag>
            </template>
            <!-- 人数列特殊模板 -->
            <template v-else-if="col.prop === 'stuNum'" #default="scope">
              <el-tag v-if="scope.row.stuNum" size="small" type="success" effect="plain">
                {{ scope.row.stuNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 讲台类型列特殊模板 -->
            <template v-else-if="col.prop === 'platformType'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatDict(scope.row.platformType, platformTypeList) }}
              </el-tag>
            </template>
            <!-- 投影类型列特殊模板 -->
            <template v-else-if="col.prop === 'tyType'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatDict(scope.row.tyType, tyTypeList) }}
              </el-tag>
            </template>
            <!-- 电视机列特殊模板 -->
            <template v-else-if="col.prop === 'tvType'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatDict(scope.row.tvType, tvTypeList) }}
              </el-tag>
            </template>
          </el-table-column>
        </template>
          <el-table-column label="操作" width="380" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                v-if="!scope.row.classCode || !scope.row.position"
                icon="Setting" 
                link
                type="primary" 
                @click="handleArrange(scope.row)">
                教室安排
              </el-button>
              <el-button  
                icon="Close" 
                link
                type="danger" 
                @click="handleCancelArrange(scope.row)">
                取消教室安排
              </el-button>
              <el-button 
                icon="Collection" 
                link
                type="success" 
                @click="handleAssets(scope.row)"
                class="ml10">
                教室公物
              </el-button>
              <el-button 
                icon="Lock" 
                link
                type="warning" 
                @click="handlePassword(scope.row)"
                class="ml10">
                门锁密码
              </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>

    <!-- 教室安排表单弹窗 -->
    <arrange-dialog ref="arrangeDialogRef" @refresh="getDataList" />
    <!-- 教室公物编辑弹窗 -->
    <assets-dialog ref="assetsDialogRef" @refresh="getDataList" />
    <!-- 门锁密码编辑弹窗 -->
    <password-dialog ref="passwordDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="ClassroomBase">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, exportData, syncClassroomArrangement } from "/@/api/stuwork/classroombase";
import { getDeptListByLevelTwo } from "/@/api/basic/basicdept";
import { queryAllClass } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import ArrangeDialog from './arrange.vue'
import AssetsDialog from './assets.vue'
import PasswordDialog from './password.vue'
import { delClassRoomAssign } from '/@/api/stuwork/teachclassroomassign'
import { List, OfficeBuilding, CircleCheck, Location, UserFilled, Collection, Setting, Menu, Calendar, Search, Document, Close, Lock } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const searchFormRef = ref()
const columnControlRef = ref<any>()
const showSearch = ref(true)
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const classStatusList = ref<any[]>([])
const platformTypeList = ref<any[]>([])
const tyTypeList = ref<any[]>([])
const tvTypeList = ref<any[]>([])
const arrangeDialogRef = ref()
const assetsDialogRef = ref()
const passwordDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'buildingNo', label: '楼号', icon: OfficeBuilding },
  { prop: 'deptName', label: '学院', icon: OfficeBuilding },
  { prop: 'classStatus', label: '班级状态', icon: CircleCheck },
  { prop: 'position', label: '教室位置', icon: Location },
  { prop: 'stuNum', label: '人数', icon: UserFilled },
  { prop: 'teacherRealName', label: '班主任', icon: UserFilled },
  { prop: 'platformType', label: '讲台类型', icon: Collection },
  { prop: 'tyType', label: '投影类型', icon: Collection },
  { prop: 'tvType', label: '电视机', icon: Collection },
  { prop: 'chairCnt', label: '方凳数量', icon: Calendar },
  { prop: 'tableCnt', label: '课桌数量', icon: Calendar },
  { prop: 'password', label: '锁密码', icon: Calendar }
]

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

// 班级状态列表
const classStatusListData = [
  { label: '在校', value: '0' },
  { label: '顶岗', value: '1' },
  { label: '更岗', value: '2' },
  { label: '离校', value: '3' }
]

// 搜索表单
const searchForm = reactive({
  deptName: '',
  classCode: '',
  classStatus: '',
  position: ''
})

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: async (queryParams: any) => {
    try {
      const response = await fetchList(queryParams)
      // 处理 ipage 数据结构
      if (response && response.data) {
        if (response.data.ipage) {
          // 如果 ipage 是包含 records 和 total 的对象
          if (Array.isArray(response.data.ipage)) {
            // ipage 是数组
            return {
              ...response,
              data: {
                records: response.data.ipage || [],
                total: response.data.total || response.data.ipage.length || 0
              }
            }
          } else {
            // ipage 是对象，包含 records 和 total
            return {
              ...response,
              data: {
                records: response.data.ipage.records || [],
                total: response.data.ipage.total || 0
              }
            }
          }
        }
        // 如果没有 ipage，尝试直接使用 data
        return {
          ...response,
          data: {
            records: response.data.records || response.data || [],
            total: response.data.total || 0
          }
        }
      }
      // 如果 response 结构不对，返回空数据
      return {
        ...response,
        data: {
          records: [],
          total: 0
        }
      }
    } catch (err: any) {
      // 确保即使出错也返回正确的数据结构
      throw err
    }
  },
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

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

// 格式化班级状态
const formatClassStatus = (value: string) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = classStatusList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化字典
const formatDict = (value: string, dictList: any[]) => {
  if (!value) return '-'
  const item = dictList.find((item: any) => item.value === value)
  return item ? item.label : value
}

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

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  getDataList()
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportData(searchForm)
    // 创建下载链接
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const elink = document.createElement('a')
    elink.style.display = 'none'
    elink.href = url
    elink.setAttribute('download', `教室安排及公物管理_${new Date().getTime()}.xlsx`)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 同步教室安排
const handleSync = async () => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要同步教室安排吗？')
    await syncClassroomArrangement()
    useMessage().success('同步成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '同步失败')
    }
  }
}

// 教室安排
const handleArrange = (row: any) => {
  arrangeDialogRef.value?.openDialog(row)
}

// 取消教室安排
const handleCancelArrange = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要取消教室安排吗？')
    await delClassRoomAssign(row)
    useMessage().success('取消成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || '取消失败')
      }
    }
  }
}

// 教室公物
const handleAssets = (row: any) => {
  assetsDialogRef.value?.openDialog(row)
}

// 门锁密码
const handlePassword = (row: any) => {
  passwordDialogRef.value?.openDialog(row)
}

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

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await queryAllClass()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

// 获取讲台类型字典
const getPlatformTypeDict = async () => {
  try {
    const res = await getDicts('platform_type')
    if (res.data) {
      platformTypeList.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) {
    platformTypeList.value = []
  }
}

// 获取投影类型字典
const getTyTypeDict = async () => {
  try {
    const res = await getDicts('ty_type')
    if (res.data) {
      tyTypeList.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) {
    tyTypeList.value = []
  }
}

// 获取电视机类型字典
const getTvTypeDict = async () => {
  try {
    const res = await getDicts('tv_type')
    if (res.data) {
      tvTypeList.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) {
    tvTypeList.value = []
  }
}

// 初始化
onMounted(() => {
  classStatusList.value = classStatusListData
  getDeptListData()
  getClassListData()
  getPlatformTypeDict()
  getTyTypeDict()
  getTvTypeDict()
})
</script>

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

