<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-input 
              v-model="searchForm.schoolTerm" 
              placeholder="请输入学期" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="searchForm.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="classCode">
            <el-select 
              v-model="searchForm.classCode" 
              placeholder="请选择班号" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in filteredClassList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </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>
            <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="Download" 
            type="success" 
            class="ml10" 
            @click="handleExport">
            导 出
          </el-button>
          <el-button 
            icon="DataAnalysis" 
            type="info" 
            class="ml10" 
            @click="handleRank">
            学期统计
          </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">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip />
        <el-table-column prop="classNo" label="班号" show-overflow-tooltip />
        <el-table-column prop="realName" label="学生" show-overflow-tooltip />
        <el-table-column prop="recordTime" label="记录时间" show-overflow-tooltip />
        <el-table-column prop="score" label="分数" show-overflow-tooltip />
        <el-table-column prop="note" label="检查记录" show-overflow-tooltip />
        <el-table-column prop="handleResult" label="处理结果" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="Delete" 
              text 
              type="danger" 
              @click="handleDelete([scope.row.id])">
              删除
            </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 
      title="学期统计" 
      v-model="rankDialogVisible"
      :close-on-click-modal="false" 
      draggable
      width="800px">
      <el-form :inline="true" :model="rankForm">
        <el-form-item label="学年">
          <el-select 
            v-model="rankForm.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="学期">
          <el-input 
            v-model="rankForm.schoolTerm" 
            placeholder="请输入学期" 
            clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getRankData">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table 
        :data="rankData" 
        v-loading="rankLoading" 
        border 
        style="margin-top: 20px">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip />
        <el-table-column prop="classNo" label="班号" show-overflow-tooltip />
        <el-table-column prop="totalScore" label="总分数" show-overflow-tooltip />
        <el-table-column prop="count" label="记录数" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rankDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ClassCheckDaily">
import { ref, reactive, defineAsyncComponent, computed, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, exportData, getRank } from "/@/api/stuwork/classcheckdaily";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { getDeptList } from '/@/api/basic/basicclass'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import request from "/@/utils/request";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classCode: '',
  realName: ''
})

// 根据学院筛选班级列表
const filteredClassList = computed(() => {
  if (!searchForm.deptCode) {
    return classList.value
  }
  return classList.value.filter((item: any) => item.deptCode === searchForm.deptCode)
})

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

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

// 学期统计相关
const rankDialogVisible = ref(false)
const rankLoading = ref(false)
const rankData = ref<any[]>([])
const rankForm = reactive({
  schoolYear: '',
  schoolTerm: ''
})

// 学院选择变化
const handleDeptChange = () => {
  // 清空班号选择
  searchForm.classCode = ''
}

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

// 重置
const handleReset = () => {
  searchFormRef.value?.formRef?.resetFields()
  searchForm.schoolYear = ''
  searchForm.schoolTerm = ''
  searchForm.deptCode = ''
  searchForm.classCode = ''
  searchForm.realName = ''
  getDataList()
}

// 删除
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('确定要删除选中的记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }

  try {
    await delObjs(ids)
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败')
  }
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportData(searchForm)
    // 处理返回的文件流
    const blob = new Blob([res.data])
    const elink = document.createElement('a')
    elink.download = '日常巡检.xlsx'
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 打开学期统计对话框
const handleRank = () => {
  rankDialogVisible.value = true
  rankForm.schoolYear = ''
  rankForm.schoolTerm = ''
  rankData.value = []
}

// 获取学期统计数据
const getRankData = async () => {
  if (!rankForm.schoolYear || !rankForm.schoolTerm) {
    useMessage().warning('请选择学年和学期')
    return
  }
  
  try {
    rankLoading.value = true
    const res = await getRank({
      schoolYear: rankForm.schoolYear,
      schoolTerm: rankForm.schoolTerm
    })
    if (res.data) {
      rankData.value = Array.isArray(res.data) ? res.data : []
    } else {
      rankData.value = []
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取统计数据失败')
    rankData.value = []
  } finally {
    rankLoading.value = false
  }
}

// 获取学院列表
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 getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取班号列表失败', err)
    classList.value = []
  }
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data) {
      schoolYearList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学年列表失败', err)
    schoolYearList.value = []
  }
}

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