// import MemoryStorage from './storage/MemoryStorage.js';
import LocalStorage from './storage/LocalStorage.js'
// import SessionStorage from './storage/SessionStorage.js';
import IndexedDBStorage from './storage/IndexedDBStorage.js'
import ServerStorage from './storage/ServerStorage.js'

/**
 * 自动保存管理器
 * 协调各种存储方式，处理冲突合并
 */
class AutoSaveManager {
  constructor(
    key,
    serverOptions = {
      endpoint: process.env.VUE_APP_BASE_API,
      syncEndpoint: process.env.VUE_APP_BASE_API,
      historyEndpoint: process.env.VUE_APP_BASE_API
    }
  ) {
    this.key = key

    try {
      this.storages = {
        // memory: new MemoryStorage(key),
        localStorage: new LocalStorage(key),
        // sessionStorage: new SessionStorage(key),
        // indexedDB: new IndexedDBStorage(key),
        server: new ServerStorage(key, serverOptions)
      }
    } catch (error) {
      console.error('初始化存储失败:', error)
      // 如果某个存储初始化失败，只使用可用的存储
      this.storages = {
        // memory: new MemoryStorage(key),
        localStorage: new LocalStorage(key)
        // sessionStorage: new SessionStorage(key)
      }
    }

    this.states = {}
    this.initStates()

    this.isSaving = false
    this.saveTimer = null
    this.debounceDelay = 1000 // 防抖延迟
    this.currentContent = ''
    this.lastSavedContent = ''

    // 异步初始化
    this.initPromise = this.init()
  }

  /**
   * 初始化状态对象
   */
  initStates() {
    for (const type in this.storages) {
      this.states[type] = {
        status: 'idle',
        lastSaved: null,
        error: null,
        initialized: false
      }
    }
  }

  /**
   * 等待初始化完成
   */
  async waitForInit() {
    await this.initPromise
  }

  /**
   * 初始化管理器
   */
  async init() {
    try {
      // 加载所有存储的数据
      await this.loadFromAllStorages()

      // 设置页面关闭前保存
      this.setupBeforeUnload()

      // 设置页面崩溃检测
      this.setupCrashDetection()

      console.log(`AutoSaveManager 初始化完成，key: ${this.key}`)
    } catch (error) {
      console.error('AutoSaveManager 初始化失败:', error)
    }
  }

  /**
   * 从所有存储加载数据并合并
   */
  async loadFromAllStorages() {
    const results = {}

    // 并行加载所有存储
    const promises = Object.entries(this.storages).map(
      async ([type, storage]) => {
        try {
          // 确保存储已初始化
          if (storage.waitForInit) {
            await storage.waitForInit()
          }

          const result = await storage.load()
          results[type] = result
          this.updateState(type, 'loaded', {
            ...result,
            initialized: true
          })

          return result
        } catch (error) {
          console.error(`加载${type}存储失败:`, error)
          this.updateState(type, 'error', {
            error: error.message,
            initialized: false
          })
          return null
        }
      }
    )

    await Promise.allSettled(promises)

    // 选择最新版本的内容
    // this.currentContent = this.resolveConflicts(results);
    this.lastSavedContent = this.currentContent

    return this.currentContent
  }

  /**
   * 解决冲突：选择最新版本的内容
   * @param {object} results - 所有存储的加载结果
   * @returns {string} 合并后的内容
   */
  resolveConflicts(results) {
    let latestContent = ''
    let latestTimestamp = 0

    Object.entries(results).forEach(([type, result]) => {
      if (result && result.success && result.data) {
        let data = result.data
        let timestamp = 0
        let content = ''

        if (typeof data === 'object' && data !== null) {
          timestamp = data.timestamp || data.lastModified || 0
          content = data.content || ''
        } else if (typeof data === 'string') {
          content = data
          timestamp = Date.now() // 字符串数据给一个默认时间戳
        }

        if (timestamp > latestTimestamp) {
          latestTimestamp = timestamp
          latestContent = content
        }
      }
    })

    return latestContent || ''
  }

  /**
   * 保存内容（防抖处理）
   * @param {string} content - 要保存的内容
   */
  save(content) {
    this.currentContent = content

    // 如果内容没有变化，不保存
    if (content === this.lastSavedContent) {
      return
    }

    // 清除之前的定时器
    if (this.saveTimer) {
      clearTimeout(this.saveTimer)
    }

    // 设置新的定时器
    this.saveTimer = setTimeout(() => {
      this.doSave(content)
    }, this.debounceDelay)
  }

  /**
   * 执行保存操作
   * @param {string} content - 要保存的内容
   */
  async doSave(content) {
    if (this.isSaving) {
      return
    }

    this.isSaving = true
    this.lastSavedContent = content

    try {
      // 并行保存到所有存储
      const promises = Object.entries(this.storages).map(
        async ([type, storage]) => {
          try {
            // 检查存储是否可用
            if (!storage || this.states[type]?.error) {
              this.updateState(type, 'error', {
                error: '存储不可用',
                retry: true
              })
              return null
            }

            this.updateState(type, 'saving')
            const result = await storage.save(content)

            if (result && result.success) {
              this.updateState(type, 'saved', result)
            } else {
              this.updateState(type, 'error', {
                error: result?.error || '保存失败',
                retry: true
              })
            }

            return result
          } catch (error) {
            console.error(`保存到${type}失败:`, error)
            this.updateState(type, 'error', {
              error: error.message,
              retry: true
            })
            return null
          }
        }
      )

      await Promise.allSettled(promises)
    } finally {
      this.isSaving = false
    }
  }

  /**
   * 更新存储状态
   * @param {string} type - 存储类型
   * @param {string} status - 状态
   * @param {object} data - 相关数据
   */
  updateState(type, status, data = {}) {
    this.states[type] = {
      ...this.states[type],
      status,
      ...data,
      lastUpdated: Date.now()
    }

    if (status === 'saved' && data.timestamp) {
      this.states[type].lastSaved = data.timestamp
    }
  }

  /**
   * 获取所有存储状态
   * @returns {object} 状态对象
   */
  getAllStates() {
    return { ...this.states }
  }

  /**
   * 获取指定存储的历史版本
   * @param {string} storageType - 存储类型
   * @returns {Promise<Array>} 历史版本列表
   */
  async getHistory(storageType) {
    if (this.storages[storageType]) {
      return await this.storages[storageType].getHistory()
    }
    return { success: false, error: '存储类型不存在' }
  }

  /**
   * 从历史版本恢复
   * @param {string} storageType - 存储类型
   * @param {object} versionData - 版本数据
   */
  async restoreFromHistory(storageType, versionData) {
    if (this.storages[storageType]) {
      const content = versionData.content || versionData
      await this.doSave(content)
      this.currentContent = content
      return { success: true, content }
    }
    return { success: false, error: '存储类型不存在' }
  }

  /**
   * 设置页面关闭前保存
   */
  setupBeforeUnload() {
    window.addEventListener('beforeunload', (event) => {
      if (this.currentContent !== this.lastSavedContent) {
        // 同步保存（不防抖）
        this.doSaveSync(this.currentContent)
      }
    })
  }

  /**
   * 同步保存（用于页面关闭前）
   * @param {string} content - 要保存的内容
   */
  async doSaveSync(content) {
    // 只保存到本地存储，确保数据不丢失
    const localStorages = ['memory', 'localStorage', 'sessionStorage']

    localStorages.forEach(async (type) => {
      try {
        await this.storages[type].save(content)
      } catch (error) {
        console.error(`页面关闭前保存到${type}失败:`, error)
      }
    })
  }

  /**
   * 设置页面崩溃检测
   */
  setupCrashDetection() {
    // 使用 Page Visibility API 检测页面状态
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') {
        // 页面恢复显示，检查是否需要同步
        this.checkAndSync()
      }
    })

    // 监听页面冻结和恢复
    document.addEventListener('freeze', () => {
      localStorage.setItem(`pageFrozen_${this.key}`, Date.now())
    })

    document.addEventListener('resume', () => {
      const frozenTime = localStorage.getItem(`pageFrozen_${this.key}`)
      if (frozenTime && Date.now() - frozenTime > 5000) {
        // 页面被冻结超过5秒，可能是崩溃恢复
        this.showCrashNotification()
      }
      localStorage.removeItem(`pageFrozen_${this.key}`)
    })
  }

  /**
   * 检查并同步数据
   */
  async checkAndSync() {
    // 重新加载所有数据并合并
    await this.loadFromAllStorages()

    // 如果有服务器存储，尝试同步离线队列
    if (this.storages.server) {
      this.storages.server.processQueue()
    }
  }

  /**
   * 显示崩溃通知
   */
  showCrashNotification() {
    const notification = document.createElement('div')
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: #ff4444;
      color: white;
      padding: 15px;
      border-radius: 5px;
      z-index: 10000;
      box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    `
    notification.innerHTML = `
      <strong>页面恢复</strong><br>
      检测到页面可能发生了异常，已自动恢复您的数据。
    `
    document.body.appendChild(notification)

    setTimeout(() => {
      notification.remove()
    }, 5000)
  }

  /**
   * 获取备份文件列表
   * @returns {Promise<Array>} 备份文件列表
   */
  async getBackupFiles() {
    const backupPromises = Object.entries(this.storages).map(
      async ([type, storage]) => {
        if (typeof storage.getBackupFiles === 'function') {
          try {
            const result = await storage.getBackupFiles()
            return { type, ...result }
          } catch (error) {
            return { type, success: false, error: error.message }
          }
        }
        return { type, success: false, error: '不支持备份管理' }
      }
    )

    const results = await Promise.all(backupPromises)
    return results
  }

  /**
   * 立即保存当前内容
   */
  async saveImmediately(currentContent) {
    if (this.saveTimer) {
      clearTimeout(this.saveTimer)
    }
    await this.doSave(currentContent)
  }
}

export default AutoSaveManager
