// 存储工具类 - 对应Flutter的storage_util.dart
class StorageUtil {
  constructor() {
    this.prefix = 'lanmei_'; // 应用前缀，避免与其他应用冲突
  }

  // 初始化
  init() {
    console.log('存储工具初始化完成');
  }

  // 获取带前缀的key
  getKey(key) {
    return this.prefix + key;
  }

  // 设置数据
  async set(key, value) {
    try {
      const storageKey = this.getKey(key);
      const data = {
        value: value,
        timestamp: Date.now()
      };
      
      wx.setStorageSync(storageKey, data);
      console.log(`存储数据: ${key} =`, value);
      return true;
    } catch (error) {
      console.error(`存储数据失败: ${key}`, error);
      return false;
    }
  }

  // 获取数据
  async get(key, defaultValue = null) {
    try {
      const storageKey = this.getKey(key);
      const data = wx.getStorageSync(storageKey);
      
      if (data && data.value !== undefined) {
        console.log(`读取数据: ${key} =`, data.value);
        return data.value;
      } else {
        console.log(`读取数据: ${key} = 默认值`, defaultValue);
        return defaultValue;
      }
    } catch (error) {
      console.error(`读取数据失败: ${key}`, error);
      return defaultValue;
    }
  }

  // 删除数据
  async remove(key) {
    try {
      const storageKey = this.getKey(key);
      wx.removeStorageSync(storageKey);
      console.log(`删除数据: ${key}`);
      return true;
    } catch (error) {
      console.error(`删除数据失败: ${key}`, error);
      return false;
    }
  }

  // 清除所有数据
  async clear() {
    try {
      const storageInfo = wx.getStorageInfoSync();
      const keys = storageInfo.keys.filter(key => key.startsWith(this.prefix));
      
      keys.forEach(key => {
        wx.removeStorageSync(key);
      });
      
      console.log(`清除所有数据: ${keys.length} 项`);
      return true;
    } catch (error) {
      console.error('清除数据失败:', error);
      return false;
    }
  }

  // 检查数据是否存在
  async exists(key) {
    try {
      const storageKey = this.getKey(key);
      const data = wx.getStorageSync(storageKey);
      return data !== '' && data !== null && data !== undefined;
    } catch (error) {
      console.error(`检查数据存在失败: ${key}`, error);
      return false;
    }
  }

  // 获取存储信息
  async getInfo() {
    try {
      const storageInfo = wx.getStorageInfoSync();
      const appKeys = storageInfo.keys.filter(key => key.startsWith(this.prefix));
      
      return {
        totalKeys: storageInfo.keys.length,
        appKeys: appKeys.length,
        currentSize: storageInfo.currentSize,
        limitSize: storageInfo.limitSize,
        keys: appKeys.map(key => key.replace(this.prefix, ''))
      };
    } catch (error) {
      console.error('获取存储信息失败:', error);
      return null;
    }
  }

  // 设置过期数据
  async setWithExpire(key, value, expireTime) {
    try {
      const storageKey = this.getKey(key);
      const data = {
        value: value,
        timestamp: Date.now(),
        expire: Date.now() + expireTime * 1000 // expireTime为秒数
      };
      
      wx.setStorageSync(storageKey, data);
      console.log(`存储带过期时间的数据: ${key} =`, value, `过期时间: ${expireTime}秒`);
      return true;
    } catch (error) {
      console.error(`存储带过期时间的数据失败: ${key}`, error);
      return false;
    }
  }

  // 获取数据（检查过期时间）
  async getWithExpireCheck(key, defaultValue = null) {
    try {
      const storageKey = this.getKey(key);
      const data = wx.getStorageSync(storageKey);
      
      if (!data || data.value === undefined) {
        return defaultValue;
      }

      // 检查是否过期
      if (data.expire && Date.now() > data.expire) {
        console.log(`数据已过期，删除: ${key}`);
        await this.remove(key);
        return defaultValue;
      }

      console.log(`读取数据: ${key} =`, data.value);
      return data.value;
    } catch (error) {
      console.error(`读取数据失败: ${key}`, error);
      return defaultValue;
    }
  }

  // 清理过期数据
  async clearExpiredData() {
    try {
      const storageInfo = wx.getStorageInfoSync();
      const appKeys = storageInfo.keys.filter(key => key.startsWith(this.prefix));
      let clearedCount = 0;

      appKeys.forEach(storageKey => {
        try {
          const data = wx.getStorageSync(storageKey);
          if (data && data.expire && Date.now() > data.expire) {
            wx.removeStorageSync(storageKey);
            clearedCount++;
            console.log(`清理过期数据: ${storageKey}`);
          }
        } catch (error) {
          console.error(`清理过期数据失败: ${storageKey}`, error);
        }
      });

      console.log(`清理过期数据完成: ${clearedCount} 项`);
      return clearedCount;
    } catch (error) {
      console.error('清理过期数据失败:', error);
      return 0;
    }
  }

  // 批量设置数据
  async setBatch(dataMap) {
    try {
      const results = [];
      for (const [key, value] of Object.entries(dataMap)) {
        const result = await this.set(key, value);
        results.push({ key, success: result });
      }
      
      const successCount = results.filter(r => r.success).length;
      console.log(`批量设置数据: ${successCount}/${results.length} 成功`);
      return results;
    } catch (error) {
      console.error('批量设置数据失败:', error);
      return [];
    }
  }

  // 批量获取数据
  async getBatch(keys, defaultValue = null) {
    try {
      const results = {};
      for (const key of keys) {
        results[key] = await this.get(key, defaultValue);
      }
      
      console.log(`批量获取数据: ${keys.length} 项`);
      return results;
    } catch (error) {
      console.error('批量获取数据失败:', error);
      return {};
    }
  }

  // 用户相关数据操作的便捷方法
  async setUserData(userData) {
    return await this.set('userInfo', userData);
  }

  async getUserData() {
    return await this.get('userInfo');
  }

  async setToken(token) {
    return await this.set('token', token);
  }

  async getToken() {
    return await this.get('token');
  }

  async setCustomId(customId) {
    return await this.set('customId', customId);
  }

  async getCustomId() {
    return await this.get('customId');
  }

  // 应用设置相关
  async setAppSettings(settings) {
    return await this.set('appSettings', settings);
  }

  async getAppSettings() {
    return await this.get('appSettings', {
      theme: 'auto',
      language: 'zh',
      notifications: true,
      locationPrivacy: 1,
      autoLocation: true
    });
  }

  // 缓存数据操作
  async setCacheData(key, data, expireTime = 3600) {
    return await this.setWithExpire(`cache_${key}`, data, expireTime);
  }

  async getCacheData(key) {
    return await this.getWithExpireCheck(`cache_${key}`);
  }

  async clearCache() {
    try {
      const storageInfo = wx.getStorageInfoSync();
      const cacheKeys = storageInfo.keys.filter(key => 
        key.startsWith(this.prefix + 'cache_')
      );
      
      cacheKeys.forEach(key => {
        wx.removeStorageSync(key);
      });
      
      console.log(`清除缓存数据: ${cacheKeys.length} 项`);
      return cacheKeys.length;
    } catch (error) {
      console.error('清除缓存数据失败:', error);
      return 0;
    }
  }
}

// 创建单例
const storageUtil = new StorageUtil();

module.exports = storageUtil; 