/**
 * 按俱乐部拉取公告/轮播（必须带 X-Club-Id，否则会落到默认 xq）
 */
import { buildClubHeaders, getClubId } from './club-context';

export function isGonggaoCacheValid(app) {
  const g = app.globalData || {};
  const cid = getClubId(app);
  return g._gonggaoClubId === cid && (g.shangpingonggao || (g.shangpinlunbo && g.shangpinlunbo.length));
}

export function applyGonggaoToGlobal(app, data) {
  if (!data) return;
  const g = app.globalData;
  g.shangpingonggao = data.shangpingonggao || '';
  g.shangpinlunbo = data.shangpinlunbo || [];
  g._gonggaoClubId = getClubId(app);
}

export function fetchGonggaoLunbo(app, pageKey = 'order_pool') {
  const apiBase = app.globalData && app.globalData.apiBaseUrl;
  if (!apiBase) {
    return Promise.resolve(null);
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${apiBase}/peizhi/shangpingonggao/`,
      method: 'POST',
      header: buildClubHeaders({ 'content-type': 'application/json' }),
      data: { page_key: pageKey },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          applyGonggaoToGlobal(app, res.data);
          resolve(res.data);
        } else {
          reject(new Error('shangpingonggao 请求失败'));
        }
      },
      fail: reject,
    });
  });
}
