/**
 * 协议页面
 * 显示用户服务协议或隐私协议
 */
Page({
  data: {
    statusBarHeight: 20,
    title: '',
    content: ''
  },

  onLoad(options) {
    const code = options.code || 'user_service'
    
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 20
    })
    
    this.loadAgreement(code);
  },

  loadAgreement(code) {
    wx.showLoading({ title: '加载中...' });
    
    // 优先读取本地缓存
    const cached = wx.getStorageSync(`agreement_${code}`);
    const CACHE_DURATION = 60 * 60 * 1000; // 1小时
    const now = Date.now();
    
    if (cached && cached.timestamp && (now - cached.timestamp < CACHE_DURATION)) {
      this.setData({
        title: cached.data.title,
        content: cached.data.content
      });
      wx.hideLoading();
      return;
    }

    // 网络请求
    wx.request({
      url: `https://ai-c.maimanji.com/api/agreements?code=${code}`,
      method: 'GET',
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          const data = res.data.data;
          this.setData({
            title: data.title,
            content: data.content
          });
          
          // 写入缓存
          wx.setStorageSync(`agreement_${code}`, {
            data: data,
            timestamp: now
          });
        } else {
          wx.showToast({ title: '协议不存在', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: '加载失败', icon: 'none' });
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack()
  }
})
