<template>
  <el-dialog :title="title" v-model="visible" :width="width" append-to-body @close="handleClose">
    <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="uploadUrl" :disabled="isUploading" :on-progress="handleProgress" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-success="handleSuccess" :auto-upload="false" :show-file-list="true" drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link v-if="templateUrl" type="primary" underline="never" style="font-size: 12px; vertical-align: baseline" @click="handleDownloadTemplate">下载模板</el-link>
        </div>
      </template>
    </el-upload>
    <!-- 手动显示已选文件名（drag模式下el-upload可能不显示文件列表） -->
    <div v-if="selectedFile && !isUploading" class="selected-file-info">
      <el-icon><Document /></el-icon>
      <span class="file-name">{{ selectedFile.name }}</span>
      <span class="file-size">({{ formatSize(selectedFile.size) }})</span>
      <el-button type="danger" link icon="Delete" @click="clearSelectedFile">移除</el-button>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="isUploading" @click="handleSubmit">{{ isUploading ? '导入中...' : '确 定' }}</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { Document } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

const { proxy } = getCurrentInstance()

const props = defineProps({
  title: { type: String, default: '数据导入' },
  width: { type: String, default: '400px' },
  action: { type: String, required: true },
  templateAction: { type: String, default: '' },
  templateFileName: { type: String, default: 'template' }
})

const emit = defineEmits(['success'])

const uploadRef = ref(null)
const visible = ref(false)
const selectedFile = ref(null)
const isUploading = ref(false)
const headers = { Authorization: 'Bearer ' + getToken() }

const uploadUrl = computed(() => {
  return import.meta.env.VITE_SERVICE_BASE_TITLE + props.action
})

const templateUrl = computed(() => !!props.templateAction)

function formatSize(bytes) {
  if (!bytes) return '0 B'
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / 1024 / 1024).toFixed(1) + ' MB'
}

function open() {
  isUploading.value = false
  visible.value = true
  nextTick(() => {
    selectedFile.value = null
    uploadRef.value?.clearFiles()
  })
}

function handleClose() {
  isUploading.value = false
  selectedFile.value = null
  uploadRef.value?.clearFiles()
}

function handleDownloadTemplate() {
  request({ url: props.templateAction, method: 'get', responseType: 'blob' }).then(res => {
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${props.templateFileName}_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  })
}

function handleProgress() {
  isUploading.value = true
}

const handleFileChange = (file) => {
  selectedFile.value = file.raw || file
}

const handleFileRemove = () => {
  selectedFile.value = null
}

function clearSelectedFile() {
  selectedFile.value = null
  uploadRef.value?.clearFiles()
}

function handleSuccess(response) {
  visible.value = false
  isUploading.value = false
  selectedFile.value = null
  uploadRef.value?.clearFiles()
  proxy.$alert("<div style='overflow:auto;overflow-x:hidden;max-height:70vh;padding:10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
  emit('success')
}

function handleSubmit() {
  if (!selectedFile.value) {
    proxy.$modal.msgError("请选择要导入的Excel文件。")
    return
  }
  const name = selectedFile.value.name || ''
  if (!name.toLowerCase().endsWith('.xls') && !name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 xls 或 xlsx 的文件。")
    return
  }
  isUploading.value = true
  uploadRef.value.submit()
}

defineExpose({ open })
</script>

<style scoped>
.selected-file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
  padding: 8px 12px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
}
.selected-file-info .file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
  font-weight: 500;
}
.selected-file-info .file-size {
  color: #909399;
  flex-shrink: 0;
}
</style>
