/**
 * ============================================================================
 * 数据存储管理模块
 * 使用 localStorage 实现数据持久化
 * ============================================================================
 */

const Storage = {
  // 存储键名前缀
  PREFIX: 'operator_efficiency_',

  /**
   * 生成完整的存储键名
   * @param {string} key - 键名
   * @returns {string} 完整键名
   */
  _getKey(key) {
    return this.PREFIX + key;
  },

  /**
   * 获取数据
   * @param {string} key - 键名
   * @param {*} defaultValue - 默认值
   * @returns {*} 存储的数据
   */
  get(key, defaultValue = null) {
    try {
      const fullKey = this._getKey(key);
      const data = localStorage.getItem(fullKey);
      if (data === null) {
        return defaultValue;
      }
      return JSON.parse(data);
    } catch (error) {
      console.error(`Storage.get error [${key}]:`, error);
      return defaultValue;
    }
  },

  /**
   * 设置数据
   * @param {string} key - 键名
   * @param {*} value - 要存储的值
   * @returns {boolean} 是否成功
   */
  set(key, value) {
    try {
      const fullKey = this._getKey(key);
      const data = JSON.stringify(value);
      localStorage.setItem(fullKey, data);
      return true;
    } catch (error) {
      console.error(`Storage.set error [${key}]:`, error);
      return false;
    }
  },

  /**
   * 删除数据
   * @param {string} key - 键名
   * @returns {boolean} 是否成功
   */
  remove(key) {
    try {
      const fullKey = this._getKey(key);
      localStorage.removeItem(fullKey);
      return true;
    } catch (error) {
      console.error(`Storage.remove error [${key}]:`, error);
      return false;
    }
  },

  /**
   * 清空所有应用数据
   * @returns {boolean} 是否成功
   */
  clear() {
    try {
      const keys = Object.keys(localStorage);
      keys.forEach(key => {
        if (key.startsWith(this.PREFIX)) {
          localStorage.removeItem(key);
        }
      });
      return true;
    } catch (error) {
      console.error('Storage.clear error:', error);
      return false;
    }
  },

  /**
   * 初始化默认数据
   */
  init() {
    // 初始化模块数据
    if (this.get('modules') === null) {
      this.set('modules', [
        {
          id: 1,
          name: '环境部署',
          icon: '🖥️',
          desc: '一键配置和部署开发环境,支持多版本选择和组件定制',
          url: 'deployment.html',
          enabled: true
        },
        {
          id: 2,
          name: '学习共享',
          icon: '📚',
          desc: '算子开发知识库,汇集从入门到进阶的完整学习资料',
          url: 'learning.html',
          enabled: true
        },
        {
          id: 3,
          name: '材料查询',
          icon: '🔍',
          desc: '按业务范围快速查询开发文档、API手册和问题解决方案',
          url: 'query.html',
          enabled: true
        }
      ]);
    }

    // 初始化学习分类数据
    if (this.get('learningCategories') === null) {
      this.set('learningCategories', [
        {
          id: 1,
          name: '基础入门',
          icon: '🌱',
          items: [
            {
              id: 1,
              title: '算子开发入门',
              desc: '了解算子的基本概念、开发流程和核心原理',
              wikiUrl: 'https://wiki.example.com/operator/intro'
            },
            {
              id: 2,
              title: '开发环境搭建',
              desc: '完整的开发环境配置指南,包括工具链和依赖安装',
              wikiUrl: 'https://wiki.example.com/operator/setup'
            },
            {
              id: 3,
              title: 'Hello World 教程',
              desc: '从零开始编写第一个算子,体验完整的开发流程',
              wikiUrl: 'https://wiki.example.com/operator/helloworld'
            }
          ]
        },
        {
          id: 2,
          name: '进阶技巧',
          icon: '🚀',
          items: [
            {
              id: 1,
              title: '性能优化实践',
              desc: '算子性能调优技巧和最佳实践,提升计算效率',
              wikiUrl: 'https://wiki.example.com/operator/performance'
            },
            {
              id: 2,
              title: '多线程与并行计算',
              desc: '利用多线程加速算子执行的策略和实现',
              wikiUrl: 'https://wiki.example.com/operator/multithreading'
            },
            {
              id: 3,
              title: '内存管理与优化',
              desc: '高效的内存分配和释放策略,避免内存泄漏',
              wikiUrl: 'https://wiki.example.com/operator/memory'
            }
          ]
        },
        {
          id: 3,
          name: '高级主题',
          icon: '⚡',
          items: [
            {
              id: 1,
              title: '自定义算子内核',
              desc: '深入理解算子内核原理,开发自定义内核',
              wikiUrl: 'https://wiki.example.com/operator/kernel'
            },
            {
              id: 2,
              title: '算子融合技术',
              desc: '多个算子融合执行,减少内存访问开销',
              wikiUrl: 'https://wiki.example.com/operator/fusion'
            },
            {
              id: 3,
              title: '硬件加速优化',
              desc: '利用 GPU、NPU 等硬件加速算子执行',
              wikiUrl: 'https://wiki.example.com/operator/hardware'
            }
          ]
        }
      ]);
    }

    // 初始化查询分类数据
    if (this.get('queryCategories') === null) {
      this.set('queryCategories', [
        {
          id: 1,
          name: '算子库',
          icon: '📦',
          items: [
            {
              id: 1,
              title: '常用算子列表',
              desc: '所有可用算子的完整列表,包括参数说明和使用示例',
              wikiUrl: 'https://wiki.example.com/query/operators-list'
            },
            {
              id: 2,
              title: '算子性能对比',
              desc: '各算子的性能基准测试数据和对比分析',
              wikiUrl: 'https://wiki.example.com/query/operators-performance'
            },
            {
              id: 3,
              title: '算子迁移指南',
              desc: '从其他框架迁移算子的详细步骤和注意事项',
              wikiUrl: 'https://wiki.example.com/query/operators-migration'
            }
          ]
        },
        {
          id: 2,
          name: 'API文档',
          icon: '📖',
          items: [
            {
              id: 1,
              title: '核心API参考',
              desc: '主要接口的详细说明,包括参数、返回值和示例',
              wikiUrl: 'https://wiki.example.com/query/api-core'
            },
            {
              id: 2,
              title: '工具类API',
              desc: '辅助工具函数库,简化开发流程',
              wikiUrl: 'https://wiki.example.com/query/api-utils'
            },
            {
              id: 3,
              title: '调试API',
              desc: '用于调试和诊断的接口文档',
              wikiUrl: 'https://wiki.example.com/query/api-debug'
            }
          ]
        },
        {
          id: 3,
          name: '问题排查',
          icon: '🔧',
          items: [
            {
              id: 1,
              title: '常见错误码',
              desc: '错误码大全及对应的解决方案',
              wikiUrl: 'https://wiki.example.com/query/errors'
            },
            {
              id: 2,
              title: '调试技巧',
              desc: '高效的调试方法和工具使用指南',
              wikiUrl: 'https://wiki.example.com/query/debugging'
            },
            {
              id: 3,
              title: '性能分析',
              desc: '性能瓶颈定位和分析工具使用',
              wikiUrl: 'https://wiki.example.com/query/profiling'
            }
          ]
        },
        {
          id: 4,
          name: '最佳实践',
          icon: '✨',
          items: [
            {
              id: 1,
              title: '代码规范',
              desc: '编码风格指南和命名约定',
              wikiUrl: 'https://wiki.example.com/query/coding-standards'
            },
            {
              id: 2,
              title: '测试策略',
              desc: '单元测试、集成测试的最佳实践',
              wikiUrl: 'https://wiki.example.com/query/testing'
            },
            {
              id: 3,
              title: '文档编写',
              desc: '如何编写清晰完整的技术文档',
              wikiUrl: 'https://wiki.example.com/query/documentation'
            }
          ]
        }
      ]);
    }

    // 初始化部署历史数据
    if (this.get('deploymentHistory') === null) {
      this.set('deploymentHistory', []);
    }

    console.log('[Storage] Initialized successfully');
  }
};

// 自动初始化
Storage.init();

// 导出到全局
window.Storage = Storage;