<!--
  -    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="请选择招生计划">
            <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="schoolName">
          <el-input v-model="queryForm.schoolName" clearable placeholder="学校名称" />
        </el-form-item>
        <el-form-item label="学校代码" prop="schoolCode">
          <el-input v-model="queryForm.schoolCode" clearable placeholder="学校代码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
          <el-button icon="Refresh" class="ml10" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="mb15">
        <el-button
          v-if="hasAuth('recruit_recruitschoolcode_add')"
          type="primary"
          icon="FolderAdd"
          @click="addOrUpdateHandle()"
        >
          新增
        </el-button>
        <el-button
          v-if="hasAuth('recruit_recruitschoolcode_add')"
          type="primary"
          plain
          icon="UploadFilled"
          class="ml10"
          @click="handleExportIn"
        >
          导入
        </el-button>
      </div>

      <!-- 表格 -->
      <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="groupId" label="招生计划名称" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ getPlanName(scope.row.groupId) }}
          </template>
        </el-table-column>
        <el-table-column prop="schoolCode" label="学校代码" align="center" show-overflow-tooltip />
        <el-table-column prop="schoolName" label="学校名称" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="hasAuth('recruit_recruitschoolcode_edit')"
              type="primary"
              link
              icon="EditPen"
              @click="addOrUpdateHandle(scope.row.id)"
            >
              修改
            </el-button>
            <el-button
              v-if="hasAuth('recruit_recruitschoolcode_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" />

      <!-- 导入弹窗 -->
      <el-dialog v-model="dialogViewVisible" title="导入学校代码" append-to-body width="600px">
        <el-form :model="exportForm" inline>
          <el-form-item label="招生计划" prop="groupId">
            <el-select v-model="exportForm.groupId" filterable clearable placeholder="请选择招生计划">
              <el-option
                v-for="item in planList"
                :key="item.id"
                :label="item.groupName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <el-upload
          class="upload-container"
          ref="uploadFormRef"
          action="doUpload"
          :limit="1"
          :file-list="fileList"
          :before-upload="beforeUpload"
        >
          <template #trigger>
            <el-button type="primary">选取文件</el-button>
          </template>
          <a href="schoolCode.xlsx" rel="external nofollow" download="常州中学代码模版">
            <el-button type="success" class="ml10">下载模板</el-button>
          </a>
          <template #tip>
            <div class="el-upload__tip">只能上传excel文件，且不超过5MB</div>
            <div class="el-upload-list__item-name">{{ fileName }}</div>
          </template>
        </el-upload>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogViewVisible = false; impoerLoadinBtn = false">取消</el-button>
            <el-button type="primary" @click="submitUpload" :loading="impoerLoadinBtn">导入</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="recruitschoolcode">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { useAuth } from '/@/hooks/auth'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import { delObj, fetchList } from '/@/api/recruit/recruitschoolcode'
import request from '/@/utils/request'

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

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

// 弹窗状态
const dialogViewVisible = ref(false)
const impoerLoadinBtn = ref(false)

// 数据
const planList = ref<any[]>([])
const fileList = ref<any[]>([])
const fileName = ref('')
const files = ref<File | null>(null)

// 查询表单
const queryForm = reactive({
  groupId: '',
  schoolName: '',
  schoolCode: ''
})

// 导出表单
const exportForm = reactive({
  groupId: ''
})

// 获取计划名称
const getPlanName = (groupId: string) => {
  const item = planList.value.find(item => item.id === groupId)
  return item ? item.groupName : ''
}

// 表格状态
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 } = useTable(state)

// 初始化
const init = async () => {
  try {
    const data = await getList()
    planList.value = data.data || []
    if (planList.value.length > 0) {
      queryForm.groupId = planList.value[0].id
    }
    getDataList()
  } catch (error) {
    // console.log(error)
  }
}

// 上传验证
const beforeUpload = (file: File) => {
  const fileLast = file.name.split('.')
  const extension = fileLast[fileLast.length - 1] === 'xls'
  const extension2 = fileLast[fileLast.length - 1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 5
  
  if (!extension && !extension2) {
    message.warning('上传模板只能是 xls、xlsx格式!')
    return false
  }
  if (!isLt2M) {
    message.warning('上传模板大小不能超过 5MB!')
    return false
  }
  fileName.value = file.name
  files.value = file
  return false // 返回false不会自动上传
}

// 提交上传
const submitUpload = async () => {
  if (fileName.value === '') {
    message.warning('请选择要上传的文件！')
    return
  }
  if (exportForm.groupId === '') {
    message.warning('请选择招生计划！')
    return
  }
  
  impoerLoadinBtn.value = true
  try {
    const fileFormData = new FormData()
    fileFormData.append('file', files.value!, fileName.value)
    
    const res = await request({
      method: 'post',
      url: `/recruit/recruitschoolcode/exportSchoolCode?groupId=${exportForm.groupId}`,
      data: fileFormData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data === 'fail') {
      message.error('请上传正确的学校代码模板')
      return
    }
    if (res.data && res.data === 0) {
      message.error(res.data.msg)
    } else if (res.data && res.data === 10) {
      message.error(res.data.msg)
    } else {
      message.success('操作成功')
      dialogViewVisible.value = false
      state.pagination!.current = 1
      getDataList()
    }
  } catch (error: any) {
    message.error(error.msg || '导入失败')
  } finally {
    impoerLoadinBtn.value = false
  }
}

// 导入
const handleExportIn = () => {
  fileName.value = ''
  exportForm.groupId = ''
  dialogViewVisible.value = true
}

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

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

// 重置查询
const resetQuery = () => {
  searchFormRef.value?.resetFields()
  queryForm.groupId = ''
  queryForm.schoolName = ''
  queryForm.schoolCode = ''
  if (planList.value.length > 0) {
    queryForm.groupId = planList.value[0].id
  }
  getDataList()
}

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

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