/**
 * 插件系统
 * 统一管理和注册所有插件
 */

import { createLogger } from '@/common/utils/logger.js'

const logger = createLogger('Plugins')

// 插件注册表
const plugins = new Map()

/**
 * 插件基类
 */
export class Plugin {
  constructor(name, options = {}) {
    this.name = name
    this.options = options
    this.installed = false
  }

  /**
   * 安装插件
   * @param {Object} app - 应用实例
   */
  install(app) {
    if (this.installed) {
      logger.warn(`Plugin ${this.name} already installed`)
      return
    }

    try {
      this._install(app)
      this.installed = true
      logger.info(`Plugin ${this.name} installed successfully`)
    } catch (error) {
      logger.error(`Failed to install plugin ${this.name}`, null, error)
      throw error
    }
  }

  /**
   * 卸载插件
   * @param {Object} app - 应用实例
   */
  uninstall(app) {
    if (!this.installed) {
      logger.warn(`Plugin ${this.name} not installed`)
      return
    }

    try {
      this._uninstall(app)
      this.installed = false
      logger.info(`Plugin ${this.name} uninstalled successfully`)
    } catch (error) {
      logger.error(`Failed to uninstall plugin ${this.name}`, null, error)
      throw error
    }
  }

  /**
   * 插件安装逻辑（子类实现）
   * @protected
   */
  _install(app) {
    throw new Error(`Plugin ${this.name} must implement _install method`)
  }

  /**
   * 插件卸载逻辑（子类实现）
   * @protected
   */
  _uninstall(app) {
    // 默认空实现
  }
}

/**
 * 请求拦截器插件
 */
export class RequestInterceptorPlugin extends Plugin {
  constructor(options = {}) {
    super('RequestInterceptor', options)
  }

  _install(app) {
    const { request, response, error } = this.options

    // 请求拦截器
    if (request) {
      uni.addInterceptor('request', {
        invoke: (args) => {
          logger.debug('Request interceptor invoke', args)
          return request(args) || args
        },
        success: (res) => {
          logger.debug('Request interceptor success', res)
          return res
        },
        fail: (err) => {
          logger.error('Request interceptor fail', null, err)
          if (error) {
            error(err)
          }
          return err
        }
      })
    }

    // 响应拦截器
    if (response) {
      uni.addInterceptor('request', {
        returnValue: (res) => {
          logger.debug('Response interceptor', res)
          return response(res) || res
        }
      })
    }
  }

  _uninstall(app) {
    uni.removeInterceptor('request')
  }
}

/**
 * 路由拦截器插件
 */
export class RouteInterceptorPlugin extends Plugin {
  constructor(options = {}) {
    super('RouteInterceptor', options)
  }

  _install(app) {
    const { beforeEach, afterEach } = this.options

    // 页面跳转拦截
    const routeMethods = ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch', 'navigateBack']

    routeMethods.forEach(method => {
      uni.addInterceptor(method, {
        invoke: (args) => {
          logger.debug(`Route interceptor ${method} invoke`, args)
          
          if (beforeEach) {
            const result = beforeEach(args, method)
            if (result === false) {
              return false
            }
            if (result && typeof result === 'object') {
              return result
            }
          }
          
          return args
        },
        success: (res) => {
          logger.debug(`Route interceptor ${method} success`, res)
          
          if (afterEach) {
            afterEach(res, method)
          }
          
          return res
        },
        fail: (err) => {
          logger.error(`Route interceptor ${method} fail`, null, err)
          return err
        }
      })
    })
  }

  _uninstall(app) {
    const routeMethods = ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch', 'navigateBack']
    routeMethods.forEach(method => {
      uni.removeInterceptor(method)
    })
  }
}

/**
 * 全局错误处理插件
 */
export class ErrorHandlerPlugin extends Plugin {
  constructor(options = {}) {
    super('ErrorHandler', options)
  }

  _install(app) {
    const { onError, onUnhandledRejection } = this.options

    // 全局错误处理
    if (onError) {
      uni.onError((error) => {
        logger.error('Global error', null, new Error(error))
        onError(error)
      })
    }

    // 未处理的 Promise 拒绝
    if (onUnhandledRejection) {
      uni.onUnhandledRejection((event) => {
        logger.error('Unhandled promise rejection', { reason: event.reason })
        onUnhandledRejection(event)
      })
    }

    // 页面错误处理
    const originalOnError = app.config.errorHandler
    app.config.errorHandler = (error, instance, info) => {
      logger.error('Vue error', { info }, error)
      
      if (onError) {
        onError(error, instance, info)
      }
      
      if (originalOnError) {
        originalOnError(error, instance, info)
      }
    }
  }
}

/**
 * 性能监控插件
 */
export class PerformancePlugin extends Plugin {
  constructor(options = {}) {
    super('Performance', options)
  }

  _install(app) {
    const { enabled = true, sampleRate = 0.1 } = this.options

    if (!enabled || Math.random() > sampleRate) {
      return
    }

    // 页面性能监控
    const pageStartTimes = new Map()

    // 监控页面加载时间
    uni.addInterceptor('navigateTo', {
      invoke: (args) => {
        pageStartTimes.set(args.url, Date.now())
        return args
      }
    })

    // 监控页面渲染完成时间
    const originalOnReady = app.config.globalProperties.$mp?.onReady
    if (originalOnReady) {
      app.config.globalProperties.$mp.onReady = function() {
        const currentPage = getCurrentPages().pop()
        const startTime = pageStartTimes.get(currentPage?.route)
        
        if (startTime) {
          const loadTime = Date.now() - startTime
          logger.performance('Page Load', loadTime, {
            page: currentPage?.route
          })
          pageStartTimes.delete(currentPage?.route)
        }
        
        return originalOnReady.call(this)
      }
    }

    // 监控 API 请求性能
    uni.addInterceptor('request', {
      invoke: (args) => {
        args._startTime = Date.now()
        return args
      },
      success: (res) => {
        if (res.config && res.config._startTime) {
          const duration = Date.now() - res.config._startTime
          logger.performance('API Request', duration, {
            url: res.config.url,
            method: res.config.method,
            status: res.statusCode
          })
        }
        return res
      }
    })
  }
}

/**
 * 缓存插件
 */
export class CachePlugin extends Plugin {
  constructor(options = {}) {
    super('Cache', options)
  }

  _install(app) {
    const { 
      defaultExpire = 24 * 60 * 60 * 1000, // 24小时
      maxSize = 50 * 1024 * 1024, // 50MB
      cleanupInterval = 60 * 60 * 1000 // 1小时
    } = this.options

    const cache = new Map()
    let currentSize = 0

    // 缓存管理器
    const cacheManager = {
      set(key, value, expire = defaultExpire) {
        const item = {
          value,
          expire: Date.now() + expire,
          size: JSON.stringify(value).length
        }

        // 检查缓存大小
        if (currentSize + item.size > maxSize) {
          this.cleanup()
        }

        // 如果还是超出大小限制，删除最旧的项
        while (currentSize + item.size > maxSize && cache.size > 0) {
          const oldestKey = cache.keys().next().value
          this.delete(oldestKey)
        }

        cache.set(key, item)
        currentSize += item.size

        logger.debug('Cache set', { key, size: item.size, expire })
      },

      get(key) {
        const item = cache.get(key)
        
        if (!item) {
          return null
        }

        if (Date.now() > item.expire) {
          this.delete(key)
          return null
        }

        logger.debug('Cache hit', { key })
        return item.value
      },

      delete(key) {
        const item = cache.get(key)
        if (item) {
          cache.delete(key)
          currentSize -= item.size
          logger.debug('Cache delete', { key, size: item.size })
        }
      },

      clear() {
        cache.clear()
        currentSize = 0
        logger.debug('Cache cleared')
      },

      cleanup() {
        const now = Date.now()
        const keysToDelete = []

        for (const [key, item] of cache) {
          if (now > item.expire) {
            keysToDelete.push(key)
          }
        }

        keysToDelete.forEach(key => this.delete(key))
        logger.debug('Cache cleanup', { deleted: keysToDelete.length })
      },

      size() {
        return cache.size
      },

      memoryUsage() {
        return currentSize
      }
    }

    // 定期清理过期缓存
    setInterval(() => {
      cacheManager.cleanup()
    }, cleanupInterval)

    // 将缓存管理器添加到全局
    app.config.globalProperties.$cache = cacheManager
    
    // 也可以通过 uni 访问
    uni.$cache = cacheManager
  }
}

/**
 * 插件管理器
 */
export class PluginManager {
  constructor() {
    this.plugins = new Map()
    this.app = null
  }

  /**
   * 注册插件
   * @param {Plugin} plugin - 插件实例
   */
  register(plugin) {
    if (!(plugin instanceof Plugin)) {
      throw new Error('Plugin must be an instance of Plugin class')
    }

    if (this.plugins.has(plugin.name)) {
      logger.warn(`Plugin ${plugin.name} already registered`)
      return
    }

    this.plugins.set(plugin.name, plugin)
    logger.info(`Plugin ${plugin.name} registered`)

    // 如果应用已经初始化，立即安装插件
    if (this.app) {
      plugin.install(this.app)
    }
  }

  /**
   * 卸载插件
   * @param {string} name - 插件名称
   */
  unregister(name) {
    const plugin = this.plugins.get(name)
    if (!plugin) {
      logger.warn(`Plugin ${name} not found`)
      return
    }

    if (plugin.installed && this.app) {
      plugin.uninstall(this.app)
    }

    this.plugins.delete(name)
    logger.info(`Plugin ${name} unregistered`)
  }

  /**
   * 获取插件
   * @param {string} name - 插件名称
   * @returns {Plugin|null} 插件实例
   */
  get(name) {
    return this.plugins.get(name) || null
  }

  /**
   * 安装所有插件
   * @param {Object} app - 应用实例
   */
  installAll(app) {
    this.app = app

    for (const plugin of this.plugins.values()) {
      if (!plugin.installed) {
        plugin.install(app)
      }
    }

    logger.info(`Installed ${this.plugins.size} plugins`)
  }

  /**
   * 卸载所有插件
   */
  uninstallAll() {
    for (const plugin of this.plugins.values()) {
      if (plugin.installed && this.app) {
        plugin.uninstall(this.app)
      }
    }

    logger.info('All plugins uninstalled')
  }

  /**
   * 获取已安装的插件列表
   * @returns {Array} 插件名称列表
   */
  getInstalledPlugins() {
    return Array.from(this.plugins.values())
      .filter(plugin => plugin.installed)
      .map(plugin => plugin.name)
  }

  /**
   * 获取所有插件列表
   * @returns {Array} 插件名称列表
   */
  getAllPlugins() {
    return Array.from(this.plugins.keys())
  }
}

// 创建全局插件管理器实例
const pluginManager = new PluginManager()

// 导出插件管理器和插件类
export {
  pluginManager,
  Plugin,
  RequestInterceptorPlugin,
  RouteInterceptorPlugin,
  ErrorHandlerPlugin,
  PerformancePlugin,
  CachePlugin
}

// 导出默认插件管理器
export default pluginManager