<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="termId">
            <el-select 
              v-model="state.queryForm.termId" 
              placeholder="请选择批次" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in termList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="state.queryForm.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="classCode">
            <el-select 
              v-model="state.queryForm.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>
            <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>

      <!-- Tab切换 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="免学费审批" name="pending"></el-tab-pane>
            <el-tab-pane label="已审批" name="approved"></el-tab-pane>
          </el-tabs>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            class="ml10 mr20"
            style="float: right;"
            @queryTable="getDataList">
          </right-toolbar>
        </div>
      </el-row>

      <!-- 免学费审批表格 -->
      <el-table 
        v-if="activeTab === 'pending'"
        :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="termTitle" label="免学费批次" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="majorName" label="专业名称" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="classNo" label="班号" show-overflow-tooltip align="center" width="120" />
        <el-table-column prop="teacherName" label="班主任" show-overflow-tooltip align="center" width="100" />
        <el-table-column prop="num" label="人数" show-overflow-tooltip align="center" width="80">
          <template #default="scope">
            <span>{{ scope.row.num !== undefined && scope.row.num !== null ? scope.row.num : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 已审批表格（带合计） -->
      <el-table 
        v-if="activeTab === 'approved'"
        :data="state.dataList" 
        v-loading="state.loading"
        border 
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        show-summary
        :summary-method="getSummaries">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="termTitle" label="免学费批次" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="classNum" label="申报班级数" show-overflow-tooltip align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.classNum !== undefined && scope.row.classNum !== null ? scope.row.classNum : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stuNum" label="申报人数" show-overflow-tooltip align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.stuNum !== undefined && scope.row.stuNum !== null ? scope.row.stuNum : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination 
        @size-change="sizeChangeHandle" 
        @current-change="currentChangeHandle" 
        v-bind="state.pagination" />
    </div>

    <!-- 查看详情弹窗 -->
    <detail-dialog ref="detailDialogRef" />
  </div>
</template>

<script setup lang="ts" name="TuitionFreeStuApprove">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { getApproveData, getApprovedData } from "/@/api/stuwork/tuitionfreestuapprove";
import { getDeptList } from "/@/api/basic/basicclass";
import { getClassListByRole } from "/@/api/basic/basicclass";
import request from '/@/utils/request'
import DetailDialog from './detail.vue'

// 定义变量内容
const searchFormRef = ref()
const detailDialogRef = ref()
const showSearch = ref(true)
const activeTab = ref('pending')
const termList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])

// 表格样式
const tableStyle = {
  cellStyle: { padding: '8px 0' },
  headerCellStyle: { background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }
}

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

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

// Tab切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'pending') {
    state.pageList = getApproveData
  } else {
    state.pageList = getApprovedData
  }
  getDataList()
}

// 合计方法（仅用于已审批表格）
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'classNum' || column.property === 'stuNum') {
      const values = data.map((item: any) => Number(item[column.property] || 0))
      const sum = values.reduce((prev: number, curr: number) => {
        return prev + curr
      }, 0)
      sums[index] = sum
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.termId = ''
  state.queryForm.deptCode = ''
  state.queryForm.classCode = ''
  getDataList()
}

// 查看详情
const handleViewDetail = (row: any) => {
  detailDialogRef.value?.openDialog(row)
}

// 获取批次列表
const getTermList = async () => {
  try {
    const res = await request({
      url: '/stuwork/tuitionfreeterm/list',
      method: 'get'
    })
    if (res.data && Array.isArray(res.data)) {
      termList.value = res.data
    } else {
      termList.value = []
    }
  } catch (err) {
    termList.value = []
  }
}

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

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

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

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

