<template>
  <div class="downloader-container">
    <!-- 头部 -->
    <header class="header">
      <div class="logo">
        <el-icon>
          <Download />
        </el-icon>
        文件下载器
      </div>
      <div style="display: flex; align-items: center; gap: 20px;">
        <el-dropdown @command="handleUserCommand">
          <span class="user-info">
            <el-icon>
              <User />
            </el-icon>
            {{ userName }}
            <el-icon>
              <ArrowDown />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="settings">个人设置</el-dropdown-item>
              <el-dropdown-item command="history">下载历史</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 配置区域（可折叠） -->
      <el-collapse v-model="activeCollapse" class="config-collapse">
        <el-collapse-item title="📁 Excel文件管理" name="upload">
          <!-- Excel文件列表 -->
          <!-- v-if="downloadStore.excelFiles.length > 0" -->
          <div v-if="upTotal > 0" style="margin-bottom: 20px;">
            <h4 style="margin-bottom: 15px; color: #333;">已上传的Excel文件 ({{ upTotal }}个)</h4>
            <el-table :data="upTableData" size="small" border style="width: 100%">
              <el-table-column prop="uploadName" label="文件名" />
              <el-table-column prop="totalRows" label="总行数" width="100" align="center" />
              <el-table-column prop="createTime" label="上传时间" width="180">
                <!-- <template #default="{ row }">
                  {{ new Date(row.uploadTime).toLocaleString() }}
                </template> -->
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                  <el-button @click="selectExcelFile(row.batchId)" type="primary" size="small">
                    选择
                  </el-button>
                  <el-button @click="deleteExcelFile(row.batchId)" type="danger" size="small">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination v-model:current-page="upQuery.current" v-model:page-size="upQuery.pageSize"
                :page-sizes="[5, 10, 20, 50, 100]" :total="upTotal" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleUpSizeChange" @current-change="handleUpCurrentChange" />
            </div>
          </div>
          <el-divider />

          <!-- Excel文件上传配置 -->
          <div class="upload-section">
            <el-upload ref="uploadRef" :auto-upload="false" :show-file-list="false" accept=".xlsx,.xls"
              :on-change="handleFileChange">
              <el-button type="primary" size="large">
                <el-icon>
                  <Upload />
                </el-icon>
                选择Excel文件
              </el-button>
            </el-upload>

            <div v-if="selectedFile" style="margin-top: 15px;">
              <el-alert :title="`已选择文件: ${selectedFile.name}`" type="success" :closable="false" />
            </div>

            <!-- Excel列选择 -->
            <div v-if="excelColumns.length > 0" style="margin-top: 20px;">
              <h4 style="margin-bottom: 15px; color: #333;">配置Excel列映射</h4>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="文件名列（可多选，用'-'连接）">
                    <el-select v-model="columnMapping.fileNameColumns" multiple placeholder="选择文件名列" style="width: 100%"
                      @change="handleColumnMappingChange">
                      <el-option v-for="column in excelColumns" :key="column" :label="column" :value="column" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="URL列">
                    <el-select v-model="columnMapping.url" placeholder="选择URL列" style="width: 100%"
                      @change="handleColumnMappingChange">
                      <el-option v-for="column in excelColumns" :key="column" :label="column" :value="column" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 预览数据 -->
              <div v-if="previewData.length > 0" style="margin-top: 15px;">
                <h5 style="margin-bottom: 10px; color: #666;">
                  数据预览 (前5行) - 总计: {{ rawExcelData.length }} 行
                </h5>
                <el-table :data="previewData" size="small" border style="width: 100%">
                  <el-table-column prop="fileName" label="文件名" />
                  <el-table-column prop="url" label="URL" show-overflow-tooltip />
                </el-table>
                <div v-if="rawExcelData.length > 1000" style="margin-top: 10px;">
                  <el-alert title="文件较大提示" type="warning" :closable="false" show-icon>
                    <template #default>
                      <div style="font-size: 12px; line-height: 1.5;">
                        <p>• 当前文件包含 {{ rawExcelData.length }} 行数据</p>
                        <p>• 已优化：只保留 {{ Object.keys(rawExcelData[0] || {}).length }} 个必要字段</p>
                        <p>• 大文件处理可能需要较长时间，请耐心等待</p>
                        <p>• 建议分批处理或使用较小的Excel文件</p>
                      </div>
                    </template>
                  </el-alert>
                </div>
              </div>
            </div>

            <!-- 下载路径设置 -->
            <div style="margin-top: 20px;">
              <h4 style="margin-bottom: 15px; color: #333;">下载设置</h4>

              <!-- 操作系统信息 -->
              <div style="margin-bottom: 15px;">
                <el-alert
                  :title="`当前操作系统: ${downloadStore.getOperatingSystem() === 'windows' ? 'Windows' : downloadStore.getOperatingSystem() === 'mac' ? 'macOS' : downloadStore.getOperatingSystem() === 'linux' ? 'Linux' : '未知'}`"
                  type="info" :closable="false" show-icon />
              </div>

              <!-- 浏览器默认下载路径显示 -->
              <div style="margin-bottom: 15px;">
                <el-alert :title="`默认下载路径: ${downloadStore.getDefaultDownloadPath()}`" type="info" :closable="false"
                  show-icon />
              </div>

              <el-row :gutter="20">
                <el-col :span="16">
                  <el-form-item label="文件名前缀">
                    <el-input v-model="customSubFolder" placeholder="例如: vue-downloader (留空则不添加前缀)"
                      @input="updateDownloadPath" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-button @click="clearFileNamePrefix" type="info">
                    清空前缀
                  </el-button>
                </el-col>
              </el-row>

              <!-- 文件名前缀说明 -->
              <div v-if="customSubFolder && customSubFolder.trim()" style="margin-top: 10px;">
                <el-alert title="文件名前缀说明" type="success" :closable="false" show-icon>
                  <template #default>
                    <div style="font-size: 12px; line-height: 1.5;">
                      <p><strong>示例：</strong></p>
                      <p>• 原文件名: <code>document.pdf</code></p>
                      <p>• 添加前缀后: <code>vue-downloader_document.pdf</code></p>
                      <p>• 所有下载的文件都会自动添加此前缀</p>
                    </div>
                  </template>
                </el-alert>
              </div>

              <!-- 通知设置 -->
              <div style="margin-top: 15px;">
                <el-form-item label="下载完成通知">
                  <el-switch v-model="downloadStore.enableNotifications" @change="downloadStore.setEnableNotifications"
                    active-text="启用" inactive-text="禁用" />
                  <span style="margin-left: 10px; color: #666; font-size: 12px;">
                    下载全部完成后在右下角显示通知
                  </span>
                </el-form-item>
              </div>
            </div>

            <div style="margin-top: 20px;">
              <el-button type="success" size="large" :disabled="!canParse" @click="parseExcelFile" :loading="parsing">
                <el-icon>
                  <Document />
                </el-icon>
                {{ parsing ? '解析中...' : '解析并添加下载任务' }}
              </el-button>

              <!-- 处理进度显示 -->
              <div v-if="parsing && processingMessage" style="margin-top: 15px;">
                <el-progress :percentage="processingProgress" :format="(percentage) => `${percentage}%`"
                  :stroke-width="8" status="success" />
                <div style="margin-top: 8px; color: #666; font-size: 14px;">
                  {{ processingMessage }}
                </div>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <!-- 下载列表（主要区域） -->
      <div class="download-list-main">
        <div class="download-header">
          <div class="download-title">
            <h2 style="color: #333; margin: 0;">
              <el-icon>
                <List />
              </el-icon>
              下载任务管理
            </h2>
            <div class="download-stats">
              <!-- <el-tag type="info">总计: {{ downloadStore.downloads.length }}</el-tag>
              <el-tag type="primary">等待: {{ downloadStore.pendingDownloads.length }}</el-tag>
              <el-tag type="success">下载中: {{ downloadStore.activeDownloads.length }}</el-tag>
              <el-tag type="warning">已完成: {{ downloadStore.completedDownloads.length }}</el-tag>
              <el-tag type="danger">失败: {{ downloadStore.failedDownloads.length }}</el-tag> -->
              <el-tag type="info">总计: {{ totalNumObj.countNum }}</el-tag>
              <el-tag type="primary">等待: {{ totalNumObj.status0 }}</el-tag>
              <el-tag type="success">下载中: {{ totalNumObj.status1 }}</el-tag>
              <el-tag type="warning">已完成: {{ totalNumObj.status3 }}</el-tag>
              <el-tag type="danger">失败: {{ totalNumObj.status4 }}</el-tag>
            </div>
          </div>

          <div class="download-actions">
            <!-- 状态筛选 -->
            <el-select v-model="statusFilter" placeholder="按状态筛选" clearable style="width: 150px; margin-right: 10px;"
              @change="handleStatusFilterChange">
              <el-option label="全部" value="" />
              <el-option label="等待中" value="pending" />
              <el-option label="下载中" value="downloading" />
              <el-option label="已暂停" value="paused" />
              <el-option label="已完成" value="completed" />
              <el-option label="失败" value="error" />
            </el-select>

            <!-- 页面级别操作 -->
            <el-button @click="downloadCurrentPage" type="info" size="small">
              下载当前页
            </el-button>
            <el-button @click="pauseCurrentPage" type="warning" size="small">
              暂停当前页
            </el-button>
            <el-divider direction="vertical" />
            <el-button @click="clearCompleted" size="small">
              清除已完成
            </el-button>
            <el-button @click="clearAll" type="danger" size="small">
              清除所有
            </el-button>
          </div>
        </div>

        <!-- 下载任务列表 -->
        <div v-if="downloadStore.downloads.length === 0" class="empty-state">
          <el-icon size="64">
            <Document />
          </el-icon>
          <h3>暂无下载任务</h3>
          <p>请在上方配置区域上传Excel文件并解析添加下载任务</p>
        </div>

        <div v-else class="download-table-container">
          <!-- 分页表格 -->
          <el-table :data="paginatedDownloads" style="width: 100%" border stripe highlight-current-row>

            <el-table-column label="Excel文件" width="180">
              <template #default="{ row }">
                <div class="excel-file-info">
                  <el-icon>
                    <Document />
                  </el-icon>
                  <span class="excel-file-name">{{ row.excelFileName || '-' }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="文件名" min-width="250">
              <template #default="{ row }">
                <div class="file-info">
                  <div class="file-icon">
                    <el-icon>
                      <Document />
                    </el-icon>
                  </div>
                  <div class="file-details">
                    <div class="file-name">
                      <!-- <span v-if="downloadStore.customSubFolder" class="file-prefix">
                        {{ downloadStore.customSubFolder }}_
                      </span> -->
                      <span v-if="row.filePrefix" class="file-prefix">
                        {{ row.filePrefix }}_
                      </span>
                      {{ row.fileName }}
                    </div>
                    <div class="file-url">{{ row.url }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :class="`status-badge status-${row.status}`" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>

            <!-- <el-table-column label="进度" width="200" align="center">
              <template #default="{ row }">
                <div v-if="row.status === 'downloading'" class="progress-container">
                  <el-progress :percentage="row.progress" :format="(percentage) => `${percentage}%`" size="small"
                    :stroke-width="8" />
                  <div class="speed-info">
                    {{ formatSpeed(row.speed) }}
                  </div>
                </div>
                <span v-else-if="row.status === 'completed'" class="completed-text">
                  100%
                </span>
                <span v-else class="pending-text">
                  {{ row.progress }}%
                </span>
              </template>
            </el-table-column> -->

            <!-- <el-table-column label="大小" width="120" align="center" prop="fileLength">
              <template #default="{ row }">
                <span v-if="row.totalBytes > 0" class="size-info">
                  {{ formatBytes(row.downloadedBytes) }} / {{ formatBytes(row.totalBytes) }}
                </span>
                <span v-else class="size-info">-</span>
              </template>
            </el-table-column> -->
            <el-table-column label="大小" width="120" align="center">
              <template #default="{ row }">
                <span v-if="row.status == 'pending'">-</span>
                <span v-else class="size-info">
                  {{ row.fileSize }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <div class="download-actions">
                  <el-button v-if="row.status === 'pending'" @click="startSingleDownload(row)" type="primary"
                    size="small">
                    开始
                  </el-button>

                  <!-- <el-button v-if="row.status === 'downloading'" @click="downloadStore.pauseDownload(row.id)"
                    type="warning" size="small">
                    暂停
                  </el-button> -->

                  <el-button v-if="row.status === 'paused'" @click="resumeSingleDownload(row.id)" type="success"
                    size="small">
                    继续
                  </el-button>

                  <el-button v-if="row.status === 'error'" @click="startSingleDownload(row)" type="warning"
                    size="small">
                    重试
                  </el-button>
                  <el-button @click="deleteRow(row)" type="danger" size="small">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页器 -->
          <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100, 500]" :total="deTotal" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Upload, Document, List, Warning, User, ArrowDown } from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import { useDownloadStore } from '../stores/download'
import * as XLSX from 'xlsx'
import http from '@/utils/request.js';
import config from '@/api/api.js';
import axios from "axios";
import { el, ro } from 'element-plus/es/locales.mjs'

const statusMap = {
  0: 'pending',
  1: 'downloading',
  2: 'paused',
  3: 'completed',
  4: 'error'
}
const statusMap1 = {
  'pending': 0,
  'downloading': 1,
  'paused': 2,
  'completed': 3,
  'error': 4
}

const userName = ref('')
const router = useRouter()
const authStore = useAuthStore()
const downloadStore = useDownloadStore()

const uploadRef = ref()
const selectedFile = ref(null)
const parsing = ref(false)
const processingProgress = ref(0)
const processingMessage = ref('')
const customSubFolder = ref('')
const excelColumns = ref([])
const previewData = ref([])
const rawExcelData = ref([])
const activeCollapse = ref(['upload']) // 默认展开配置区域

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
// 已上传文件列表
let upQuery = ref({
  current: 1,
  pageSize: 5
})
let upTableData = reactive([])
let upTotal = ref(0)
// 下载任务管理列表
let deTotal = ref(0)

let columnMapping = ref({
  fileNameColumns: [],
  url: ''
})

// 状态筛选
let statusFilter = ref('')

// 计算是否可以解析
const canParse = computed(() => {
  return selectedFile.value &&
    columnMapping.value.fileNameColumns.length > 0 &&
    columnMapping.value.url &&
    previewData.value.length > 0
})

// 计算分页后的下载列表
const paginatedDownloads = computed(() => {
  // const start = (currentPage.value - 1) * pageSize.value
  // const end = start + pageSize.value
  // return filteredDownloads.value.slice(start, end)
  return filteredDownloads.value.slice(0)
})

// 计算筛选后的下载列表
const filteredDownloads = computed(() => {
  return downloadStore.downloads.filter(item => {
    // if (statusFilter.value) {
    //   return item.status === statusFilter.value
    // }
    return true
  })
})

// 选择Excel文件
const selectExcelFile = async (fileId) => {
  // try {
  //   const fileInfo = downloadStore.getExcelFileInfo(fileId)
  //   if (!fileInfo) {
  //     ElMessage.error('文件信息不存在')
  //     return
  //   }

  //   downloadStore.setCurrentExcelFile(fileId)

  //   // 加载第一页数据
  //   const pageData = await downloadStore.loadExcelDataPage(fileId, 1, 10)
  //   rawExcelData.value = pageData.data

  //   // 设置列映射
  //   columnMapping.value = fileInfo.columnMapping || { fileNameColumns: [], url: '' }

  //   // 设置列名
  //   if (pageData.data.length > 0) {
  //     excelColumns.value = Object.keys(pageData.data[0])
  //   }

  //   // 生成预览数据
  //   generatePreviewData()

  //   ElMessage.success(`已选择文件: ${fileInfo.fileName}`)
  // } catch (error) {
  //   console.error('选择Excel文件失败:', error)
  //   ElMessage.error('选择Excel文件失败: ' + error.message)
  // }
  http.post(config.uploadBatchQueryUpload, { batchId: fileId }).then(res => {
    if (res.code === 200) {
      if (!res.data || res.data.details.length === 0) {
        ElMessage.error('文件信息不存在')
        return
      }
      downloadStore.setCurrentExcelFile(fileId)
      selectedFile.value = {
        name: res.data.uploadName,
      }
      excelColumns.value = res.data.fileColumnNameAll || []
      columnMapping.value.fileNameColumns = res.data.fileColumnName || []
      columnMapping.value.url = res.data.urlColumnName
      var list = []
      for (const element of res.data.details) {
        list.push({
          fileName: element.fileName,
          url: element.fileUrl
        })
      }
      // 总数据
      rawExcelData.value = list || []
      // 生成预览数据
      if (list.length > 5) {
        previewData.value = list.slice(0, 5)
      } else {
        previewData.value = list || []
      }
      customSubFolder.value = res.data.filePrefix || ''
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 删除Excel文件
const deleteExcelFile = async (fileId) => {
  // 先尝试简单的确认
  const confirmed = confirm('确定要删除这个Excel文件吗？删除后将无法恢复。')
  if (!confirmed) {
    return
  }

  try {
    await downloadStore.deleteExcelFile(fileId)
    ElMessage.success('Excel文件已删除')

    http.post(config.uploadBatchDelete, { batchId: fileId }).then(res => {
      if (res.code === 200) {
        loadUpTableData()
        loadDetailTableData()
      } else {
        ElMessage.error(res.message)
      }
    })
  } catch (error) {
    console.error('删除Excel文件失败:', error)
    ElMessage.error('删除Excel文件失败: ' + (error.message || '未知错误'))
  }
  
}

// 处理文件选择
const handleFileChange = async (file) => {
  selectedFile.value = file.raw

  try {
    // 检查文件大小，超过5MB时显示警告
    if (file.raw.size > 5 * 1024 * 1024) {
      await ElMessageBox.confirm(
        `文件大小: ${(file.raw.size / 1024 / 1024).toFixed(1)}MB，较大文件可能需要较长处理时间。是否继续？`,
        '文件较大',
        {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    }

    // 显示加载提示
    ElMessage.info('正在读取Excel文件，请稍候...')

    // 先读取完整数据以获取列名
    const fullData = await readExcelFileOptimized(file.raw)

    if (fullData.length > 0) {
      // 保存原始完整数据用于后续优化
      window.originalExcelData = fullData

      // 获取所有列名并保存原始列名
      const allColumns = Object.keys(fullData[0])
      excelColumns.value = allColumns
      window.originalColumns = allColumns

      // 尝试自动匹配列名
      autoMatchColumns()

      // 生成预览数据
      generatePreviewData()

      // 如果自动匹配成功，则优化数据
      if (columnMapping.value.fileNameColumns.length > 0 && columnMapping.value.url) {
        const optimizedData = optimizeExcelData(fullData)
        rawExcelData.value = optimizedData
        ElMessage.success(`成功读取 ${fullData.length} 行数据，优化后保留 ${Object.keys(optimizedData[0] || {}).length} 个字段`)
      } else {
        rawExcelData.value = fullData
        ElMessage.success(`成功读取 ${fullData.length} 行数据，请手动配置列映射`)
      }
    }
  } catch (error) {
    console.error('Excel读取错误:', error)
    ElMessage.error('读取Excel文件失败: ' + error.message)
  }
}

// 自动匹配列名
const autoMatchColumns = () => {
  const columns = excelColumns.value

  // 尝试匹配文件名列
  const fileNamePatterns = ['fileName', 'filename', 'name', 'file', '文件名', '文件名称']
  for (const pattern of fileNamePatterns) {
    const match = columns.find(col =>
      col.toLowerCase().includes(pattern.toLowerCase())
    )
    if (match) {
      columnMapping.value.fileNameColumns = [match]
      break
    }
  }

  // 尝试匹配URL列
  const urlPatterns = ['url', 'link', '地址', '链接', '下载地址']
  for (const pattern of urlPatterns) {
    const match = columns.find(col =>
      col.toLowerCase().includes(pattern.toLowerCase())
    )
    if (match) {
      columnMapping.value.url = match
      break
    }
  }

  // 自动优化数据
  if (columnMapping.value.fileNameColumns.length > 0 && columnMapping.value.url) {
    optimizeDataAfterColumnMapping()
  }
}

// 列映射配置后优化数据
const optimizeDataAfterColumnMapping = () => {
  if (!rawExcelData.value.length) return

  // 获取原始完整数据（如果存在）
  const originalData = window.originalExcelData || rawExcelData.value

  // 优化数据：只保留需要的字段
  const optimizedData = optimizeExcelData(originalData)
  rawExcelData.value = optimizedData

  // 确保excelColumns保持原始的所有列名，用于列选择
  if (window.originalColumns) {
    excelColumns.value = window.originalColumns
  }

  // 重新生成预览数据
  generatePreviewData()

  // console.log(`数据优化完成：从 ${Object.keys(originalData[0] || {}).length} 个字段优化到 ${Object.keys(optimizedData[0] || {}).length} 个字段`)
}

// 生成预览数据
const generatePreviewData = () => {
  if (!columnMapping.value.fileNameColumns.length || !columnMapping.value.url) {
    previewData.value = []
    return
  }

  const preview = rawExcelData.value.slice(0, 5).map(row => {
    // 组合多个文件名列
    const fileNameParts = columnMapping.value.fileNameColumns.map(col => row[col] || '').filter(part => part)
    let fileName = fileNameParts.join('-')

    // 从URL中提取扩展名
    const url = row[columnMapping.value.url] || ''
    const extension = getFileExtensionFromUrl(url)
    if (extension) {
      fileName += extension
    }

    return {
      fileName: fileName,
      url: url
    }
  }).filter(item => item.fileName && item.url)

  previewData.value = preview
}

// 处理列映射变化
const handleColumnMappingChange = () => {
  // 生成预览数据
  generatePreviewData()

  // 如果列映射配置完整，则优化数据
  if (columnMapping.value.fileNameColumns.length > 0 && columnMapping.value.url) {
    optimizeDataAfterColumnMapping()
  }
}

// 优化数据：只保留需要的字段
const optimizeExcelData = (data) => {
  if (!columnMapping.value.fileNameColumns.length || !columnMapping.value.url) {
    return []
  }

  const neededColumns = [...columnMapping.value.fileNameColumns, columnMapping.value.url]

  return data.map(row => {
    const optimizedRow = {}
    neededColumns.forEach(col => {
      optimizedRow[col] = row[col] || ''
    })
    return optimizedRow
  })
}

// 从URL中提取文件扩展名
const getFileExtensionFromUrl = (url) => {
  try {
    // 解析URL
    const urlObj = new URL(url)
    const pathname = urlObj.pathname

    // 从路径中提取文件名
    const fileName = pathname.split('/').pop()

    // 检查文件名是否包含扩展名
    if (fileName && fileName.includes('.')) {
      const extension = fileName.substring(fileName.lastIndexOf('.'))
      // 验证扩展名格式（至少2个字符，只包含字母和数字）
      if (extension.length >= 2 && /^\.\w+$/.test(extension)) {
        return extension
      }
    }
    // 如果没有找到有效的扩展名，返回.tmp
    return '.tmp'
  } catch (error) {
    // URL解析失败，返回.tmp
    return '.tmp'
  }
}

// 选择下载路径
const selectDownloadPath = () => {
  ElMessageBox.prompt('请输入自定义子文件夹名称', '设置下载子文件夹', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: customSubFolder.value,
    inputPlaceholder: '例如: vue-downloader-files (留空则直接下载到默认路径)'
  }).then(({ value }) => {
    customSubFolder.value = value
    updateDownloadPath()
    ElMessage.success('下载路径已设置')
  }).catch(() => {
    // 用户取消
  })
}

// 清空文件名前缀
const clearFileNamePrefix = () => {
  customSubFolder.value = ''
  updateDownloadPath()
  ElMessage.success('文件名前缀已清空')
}

// 检测浏览器默认下载路径
const detectBrowserDownloadPath = () => {
  // 初始化时更新文件名前缀
  updateDownloadPath()
}

// 更新文件名前缀
const updateDownloadPath = () => {
  // 更新store中的文件名前缀
  downloadStore.setCustomSubFolder(customSubFolder.value)
}

// 组件挂载时初始化
onMounted(() => {
  // 先初始化下载store
  downloadStore.initialize()
  userName.value = sessionStorage.getItem('userName') || ''

  // 从下载store中同步文件名前缀
  customSubFolder.value = downloadStore.customSubFolder || ''

  detectBrowserDownloadPath()
  loadUpTableData()
  loadDetailTableData()
})

// 已上传 Excel 文件列表数据加载
const loadUpTableData = () => {
  http.post(config.uploadBatchList, upQuery.value).then(res => {
    if (res.code === 200) {
      for (let element of res.data.rows) {
        element.createTime = element.createTime ? element.createTime.substring(0, 10) : ''
      }
      upTableData = res.data.rows
      upTotal.value = res.data.total
    } else {
      ElMessage.error(res.message)
    }
  })
}

function loadDetailTableData() {
  http.post(config.uploadDetailList, {
    current: currentPage.value,
    pageSize: pageSize.value,
    fileStatus: statusMap1[statusFilter.value]
  }).then(res => {
    if (res.code === 200) {
      var list = []
      var filePrefix = ''
      for (const element of res.data.rows) {
        filePrefix = element.filePrefix
        list.push({
          "id": element.detailId,
          "fileName": element.fileName,
          "url": element.fileUrl,
          "excelFileName": element.uploadName,
          "excelFileId": "",
          "status": statusMap[element.fileStatus],
          "progress": 0,
          "downloadedBytes": 0,
          "fileSize": element.fileLength,
          "speed": 0,
          "startTime": element.createTime,
          "endTime": null,
          "error": null,
          "retryCount": 0,
          "maxRetries": 3,
          "controller": null,
          "filePrefix": element.filePrefix
        })
      }
      // console.log('--lsit:',list)
      downloadStore.downloads = list
      downloadStore.setCustomSubFolder(filePrefix)
      customSubFolder.value = filePrefix
      deTotal.value = res.data.total
      loadUploadDetailTotalNum()
    } else {
      ElMessage.error(res.message)
    }
  })
}

let totalNumObj = ref({
  countNum: 0,
  fileLength: '',
  status0: 0,
  status1: 0,
  status2: 0,
  status3: 0,
  status4: 0,
})
function loadUploadDetailTotalNum() {
  http.post(config.uploadDetailTotalNum).then(res => {
    if (res.code === 200) {
      totalNumObj.value.countNum = res.data.countNum
      totalNumObj.value.status3 = res.data.status3
      totalNumObj.value.status4 = res.data.status4
      totalNumObj.value.fileLength = res.data.fileLength
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 清除已完成
function clearCompleted() {
  downloadStore.clearCompleted()
  http.post(config.uploadDetailDeleteAll, {
    type: 0
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.message)
      currentPage.value = 1
      // loadUploadDetailList()
      loadDetailTableData()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 清除所有
function clearAll() {
  downloadStore.clearAll()
  http.post(config.uploadDetailDeleteAll, {
    type: 1
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.message)
      deQuery.value.current = 1
      // loadUploadDetailList()
      loadDetailTableData()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 删除单行
function deleteRow(row) {
  downloadStore.cancelDownload(row.id)
  http.post(config.uploadDetailDelete, {
    detailId: row.detailId
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.message)
      currentPage.value = 1
      loadDetailTableData()
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 解析Excel文件
const parseExcelFile = async () => {
  if (rawExcelData.value.length > 10000) {
    ElMessage.error('文件数据量太大,请拆分处理，每次不超过10000条')
    return
  }
  if (!canParse.value) {
    ElMessage.warning('请先选择Excel文件并配置列映射')
    return
  }
  // 数据预览列表 URL 列必须是有效的 HTTP/HTTPS URL
  const url = previewData.value[0]?.url
  if (!url || !/^https?:\/\//i.test(url)) {
    ElMessage.warning('预览数据中的URL格式不正确，请检查列映射')
    return
  }

  parsing.value = true
  processingProgress.value = 0
  processingMessage.value = '正在处理Excel数据...'

  try {
    // 显示处理进度
    ElMessage.info('正在处理Excel数据，请稍候...')

    // 使用setTimeout来避免阻塞UI
    await new Promise(resolve => setTimeout(resolve, 100))

    // 获取完整数据（从原始数据或当前数据）
    const allData = window.originalExcelData || rawExcelData.value
    // 过滤有效数据（分批处理）
    const batchSize = 1000 // 每批处理1000行
    const validData = []
    const totalBatches = Math.ceil(allData.length / batchSize)

    for (let i = 0; i < allData.length; i += batchSize) {
      const batchIndex = Math.floor(i / batchSize) + 1
      const batch = allData.slice(i, i + batchSize)

      // 更新进度
      processingProgress.value = Math.round((batchIndex / totalBatches) * 30) // 前30%用于数据过滤
      processingMessage.value = `正在过滤数据... (${batchIndex}/${totalBatches})`

      const batchValidData = batch.filter(row => {
        const fileNameParts = columnMapping.value.fileNameColumns.map(col => row[col] || '').filter(part => part)
        let fileName = fileNameParts.join('-')
        const url = row[columnMapping.value.url]

        // 从URL中提取扩展名
        const extension = getFileExtensionFromUrl(url)
        if (extension) {
          fileName += extension
        }

        return fileName && url
      })

      validData.push(...batchValidData)

      // 每处理一批数据后让出控制权，避免阻塞UI
      if (i + batchSize < allData.length) {
        await new Promise(resolve => setTimeout(resolve, 10))
      }
    }

    if (validData.length === 0) {
      ElMessage.warning('Excel文件中没有找到有效数据')
      return
    }
    // 保存文件到本地之前先删除本地所有文件
    downloadStore.clearAll()
    // 保存Excel文件到本地存储
    processingProgress.value = 30
    processingMessage.value = '正在保存Excel文件到本地...'

    const excelFileInfo = await downloadStore.saveExcelFileToLocal(
      selectedFile.value,
      allData,
      columnMapping.value
    )

    // 显示确认对话框
    await ElMessageBox.confirm(
      `找到 ${validData.length} 个有效下载任务，是否开始添加？`,
      '确认添加下载任务',
      {
        confirmButtonText: '确定添加',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    // 上传后端
    uploadDetails()

    // 临时禁用自动下载
    const originalBatchDownloading = downloadStore.isBatchDownloading
    downloadStore.isBatchDownloading = true

    // 分批添加下载任务
    const addBatchSize = 500 // 每批添加500个任务
    const totalAddBatches = Math.ceil(validData.length / addBatchSize)

    for (let i = 0; i < validData.length; i += addBatchSize) {
      const batchIndex = Math.floor(i / addBatchSize) + 1
      const batch = validData.slice(i, i + addBatchSize)

      // 更新进度
      processingProgress.value = 30 + Math.round((batchIndex / totalAddBatches) * 70) // 后70%用于添加任务
      processingMessage.value = `正在添加下载任务... (${batchIndex}/${totalAddBatches})`

      batch.forEach(row => {
        const fileNameParts = columnMapping.value.fileNameColumns.map(col => row[col] || '').filter(part => part)
        let fileName = fileNameParts.join('-')
        const url = row[columnMapping.value.url]

        // 从URL中提取扩展名
        const extension = getFileExtensionFromUrl(url)
        if (extension) {
          fileName += extension
        }

        downloadStore.addDownload(fileName, url, selectedFile.value.name, excelFileInfo.id)
      })

      // 每批添加后让出控制权
      if (i + addBatchSize < validData.length) {
        await new Promise(resolve => setTimeout(resolve, 50))
      }
    }

    // 恢复自动下载状态
    downloadStore.isBatchDownloading = originalBatchDownloading

    ElMessage.success(`成功添加 ${validData.length} 个下载任务`)

    // 重置状态
    selectedFile.value = null
    excelColumns.value = []
    previewData.value = []
    rawExcelData.value = []
    columnMapping.value = { fileNameColumns: [], url: '' }

    // 清空上传组件
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }

  } catch (error) {
    if (error.message.includes('cancel')) {
      ElMessage.info('已取消添加下载任务')
    } else {
      console.error('解析Excel文件错误:', error)
      ElMessage.error('解析Excel文件失败: ' + error.message)
    }
  } finally {
    parsing.value = false
    processingProgress.value = 0
    processingMessage.value = ''
  }
}

function getDetailList() {
  if (!columnMapping.value.fileNameColumns.length || !columnMapping.value.url) {
    ElMessage.error('请先选择文件列名和 URL 列')
    return []
  }

  const preview = rawExcelData.value.map(row => {
    // 组合多个文件名列
    const fileNameParts = columnMapping.value.fileNameColumns.map(col => row[col] || '').filter(part => part)
    let fileName = fileNameParts.join('-')

    // 从URL中提取扩展名
    const url = row[columnMapping.value.url] || ''
    const extension = getFileExtensionFromUrl(url)
    if (extension) {
      fileName += extension
    }

    return {
      fileName: fileName,
      fileUrl: url
    }
  }).filter(item => item.fileName && item.fileUrl)

  return preview
}

var upDetailId = ''
let detailList = reactive([])

function uploadDetails() {
  detailList = getDetailList()
  http.post(config.uploadBatchFileUpload, {
    uploadName: selectedFile.value.name,
    uploadUrl: '',
    totalRows: rawExcelData.value.length,
    fileColumnNameAll: excelColumns.value,
    fileColumnName: columnMapping.value.fileNameColumns,
    urlColumnName: columnMapping.value.url,
    filePrefix: customSubFolder.value,
    notifyStatus: downloadStore.enableNotifications,
    // details: detailList
  }).then(res => {
    if (res.code === 200) {
      upDetailId = res.data
      uploadDetailsFile()
    } else {
      detailList = []
      ElMessage.error(res.message)
    }
  })
}
function uploadDetailsFile() {
  var uplist = []
  if (detailList.length > 500) {
    uplist = detailList.slice(0, 500)
    detailList = detailList.slice(500)
  } else {
    uplist = detailList
    detailList = []
  }
  http.post(config.fileUploadDetail, {
    batchId: upDetailId,
    details: uplist
  }).then(res => {
    if (res.code === 200) {
      if (detailList.length > 0) {
        uploadDetailsFile()
      } else {
        ElMessage.success('上传任务完成')
        loadUpTableData()
        loadDetailTableData()
      }
    }
  })
}

// 下载当前页所有任务
const downloadCurrentPage = async () => {
  const currentPageItems = paginatedDownloads.value
  if (currentPageItems.length === 0) {
    ElMessage.warning('当前页没有下载任务')
    return
  }

  // 过滤出可以开始下载的任务
  const startableItems = currentPageItems.filter(item =>
    ['pending', 'paused', 'error'].includes(item.status)
  )

  if (startableItems.length === 0) {
    ElMessage.warning('当前页没有可以开始下载的任务')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要下载当前页的 ${startableItems.length} 个任务吗？`, '下载当前页', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    // 获取当前页所有任务的ID
    const currentPageIds = startableItems.map(item => item.id)

    // 使用store的批量下载方法
    await downloadStore.batchStartDownloads(currentPageIds)

    ElMessage.success(`已开始下载当前页的 ${startableItems.length} 个任务`)
  } catch {
    // 用户取消
  }
}
async function getFileSize(url) {
  try {
    const response = await axios.head(url);
    const size = response.headers["content-length"];
    return size ? parseInt(size, 10) : null;
  } catch (err) {
    console.error("获取文件大小失败:", err);
    return null;
  }
}

// 暂停当前页所有任务
const pauseCurrentPage = async () => {
  const currentPageItems = paginatedDownloads.value
  if (currentPageItems.length === 0) {
    ElMessage.warning('当前页没有下载任务')
    return
  }

  // 过滤出可以暂停的任务（只有下载中的任务可以暂停）
  const pausableItems = currentPageItems.filter(item =>
    item.status === 'downloading'
  )

  if (pausableItems.length === 0) {
    ElMessage.warning('当前页没有正在下载的任务')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要暂停当前页的 ${pausableItems.length} 个任务吗？`, '暂停当前页', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 获取当前页所有任务的ID
    const currentPageIds = pausableItems.map(item => item.id)

    // 使用store的批量暂停方法
    downloadStore.batchPauseDownloads(currentPageIds)

    ElMessage.success(`已暂停当前页的 ${pausableItems.length} 个任务`)
  } catch {
    // 用户取消
  }
}

// 处理下载任务管理 列表分页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadDetailTableData()
}
// 处理下载任务管理 列表页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadDetailTableData()
}

// 处理已上传Excel文件 列表分页条数变化
const handleUpSizeChange = (size) => {
  upQuery.value.pageSize = size
  upQuery.value.current = 1
  loadUpTableData()
}
// 处理已上传Excel文件 列表页码变化
const handleUpCurrentChange = (page) => {
  upQuery.value.current = page
  loadUpTableData()
}

// 处理状态筛选变化
const handleStatusFilterChange = () => {
  currentPage.value = 1 // 重置当前页为1，以便重新加载数据
  loadDetailTableData()
}

// 单个文件下载
const startSingleDownload = async (row) => {
  downloadStore.setCustomSubFolder(row.filePrefix)

  downloadStore.isSingleDownloading = true
  try {
    await downloadStore.startDownload(row.id)
    loadDetailTableData()
    loadUploadDetailTotalNum()
  } finally {
    downloadStore.isSingleDownloading = false
  }
}

// 单个文件恢复下载
const resumeSingleDownload = async (downloadId) => {
  downloadStore.isSingleDownloading = true
  try {
    await downloadStore.resumeDownload(downloadId)
    loadDetailTableData()
    loadUploadDetailTotalNum()
  } finally {
    downloadStore.isSingleDownloading = false
  }
}

// 优化的Excel文件读取方法
const readExcelFileOptimized = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e) => {
      try {
        // 优先使用Worker处理，如果失败则使用主线程
        processLargeExcelFileWithWorker(e.target.result, resolve, (workerError) => {
          console.warn('Worker处理失败，使用主线程处理:', workerError)
          // 备用方案：使用主线程处理
          try {
            const result = processExcelInMainThread(e.target.result)
            resolve(result)
          } catch (mainThreadError) {
            reject(new Error(`主线程处理也失败: ${mainThreadError.message}`))
          }
        })
      } catch (error) {
        reject(error)
      }
    }

    reader.onerror = () => {
      reject(new Error('读取文件失败'))
    }

    reader.readAsArrayBuffer(file)
  })
}

// 主线程处理Excel文件（备用方案）
const processExcelInMainThread = (arrayBuffer) => {
  try {
    const data = new Uint8Array(arrayBuffer)
    const workbook = XLSX.read(data, {
      type: 'array',
      cellDates: true,
      cellNF: false,
      cellStyles: false,
      cellHTML: false,
      cellFormula: false,
      cellText: false
    })

    if (!workbook.SheetNames || workbook.SheetNames.length === 0) {
      throw new Error('Excel文件中没有找到工作表')
    }

    const sheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[sheetName]

    if (!worksheet) {
      throw new Error('无法读取工作表数据')
    }

    // 限制最大行数，防止内存溢出
    const maxRows = 50000 // 主线程限制更严格
    const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1')
    if (range.e.r > maxRows) {
      range.e.r = maxRows - 1
      worksheet['!ref'] = XLSX.utils.encode_range(range)
    }

    const jsonData = XLSX.utils.sheet_to_json(worksheet, {
      header: 1,
      defval: '',
      blankrows: false
    })

    if (!jsonData || jsonData.length === 0) {
      throw new Error('Excel文件中没有数据')
    }

    // 转换为对象数组
    const headers = jsonData[0]
    if (!headers || headers.length === 0) {
      throw new Error('Excel文件中没有列标题')
    }

    const rows = jsonData.slice(1).map(row => {
      const obj = {}
      headers.forEach((header, index) => {
        obj[header] = row[index] || ''
      })
      return obj
    })

    return rows
  } catch (error) {
    throw new Error('主线程Excel解析失败: ' + error.message)
  }
}

// 使用Web Worker处理Excel文件
const processLargeExcelFileWithWorker = (arrayBuffer, resolve, reject) => {
  try {
    // 创建Web Worker
    const worker = new Worker('/excel-worker.js')

    // 设置超时时间
    const timeout = setTimeout(() => {
      worker.terminate()
      reject(new Error('Excel解析超时，请尝试使用较小的文件'))
    }, 120000) // 增加到120秒超时

    worker.onmessage = (e) => {
      clearTimeout(timeout)
      worker.terminate()

      if (e.data.type === 'success') {
        resolve(e.data.data)
      } else {
        reject(new Error(e.data.error || 'Worker处理失败'))
      }
    }

    worker.onerror = (error) => {
      clearTimeout(timeout)
      worker.terminate()
      console.error('Worker error:', error)
      reject(new Error('Worker处理失败: ' + (error.message || '未知错误')))
    }

    // 发送数据给Worker
    worker.postMessage({
      type: 'parseExcel',
      data: arrayBuffer
    })
  } catch (error) {
    console.error('Worker创建失败:', error)
    reject(new Error('Worker创建失败: ' + error.message))
  }
}

// 保留原方法作为备用
const readExcelFile = (file) => {
  return readExcelFileOptimized(file)
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '等待中',
    downloading: '下载中',
    completed: '已完成',
    error: '失败',
    paused: '已暂停',
    0: '等待中',
    1: '下载中',
    2: '已暂停',
    3: '已完成',
    4: '失败'
  }
  return statusMap[status] || status
}

// 格式化速度
const formatSpeed = (bytesPerSecond) => {
  if (bytesPerSecond === 0) return '0 B/s'

  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s']
  let size = bytesPerSecond
  let unitIndex = 0

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }

  return `${size.toFixed(1)} ${units[unitIndex]}`
}

// 格式化字节数
const formatBytes = (bytes) => {
  if (bytes === 0) return '0 B'

  const units = ['B', 'KB', 'MB', 'GB']
  let size = bytes
  let unitIndex = 0

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }

  return `${size.toFixed(1)} ${units[unitIndex]}`
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    authStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

// 处理用户下拉菜单命令
const handleUserCommand = (command) => {
  if (command === 'settings') {
    ElMessage.info('跳转到个人设置页面')
    // 实际跳转逻辑
    router.push('/settings')
  } else if (command === 'history') {
    ElMessage.info('跳转到下载历史页面')
    // 实际跳转逻辑
    router.push('/history')
  } else if (command === 'logout') {
    handleLogout()
  }
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.user-info:hover {
  background-color: #f5f5f5;
}
</style>