<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="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>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="Document" 
            type="primary" 
            class="ml10" 
            :disabled="selectedRows.length === 0"
            @click="handleApply">
            申请免学费
          </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"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="deptName" 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="majorName" label="专业" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column prop="stuNo" label="学号" show-overflow-tooltip align="center" width="120" />
        <el-table-column prop="realName" label="姓名" show-overflow-tooltip align="center" width="100" />
        <el-table-column prop="gender" label="性别" show-overflow-tooltip align="center" width="80">
          <template #default="scope">
            <span>{{ formatGender(scope.row.gender) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" show-overflow-tooltip align="center" min-width="180" />
        <el-table-column prop="bankCard" label="中职卡号" show-overflow-tooltip align="center" width="150" />
        <el-table-column prop="phone" label="联系方式" show-overflow-tooltip align="center" width="120" />
        <el-table-column prop="education" label="生源" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <span>{{ formatEducation(scope.row.education) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="majorLevel" label="层次" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <span>{{ formatMajorLevel(scope.row.majorLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="入学年份" show-overflow-tooltip align="center" width="100" />
        <el-table-column prop="gradeCurr" label="当前年纪" show-overflow-tooltip align="center" width="100" />
        <el-table-column prop="temporaryyeYear" label="借读学年" show-overflow-tooltip align="center" width="120" />
      </el-table>

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

    <!-- 申请免学费弹窗 -->
    <el-dialog 
      title="申请免学费" 
      v-model="applyDialogVisible" 
      :width="500" 
      :close-on-click-modal="false" 
      draggable>
      <el-form 
        ref="applyFormRef" 
        :model="applyForm" 
        :rules="applyRules" 
        label-width="120px">
        <el-form-item label="批次" prop="termId">
          <el-select 
            v-model="applyForm.termId" 
            placeholder="请选择批次" 
            clearable
            filterable
            style="width: 100%">
            <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>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :disabled="applyLoading">确 认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="TuitionFreeStuApply">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, applyObj } from "/@/api/stuwork/tuitionfreestuapply";
import { getClassListByRole } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import request from '/@/utils/request'

// 定义变量内容
const searchFormRef = ref()
const applyFormRef = ref()
const showSearch = ref(true)
const classList = ref<any[]>([])
const termList = ref<any[]>([])
const genderList = ref<any[]>([])
const educationList = ref<any[]>([])
const majorLevelList = ref<any[]>([])
const selectedRows = ref<any[]>([])
const applyDialogVisible = ref(false)
const applyLoading = ref(false)

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

// 申请表单
const applyForm = reactive({
  termId: ''
})

// 申请表单验证规则
const applyRules = {
  termId: [
    { required: true, message: '请选择批次', trigger: 'change' }
  ]
}

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

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

// 格式化性别
const formatGender = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = genderList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化生源
const formatEducation = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = educationList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化层次
const formatMajorLevel = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = majorLevelList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

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

// 申请免学费
const handleApply = () => {
  if (selectedRows.value.length === 0) {
    useMessage().warning('请至少选择一名学生')
    return
  }
  applyDialogVisible.value = true
  applyForm.termId = ''
}

// 提交申请
const handleSubmit = async () => {
  if (!applyFormRef.value) return
  
  await applyFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      applyLoading.value = true
      try {
        const { confirm } = useMessageBox()
        await confirm(`确定要为选中的 ${selectedRows.value.length} 名学生申请免学费吗？`)
        
        const studentIds = selectedRows.value.map((row: any) => row.id || row.stuNo)
        await applyObj({
          termId: applyForm.termId,
          studentIds: studentIds
        })
        useMessage().success('申请成功')
        applyDialogVisible.value = false
        selectedRows.value = []
        getDataList()
      } catch (err: any) {
        if (err !== 'cancel') {
          useMessage().error(err.msg || '申请失败')
        }
      } finally {
        applyLoading.value = false
      }
    }
  })
}

// 获取批次列表
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 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 = []
  }
}

// 获取性别字典
const getGenderDict = async () => {
  try {
    const res = await getDicts('sexy')
    if (res.data && Array.isArray(res.data)) {
      genderList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      genderList.value = []
    }
  } catch (err) {
    genderList.value = []
  }
}

// 获取生源字典
const getEducationDict = async () => {
  try {
    const res = await getDicts('pre_school_education')
    if (res.data && Array.isArray(res.data)) {
      educationList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      educationList.value = []
    }
  } catch (err) {
    educationList.value = []
  }
}

// 获取层次字典
const getMajorLevelDict = async () => {
  try {
    const res = await getDicts('basic_major_level')
    if (res.data && Array.isArray(res.data)) {
      majorLevelList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      majorLevelList.value = []
    }
  } catch (err) {
    majorLevelList.value = []
  }
}

// 初始化
onMounted(() => {
  getTermList()
  getClassListData()
  getGenderDict()
  getEducationDict()
  getMajorLevelDict()
})
</script>

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