<template>
  <div class="import-data-container app-container">
    <!-- 步骤指示器 -->
    <el-steps
      :active="currentStep"
      finish-status="success"
      align-center
      class="steps-container"
    >
      <el-step title="选择配置" description="选择分类" />
      <el-step title="上传文件" description="上传Excel数据文件" />
    </el-steps>

    <!-- 第一步：选择分类 -->
    <div v-if="currentStep === 0" class="step-wrapper">
      <div class="step-header">
        <h2>选择分类</h2>
      </div>

      <!-- 选择分类 -->
      <div class="category-selection">
        <el-alert
          title="请选择数据分类"
          type="info"
          show-icon
          :closable="false"
        />

        <div v-loading="categoriesLoading" class="category-list">
          <div
            v-for="category in categoriesList"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategoryId === category.id }"
            @click="selectCategory(category)"
          >
            <div class="category-name">{{ category.name }}</div>
            <div class="category-desc">
              {{ category.description || '暂无描述' }}
            </div>
            <div v-if="category.fieldConfig" class="category-fields">
              <el-tag
                v-for="field in parseFieldConfig(category.fieldConfig)"
                :key="field.fieldName"
                size="mini"
                type="info"
              >
                {{ field.displayLabel }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <div class="step-actions">
        <el-button
          type="primary"
          :disabled="!selectedCategoryId"
          @click="nextStep"
        >
          下一步
        </el-button>
      </div>
    </div>

    <!-- 第二步：上传文件 -->
    <div v-if="currentStep === 1" class="step-wrapper">
      <div class="step-header">
        <h2>上传Excel文件</h2>
      </div>

      <div class="file-upload">
        <!-- 物流数据文件格式要求 -->
        <el-alert
          :title="`当前选择分类是：${selectedCategory.name}`"
          type="warning"
          show-icon
          :closable="false"
        />

        <el-upload
          ref="upload"
          :action="uploadUrl"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :show-file-list="true"
          :file-list="fileList"
          :on-remove="onFileRemove"
          accept=".xlsx,.xls"
          multiple
          drag
          class="upload-area"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">
            支持多选Excel文件(.xlsx/.xls)，单文件不超过10MB，文件数量不超过40个
            <el-button
              type="text"
              @click="clearAllFiles"
            >清空文件列表</el-button>
          </div>
        </el-upload>

        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button
            type="primary"
            :loading="saveLoading"
            :disabled="!fileList.length"
            @click="saveData"
          >
            保存数据
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCategoriesSimple, saveImportedData } from '@/api/sales-analysis'
import * as XLSX from 'xlsx'

export default {
  name: 'ImportData',
  data() {
    return {
      currentStep: 0,
      selectedDataSource: null, // 'logistics' 或 'fba'
      selectedCategoryId: null,
      selectedCategory: null,
      selectedShopName: null,
      categoriesList: [],
      categoriesLoading: false,
      shopsList: [],
      shopsLoading: false,
      processResult: {},
      saveLoading: false,
      saveResult: null,
      fileList: [],
      processingFiles: false,
      errorData: [],
      errorDataVisible: false
    }
  },
  computed: {
    uploadUrl() {
      if (this.selectedDataSource === 'fba') {
        return process.env.VUE_APP_BASE_API + '/analysis-data/import/fba'
      }
      return process.env.VUE_APP_BASE_API + '/analysis-data/import'
    },
    uploadData() {
      if (this.selectedDataSource === 'fba') {
        return {
          shopName: this.selectedShopName
        }
      }
      return {
        categoryId: this.selectedCategoryId
      }
    }
  },
  mounted() {
    this.fetchCategoriesList()
  },
  methods: {
    // 解析字段配置字符串为 JSON 对象
    parseFieldConfig(fieldConfig) {
      try {
        if (!fieldConfig || typeof fieldConfig === 'object') {
          return fieldConfig || []
        }
        return JSON.parse(fieldConfig)
      } catch (error) {
        console.warn('解析字段配置失败:', error)
        return []
      }
    },

    showErrorData() {
      this.errorDataVisible = true
      this.errorData = this.processResult.errorDetails
    },
    // 选择数据来源
    selectDataSource(source) {
      this.selectedDataSource = source
      // 清空之前的选择
      this.selectedCategoryId = null
      this.selectedCategory = null
      this.selectedShopName = null
    },

    // 获取分类列表
    async fetchCategoriesList() {
      try {
        this.categoriesLoading = true
        const response = await getCategoriesSimple()

        if (response.code === 200) {
          this.categoriesList = response.data || []
        } else {
          this.$message.error(response.message || '获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      } finally {
        this.categoriesLoading = false
      }
    },

    // 选择分类
    selectCategory(category) {
      this.selectedCategoryId = category.id
      this.selectedCategory = category
    },

    // 下一步
    nextStep() {
      this.currentStep++
    },

    // 上一步
    prevStep() {
      this.currentStep--
    },

    // 上传前验证
    beforeUpload(file) {
      console.log('上传前验证:', {
        name: file.name,
        type: file.type,
        size: file.size,
        lastModified: file.lastModified
      })

      const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
      if (!isExcel) {
        console.log('文件类型验证失败:', file.name)
        this.$message.error('只能上传Excel文件！')
        return false
      }

      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        console.log('文件大小验证失败:', file.size / 1024 / 1024 + 'MB')
        this.$message.error('上传文件大小不能超过10MB！')
        return false
      }

      console.log('前端验证通过，准备上传')

      // 对于多文件上传，我们先不让它自动上传，而是添加到文件列表
      this.addToFileList(file)
      return false // 阻止自动上传
    },

    // 添加文件到列表
    addToFileList(file) {
      const fileItem = {
        name: file.name,
        size: file.size,
        status: 'ready',
        file: file,
        uid: Date.now() + Math.random()
      }
      this.fileList.push(fileItem)
    },

    // 移除文件
    onFileRemove(file) {
      const index = this.fileList.findIndex((item) => item.uid === file.uid)
      if (index > -1) {
        this.fileList.splice(index, 1)
      }
    },

    // 清空文件列表
    clearAllFiles() {
      this.fileList = []
    },

    // 上传成功
    onUploadSuccess(response) {
      console.log('上传成功回调:', response)

      if (response.code === 200) {
        this.processResult = response.data || {}
        this.$message.success(response.message || '文件处理完成')
        this.currentStep = 3
      } else {
        console.error('处理失败:', response)
        this.$message.error(response.message || '文件处理失败')
      }
    },

    // 上传失败
    onUploadError(error) {
      console.error('上传失败:', error)
      let errorMessage = '文件上传失败'

      // 尝试从错误中提取详细信息
      if (error && error.message) {
        errorMessage = error.message
      } else if (typeof error === 'string') {
        errorMessage = error
      }

      this.$message.error(errorMessage)
    },

    // 保存数据
    async saveData() {
      console.log(this.selectedCategory)

      try {
        this.saveLoading = true

        // 存储所有文件的解析数据
        const allParsedData = []

        // 遍历文件列表
        for (const fileItem of this.fileList) {
          try {
            // 读取文件内容
            const reader = new FileReader()
            const fileData = await new Promise((resolve, reject) => {
              reader.onload = (e) => resolve(e.target.result)
              reader.onerror = (e) => reject(e)
              reader.readAsArrayBuffer(fileItem.file)
            })

            // 解析Excel文件
            const workbook = XLSX.read(fileData, { type: 'array' })
            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]

            // 将工作表转换为JSON数据
            const jsonData = XLSX.utils.sheet_to_json(worksheet, {
              header: 1,
              raw: false, // 将所有值转换为字符串
              defval: '' // 空单元格的默认值
            })

            // 验证数据格式
            if (jsonData.length < 2) {
              throw new Error(`文件 ${fileItem.name} 数据行数不足`)
            }

            // 获取表头
            const headers = jsonData[0]

            // 验证字段配置
            const fieldConfig = this.parseFieldConfig(
              this.selectedCategory.fieldConfig
            )
            const requiredFields = fieldConfig
              .filter((field) => field.required)
              .map((field) => field.fieldName)

            // 检查必填字段是否存在
            const missingFields = requiredFields.filter(
              (field) => !headers.includes(field)
            )
            if (missingFields.length > 0) {
              throw new Error(
                `文件 ${fileItem.name} 缺少必填字段: ${missingFields.join(
                  ', '
                )}`
              )
            }

            // 处理数据行
            const parsedRows = []
            for (let i = 1; i < jsonData.length; i++) {
              const row = jsonData[i]
              if (row.length === 0 || row.every((cell) => !cell)) continue // 跳过空行

              // 创建符合目标结构的数据对象
              const rowData = {
                id: null,
                date: '', // 默认当前日期，可以从Excel中获取
                shopName: '',
                productCode: '',
                productName: '',
                customerName: '',
                category: this.selectedCategory.name,
                categorySpecs: '',
                quantity: 0,
                totalAmount: '',
                source: '',
                status: 1,
                deliveryType: '',
                destination: '',
                remarks: '',
                orderNumber: '',
                rowNumber: i + 1,
                brand: '',
                createdAt: null,
                updatedAt: null
              }

              const specs = {}

              // 根据表头映射数据
              headers.forEach((header, index) => {
                const value = row[index] || ''
                const headerTrim = header.trim().replace(/[\r\n]+/g, '')
                console.log(headerTrim == '販売数量')
                switch (headerTrim) {
                  case '出库日期':
                  case '日付':
                    // 转换日期格式 从 2025/7/18 到 2025-07-18
                    if (value) {
                      const parts = value.split('/')
                      if (parts.length === 3) {
                        const year = parts[0]
                        const month = parts[1].padStart(2, '0')
                        const day = parts[2].padStart(2, '0')
                        rowData.date = `${year}-${month}-${day}`
                      } else {
                        rowData.date = value
                      }
                    }
                    break
                  case '店铺':
                  case '販売店舗':
                    rowData.shopName = value
                    break
                  case '商品コード':
                    rowData.productCode = value
                    break
                  case '商品名':
                    rowData.productName = value
                    break
                  case '客户名':
                    rowData.customerName = value
                    break
                  case '分类':
                    rowData.category = value
                    break
                  case '販売\n数量':
                  case '販売数量':
                    rowData.quantity = parseInt(value) || 0
                    break
                  case '販売金額\n合計':
                  case '販売金額合計':
                    rowData.totalAmount = value.toString()
                    break
                  case '来源':
                    if (value) rowData.source = value
                    break
                  case '出库类型':
                    if (value) rowData.deliveryType = value
                    break
                  case '目的地':
                    rowData.destination = value
                    break
                  case '备注':
                    rowData.remarks = value
                    break
                  case '订单号':
                    rowData.orderNumber = value
                    break
                  case '品牌':
                    rowData.brand = value
                    break
                  default:
                    fieldConfig.forEach((field) => {
                      const headerTrim = header.trim().replace(/[\r\n]+/g, '')
                      if (headerTrim.includes(field.displayLabel)) {
                        specs[field.displayLabel] = value
                      }
                    })
                    rowData.categorySpecs = JSON.stringify(specs)
                    break
                }
              })

              parsedRows.push(rowData)
            }

            allParsedData.push(...parsedRows)

            // 更新文件状态
            fileItem.status = 'success'
            fileItem.parsedCount = parsedRows.length
          } catch (error) {
            console.error(`解析文件 ${fileItem.name} 失败:`, error)
            fileItem.status = 'error'
            fileItem.error = error.message
            this.$message.error(
              `解析文件 ${fileItem.name} 失败: ${error.message}`
            )
          }
        }

        if (allParsedData.length === 0) {
          throw new Error('没有可用的数据可以保存')
        }

        // 调用API保存数据
        const response = await saveImportedData(allParsedData)

        if (response.code === 200) {
          this.saveResult = response.data
          this.$message.success(response.message || '数据保存成功')
          this.currentStep = 0
          // 清空文件列表
          this.fileList = []
        } else {
          throw new Error(response.message || '数据保存失败')
        }
      } catch (error) {
        console.error('保存数据失败:', error)
        this.$message.error(error.message || '数据保存失败')
      } finally {
        this.saveLoading = false
      }
    }
  }
}
</script>

<style scoped>
.import-data-container {
  padding: 0;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.import-data-container > .card {
  flex: 1;
  margin: 0;
}

.step-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
.step-actions .el-button {
  padding-left: 40px;
  padding-right: 40px;
  padding-top: 14px;
  padding-bottom: 14px;
  font-size: 16px;
}
.steps-container {
  padding: 20px;
  background-color: #fff;
}
.step-wrapper {
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  width: 100%;
  flex-grow: 1;
  height: 0;
}
.step-header {
  text-align: center;
  margin-bottom: 30px;
}
.step-header h2 {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 8px;
}
.step-header p {
  color: #909399;
}
.source-options {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin: 40px 0;
}
.source-option {
  width: 320px;
  padding: 25px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  display: flex;
  align-items: center;
  background-color: #fff;
}
.source-option:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.source-option.active {
  border-color: #409eff;
  background-color: #f7faff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}
.source-icon {
  font-size: 36px;
  color: #409eff;
  margin-right: 20px;
}
.source-info h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 8px;
}
.source-info p {
  font-size: 13px;
  color: #606266;
  margin: 0;
  line-height: 1.5;
}
/* 分类选择样式 */
.category-selection {
  padding: 20px;
}

/* 店铺选择样式 */
.shop-selection {
  padding: 20px;
}

.shop-list {
  margin: 30px 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.shop-item {
  padding: 10px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.shop-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.shop-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.shop-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.shop-customer {
  color: #666;
  font-size: 14px;
}

.category-list {
  margin: 30px 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 30px;
}

.category-item {
  padding: 20px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.category-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.category-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.category-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.category-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.category-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

/* 文件上传样式 */
.file-upload {
  padding: 20px;
}

.upload-area {
  margin: 30px 0;
}
.upload-area /deep/.el-upload-list {
  max-height: 180px;
  overflow-y: auto;
}

.batch-actions {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  text-align: center;
}

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

/* 数据预览样式 */
.data-preview {
}

.statistics {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 6px;
  border: 2px solid #e8e8e8;
}

.stat-card.success {
  border-color: #67c23a;
}

.stat-card.warning {
  border-color: #e6a23c;
}

.stat-card.danger {
  border-color: #f56c6c;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  color: #666;
  font-size: 12px;
}

.stat-label small {
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
}

.error-section {
  margin-bottom: 30px;
}

.error-list {
  margin: 0;
  padding-left: 20px;
  color: #e6a23c;
}

.data-table h4 {
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
  text-align: center;
  margin-top: 20px;
}

/* 保存数据样式 */
.save-data {
  padding: 40px;
  text-align: center;
}

.saving {
  color: #409eff;
}

.saving i {
  font-size: 48px;
  margin-bottom: 20px;
}

.save-success {
  padding: 20px;
}

.saving p {
  font-size: 16px;
  margin: 0;
}

.save-success h3 {
  margin: 20px 0;
  color: #333;
}

.save-success p {
  color: #666;
  margin-bottom: 30px;
}

.save-statistics {
  margin: 30px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.stat-item.success {
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
}

.stat-item.warning {
  background: #fffbf0;
  border: 1px solid #ffeaa7;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-item.success .stat-value {
  color: #67c23a;
}

.stat-item.warning .stat-value {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.failed-info {
  margin-top: 20px;
}

.failed-info ul {
  margin: 10px 0;
  padding-left: 20px;
}

.failed-info li {
  margin: 5px 0;
  color: #f56c6c;
}

.final-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}
</style>
