<template>
  <el-dialog
    v-model="dialogVisible"
    title="导入"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="import-dialog">
      <el-upload
        ref="uploadRef"
        class="upload-container"
        drag
        :action="uploadAction"
        :headers="headers"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-progress="handleProgress"
        :file-list="fileList"
        :limit="1"
        :auto-upload="true"
        :show-file-list="false"
        name="fileUpload"
        accept=".xlsx,.xls,.txt"
      >
        <div class="upload-content">
          <el-icon class="upload-icon"><UploadFilled /></el-icon>
          <div class="upload-text">
            <p class="upload-title">点击或拖动Excel文件到此处进行上传目录结构</p>
            <p class="upload-tip">支持 .xlsx, .xls 格式文件</p>
          </div>
        </div>
      </el-upload>

      <!-- 上传进度显示 -->
      <div v-if="uploading" class="upload-progress">
        <el-progress 
          :percentage="uploadProgress" 
          :status="uploadProgress === 100 ? 'success' : ''"
          :show-text="false"
        />
        <p class="progress-text">上传中... {{ uploadProgress }}%</p>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { getToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import useAppStore from '@/store/modules/app'

const appStore = useAppStore()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const uploadRef = ref(null)
const fileList = ref([])
const uploading = ref(false)
const uploadProgress = ref(0)

// 获取token用于请求头
// const token = computed(() => appStore.token)

const headers = ref({ Token: getToken() })

// 上传参数
const uploadData = computed(() => ({
  pid: props.projectId
}))

// 上传地址
const uploadAction = computed(() => import.meta.env.VITE_APP_BASE_API + '/core/encryption/excelFileUpLoad')

// 上传前验证
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || 
                 file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                 file.name.endsWith('.xlsx') || 
                 file.name.endsWith('.xls') ||
                 file.name.endsWith('.txt') 
  
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }

  // 开始上传
  uploading.value = true
  uploadProgress.value = 0
  return true
}

// 上传成功处理
const handleSuccess = (response, file, fileList) => {
  uploading.value = false
  uploadProgress.value = 0

  if (response && response.flag) {
    ElMessage.success('导入成功！')
    emit('success', response.data)
    // 延迟关闭对话框，让用户看到成功提示
    setTimeout(() => {
      dialogVisible.value = false
    }, 1500)
  } else {
    ElMessage.error(response?.msg || '导入失败')
    uploading.value = false
  }
}

// 上传错误处理
const handleError = (error, file, fileList) => {
  uploading.value = false
  uploadProgress.value = 0
  console.error('上传错误:', error)
  ElMessage.error('上传失败，请重试')
}

// 上传进度处理
const handleProgress = (event, file, fileList) => {
  uploadProgress.value = Math.round(event.percent)
}

// 监听可见性变化，重置状态
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    // 关闭时重置状态
    fileList.value = []
    uploading.value = false
    uploadProgress.value = 0
  } else {
    // 打开时确保状态重置
    fileList.value = []
    uploading.value = false
    uploadProgress.value = 0
  }
})

// 监听上传完成或失败后自动关闭
watch(uploading, (newVal) => {
  if (!newVal && uploadProgress.value === 100) {
    // 上传完成，3秒后自动关闭
    setTimeout(() => {
      if (!uploading.value) {
        dialogVisible.value = false
      }
    }, 3000)
  }
})
</script>

<style scoped>
.import-dialog {
  padding: 20px;
  text-align: center;
}

.upload-container {
  width: 100%;
  margin-bottom: 20px;
}

.upload-content {
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 64px;
  color: #409EFF;
  margin-bottom: 16px;
}

.upload-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.5;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.upload-progress {
  margin-top: 20px;
  padding: 0 20px;
}

.progress-text {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
  text-align: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  padding: 40px 20px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  margin-right: 0;
}

:deep(.el-dialog__headerbtn) {
  display: none; /* 隐藏关闭按钮 */
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-progress-bar) {
  margin-top: 8px;
}
</style>