<!--
  -    Copyright (c) 2018-2025, cyweb All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  -
  -->

<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline class="mb-4">
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
          <el-button type="primary" plain icon="Refresh" class="ml10" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item v-if="permissions.recruit_recruitstudentplan_add">
          <el-button type="primary" icon="FolderAdd" class="ml10" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :data="state.dataList"
        v-loading="state.loading"
        border
        stripe
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="majorCode" label="专业代码" align="center" show-overflow-tooltip />
        <el-table-column prop="xy" label="系部" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentNum" label="拟招人数（不限男女）和拟招男女生数互斥" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentBoyNum" label="拟招男生数" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentGirlNum" label="拟招女生数" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentOverNum" label="拟招过载人数(不限男女) 和拟招过载男女生数互斥" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentOverBoyNum" label="拟招过载男生数" align="center" show-overflow-tooltip />
        <el-table-column prop="needStudentOverGirlNum" label="拟招过载女生数" align="center" show-overflow-tooltip />
        <el-table-column prop="scoreLine" label="录取分数线" align="center" show-overflow-tooltip />
        <el-table-column prop="scoreMinLine" label="最低录取分数线" align="center" show-overflow-tooltip />
        <el-table-column prop="planStudentNum" label="计划招生人数（不限男女）" align="center" show-overflow-tooltip />
        <el-table-column prop="planStudentBoyNum" label="计划招生男生数" align="center" show-overflow-tooltip />
        <el-table-column prop="planStudentGirlNum" label="计划招生女生数" align="center" show-overflow-tooltip />
        <el-table-column prop="degreeOfEducation" label="生源" align="center" show-overflow-tooltip />
        <el-table-column prop="scoreFeeConf" label="捐资助学费配置" align="center" show-overflow-tooltip />
        <el-table-column prop="tuition" label="学费配置，和生源对应" align="center" show-overflow-tooltip />
        <el-table-column prop="remarks" label="备注信息" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="permissions.recruit_recruitstudentplan_edit"
              type="primary"
              link
              icon="EditPen"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="permissions.recruit_recruitstudentplan_del"
              type="danger"
              link
              icon="Delete"
              @click="handleDel(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑' : '新增'"
        width="600px"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="formRules"
          label-width="180px"
        >
          <el-form-item label="专业代码" prop="majorCode">
            <el-input v-model="form.majorCode" placeholder="请输入专业代码" clearable />
          </el-form-item>
          <el-form-item label="系部" prop="xy">
            <el-input v-model="form.xy" placeholder="请输入系部" clearable />
          </el-form-item>
          <el-form-item label="拟招人数（不限男女）" prop="needStudentNum">
            <el-input-number v-model="form.needStudentNum" :min="0" placeholder="请输入拟招人数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="拟招男生数" prop="needStudentBoyNum">
            <el-input-number v-model="form.needStudentBoyNum" :min="0" placeholder="请输入拟招男生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="拟招女生数" prop="needStudentGirlNum">
            <el-input-number v-model="form.needStudentGirlNum" :min="0" placeholder="请输入拟招女生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="拟招过载人数(不限男女)" prop="needStudentOverNum">
            <el-input-number v-model="form.needStudentOverNum" :min="0" placeholder="请输入拟招过载人数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="拟招过载男生数" prop="needStudentOverBoyNum">
            <el-input-number v-model="form.needStudentOverBoyNum" :min="0" placeholder="请输入拟招过载男生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="拟招过载女生数" prop="needStudentOverGirlNum">
            <el-input-number v-model="form.needStudentOverGirlNum" :min="0" placeholder="请输入拟招过载女生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="录取分数线" prop="scoreLine">
            <el-input-number v-model="form.scoreLine" :min="0" placeholder="请输入录取分数线" style="width: 100%" />
          </el-form-item>
          <el-form-item label="最低录取分数线" prop="scoreMinLine">
            <el-input-number v-model="form.scoreMinLine" :min="0" placeholder="请输入最低录取分数线" style="width: 100%" />
          </el-form-item>
          <el-form-item label="计划招生人数（不限男女）" prop="planStudentNum">
            <el-input-number v-model="form.planStudentNum" :min="0" placeholder="请输入计划招生人数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="计划招生男生数" prop="planStudentBoyNum">
            <el-input-number v-model="form.planStudentBoyNum" :min="0" placeholder="请输入计划招生男生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="计划招生女生数" prop="planStudentGirlNum">
            <el-input-number v-model="form.planStudentGirlNum" :min="0" placeholder="请输入计划招生女生数" style="width: 100%" />
          </el-form-item>
          <el-form-item label="生源" prop="degreeOfEducation">
            <el-input v-model="form.degreeOfEducation" placeholder="请输入生源" clearable />
          </el-form-item>
          <el-form-item label="捐资助学费配置" prop="scoreFeeConf">
            <el-input v-model="form.scoreFeeConf" placeholder="请输入捐资助学费配置" clearable />
          </el-form-item>
          <el-form-item label="学费配置，和生源对应" prop="tuition">
            <el-input v-model="form.tuition" placeholder="请输入学费配置" clearable />
          </el-form-item>
          <el-form-item label="备注信息" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" clearable />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="recruitstudentplan">
import { ref, reactive, computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { addObj, delObj, fetchList, putObj } from '/@/api/recruit/recruitstudentplan'

// 使用 Pinia store
const userInfoStore = useUserInfo()
const { userInfos } = storeToRefs(userInfoStore)

// 创建权限对象
const permissions = computed(() => {
  const perms: Record<string, boolean> = {}
  userInfos.value.authBtnList.forEach((perm: string) => {
    perms[perm] = true
  })
  return perms
})

// 消息提示 hooks
const message = useMessage()
const messageBox = useMessageBox()

// 表格引用
const tableRef = ref()
const formRef = ref()

// 弹窗状态
const dialogVisible = ref(false)
const submitLoading = ref(false)

// 查询表单
const queryForm = reactive({})

// 表单数据
const form = reactive({
  id: '',
  majorCode: '',
  xy: '',
  needStudentNum: undefined,
  needStudentBoyNum: undefined,
  needStudentGirlNum: undefined,
  needStudentOverNum: undefined,
  needStudentOverBoyNum: undefined,
  needStudentOverGirlNum: undefined,
  scoreLine: undefined,
  scoreMinLine: undefined,
  planStudentNum: undefined,
  planStudentBoyNum: undefined,
  planStudentGirlNum: undefined,
  degreeOfEducation: '',
  scoreFeeConf: '',
  tuition: '',
  remarks: ''
})

// 表单验证规则
const formRules = {}

// 表格状态
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: queryForm,
  pageList: async (params: any) => {
    const response = await fetchList(params)
    return {
      data: {
        records: response.data.records,
        total: response.data.total
      }
    }
  }
})

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

// 重置查询
const resetQuery = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = ''
  })
  getDataList()
}

// 新增
const handleAdd = () => {
  Object.keys(form).forEach(key => {
    if (key === 'id') {
      form[key] = ''
    } else if (typeof form[key] === 'number') {
      form[key] = undefined
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: any) => {
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除
const handleDel = async (row: any) => {
  try {
    await messageBox.confirm(`是否确认删除ID为${row.id}的记录？`)
    await delObj(row.id)
    message.success('删除成功')
    getDataList()
  } catch {
    // 用户取消
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await putObj(form)
          message.success('修改成功')
        } else {
          await addObj(form)
          message.success('添加成功')
        }
        dialogVisible.value = false
        getDataList()
      } catch (error: any) {
        message.error(error.msg || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

onMounted(() => {
  getDataList()
})
</script>

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