<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="schoolYear">
            <el-select 
              v-model="searchForm.schoolYear" 
              placeholder="请选择学年" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学期" prop="schoolTerm">
            <el-select 
              v-model="searchForm.schoolTerm" 
              placeholder="请选择学期" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <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="stuNo">
            <el-input 
              v-model="searchForm.stuNo" 
              placeholder="请输入学号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input 
              v-model="searchForm.realName" 
              placeholder="请输入姓名" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="日期范围" prop="dateRange">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 240px" />
          </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="User" 
            type="success" 
            class="ml10" 
            @click="teacherDialogRef.openDialog()">
            指定带班教师
          </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="schoolYear" label="学年" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><Calendar /></el-icon>
            <span style="margin-left: 4px">学年</span>
          </template>
        </el-table-column>
        <el-table-column prop="schoolTerm" label="学期" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><Clock /></el-icon>
            <span style="margin-left: 4px">学期</span>
          </template>
          <template #default="scope">
            <el-tag size="small" type="primary" effect="plain">
              {{ formatSchoolTerm(scope.row.schoolTerm) }}
            </el-tag>
          </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="stuNo" label="学号" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><CreditCard /></el-icon>
            <span style="margin-left: 4px">学号</span>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="姓名" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><Avatar /></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="className" 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="startTime" 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>{{ scope.row.startTime ? scope.row.startTime.split(' ')[0] : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" 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>{{ scope.row.endTime ? scope.row.endTime.split(' ')[0] : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="attendanceTeacherName" label="带班教师" show-overflow-tooltip align="center">
          <template #header>
            <el-icon><UserFilled /></el-icon>
            <span style="margin-left: 4px">带班教师</span>
          </template>
          <template #default="scope">
            <span>{{ scope.row.attendanceTeacherName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #header>
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 4px">操作</span>
          </template>
          <template #default="scope">
            <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" />

    <!-- 指定带班教师弹窗 -->
    <teacher-dialog ref="teacherDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="StuWorkStudyAlternate">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/stuworkstudyalternate";
import { getDeptList } from "/@/api/basic/basicclass";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import FormDialog from './form.vue'
import TeacherDialog from './teacher.vue'
import { List, Calendar, Clock, OfficeBuilding, CreditCard, Avatar, Grid, UserFilled, Setting } from '@element-plus/icons-vue'

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classNo: '',
  stuNo: '',
  realName: '',
  dateRange: null as [string, string] | null
})

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

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

// 查询
const handleSearch = () => {
  // 处理日期范围
  const params: any = { ...searchForm }
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.dateRangeStr = `${searchForm.dateRange[0]},${searchForm.dateRange[1]}`
  }
  delete params.dateRange
  
  // 处理学年数组
  if (params.schoolYear) {
    params.schoolYear = [params.schoolYear]
  }
  
  // 更新查询参数
  Object.assign(searchForm, params)
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.schoolYear = ''
  searchForm.schoolTerm = ''
  searchForm.deptCode = ''
  searchForm.classNo = ''
  searchForm.stuNo = ''
  searchForm.realName = ''
  searchForm.dateRange = null
  getDataList()
}

// 删除
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 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 getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    }
  } catch (err) {
    console.error('获取学年列表失败', err)
    schoolYearList.value = []
  }
}

// 获取学期列表
const getSchoolTermList = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data
    }
  } catch (err) {
    console.error('获取学期列表失败', err)
    schoolTermList.value = []
  }
}

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

