<template>
  <div class="cattle-data-import">
    <el-card class="import-card">
      <template #header>
        <div class="card-header">
          <span>牛只数据导入</span>
        </div>
      </template>

      <div class="import-content">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
          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">
              只能上传 Excel 文件（.xlsx, .xls），模板格式：时间、产品/品种、所在产地、活牛价格(元/斤)
            </div>
          </template>
        </el-upload>

        <div class="import-actions" v-if="fileList.length > 0">
          <el-button 
            type="primary" 
            :loading="importing"
            @click="handleImport"
            size="large"
          >
            <el-icon><upload /></el-icon>
            导入数据
          </el-button>
          <el-button @click="handleClear" size="large">清空</el-button>
        </div>

        <div v-if="importResult" class="import-result">
          <el-alert
            :title="importResult.title"
            :type="importResult.type"
            :description="importResult.message"
            show-icon
            :closable="false"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Upload } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import api from '../utils/api'

const uploadRef = ref(null)
const fileList = ref([])
const importing = ref(false)
const importResult = ref(null)
let isMounted = true

// 组件卸载时标记
onBeforeUnmount(() => {
  isMounted = false
})

// 处理文件选择
const handleFileChange = (file) => {
  fileList.value = [file]
  importResult.value = null
}

// 处理导入
const handleImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  const file = fileList.value[0].raw
  if (!file) {
    ElMessage.error('文件读取失败')
    return
  }

  try {
    importing.value = true
    importResult.value = null

    // 读取Excel文件
    const workbook = XLSX.read(await file.arrayBuffer(), { type: 'array' })
    const sheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[sheetName]
    
    // 转换为JSON
    const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
    
    if (data.length < 2) {
      throw new Error('Excel文件数据为空或格式不正确')
    }

    // 处理数据：截取所在产地到"市"
    const processedData = processExcelData(data)

    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)

    // 调用后端接口（FormData会自动设置Content-Type，不需要手动设置）
    const response = await api.post('/cattle-data/import', formData, {
      timeout: 60000
    })

    // 检查组件是否仍然挂载
    if (!isMounted) return
    
    importing.value = false
    
    if (response.code === 200) {
      const count = response.data ? response.data.length : 0
      if (isMounted) {
        importResult.value = {
          type: 'success',
          title: '导入成功',
          message: `成功导入 ${count} 条数据`
        }
        ElMessage.success(`成功导入 ${count} 条数据`)
        handleClear()
      }
    } else {
      throw new Error(response.message || '导入失败')
    }
  } catch (error) {
    // 检查组件是否仍然挂载
    if (!isMounted) return
    
    importing.value = false
    const errorMsg = error.message || '导入失败，请检查文件格式'
    if (isMounted) {
      importResult.value = {
        type: 'error',
        title: '导入失败',
        message: errorMsg
      }
      ElMessage.error(errorMsg)
    }
  }
}

// 处理Excel数据（截取所在产地到"市"）
const processExcelData = (data) => {
  // 这里的数据处理逻辑会在后端完成
  // 前端主要负责文件上传
  return data
}

// 清空
const handleClear = () => {
  if (!isMounted) return
  
  fileList.value = []
  importResult.value = null
  
  // 使用 nextTick 确保 DOM 已更新
  nextTick(() => {
    if (isMounted && uploadRef.value) {
      try {
        uploadRef.value.clearFiles()
      } catch (error) {
        // 忽略 DOM 访问错误
        console.warn('Clear files error:', error)
      }
    }
  })
}
</script>

<style scoped>
.cattle-data-import {
  max-width: 800px;
  margin: 0 auto;
}

.import-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.import-content {
  padding: 20px 0;
}

.import-actions {
  margin-top: 30px;
  text-align: center;
}

.import-actions .el-button {
  margin: 0 10px;
}

.import-result {
  margin-top: 30px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 40px;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}
</style>

