<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { splitStrLast } from '@/utils/util'
import { createPro } from '../api'
import * as XLSX from 'xlsx'
import { useMapStore } from '@/stores/map'

const emit = defineEmits<Emits>()
const uploadRef = ref()
const fileList = ref([]) // 文件列表
const isShowImportDialog = ref(false)
const tableData = ref<any[]>([]) // 导入的数据
const store = useMapStore()

defineProps({
  isShowImportDialog: {
    type: Boolean,
  },
})

interface Emits {
  (e: 'update:isShowImportDialog', isShowImportDialog: boolean): void
  (e: 'create'): void
}

// 获取字典数据
const categoryList = ref<any[]>([])
const educationList = ref<any[]>([])
const schoolingList = ref<any[]>([])
const degreeCategoryList = ref<any[]>([])
const specialtyDegreeList = ref<any[]>([])

// 打开导入弹框
const handleImport = () => {
  isShowImportDialog.value = true
  tableData.value = []
  fileList.value = []

  // 获取字典数据
  categoryList.value = store.getMapValuesByKey('specialty_category')
  educationList.value = store.getMapValuesByKey('specialty_education_background')
  schoolingList.value = store.getMapValuesByKey('specialty_length_of_schooling')
  degreeCategoryList.value = store.getMapValuesByKey('specialty_degree_category')
  specialtyDegreeList.value = store.getMapValuesByKey('specialty_degree')
}

// 取消
const handleCancel = () => {
  isShowImportDialog.value = false
  tableData.value = []
  fileList.value = []
}

// 文件上传前校验
const beforeUpload = (file: any) => {
  const suffix = splitStrLast(file.name, '.')
  if (!['xlsx', 'xls'].includes(suffix)) {
    ElMessage.warning('只能上传excel文件')
    return false
  } else {
    return true
  }
}

// 读取Excel文件
const readExcel = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        resolve(jsonData)
      } catch (error) {
        reject(error)
      }
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

// 根据字典label查找value
const findValueByLabel = (list: any[], label: string) => {
  const item = list.find((item: any) => item.label === label)
  return item ? item.value : ''
}

// 解析Excel数据
const parseExcelData = (jsonData: any[]) => {
  const result: any[] = []

  jsonData.forEach((row: any, index: number) => {
    // 根据Excel列名映射数据
    const item: any = {
      id: index + 1,
      code: row['专业代码'] || row['code'] || '',
      name: row['专业名称'] || row['name'] || '',
      category: '',
      category_name: row['专业类别'] || row['category_name'] || '',
      education_background: '',
      education_background_name: row['学历'] || row['education_background_name'] || '',
      length_of_schooling: '',
      length_of_schooling_name: row['学制'] || row['length_of_schooling_name'] || '',
      degree_category: '',
      degree_category_name: row['学位门类'] || row['degree_category_name'] || '',
      degree: '',
      degree_name: row['学位'] || row['degree_name'] || '',
      status: 'pending', // 初始状态：待导入
      errorMsg: '', // 错误信息
    }

    // 根据名称查找对应的value
    if (item.category_name) {
      item.category = findValueByLabel(categoryList.value, item.category_name)
    }
    if (item.education_background_name) {
      item.education_background = findValueByLabel(educationList.value, item.education_background_name)
    }
    if (item.length_of_schooling_name) {
      item.length_of_schooling = findValueByLabel(schoolingList.value, item.length_of_schooling_name)
    }
    if (item.degree_category_name) {
      item.degree_category = findValueByLabel(degreeCategoryList.value, item.degree_category_name)
    }
    if (item.degree_name) {
      item.degree = findValueByLabel(specialtyDegreeList.value, item.degree_name)
    }

    result.push(item)
  })

  return result
}

// 文件上传处理
const handleFileChange = async (file: any) => {
  try {
    const jsonData = await readExcel(file.raw)
    tableData.value = parseExcelData(jsonData as any[])
    ElMessage.success('Excel解析成功')
  } catch (error) {
    ElMessage.error('Excel解析失败，请检查文件格式')
    console.error('Excel解析错误:', error)
  }
}

// 批量导入
const handleBatchImport = async () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('请先上传Excel文件')
    return
  }

  // 验证数据
  const invalidData = tableData.value.filter(
    (item) =>
      !item.code ||
      !item.name ||
      !item.category ||
      !item.education_background ||
      !item.length_of_schooling ||
      !item.degree_category ||
      !item.degree
  )
  if (invalidData.length > 0) {
    ElMessage.warning('存在数据不完整，请检查')
    return
  }

  let successCount = 0
  let failCount = 0

  // 逐条导入
  for (const item of tableData.value) {
    if (item.status === 'success') continue // 跳过已成功的

    item.status = 'importing'

    try {
      const params: any = {
        code: item.code,
        name: item.name,
        category: item.category,
        education_background: item.education_background,
        length_of_schooling: item.length_of_schooling,
        degree_category: item.degree_category,
        degree: item.degree,
        status: '1',
      }

      await createPro(params)
      item.status = 'success'
      successCount++
    } catch (error: any) {
      item.status = 'failed'
      item.errorMsg = error.message || '导入失败'
      failCount++
    }
  }

  // 显示导入结果
  if (failCount === 0) {
    ElMessage.success(`成功导入 ${successCount} 条数据`)
    emit('create')
    setTimeout(() => {
      handleCancel()
    }, 1500)
  } else {
    ElMessage.warning(`成功导入 ${successCount} 条，失败 ${failCount} 条`)
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: any = {
    pending: '待导入',
    importing: '导入中',
    success: '成功',
    failed: '失败',
  }
  return statusMap[status] || ''
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: any = {
    pending: 'info',
    importing: 'warning',
    success: 'success',
    failed: 'danger',
  }
  return typeMap[status] || 'info'
}
</script>

<template>
  <el-button type="primary" round @click="handleImport">批量导入</el-button>
  <el-dialog
    draggable
    v-model="isShowImportDialog"
    :close-on-click-modal="false"
    :before-close="handleCancel"
    title="批量导入专业"
    width="1000px">
    <div>
      <el-upload
        style="text-align: center"
        class="file-import"
        ref="uploadRef"
        action="#"
        accept=".xls,.xlsx"
        drag
        :auto-upload="false"
        :file-list="fileList"
        :limit="1"
        :before-upload="beforeUpload"
        :on-change="handleFileChange">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖至此处，点击上传</div>
      </el-upload>
      <div style="margin-bottom: 10px; text-align: right">
        <a href="/center_resource/专业导入模板.xlsx" download="专业导入模板">
          <el-link type="primary">下载模板</el-link>
        </a>
      </div>

      <!-- 数据预览表格 -->
      <el-table v-if="tableData.length > 0" :data="tableData" border max-height="400" style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="code" label="专业代码" align="center" />
        <el-table-column prop="name" label="专业名称" align="center" />
        <el-table-column prop="category_name" label="专业类别" align="center" />
        <el-table-column prop="education_background_name" label="学历" align="center" />
        <el-table-column prop="length_of_schooling_name" label="学制" align="center" />
        <el-table-column prop="degree_category_name" label="学位门类" align="center" />
        <el-table-column prop="degree_name" label="学位" align="center" />
        <el-table-column label="导入状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" align="center" width="200">
          <template #default="{ row }">
            <span style="color: red">{{ row.errorMsg }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleBatchImport" :disabled="tableData.length === 0"> 开始导入 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.file-import {
  margin-bottom: 20px;
}
</style>
