import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from './auth'
import http from '@/utils/request.js';
import config from '@/api/api.js';

export const useDownloadStore = defineStore('download', () => {
  const authStore = useAuthStore()

  // 下载列表
  const downloads = ref([])
  
  // 下载设置
  const downloadPath = ref('')
  const customSubFolder = ref('')
  const maxConcurrentDownloads = ref(3)
  const activeDownloadCount = ref(0)
  const enableNotifications = ref(true)
  
  // 下载控制标志
  const isBatchDownloading = ref(false)
  const isSingleDownloading = ref(false)

  // Excel文件存储相关
  const excelFiles = ref([]) // 存储Excel文件信息
  const currentExcelFile = ref(null) // 当前处理的Excel文件

  // 从本地存储加载数据
  const loadFromStorage = () => {
    try {
      // 加载用户设置
      const userSettings = authStore.getUserSettings()
      maxConcurrentDownloads.value = userSettings.maxConcurrentDownloads || 3
      customSubFolder.value = userSettings.fileNamePrefix || ''
      enableNotifications.value = userSettings.enableNotifications !== false
      
      // 加载下载列表
      const storedDownloads = localStorage.getItem('vue_downloader_downloads')
      if (storedDownloads) {
        downloads.value = JSON.parse(storedDownloads)
      }

      // 加载Excel文件列表
      const storedExcelFiles = localStorage.getItem('vue-downloader-excel-files')
      if (storedExcelFiles) {
        excelFiles.value = JSON.parse(storedExcelFiles)
      }
    } catch (error) {
      console.error('加载下载数据失败:', error)
    }
  }

  // 保存到本地存储
  const saveToStorage = () => {
    try {
      localStorage.setItem('vue_downloader_downloads', JSON.stringify(downloads.value))
      localStorage.setItem('vue-downloader-settings', JSON.stringify({
        customSubFolder: customSubFolder.value,
        enableNotifications: enableNotifications.value,
        maxConcurrentDownloads: maxConcurrentDownloads.value
      }))
      localStorage.setItem('vue-downloader-excel-files', JSON.stringify(excelFiles.value))
    } catch (error) {
      console.error('保存下载数据失败:', error)
    }
  }

  // 保存下载历史
  const saveDownloadHistory = () => {
    if (downloads.value.length > 0) {
      authStore.saveDownloadHistory(downloads.value)
    }
  }

  // 初始化
  const initialize = () => {
    loadFromStorage()
  }

  // 计算属性
  const pendingDownloads = computed(() => 
    downloads.value.filter(d => d.status === 'pending')
  )
  
  const activeDownloads = computed(() => 
    downloads.value.filter(d => d.status === 'downloading')
  )
  
  const completedDownloads = computed(() => 
    downloads.value.filter(d => d.status === 'completed')
  )
  
  const failedDownloads = computed(() => 
    downloads.value.filter(d => d.status === 'error')
  )

  // 检查是否所有下载都完成
  const allDownloadsCompleted = computed(() => {
    return downloads.value.length > 0 && 
           downloads.value.every(d => d.status === 'completed' || d.status === 'error')
  })

  // 添加下载任务（修改为支持Excel文件ID）
  const addDownload = (fileName, url, excelFileName = '', excelFileId = null) => {
    const download = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      fileName,
      url,
      excelFileName,
      excelFileId, // 添加Excel文件ID
      status: 'pending',
      progress: 0,
      downloadedBytes: 0,
      fileSize: 0,
      speed: 0,
      startTime: null,
      endTime: null,
      error: null,
      retryCount: 0,
      maxRetries: 3,
      controller: null
    }
    
    downloads.value.push(download)
    saveToStorage()
  }

  // 开始下载（支持多线程）
  const startDownload = async (downloadId) => {
    const download = downloads.value.find(d => d.id === downloadId)
    if (!download || download.status === 'downloading') return

    // 检查并发数限制
    if (activeDownloadCount.value >= maxConcurrentDownloads.value) {
      // 如果超过并发限制，将任务重新设为等待状态
      download.status = 'pending'
      saveToStorage()
      return
    }

    download.status = 'downloading'
    download.startTime = new Date()
    download.progress = 0
    download.downloadedBytes = 0
    download.speed = 0
    download.error = null
    activeDownloadCount.value++
    saveToStorage()

    // 创建 AbortController 用于取消下载
    download.controller = new AbortController()
    // console.log('download config.url-->',config.downLoadStatus)
    // console.log('download id-->',download.id)
    try {
      await performDownload(download)
      http.post(config.downLoadStatus,{
        detailId: download.id,
        fileStatus: 3, //下载状态 0:等待中 1:下载中 2:已暂停 3:已完成 4:失败
      }).then(res=>{ 
        if (res.code === 200) {
        } else {
          ElMessage.error(res.message)
        }
      })
    } catch (error) {
      if (error.name === 'AbortError') {
        download.status = 'paused'
        saveToStorage()
        http.post(config.downLoadStatus,{
          detailId: download.id,
          fileStatus: 2, //下载状态 0:等待中 1:下载中 2:已暂停 3:已完成 4:失败
        }).then(res=>{ 
          if (res.code === 200) {
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        // 处理重试逻辑
        if (download.retryCount < download.maxRetries) {
          download.retryCount++
          download.status = 'pending'
          saveToStorage()
          // 延迟重试
          setTimeout(() => {
            startDownload(downloadId)
          }, 2000 * download.retryCount) // 递增延迟
        } else {
          download.status = 'error'
          download.error = error.message
          saveToStorage()
          http.post(config.downLoadStatus,{
            detailId: download.id,
            fileStatus: 4, //下载状态 0:等待中 1:下载中 2:已暂停 3:已完成 4:失败
          }).then(res=>{ 
            if (res.code === 200) {
            } else {
              ElMessage.error(res.message)
            }
          })
        }
      }
    } finally {
      activeDownloadCount.value--
      // 只有在非批量下载且非单个下载模式下才自动启动下一个等待中的下载
      if (!isBatchDownloading.value && !isSingleDownloading.value) {
        startNextPendingDownload()
      }
      
      // 检查是否所有下载都完成
      checkAllDownloadsCompleted()
    }
  }

  // 启动下一个等待中的下载
  const startNextPendingDownload = () => {
    // 如果正在批量下载或单个下载，不自动启动其他任务
    if (isBatchDownloading.value || isSingleDownloading.value) return
    
    const pendingDownload = downloads.value.find(d => d.status === 'pending')
    if (pendingDownload && activeDownloadCount.value < maxConcurrentDownloads.value) {
      startDownload(pendingDownload.id)
    }
  }

  // 检查所有下载是否完成
  const checkAllDownloadsCompleted = () => {
    const allCompleted = downloads.value.every(download => 
      download.status === 'completed' || download.status === 'error'
    )
    
    if (allCompleted && enableNotifications.value) {
      const completedCount = downloads.value.filter(d => d.status === 'completed').length
      const failedCount = downloads.value.filter(d => d.status === 'error').length
      
      ElMessage({
        message: `下载完成！成功: ${completedCount} 个，失败: ${failedCount} 个`,
        type: 'success',
        duration: 5000
      })
      
      // 保存下载历史
      saveDownloadHistory()
    }
  }

  // 显示下载完成通知
  const showDownloadCompletionNotification = () => {
    const completedCount = completedDownloads.value.length
    const failedCount = failedDownloads.value.length
    
    let message = ''
    if (failedCount === 0) {
      message = `所有 ${completedCount} 个文件下载完成！`
    } else {
      message = `${completedCount} 个文件下载完成，${failedCount} 个文件下载失败`
    }
    
    // 创建通知元素
    const notification = document.createElement('div')
    notification.className = 'download-notification'
    notification.innerHTML = `
      <div class="notification-content">
        <div class="notification-icon">✅</div>
        <div class="notification-message">${message}</div>
        <div class="notification-close" onclick="this.parentElement.parentElement.remove()">×</div>
      </div>
    `
    
    // 添加样式
    notification.style.cssText = `
      position: fixed;
      bottom: 20px;
      right: 20px;
      background: #67c23a;
      color: white;
      padding: 15px 20px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      z-index: 9999;
      animation: slideIn 0.3s ease-out;
      max-width: 300px;
    `
    
    // 添加动画样式
    const style = document.createElement('style')
    style.textContent = `
      @keyframes slideIn {
        from {
          transform: translateX(100%);
          opacity: 0;
        }
        to {
          transform: translateX(0);
          opacity: 1;
        }
      }
      .notification-content {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .notification-icon {
        font-size: 20px;
      }
      .notification-message {
        flex: 1;
        font-size: 14px;
      }
      .notification-close {
        cursor: pointer;
        font-size: 18px;
        font-weight: bold;
        opacity: 0.8;
      }
      .notification-close:hover {
        opacity: 1;
      }
    `
    document.head.appendChild(style)
    
    document.body.appendChild(notification)
    
    // 5秒后自动移除
    setTimeout(() => {
      if (notification.parentElement) {
        notification.remove()
      }
    }, 5000)
  }

  // 执行下载
  const performDownload = async (download) => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      
      xhr.open('GET', download.url, true)
      xhr.responseType = 'blob'
      
      // 设置断点续传
      const existingFile = localStorage.getItem(`download_${download.id}`)
      if (existingFile) {
        const parsed = JSON.parse(existingFile)
        download.downloadedBytes = parsed.downloadedBytes || 0
        xhr.setRequestHeader('Range', `bytes=${download.downloadedBytes}-`)
      }

      // 设置超时
      xhr.timeout = 30000 // 30秒超时

      xhr.onprogress = (event) => {
        if (event.lengthComputable) {
          const total = event.total + download.downloadedBytes
          const loaded = event.loaded + download.downloadedBytes
          
          download.totalBytes = total
          download.downloadedBytes = loaded
          download.progress = Math.round((loaded / total) * 100)
          
          // 计算下载速度
          const now = Date.now()
          const timeDiff = (now - download.startTime) / 1000
          download.speed = loaded / timeDiff
          
          // 保存进度到本地存储
          localStorage.setItem(`download_${download.id}`, JSON.stringify({
            downloadedBytes: loaded,
            progress: download.progress
          }))
          
          // 定期保存到主存储（每5%进度保存一次）
          if (download.progress % 5 === 0) {
            saveToStorage()
          }
        }
      }

      xhr.onload = async () => {
        if (xhr.status === 200 || xhr.status === 206) {
          download.status = 'completed'
          download.progress = 100
          download.endTime = new Date()
          saveToStorage()
          
          // 保存文件到自定义文件夹
          const blob = xhr.response
          try {
            // 尝试使用现代浏览器的 File System Access API
            if ('showSaveFilePicker' in window) {
              await saveFileWithPicker(blob, download.fileName)
            } else {
              // 降级到传统方法
              saveFileWithLegacyMethod(blob, download.fileName)
            }
          } catch (error) {
            console.warn('文件保存失败，使用传统方法:', error)
            saveFileWithLegacyMethod(blob, download.fileName)
          }
          
          // 清除本地存储的进度
          localStorage.removeItem(`download_${download.id}`)
          
          resolve()
        } else {
          reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`))
        }
      }

      xhr.onerror = () => {
        reject(new Error('网络错误'))
      }

      xhr.onabort = () => {
        reject(new Error('下载已取消'))
      }

      xhr.ontimeout = () => {
        reject(new Error('下载超时'))
      }

      // 监听取消信号
      if (download.controller) {
        download.controller.signal.addEventListener('abort', () => {
          xhr.abort()
        })
      }

      xhr.send()
    })
  }

  // 使用现代浏览器的 File System Access API 保存文件
  const saveFileWithPicker = async (blob, fileName) => {
    try {
      // 构建带前缀的文件名
      let finalFileName = fileName
      if (customSubFolder.value && customSubFolder.value.trim()) {
        finalFileName = `${customSubFolder.value.trim()}_${fileName}`
      }
      
      const options = {
        suggestedName: finalFileName,
        types: [{
          description: '下载文件',
          accept: {
            '*/*': ['.*']
          }
        }]
      }
      
      const fileHandle = await window.showSaveFilePicker(options)
      const writable = await fileHandle.createWritable()
      await writable.write(blob)
      await writable.close()
      
      console.log(`文件已保存: ${finalFileName}`)
    } catch (error) {
      console.error('File System Access API 保存失败:', error)
      throw error
    }
  }

  // 使用传统方法保存文件
  const saveFileWithLegacyMethod = (blob, fileName) => {
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    
    // 构建带前缀的文件名
    let finalFileName = fileName
    if (customSubFolder.value && customSubFolder.value.trim()) {
      finalFileName = `${customSubFolder.value.trim()}_${fileName}`
    }
    
    a.download = finalFileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  }

  // 获取操作系统信息
  const getOperatingSystem = () => {
    const userAgent = navigator.userAgent.toLowerCase()
    
    if (userAgent.includes('windows')) {
      return 'windows'
    } else if (userAgent.includes('mac')) {
      return 'mac'
    } else if (userAgent.includes('linux')) {
      return 'linux'
    } else {
      return 'unknown'
    }
  }

  // 获取默认下载路径
  const getDefaultDownloadPath = () => {
    const os = getOperatingSystem()
    
    switch (os) {
      case 'windows':
        return 'C:\\Users\\用户名\\Downloads'
      case 'mac':
        return '/Users/用户名/Downloads'
      case 'linux':
        return '/home/用户名/Downloads'
      default:
        return '浏览器默认下载目录'
    }
  }

  // 构建完整下载路径
  const getFullDownloadPath = () => {
    const basePath = getDefaultDownloadPath()
    const os = getOperatingSystem()
    
    if (!customSubFolder.value || !customSubFolder.value.trim()) {
      return basePath
    }

    const separator = os === 'windows' ? '\\' : '/'
    return `${basePath}${separator}${customSubFolder.value.trim()}`
  }

  // 暂停下载
  const pauseDownload = (downloadId) => {
    const download = downloads.value.find(d => d.id === downloadId)
    if (download && download.controller) {
      download.controller.abort()
      download.status = 'paused'
      activeDownloadCount.value--
      saveToStorage()
      http.post(config.downLoadStatus,{
        detailId: download.id,
        fileStatus: 2, //下载状态 0:等待中 1:下载中 2:已暂停 3:已完成 4:失败
      }).then(res=>{ 
      })
      // 只有在非批量下载且非单个下载模式下才自动启动下一个等待中的下载
      if (!isBatchDownloading.value && !isSingleDownloading.value) {
        startNextPendingDownload()
      }
    }
  }

  // 恢复下载
  const resumeDownload = (downloadId) => {
    startDownload(downloadId)
  }

  // 取消下载
  const cancelDownload = (downloadId) => {
    const download = downloads.value.find(d => d.id === downloadId)
    if (download && download.controller) {
      download.controller.abort()
      if (download.status === 'downloading') {
        activeDownloadCount.value--
      }
    }
    
    const index = downloads.value.findIndex(d => d.id === downloadId)
    if (index > -1) {
      downloads.value.splice(index, 1)
      saveToStorage()
    }
    
    // 清除本地存储
    localStorage.removeItem(`download_${downloadId}`)
    
    // 删除操作不触发自动启动其他下载任务
    // 只有在非批量下载且非单个下载模式下才自动启动下一个等待中的下载
    // 删除操作应该保持当前状态，不自动启动新任务
  }

  // 批量开始下载
  const batchStartDownloads = async (downloadIds) => {
    isBatchDownloading.value = true
    try {
      for (const id of downloadIds) {
        await startDownload(id)
      }
    } finally {
      isBatchDownloading.value = false
    }
  }

  // 批量暂停下载
  const batchPauseDownloads = (downloadIds) => {
    downloadIds.forEach(id => pauseDownload(id))
  }

  // 批量删除下载
  const batchDeleteDownloads = (downloadIds) => {
    isBatchDownloading.value = true
    try {
      downloadIds.forEach(id => cancelDownload(id))
    } finally {
      isBatchDownloading.value = false
    }
  }

  // 设置下载路径
  const setDownloadPath = (path) => {
    downloadPath.value = path
  }

  // 设置自定义子文件夹
  const setCustomSubFolder = (folder) => {
    customSubFolder.value = folder
    // 同步到用户设置
    authStore.updateUserSettings({ fileNamePrefix: folder })
  }

  // 设置最大并发下载数
  const setMaxConcurrentDownloads = (count) => {
    maxConcurrentDownloads.value = count
    // 同步到用户设置
    authStore.updateUserSettings({ maxConcurrentDownloads: count })
  }

  // 设置启用通知
  const setEnableNotifications = (enabled) => {
    enableNotifications.value = enabled
    // 同步到用户设置
    authStore.updateUserSettings({ enableNotifications: enabled })
  }

  // 清除已完成的任务
  const clearCompleted = () => {
    downloads.value = downloads.value.filter(download => download.status !== 'completed')
    saveToStorage()
  }

  // 清除所有任务
  const clearAll = () => {
    downloads.value = []
    saveToStorage()
  }

  // 重试失败的下载
  const retryFailedDownloads = () => {
    downloads.value.forEach(download => {
      if (download.status === 'error') {
        download.status = 'pending'
        download.progress = 0
        download.downloadedBytes = 0
        download.speed = 0
        download.error = null
        download.retryCount = 0
        download.startTime = null
        download.endTime = null
      }
    })
    saveToStorage()
  }

  // 保存Excel文件到本地
  const saveExcelFileToLocal = async (file, data, columnMapping) => {
    try {
      const excelFileInfo = {
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        fileName: file.name,
        fileSize: file.size,
        uploadTime: new Date().toISOString(),
        totalRows: data.length,
        columnMapping: columnMapping,
        dataChunks: [], // 分块存储数据
        chunkSize: 1000 // 每块1000行
      }

      // 将数据分块保存到IndexedDB
      await saveDataToIndexedDB(excelFileInfo.id, data, excelFileInfo.chunkSize)
      
      // 保存文件信息
      excelFiles.value.push(excelFileInfo)
      saveToStorage()
      
      return excelFileInfo
    } catch (error) {
      console.error('保存Excel文件失败:', error)
      throw error
    }
  }

  // 保存数据到IndexedDB
  const saveDataToIndexedDB = async (fileId, data, chunkSize) => {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open('VueDownloaderDB', 1)
      
      request.onerror = () => reject(request.error)
      request.onsuccess = () => {
        const db = request.result
        const transaction = db.transaction(['excelData'], 'readwrite')
        const store = transaction.objectStore('excelData')
        
        // 分块保存数据
        const chunks = []
        for (let i = 0; i < data.length; i += chunkSize) {
          const chunk = data.slice(i, i + chunkSize)
          chunks.push({
            fileId: fileId,
            chunkIndex: Math.floor(i / chunkSize),
            data: chunk
          })
        }
        
        let completed = 0
        chunks.forEach(chunk => {
          const addRequest = store.add(chunk)
          addRequest.onsuccess = () => {
            completed++
            if (completed === chunks.length) {
              resolve()
            }
          }
          addRequest.onerror = () => reject(addRequest.error)
        })
      }
      
      request.onupgradeneeded = (event) => {
        const db = event.target.result
        if (!db.objectStoreNames.contains('excelData')) {
          const store = db.createObjectStore('excelData', { keyPath: ['fileId', 'chunkIndex'] })
          store.createIndex('fileId', 'fileId', { unique: false })
        }
      }
    })
  }

  // 从IndexedDB加载数据分页
  const loadExcelDataPage = async (fileId, page = 1, pageSize = 10) => {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open('VueDownloaderDB', 1)
      
      request.onerror = () => reject(request.error)
      request.onsuccess = () => {
        const db = request.result
        const transaction = db.transaction(['excelData'], 'readonly')
        const store = transaction.objectStore('excelData')
        const index = store.index('fileId')
        
        const getAllRequest = index.getAll(fileId)
        getAllRequest.onsuccess = () => {
          const chunks = getAllRequest.result
          // 按chunkIndex排序
          chunks.sort((a, b) => a.chunkIndex - b.chunkIndex)
          
          // 合并所有数据
          const allData = chunks.reduce((acc, chunk) => acc.concat(chunk.data), [])
          
          // 计算分页
          const start = (page - 1) * pageSize
          const end = start + pageSize
          const pageData = allData.slice(start, end)
          
          resolve({
            data: pageData,
            total: allData.length,
            page: page,
            pageSize: pageSize,
            totalPages: Math.ceil(allData.length / pageSize)
          })
        }
        getAllRequest.onerror = () => reject(getAllRequest.error)
      }
    })
  }

  // 删除Excel文件
  const deleteExcelFile = async (fileId) => {
    try {
      // 从IndexedDB删除数据
      await deleteDataFromIndexedDB(fileId)
      
      // 从文件列表中删除
      excelFiles.value = excelFiles.value.filter(file => file.id !== fileId)
      saveToStorage()
      
      // 删除相关的下载任务
      downloads.value = downloads.value.filter(download => download.excelFileId !== fileId)
      saveToStorage()
    } catch (error) {
      console.error('删除Excel文件失败:', error)
      throw error
    }
  }

  // 从IndexedDB删除数据
  const deleteDataFromIndexedDB = async (fileId) => {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open('VueDownloaderDB', 1)
      
      request.onerror = () => reject(request.error)
      request.onsuccess = () => {
        const db = request.result
        const transaction = db.transaction(['excelData'], 'readwrite')
        const store = transaction.objectStore('excelData')
        const index = store.index('fileId')
        
        // 先获取所有匹配的键
        const getAllKeysRequest = index.getAllKeys(fileId)
        getAllKeysRequest.onsuccess = () => {
          const keys = getAllKeysRequest.result
          if (keys.length === 0) {
            resolve() // 没有数据需要删除
            return
          }
          
          // 删除所有匹配的记录
          let completed = 0
          keys.forEach(key => {
            const deleteRequest = store.delete(key)
            deleteRequest.onsuccess = () => {
              completed++
              if (completed === keys.length) {
                resolve()
              }
            }
            deleteRequest.onerror = () => reject(deleteRequest.error)
          })
        }
        getAllKeysRequest.onerror = () => reject(getAllKeysRequest.error)
      }
    })
  }

  // 获取Excel文件信息
  const getExcelFileInfo = (fileId) => {
    return excelFiles.value.find(file => file.id === fileId)
  }

  // 获取所有Excel文件
  const getAllExcelFiles = () => {
    return excelFiles.value
  }

  // 设置当前Excel文件
  const setCurrentExcelFile = (fileId) => {
    currentExcelFile.value = fileId
  }

  // 获取当前Excel文件
  const getCurrentExcelFile = () => {
    return currentExcelFile.value
  }

  return {
    downloads,
    downloadPath,
    customSubFolder,
    maxConcurrentDownloads,
    activeDownloadCount,
    enableNotifications,
    isBatchDownloading,
    isSingleDownloading,
    pendingDownloads,
    activeDownloads,
    completedDownloads,
    failedDownloads,
    allDownloadsCompleted,
    addDownload,
    startDownload,
    pauseDownload,
    resumeDownload,
    cancelDownload,
    batchStartDownloads,
    batchPauseDownloads,
    batchDeleteDownloads,
    setDownloadPath,
    setCustomSubFolder,
    setMaxConcurrentDownloads,
    setEnableNotifications,
    clearCompleted,
    clearAll,
    retryFailedDownloads,
    getOperatingSystem,
    getDefaultDownloadPath,
    initialize,
    excelFiles,
    currentExcelFile,
    saveExcelFileToLocal,
    loadExcelDataPage,
    deleteExcelFile,
    getExcelFileInfo,
    getAllExcelFiles,
    setCurrentExcelFile,
    getCurrentExcelFile
  }
})
