<!--
  -    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 ref="searchFormRef">
        <el-form-item label="招生计划" prop="groupId">
          <el-select v-model="queryForm.groupId" filterable clearable placeholder="请选择招生计划" @change="changeG">
            <el-option
              v-for="item in planList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对接部门" prop="deptCode">
          <el-select v-model="queryForm.deptCode" filterable clearable placeholder="请选择对接部门">
            <el-option
              v-for="item in deptList"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否对接" prop="isDj">
          <el-select v-model="queryForm.isDj" filterable clearable placeholder="请选择是否对接">
            <el-option
              v-for="item in isDjList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对接人" prop="djUser">
          <el-input v-model="queryForm.djName" type="text" placeholder="请输入对接人" />
        </el-form-item>
        <el-form-item label="姓名/身份证/电话" prop="name">
          <el-input v-model="queryForm.name" clearable placeholder="请填写学生姓名/身份证/电话" />
        </el-form-item>
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="queryForm.schoolId" filterable clearable placeholder="请选择学校">
            <el-option
              v-for="item in schoolList"
              :key="item.id"
              :label="item.schoolName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="拟报专业" prop="planMajorOne">
          <el-select v-model="queryForm.planMajorOne" filterable clearable placeholder="请选择拟报专业">
            <el-option
              v-for="item in planMajorList"
              :key="item.id"
              :label="item.majorName + ' || ' + item.majorCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
          <el-button plain icon="Refresh" class="ml10" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="mb15">
        <el-button
          v-if="hasAuth('recruit_recruitprestudent_add')"
          type="primary"
          icon="FolderAdd"
          @click="addOrUpdateHandle(null)"
        >
          新增
        </el-button>
        <el-button
            v-auth="'pre_stu_success_export'"
          type="warning"
          plain
          icon="Download"
          class="ml10"
          :loading="exportLoading"
          @click="dataExportHandle"
        >
          导出
        </el-button>

        <el-button v-if="hasAuth('recruit_preexamPeople_add')" type="primary" plain icon="UserFilled" class="ml10" @click="editExam">
          审核人员管理
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :data="state.dataList"
        v-loading="state.loading"
        border
        stripe
        row-key="id"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
      
        <el-table-column prop="djName" label="对接人" width="230" align="center">
          <template #default="scope">
            <div v-if="scope.row.djName || scope.row.djTime" class="contact-cell">
              <div v-if="scope.row.djName" class="contact-name">
                <el-icon class="contact-icon"><User /></el-icon>
                <span class="contact-text">{{ scope.row.djName }}</span>
              </div>
              <span v-if="scope.row.djTime" class="time-text">{{ scope.row.djTime }}</span>
            </div>
            <span v-else class="empty-text">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="学生姓名" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="phone" label="电话" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="achievement" label="中考分数" width="90" align="center" show-overflow-tooltip />
        <el-table-column prop="admission" label="准考证号" width="130" align="left" show-overflow-tooltip />
        <el-table-column prop="planMajorOne" label="拟报专业1" align="left" show-overflow-tooltip>
          <template #default="scope">
            {{ getMajorName(scope.row.planMajorOne) }}
          </template>
        </el-table-column>
        <el-table-column prop="schoolId" label="学校" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ getSchoolName(scope.row.schoolId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="hasAuth('recruit_recruitprestudent_edit')"
              type="primary"
              link
              icon="EditPen"
              @click="addOrUpdateHandle(scope.row.id)"
            >
              修改
            </el-button>
            <el-button
              v-if="hasAuth('recruit_recruitprestudent_dj') && scope.row.isDj == '0'"
              type="primary"
              link
              icon="Connection"
              @click="handllSureDj(scope.row.id)"
            >
              确认对接
            </el-button>
            <el-button
              v-if="hasAuth('recruit_recruitprestudent_del')"
              type="danger"
              link
              icon="Delete"
              @click="deleteHandle(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 弹窗, 新增 / 修改 -->
      <table-form 
        ref="addOrUpdateRef" 
        @refreshDataList="getDataList" 
        :planList="planList" 
        :planMajorList="planMajorList" 
        :schoolList="schoolList" 
      />

      <pre-exam-people-index ref="PreExamPeopleIndexRef"></pre-exam-people-index>
    </div>
  </div>
</template>

<script setup lang="ts" name="recruitprestudent">
import { ref, reactive, onMounted, nextTick, defineAsyncComponent } from 'vue'
import { useAuth } from '/@/hooks/auth'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useDict } from '/@/hooks/dict'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { User } from '@element-plus/icons-vue'
import { delObj, fetchList, sureDJ } from '/@/api/recruit/recruitprestudent'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import { listcz } from '/@/api/recruit/recruitstudentplan'
import { queryByGroupId as schoolListApi} from '/@/api/recruit/recruitstudentschool'
import { getDeptListByLevelTwo } from '/@/api/basic/basicdept'
import {exportPreStuSuccess} from '/@/api/recruit/recruitfile'

const PreExamPeopleIndex = defineAsyncComponent(() => import('@/views/recruit/recruitPreexamPeople/index.vue'));

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

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

// 弹窗状态
const exportLoading = ref(false)

// 字典数据
const { yes_no_type: isDjList } = useDict('yes_no_type')

// 数据
const planList = ref<any[]>([])
const deptList = ref<any[]>([])
const schoolList = ref<any[]>([])
const planMajorList = ref<any[]>([])

// 查询表单
const queryForm = reactive({
  groupId: '',
  deptCode: '',
  isDj: '',
  djName: '',
  name: '',
  schoolId: '',
  planMajorOne: ''
})

// 获取专业名称
const getMajorName = (majorId: string) => {
  const item = planMajorList.value.find(item => item.id === majorId)
  return item ? item.majorName : ''
}

// 获取学校名称
const getSchoolName = (schoolId: string) => {
  const item = schoolList.value.find(item => item.id === schoolId)
  return item ? item.schoolName : ''
}

// 表格状态
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
      }
    }
  },
  createdIsNeed: false
})

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

// 初始化
const init = async () => {
  try {
    // 获取部门列表
    const deptData = await getDeptListByLevelTwo()
    deptList.value = deptData.data || []
    
    // 获取招生计划列表
    const planData = await getList()
    planList.value = planData.data || []
    if (planList.value.length > 0) {
      queryForm.groupId = planList.value[0].id
      await getMajor(queryForm.groupId)
      
      // 获取学校列表
      const schoolData = await schoolListApi({ groupId: queryForm.groupId })
      schoolList.value = schoolData.data || []
    }
    
    getDataList()
  } catch (error) {
    message.error('初始化失败')
  }
}

// 招生计划改变
const changeG = async () => {
  if (queryForm.groupId) {
    await getMajor(queryForm.groupId)
    const schoolData = await schoolListApi({ groupId: queryForm.groupId })
    schoolList.value = schoolData.data || []
  }
}

// 获取专业列表
const getMajor = async (groupId: string) => {
  try {
    const data = await listcz({ groupId })
    planMajorList.value = data.data || []
    getDataList()
  } catch (error) {
    message.error('获取专业列表失败')
  }
}

// 新增 / 修改
const addOrUpdateHandle = (id?: string | null) => {
  nextTick(() => {
    addOrUpdateRef.value?.init(id ?? null)
  })
}

// 确认对接
const handllSureDj = async (id: string) => {
  try {
    await messageBox.confirm('是否确认已对接？请谨慎操作')
    await sureDJ({ id, isDj: '1' })
    message.success('确认成功')
    getDataList()
  } catch {
    // 用户取消
  }
}

// 删除
const deleteHandle = async (id: string) => {
  try {
    await messageBox.confirm('是否确认删除本条数据？请谨慎操作')
    await delObj(id)
    message.success('删除成功')
    getDataList()
  } catch {
    // 用户取消
  }
}

// 重置查询
const resetQuery = () => {
  searchFormRef.value?.resetFields()
  queryForm.groupId = ''
  queryForm.deptCode = ''
  queryForm.isDj = ''
  queryForm.djName = ''
  queryForm.name = ''
  queryForm.schoolId = ''
  queryForm.planMajorOne = ''
  if (planList.value.length > 0) {
    queryForm.groupId = planList.value[0].id
  }
  getDataList()
}

// 导出
const dataExportHandle = async () => {
  exportLoading.value = true
  exportPreStuSuccess(queryForm).then((res:any)=>{
    message.success('导出后台执行中,请稍后查看下载任务')
    exportLoading.value = false
  })

}


// 编辑审核人员
const editExam = () => {
  // 如果组件已经加载，立即初始化
  if (PreExamPeopleIndexRef.value && typeof PreExamPeopleIndexRef.value.init === 'function') {
    nextTick(() => {
      try {
        PreExamPeopleIndexRef.value.init();
      } catch (error: any) {
        message.error('初始化预登记人员弹窗失败：' + (error.message || '未知错误'));
      }
    });
  }
  // 否则等待 watch 监听器处理
};

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

<style lang="scss" scoped>
.contact-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  white-space: nowrap;
  
  .contact-name {
    display: flex;
    align-items: center;
    gap: 6px;
    white-space: nowrap;
    
    .contact-icon {
      color: #909399;
      font-size: 14px;
      flex-shrink: 0;
    }
    
    .contact-text {
      font-weight: 500;
      white-space: nowrap;
    }
  }
  
  .time-text {
    font-size: 12px;
    color: var(--el-color-primary);
    white-space: nowrap;
  }
}

.empty-text {
  color: #c0c4cc;
}
</style>
