/**
 * 协议页面
 * 显示用户服务协议或隐私协议
 */
const config = require('../../config/index')

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 cacheKey = code === 'privacy_policy' ? 'privacy_policy' : `agreement_${code}`;
    const cached = wx.getStorageSync(cacheKey);
    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;
    }

    // 从配置文件获取API域名
    const baseUrl = String(config.API_BASE_URL || '').replace(/\/api$/, '')

    // 网络请求
    wx.request({
      url: `${baseUrl}/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(cacheKey, {
            data: data,
            timestamp: now
          });
        } else {
          wx.showToast({ title: '协议不存在', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: '加载失败', icon: 'none' });
      }
    });
  },

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