<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="schoolYear">
            <el-select 
              v-model="state.queryForm.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="state.queryForm.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>
            <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" 
            @click="handleAdd">
            新增
          </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" />
        <el-table-column prop="title" label="批次名称" show-overflow-tooltip align="center" min-width="200" />
        <el-table-column prop="schoolYear" label="学年" show-overflow-tooltip align="center" width="120" />
        <el-table-column prop="schoolTerm" label="学期" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <span>{{ formatSchoolTerm(scope.row.schoolTerm) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="季度" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <span>{{ formatQuarter(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="classify" label="类别" show-overflow-tooltip align="center" width="100">
          <template #default="scope">
            <span>{{ formatClassify(scope.row.classify) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="moneyValue" label="补助金额" show-overflow-tooltip align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.moneyValue !== undefined && scope.row.moneyValue !== null ? scope.row.moneyValue : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始日期" show-overflow-tooltip align="center" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="截止日期" show-overflow-tooltip align="center" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" show-overflow-tooltip align="center" min-width="150" />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="handleEdit(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" />
  </div>
</template>

<script setup lang="ts" name="StipendTermBatch">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/stipendtermbatch";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { parseTime } from "/@/utils/formatTime";
import FormDialog from './form.vue'

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

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

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

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

// 格式化学期
const formatSchoolTerm = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = schoolTermList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化季度
const formatQuarter = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = quarterList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

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

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

// 新增
const handleAdd = () => {
  formDialogRef.value?.openDialog('add')
}

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

// 删除
const handleDelete = async (row: any) => {
  try {
    const { confirm } = useMessageBox()
    await confirm(`确定要删除批次 "${row.title}" 吗？`)
    await delObj([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    } else {
      schoolYearList.value = []
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

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

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

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

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getQuarterDict()
  getClassifyDict()
})
</script>

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

