/** 小程序可配置图标（启动时从 qdpzhq.miniappAssets 注入 globalData） */

import { buildClubHeaders } from './club-context.js';

export const ICON_KEYS = {
  MERCHANT_GOLD_BANNER: 'merchant_gold_banner',
  MERCHANT_HOME_REGULAR: 'merchant_home_regular',
  MERCHANT_HOME_CUSTOM: 'merchant_home_custom',
  MERCHANT_HOME_LINK: 'merchant_home_link',
  MERCHANT_HOME_KEFU_KEY: 'merchant_home_kefu_key',
  MERCHANT_HOME_KEFU_LIST: 'merchant_home_kefu_list',
  MERCHANT_HOME_NOTICE: 'merchant_home_notice',
  MERCHANT_HOME_STAT_BG: 'merchant_home_stat_bg',
  MERCHANT_REGULAR: 'merchant_regular_dispatch',
  MERCHANT_CUSTOM: 'merchant_custom_dispatch',
  MERCHANT_PENDING: 'merchant_pending_settle',
  MERCHANT_KEFU_KEY: 'merchant_kefu_key',
  MERCHANT_KEFU_LIST: 'merchant_kefu_list',
  MERCHANT_LINK: 'merchant_link_dispatch',
  MERCHANT_PUNISH: 'merchant_punish',
  MERCHANT_RANK: 'merchant_rank',
  MERCHANT_REFRESH: 'merchant_refresh',
  FIGHTER_RECHARGE_MEMBER: 'fighter_recharge_member',
  FIGHTER_RECHARGE_DEPOSIT: 'fighter_recharge_deposit',
  MINE_PINDAO: 'mine_pindao',
  ICON_REFRESH: 'icon_refresh',
};

/** 仅后台上传后才展示，不使用 CDN/本地兜底 */
export const CONFIG_ONLY_ICON_KEYS = new Set([
  ICON_KEYS.FIGHTER_RECHARGE_MEMBER,
  ICON_KEYS.FIGHTER_RECHARGE_DEPOSIT,
]);

/** 逍遥梦原版金牌横幅（硬编码时代 82.png） */
export const MERCHANT_GOLD_BANNER_FALLBACK = 'https://bintao.xmxym88.com/xcx/bintao/82.png';

/** 频道入口图标默认相对路径（拼接 ossImageUrl；后台上传 mine_pindao 后覆盖） */
export const PINDAO_ICON_FALLBACK = 'beijing/tubiao/grzx_pindao.jpg';

function ossBase(app) {
  return (app && app.globalData && app.globalData.ossImageUrl) || '';
}

export function applyMiniappAssetsFromConfig(app, config) {
  if (!app || !config) return;
  const assets = config.miniappAssets || {};
  app.globalData.miniappIcons = assets.icons || {};
  app.globalData.pindaoConfig = assets.pindao || { channel_no: '', title: '频道', images: [] };
  app.globalData.posterConfig = assets.poster || {
    guanshi_bg: 'beijing/haibaobeijing.jpg',
    zuzhang_bg: 'beijing/zuzhangbeijing.jpg',
  };
}

/** 后台已上传的可配置图标（无则返回空，不显示） */
export function resolveConfiguredIcon(app, key) {
  const icons = (app && app.globalData && app.globalData.miniappIcons) || {};
  const path = icons[key];
  if (!path) return '';
  if (path.startsWith('http')) return path;
  return ossBase(app) + path;
}

/** 通用图标：有配置用配置，否则用 fallback */
export function resolveMiniappIcon(app, key, fallback = '') {
  if (CONFIG_ONLY_ICON_KEYS.has(key)) {
    return resolveConfiguredIcon(app, key);
  }
  const icons = (app && app.globalData && app.globalData.miniappIcons) || {};
  const path = icons[key];
  if (!path) return fallback;
  if (path.startsWith('http')) return path;
  return ossBase(app) + path;
}

export function getPindaoConfig(app) {
  return (app && app.globalData && app.globalData.pindaoConfig) || {
    channel_no: '',
    title: '频道',
    images: [],
  };
}

export function hasPindaoEntry(app) {
  const cfg = getPindaoConfig(app);
  if ((cfg.channel_no || '').trim()) return true;
  return (cfg.images || []).length > 0;
}

export function resolvePindaoImages(app) {
  const cfg = getPindaoConfig(app);
  const base = ossBase(app);
  return (cfg.images || []).map((url) => {
    if (!url) return '';
    return url.startsWith('http') ? url : base + url;
  }).filter(Boolean);
}

/** 预加载频道图片，减少弹窗打开后等待 */
export function preloadPindaoImages(urls) {
  (urls || []).forEach((src) => {
    if (!src) return;
    wx.getImageInfo({ src, fail: () => {} });
  });
}

/** 打开频道前拉取最新 qdpzhq 配置（避免本地缓存无 pindao 数据） */
export async function refreshPindaoConfig(app) {
  app = app || getApp();
  try {
    if (typeof app.fetchConfigSafely === 'function') {
      const config = await app.fetchConfigSafely();
      if (config && typeof config === 'object') {
        if (typeof app.applyDynamicConfig === 'function') {
          app.applyDynamicConfig(config);
        } else {
          applyMiniappAssetsFromConfig(app, config);
        }
        if (typeof app.saveConfigToStorage === 'function') {
          app.saveConfigToStorage(config);
        }
      }
    }
  } catch (e) {
    console.warn('refreshPindaoConfig failed', e);
  }
  const cfg = getPindaoConfig(app);
  const images = resolvePindaoImages(app);
  preloadPindaoImages(images);
  return { cfg, images };
}

/** 后台静默预热频道（不打断 UI） */
export function warmupPindaoConfig(app) {
  const cached = resolvePindaoImages(app || getApp());
  if (cached.length) preloadPindaoImages(cached);
  refreshPindaoConfig(app).catch(() => {});
}

export function getPosterConfig(app) {
  return (app && app.globalData && app.globalData.posterConfig) || {
    guanshi_bg: 'beijing/haibaobeijing.jpg',
    zuzhang_bg: 'beijing/zuzhangbeijing.jpg',
  };
}

export function resolvePosterBg(app, role) {
  const cfg = getPosterConfig(app);
  const rel = role === 'zuzhang' ? cfg.zuzhang_bg : cfg.guanshi_bg;
  const base = ossBase(app);
  const fallback = role === 'zuzhang' ? 'beijing/zuzhangbeijing.jpg' : 'beijing/haibaobeijing.jpg';
  const path = rel || fallback;
  return path.startsWith('http') ? path : base + path;
}

/** 进入海报页拉取当前俱乐部背景配置 */
export async function refreshPosterConfig(app) {
  app = app || getApp();
  try {
    const token = wx.getStorageSync('token');
    const header = buildClubHeaders({ 'Content-Type': 'application/json' });
    if (token) header.Authorization = 'Bearer ' + token;
    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.apiBaseUrl + '/peizhi/haibaopz',
        method: 'POST',
        header,
        success: (r) => resolve(r),
        fail: reject,
      });
    });
    const body = res?.data;
    if (body && body.code === 0 && body.data && body.data.poster) {
      app.globalData.posterConfig = body.data.poster;
      if (body.data.club_id) app.globalData.clubId = body.data.club_id;
      return body.data.poster;
    }
  } catch (e) {
    console.warn('refreshPosterConfig failed', e);
  }
  return getPosterConfig(app);
}
