<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="state.queryForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px"
              @change="handleDeptChange">
              <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-select 
              v-model="state.queryForm.classNo" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classNo"
                :label="item.classNo"
                :value="item.classNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input 
              v-model="state.queryForm.title" 
              placeholder="请输入标题" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain icon="Search" @click="getDataList">查询</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="Plus" 
            type="primary" 
            class="ml10" 
            @click="formDialogRef.openDialog()">
            新增
          </el-button>
          <el-button 
            icon="RefreshLeft" 
            type="warning" 
            class="ml10" 
            @click="handleInit">
            初始化
          </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">
        <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="classNo" label="班级" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><Grid /></el-icon>
            <span style="margin-left: 4px">班级</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" show-overflow-tooltip align="center" min-width="200">
          <template #header>
            <el-icon><Document /></el-icon>
            <span style="margin-left: 4px">标题</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip align="center" width="180">
          <template #header>
            <el-icon><Calendar /></el-icon>
            <span style="margin-left: 4px">创建时间</span>
          </template>
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" show-overflow-tooltip align="center" min-width="200">
          <template #header>
            <el-icon><EditPen /></el-icon>
            <span style="margin-left: 4px">备注</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" 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="Document" 
              text 
              type="info" 
              @click="handleFileList(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>

    <!-- 新增/编辑表单弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList" />

    <!-- 附件列表弹窗 -->
    <file-list-dialog ref="fileListDialogRef" />
  </div>
</template>

<script setup lang="ts" name="ClassConstruction">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, initObj } from "/@/api/stuwork/classconstruction";
import { getDeptList } from "/@/api/basic/basicclass";
import { list as getClassList } from "/@/api/basic/basicclass";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { parseTime } from "/@/utils/formatTime"
import FormDialog from './form.vue'
import FileListDialog from './fileList.vue'
import { List, OfficeBuilding, Grid, Document, Calendar, EditPen, Setting } from '@element-plus/icons-vue'

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

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    deptCode: '',
    classNo: '',
    title: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

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

// 学院变化时更新班级列表
const handleDeptChange = async (deptCode: string) => {
  state.queryForm.classNo = ''
  if (deptCode) {
    await getClassListByDept(deptCode)
  } else {
    classList.value = []
  }
}

// 根据学院获取班级列表
const getClassListByDept = async (deptCode: string) => {
  try {
    const res = await getClassList()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data.filter((item: any) => item.deptCode === deptCode)
    } else {
      classList.value = []
    }
  } catch (err) {
    console.error('获取班级列表失败', err)
    classList.value = []
  }
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.deptCode = ''
  state.queryForm.classNo = ''
  state.queryForm.title = ''
  classList.value = []
  getDataList()
}

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

// 删除
const handleDelete = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要删除该班级建设方案吗？')
    await delObj([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 初始化
const handleInit = async () => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要初始化班级建设方案吗？')
    await initObj()
    useMessage().success('初始化成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '初始化失败')
    }
  }
}

// 附件列表
const handleFileList = (row: any) => {
  fileListDialogRef.value?.openDialog(row)
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data && Array.isArray(res.data)) {
      deptList.value = res.data
    } else {
      deptList.value = []
    }
  } catch (err) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

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

<style scoped lang="scss"> 
</style>
