<template>
  <div class="province-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），模板格式：省份、省份均价、2023存栏、2023出栏、2024存栏、2024出栏、2025存栏、2025出栏
            </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 v-if="nationalData" class="national-data">
          <el-divider>全国总量统计</el-divider>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="2023年全国存栏量">
              {{ nationalData.nationalInventory23th || 0 }} 万头
            </el-descriptions-item>
            <el-descriptions-item label="2023年全国出栏量">
              {{ nationalData.nationalSlaughter23th || 0 }} 万头
            </el-descriptions-item>
            <el-descriptions-item label="2024年全国存栏量">
              {{ nationalData.nationalInventory24th || 0 }} 万头
            </el-descriptions-item>
            <el-descriptions-item label="2024年全国出栏量">
              {{ nationalData.nationalSlaughter24th || 0 }} 万头
            </el-descriptions-item>
            <el-descriptions-item label="2025年全国存栏量">
              {{ nationalData.nationalInventory25th || 0 }} 万头
            </el-descriptions-item>
            <el-descriptions-item label="2025年全国出栏量">
              {{ nationalData.nationalSlaughter25th || 0 }} 万头
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>
  </div>
</template>

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

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

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

// 处理文件选择
const handleFileChange = (file) => {
  fileList.value = [file]
  importResult.value = null
  nationalData.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
    nationalData.value = null

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

    // 调用后端接口
    const response = await api.post('/cattle-data/import-province', formData, {
      timeout: 60000
    })

    // 检查组件是否仍然挂载
    if (!isMounted) return
    
    importing.value = false
    
    if (response.code === 200) {
      const data = response.data || {}
      const updateCount = data.updateCount || 0
      
      if (isMounted) {
        importResult.value = {
          type: 'success',
          title: '导入成功',
          message: `成功更新 ${updateCount} 条数据，已计算全国总量`
        }
        nationalData.value = {
          nationalInventory23th: data.nationalInventory23th,
          nationalSlaughter23th: data.nationalSlaughter23th,
          nationalInventory24th: data.nationalInventory24th,
          nationalSlaughter24th: data.nationalSlaughter24th,
          nationalInventory25th: data.nationalInventory25th,
          nationalSlaughter25th: data.nationalSlaughter25th
        }
        ElMessage.success(`成功导入省份数据，更新 ${updateCount} 条记录`)
        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)
    }
  }
}

// 清空
const handleClear = () => {
  if (!isMounted) return
  
  fileList.value = []
  importResult.value = null
  
  // 保留全国总量数据，不清空
  // nationalData.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>
.province-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;
}

.national-data {
  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>

