<!--
  -    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>
  <el-dialog
    title="招生审核人员管理"
    :close-on-click-modal="false"
    v-model="visible"
    width="800"
    :append-to-body="true"
    destroy-on-close
  >
    <div class="dialog-content">
      <!-- 时间选择器和操作按钮 -->
      <el-form :inline="true" :model="queryForm">
          <el-form-item label="审核时间范围：">
            <el-time-picker
              is-range
              v-model="form.time1"
              format="HH:mm:ss"
              value-format="HH:mm:ss"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"             
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="mb15" v-if="hasAuth('recruit_recruitexampeople_add')">
          <el-button
            type="primary"
            icon="FolderAdd"
            @click="handleAdd"
          >
            新 增
          </el-button>
        </div>

      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          ref="tableRef"
          :data="state.dataList || []"
          v-loading="state.loading"
          border
          stripe
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
          empty-text="暂无数据"      
        >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="工号" align="center" prop="teacherNo" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="姓名" align="center" prop="teacherName" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150px" fixed="right">
              <template #default="scope">
                <el-button
                  v-if="hasAuth('recruit_recruitexampeople_del')"
                  type="danger"
                  link
                  icon="Delete"
                  @click="handleDel(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

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

    <!-- 保存审核人员弹窗 -->
    <add-form 
      v-model:visible="setTeachNoFormVisible" 
      :time-range="form.time1"
      @save="handleSave"
    />
  </el-dialog>
</template>

<script setup lang="ts" name="recruitexampeople">
import { ref, reactive, nextTick, defineAsyncComponent } from 'vue'
import { useAuth } from '/@/hooks/auth'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { addObj, delObj, fetchList } from '/@/api/recruit/recruitPreexamPeople'

const AddForm = defineAsyncComponent(() => import('./add-form.vue'))
const { hasAuth } = useAuth()
// 消息提示 hooks
const message = useMessage()
const messageBox = useMessageBox()

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

// 弹窗状态
const visible = ref(false)
const setTeachNoFormVisible = ref(false)

// 表单数据
const form = reactive({
  time1: [] as string[]
})

// 查询表单
const queryForm = reactive<Record<string, any>>({})

// 表格状态
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 || 0
      }
    }
  },
  createdIsNeed: false, // 弹窗组件，不在挂载时自动加载数据
  dataList: [], // 确保 dataList 初始化为空数组
  loading: false, // 确保 loading 初始化为 false
  onLoaded: async (state: any) => {
    // 如果有数据，设置时间范围
    if (state.dataList && state.dataList.length > 0) {
      form.time1 = [state.dataList[0].startTime, state.dataList[0].endTime]
    }
  }
})

// 使用 table hook
// 注意：useTable 会直接修改传入的 state 对象，所以不需要从返回值中获取 state
const { getDataList, currentChangeHandle, sizeChangeHandle, tableStyle } = useTable(state)

// 初始化
const init = () => {
  visible.value = true
  form.time1 = []
  // 等待弹窗显示后再加载数据
  nextTick(() => {
    getDataList()
  })
}

// 新增
const handleAdd = () => {
  setTeachNoFormVisible.value = true
}

// 保存审核人员
const handleSave = async (data: { teacherNo: string; startTime: string; endTime: string }) => {
  if (form.time1.length === 0) {
    message.error('审核时间不能为空')
    return
  }
  try {
    await addObj({
      teacherNo: data.teacherNo,
      startTime: data.startTime,
      endTime: data.endTime
    })
    message.success('添加成功')
    getDataList()
  } catch (error: any) {
    message.error(error.msg || '添加失败')
  }
}

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

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

// 暴露方法
defineExpose({
  init
})
</script>

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