<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { splitStrLast } from '@/utils/util'
import { addStaff } from '../api'
import * as XLSX from 'xlsx'
import { useUserStore } from '@/stores/user'
import { useProjectList } from '@/composables/useGetProjectList'
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()
const userStore = useUserStore()

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

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

// 获取字典数据
const departmentList: any = useProjectList('', '79806610719731712').departmentList
const sexList = ref<any[]>([])
const roleList = ref<any[]>([])

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

  // 获取字典数据
  sexList.value = store.getMapValuesByKey('system_gender')
  roleList.value = store.getMapValuesByKey('teacher_role')
}

// 取消
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,
      organ_id: '',
      organ_id_name: row['所属部门/学校'] || row['organ_id_name'] || '',
      name: row['姓名'] || row['name'] || '',
      gender: '',
      gender_name: row['性别'] || row['gender_name'] || '',
      mobile: row['手机号'] || row['mobile'] || '',
      role: '',
      role_name: row['角色类型'] || row['role_name'] || '',
      email: row['邮箱'] || row['email'] || '',
      account_type: '',
      account_type_name: row['账号类型'] || '',
      account_expired_time: row['账号有效期'] || row['有效期'] || '',
      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
    }

    // 根据性别名称查找value
    if (item.gender_name) {
      item.gender = findValueByLabel(sexList.value, item.gender_name)
    }

    // 账号类型映射
    if (item.account_type_name === '试用') {
      item.account_type = '2'
    } else {
      item.account_type = '1'
      item.account_type_name = '正式'
    }

    // 根据角色名称查找value（支持多个角色，用逗号分隔）
    if (item.role_name) {
      const roleNames = item.role_name.split(',').map((r: string) => r.trim())
      const roleValues = roleNames
        .map((name: string) => findValueByLabel(roleList.value, name))
        .filter((v: string) => v !== '')
      item.role = roleValues.join(',')
    }

    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 || !item.gender || !item.mobile || !item.role || !item.email,
  )
  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,
        gender: item.gender,
        mobile: item.mobile,
        role: item.role,
        email: item.email,
        status: '1',
        account_type: item.account_type,
        account_expired_time: item.account_expired_time || '',
      }

      await addStaff(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="organ_id_name" label="所属部门/学校" align="center" />
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="gender_name" label="性别" align="center" />
        <el-table-column prop="mobile" label="手机号" align="center" />
        <el-table-column prop="role_name" label="角色类型" align="center" />
        <el-table-column prop="account_type_name" label="账号类型" align="center" />
        <el-table-column prop="account_expired_time" label="账号有效期" align="center" width="180" />
        <el-table-column prop="email" 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>
