<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { splitStrLast } from '@/utils/util'
import { addSem } from '../api'
import * as XLSX from 'xlsx'
import { useUserStore } from '@/stores/user'
import { useProjectList } from '@/composables/useGetProjectList'

const emit = defineEmits<Emits>()
const uploadRef = ref()
const fileList = ref([]) // 文件列表
const isShowImportDialog = ref(false)
const tableData = ref<any[]>([]) // 导入的数据
const departmentList: any = useProjectList('', '79806610719731712').departmentList
const userStore = useUserStore()

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

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

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

// 取消
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)
  })
}

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

  jsonData.forEach((row: any, index: number) => {
    // 根据Excel列名映射数据
    const item: any = {
      id: index + 1,
      name: row['学期名称'] || row['name'] || '',
      organ_id: '',
      organ_id_name: row['所属部门/学校'] || row['organ_id_name'] || '',
      start_time: row['学期开始日期'] || row['start_time'] || '',
      end_time: row['学期结束日期'] || row['end_time'] || '',
      length: row['教学周'] || row['length'] || '',
      status: 'pending', // 初始状态：待导入
      errorMsg: '', // 错误信息
    }

    // 根据部门名称查找部门ID
    if (item.organ_id_name) {
      const department = departmentList.value?.find((d: any) => d.name === item.organ_id_name)
      if (department) {
        item.organ_id = department.id
      }
    }

    // 如果没有找到部门ID，使用当前用户的部门ID
    if (!item.organ_id && userStore.organization?.id) {
      item.organ_id = userStore.organization.id
      item.organ_id_name = userStore.organization.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.name || !item.organ_id)
  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 = {
        name: item.name,
        organ_id: item.organ_id,
        start_time: item.start_time || undefined,
        end_time: item.end_time || undefined,
        length: item.length || undefined,
        status: '1',
      }

      await addSem(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="900px">
    <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="name" label="学期名称" align="center" />
        <el-table-column prop="organ_id_name" label="所属部门/学校" align="center" />
        <el-table-column prop="start_time" label="学期开始日期" align="center" />
        <el-table-column prop="end_time" label="学期结束日期" align="center" />
        <el-table-column prop="length" 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>
