import { post } from '@vue2-client/services/api'

// 内存缓存作为IndexedDB的备用方案，防止数据库损坏时应用崩溃
const MEMORY_CACHE = new Map()
const USE_MEMORY_CACHE = true // 是否启用内存缓存

const DB_CONFIG = {
  NAME: window.__MICRO_APP_NAME__ ? `view_${window.__MICRO_APP_NAME__}` : 'view',
  STORE_NAME: 'metaCache',
  VERSION: 1,
  CURRENT_VERSION: 1
}

// 数据库健康状态标记，用于在数据库异常时切换到备用方案
let IS_DB_HEALTHY = true

const LIULI_WEB_DB_NAME = 'view_liuli_web'

export class IndexedDBManager {
  constructor () {
    this.db = undefined
    this.locks = new Map()
    this.requestTimeout = 10000
    this.isInMicroApp = !!window.__MICRO_APP_NAME__
    this.microAppName = window.__MICRO_APP_NAME__ || ''
    this.indexedDB = window?.rawWindow?.indexedDB || window.indexedDB || window.webkitindexedDB
    this.IDBKeyRange = window?.rawWindow?.IDBKeyRange || window.IDBKeyRange || window.webkitIDBKeyRange
  }

  async openDatabase () {
    try {
      return await new Promise((resolve, reject) => {
        // 添加超时机制，防止请求永久挂起
        const timeout = setTimeout(() => {
          console.error('[openDatabase] 请求超时，将尝试重建数据库')
          reject(new Error('IndexedDB open timeout'))
        }, 5000) // 5秒超时

        const checkRequest = this.indexedDB.open(DB_CONFIG.NAME)

        checkRequest.onsuccess = (e) => {
          clearTimeout(timeout) // 清除超时
          const db = e.target.result
          const currentVersion = db.version
          db.close()

          DB_CONFIG.CURRENT_VERSION = Math.max(currentVersion, DB_CONFIG.VERSION)
          const request = this.indexedDB.open(DB_CONFIG.NAME, DB_CONFIG.CURRENT_VERSION)

          // 为第二次打开也添加超时
          const openTimeout = setTimeout(() => {
            console.error('[openDatabase] 二次打开请求超时')
            reject(new Error('IndexedDB second open timeout'))
          }, 5000)

          request.onerror = (e) => {
            clearTimeout(openTimeout)
            reject(e.currentTarget.error)
          }

          request.onsuccess = (e) => {
            clearTimeout(openTimeout)
            const db = e.target.result
            if (!db.objectStoreNames.contains(DB_CONFIG.STORE_NAME)) {
              db.close()
              DB_CONFIG.CURRENT_VERSION++
              this.upgradeDatabase(resolve, reject)
            } else {
              resolve(db)
            }
          }

          request.onupgradeneeded = (e) => {
            clearTimeout(openTimeout)
            const db = e.target.result
            if (!db.objectStoreNames.contains(DB_CONFIG.STORE_NAME)) {
              db.createObjectStore(DB_CONFIG.STORE_NAME, { keyPath: 'key' })
            }
          }
        }

        checkRequest.onerror = (e) => {
          clearTimeout(timeout)
          reject(e.currentTarget.error)
        }
      })
    } catch (error) {
      console.error('[openDatabase] 打开数据库失败:', error)

      // 如果是超时错误或版本错误，尝试自动重建数据库
      if (error.message?.includes('timeout') || error.message?.includes('version')) {
        await this.forceRecreateDatabase()
        return this.openDatabase() // 递归调用，重新尝试打开
      }

      throw error
    }
  }

  async upgradeDatabase (resolve, reject) {
    console.warn('[upgradeDatabase] 升级数据库到版本:', DB_CONFIG.CURRENT_VERSION)
    const request = this.indexedDB.open(DB_CONFIG.NAME, DB_CONFIG.CURRENT_VERSION)

    request.onupgradeneeded = (e) => {
      const db = e.target.result
      if (!db.objectStoreNames.contains(DB_CONFIG.STORE_NAME)) {
        db.createObjectStore(DB_CONFIG.STORE_NAME, { keyPath: 'key' })
      }
    }

    request.onsuccess = (e) => {
      resolve(e.target.result)
    }
    request.onerror = (e) => {
      reject(e.currentTarget.error)
    }
  }

  async openDB (callback) {
    // 如果数据库不健康，直接调用回调并返回
    if (!IS_DB_HEALTHY) {
      console.warn('[openDB] 数据库不健康，跳过数据库操作')
      setTimeout(() => {
        try {
          callback(null)
        } catch (e) {
          console.error('[openDB] 回调执行错误:', e)
        }
      }, 0)
      return
    }

    try {
      if (this.db) {
        const isAlive = await this.checkConnection()
        if (isAlive) {
          callback(this.db)
          return
        }
      }

      // 添加超时机制，防止卡死
      const openDbPromise = this.openDatabase()
      const timeoutPromise = new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('openDB timeout')), 5000)
      })

      try {
        this.db = await Promise.race([openDbPromise, timeoutPromise])
        callback(this.db)
      } catch (error) {
        console.error('[openDB] 打开数据库连接超时或失败', error)
        // 标记数据库为不健康状态，后续操作使用备用方案
        IS_DB_HEALTHY = false
        try {
          callback(null)
        } catch (callbackError) {
          console.error('[openDB] 回调执行错误:', callbackError)
        }
      }
    } catch (error) {
      console.error('[openDB] 数据库操作失败:', error)

      // 版本错误时尝试重建数据库
      if (error.message?.includes('version')) {
        try {
          await this.recreateDatabase()
          callback(this.db)
        } catch (rebuildError) {
          console.error('[openDB] 重建失败，标记数据库为不健康状态', rebuildError)
          IS_DB_HEALTHY = false
          try {
            callback(null)
          } catch (callbackError) {
            console.error('[openDB] 回调执行错误:', callbackError)
          }
        }
      } else {
        // 其他错误，标记为不健康并使用备用方案
        IS_DB_HEALTHY = false
        console.error('[openDB] 不可恢复的错误，标记数据库为不健康状态')
        try {
          callback(null)
        } catch (callbackError) {
          console.error('[openDB] 回调执行错误:', callbackError)
        }
      }
    }
  }

  async checkConnection () {
    try {
      const transaction = this.db.transaction([DB_CONFIG.STORE_NAME], 'readwrite')
      const store = transaction.objectStore(DB_CONFIG.STORE_NAME)
      await this.promisifyRequest(store.add({ key: 'alive', data: true }))
      return true
    } catch (error) {
      return false
    }
  }

  promisifyRequest (request) {
    return new Promise((resolve, reject) => {
      request.onsuccess = () => {
        resolve(request.result)
      }
      request.onerror = () => {
        reject(request.error)
      }
    })
  }

  async getByWeb (key, url, params, callback, processFun) {
    // 数据库不健康时使用备用方案
    if (!IS_DB_HEALTHY) {
      console.warn(`[getByWeb] 数据库不健康，使用内存缓存或直接API调用`)
      return this.getByWebWithoutDB(key, url, params, callback, processFun)
    }

    // 锁机制：防止同一键的并发请求
    if (this.locks.has(key)) {
      const timeoutPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error(`请求超时: ${key}`))
        }, this.requestTimeout)
      })

      try {
        await Promise.race([this.locks.get(key), timeoutPromise])
        return this.getByWeb(key, url, params, callback, processFun)
      } catch (error) {
        console.error(`[getByWeb] 等待锁期间出错或超时: ${error.message}`)
        this.locks.delete(key)
      }
    }

    const lockPromise = (async () => {
      try {
        // 首先检查内存缓存
        if (USE_MEMORY_CACHE && MEMORY_CACHE.has(key)) {
          const cachedData = MEMORY_CACHE.get(key)
          callback(cachedData)
          return
        }

        // 再检查IndexedDB缓存
        const data = DB_CONFIG.NAME === LIULI_WEB_DB_NAME ? undefined : await this.getData(key)

        if (data && data.ERROR) {
          console.error(`获取配置失败：` + data.ERROR)
        }

        if (!data && url) {
          // 缓存未命中，请求网络数据
          // 获取当前 Logic 的 abortSignal，支持 cancel 模式（使用动态导入避免循环依赖）
          let abortSignal = null
          try {
            const LogicRunner = (await import('../logic/LogicRunner')).default
            abortSignal = LogicRunner.getCurrentAbortSignal()
          } catch (e) {
            console.log('[indexedDB.getByWeb] 获取 abortSignal 失败:', e.message)
          }

          let res
          try {
            res = await post(url, params, { signal: abortSignal })
          } catch (e) {
            // 重新抛出 AbortError，让上层可以正确处理取消逻辑
            // 而不是把错误当作正常结果返回
            // axios 取消请求时会抛出 CanceledError 或 AbortError
            const errorName = e.name || ''
            const errorCode = e.code || ''
            if (errorName === 'CanceledError' || errorName === 'AbortError' || errorCode === 'ERR_CANCELED') {
              console.log('[indexedDB.getByWeb] 请求被取消，抛出错误')
              throw e
            }
            res = {
              ERROR: e
            }
          }
          const processedData = processFun ? processFun(res) : res

          // 同时保存到内存缓存
          if (USE_MEMORY_CACHE) {
            MEMORY_CACHE.set(key, processedData)
          }

          // 生产环境或非移动配置时保存到IndexedDB
          if (process.env.NODE_ENV === 'production' || key !== 'webMobileConfig') {
            await this.add(key, processedData)
          }

          callback(processedData)
        } else {
          // 使用缓存数据
          if (USE_MEMORY_CACHE && data) {
            MEMORY_CACHE.set(key, data)
          }
          callback(data)
        }
      } catch (error) {
        console.error(`[getByWeb] 获取数据失败`, error)

        // IndexedDB操作失败时切换到备用方案
        if (error.name === 'InvalidStateError' || error.message?.includes('database') || error.message?.includes('transaction')) {
          console.error(`[getByWeb] 数据库操作失败，标记为不健康`)
          IS_DB_HEALTHY = false

          // 使用备用方案获取数据
          return this.getByWebWithoutDB(key, url, params, callback, processFun)
        }

        if (process.env.NODE_ENV === 'production' && key !== 'webMobileConfig') {
          await this.add(key, null)
        }
        callback(null)
      }
    })()

    this.locks.set(key, lockPromise)

    try {
      const timeoutPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error(`操作超时: ${key}`))
        }, this.requestTimeout)
      })

      await Promise.race([this.locks.get(key), timeoutPromise])
    } catch (error) {
      console.error(`[getByWeb] 执行期间出错或超时: ${error.message}`)
    } finally {
      this.locks.delete(key)
    }
  }

  // 备用方法：不使用IndexedDB，直接使用内存缓存和API
  async getByWebWithoutDB (key, url, params, callback, processFun) {
    // 首先检查内存缓存
    if (USE_MEMORY_CACHE && MEMORY_CACHE.has(key)) {
      const cachedData = MEMORY_CACHE.get(key)
      callback(cachedData)
      return
    }

    // 无URL则无法获取数据
    if (!url) {
      callback(null)
      return
    }

    // 获取当前 Logic 的 abortSignal，支持 cancel 模式（使用动态导入避免循环依赖）
    let abortSignal = null
    try {
      const LogicRunner = (await import('../logic/LogicRunner')).default
      abortSignal = LogicRunner.getCurrentAbortSignal()
    } catch (e) {
      // 如果导入失败，使用 null
    }

    // 直接通过API获取数据
    try {
      const res = await post(url, params, { signal: abortSignal })
      const processedData = processFun ? processFun(res) : res

      // 保存到内存缓存
      if (USE_MEMORY_CACHE) {
        MEMORY_CACHE.set(key, processedData)
      }

      callback(processedData)
    } catch (error) {
      // 重新抛出 AbortError，让上层可以正确处理取消逻辑
      const errorName = error.name || ''
      const errorCode = error.code || ''
      if (errorName === 'CanceledError' || errorName === 'AbortError' || errorCode === 'ERR_CANCELED') {
        console.log('[getByWebWithoutDB] 请求被取消，抛出错误')
        throw error
      }
      console.error(`[getByWebWithoutDB] 获取数据失败: ${error.message}`)
      callback(null)
    }
  }

  async getData (key) {
    return new Promise((resolve) => {
      this.openDB((db) => {
        if (!db) {
          resolve(null)
          return
        }
        const store = db.transaction(DB_CONFIG.STORE_NAME, 'readwrite').objectStore(DB_CONFIG.STORE_NAME)
        const request = store.get(key)

        request.onsuccess = (e) => {
          resolve(e.target.result?.data)
        }

        request.onerror = () => {
          resolve(null)
        }
      })
    })
  }

  async add (key, data) {
    this.openDB((db) => {
      if (!db) return

      const store = db.transaction(DB_CONFIG.STORE_NAME, 'readwrite').objectStore(DB_CONFIG.STORE_NAME)
      const request = store.add({ key, data })

      request.onerror = () => {
        // 添加失败时尝试更新
        this.update(key, data)
      }
    })
  }

  async update (key, data) {
    this.openDB((db) => {
      if (!db) return

      const store = db.transaction(DB_CONFIG.STORE_NAME, 'readwrite').objectStore(DB_CONFIG.STORE_NAME)
      store.put({ key, data })
    })
  }

  async delete (key) {
    this.openDB((db) => {
      if (!db) return

      const store = db.transaction(DB_CONFIG.STORE_NAME, 'readwrite').objectStore(DB_CONFIG.STORE_NAME)
      store.delete(key)
    })
  }

  async clear (callback) {
    this.openDB((db) => {
      if (!db) {
        if (typeof callback === 'function') callback()
        return
      }

      const store = db.transaction(DB_CONFIG.STORE_NAME, 'readwrite').objectStore(DB_CONFIG.STORE_NAME)
      const request = store.clear()

      request.onerror = () => {
        if (typeof callback === 'function') callback()
      }

      request.onsuccess = () => {
        if (typeof callback === 'function') callback()
      }
    })
  }

  clearCache () {
    // 清除缓存并刷新页面
    if (this.indexedDB) {
      this.clear(() => {
        location.reload()
      })
    } else {
      location.reload()
    }
  }

  async getAll () {
    return new Promise((resolve, reject) => {
      this.openDB((db) => {
        if (!db) {
          resolve([])
          return
        }

        const store = db.transaction(DB_CONFIG.STORE_NAME, 'readonly').objectStore(DB_CONFIG.STORE_NAME)
        const request = store.getAll()

        request.onsuccess = (e) => {
          resolve(e.target.result)
        }

        request.onerror = (e) => {
          reject(e.target.error)
        }
      })
    })
  }

  getAllLegacy (callback) {
    this.openDB((res) => {
      if (!res) {
        callback(null, new Error('打开数据库失败'))
        return
      }

      const store = res.transaction(DB_CONFIG.STORE_NAME, 'readonly').objectStore(DB_CONFIG.STORE_NAME)
      const request = store.getAll()

      request.onerror = (e) => {
        callback(null, e.target.error)
      }

      request.onsuccess = (e) => {
        callback(e.target.result)
      }
    })
  }

  async recreateDatabase () {
    try {
      if (this.db) {
        this.db.close()
        this.db = undefined
      }

      await new Promise((resolve, reject) => {
        const deleteRequest = this.indexedDB.deleteDatabase(DB_CONFIG.NAME)

        deleteRequest.onsuccess = () => {
          resolve()
        }

        deleteRequest.onerror = (e) => {
          reject(e.target.error)
        }
      })

      DB_CONFIG.CURRENT_VERSION = DB_CONFIG.VERSION
      this.db = await this.openDatabase()
      return this.db
    } catch (error) {
      console.error('重新创建数据库失败:', error)
      throw error
    }
  }

  // 强制重建数据库的方法，带有超时保护
  async forceRecreateDatabase () {
    console.warn('[forceRecreateDatabase] 开始强制重建数据库')
    try {
      // 确保关闭所有连接
      if (this.db) {
        try {
          this.db.close()
        } catch (e) {
          console.warn('[forceRecreateDatabase] 关闭现有连接出错')
        }
        this.db = undefined
      }

      // 清空锁防止死锁
      this.locks.clear()

      // 强制删除数据库，带超时保护
      await new Promise((resolve) => {
        const deleteRequest = this.indexedDB.deleteDatabase(DB_CONFIG.NAME)

        const timeout = setTimeout(() => {
          resolve() // 即使超时也继续执行
        }, 3000)

        deleteRequest.onsuccess = () => {
          clearTimeout(timeout)
          resolve()
        }

        deleteRequest.onerror = () => {
          clearTimeout(timeout)
          resolve() // 即使出错也继续执行
        }
      })

      // 重置版本
      DB_CONFIG.CURRENT_VERSION = DB_CONFIG.VERSION
    } catch (error) {
      console.error('[forceRecreateDatabase] 强制重建过程中出错:', error)
    }
  }
}

export const indexedDB = new IndexedDBManager()
