/** 小程序可配置图标（启动时从 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',
  FIGHTER_RECHARGE_VIP_BG: 'fighter_recharge_vip_bg',
  FIGHTER_DEPOSIT_BG: 'fighter_deposit_bg',
  FIGHTER_DEPOSIT_HERO: 'fighter_deposit_hero',
  FIGHTER_DEPOSIT_BENEFIT_1: 'fighter_deposit_benefit_1',
  FIGHTER_DEPOSIT_BENEFIT_2: 'fighter_deposit_benefit_2',
  FIGHTER_DEPOSIT_BENEFIT_3: 'fighter_deposit_benefit_3',
  FIGHTER_DEPOSIT_BENEFIT_4: 'fighter_deposit_benefit_4',
  FIGHTER_RECHARGE_BENEFIT_1: 'fighter_recharge_benefit_1',
  FIGHTER_RECHARGE_BENEFIT_2: 'fighter_recharge_benefit_2',
  FIGHTER_RECHARGE_BENEFIT_3: 'fighter_recharge_benefit_3',
  FIGHTER_RECHARGE_ADVANTAGE_1: 'fighter_recharge_advantage_1',
  FIGHTER_RECHARGE_ADVANTAGE_2: 'fighter_recharge_advantage_2',
  FIGHTER_RECHARGE_ADVANTAGE_3: 'fighter_recharge_advantage_3',
  FIGHTER_RECHARGE_ADVANTAGE_4: 'fighter_recharge_advantage_4',
  FIGHTER_ORDER_PENDING: 'fighter_order_pending',
  FIGHTER_ORDER_SETTLING: 'fighter_order_settling',
  FIGHTER_ORDER_DONE: 'fighter_order_done',
  FIGHTER_ORDER_CLOSED: 'fighter_order_closed',
  FIGHTER_TRADE_COMMISSION: 'fighter_trade_commission',
  FIGHTER_TRADE_WITHDRAW: 'fighter_trade_withdraw',
  FIGHTER_TRADE_SETTLE: 'fighter_trade_settle',
  FIGHTER_TRADE_DEDUCT: 'fighter_trade_deduct',
  FIGHTER_TRADE_RECHARGE: 'fighter_trade_recharge',
  FIGHTER_INVITE_SUBORDINATE: 'fighter_invite_subordinate',
  FIGHTER_INVITE_POSTER: 'fighter_invite_poster',
  FIGHTER_INVITE_CODE: 'fighter_invite_code',
  FIGHTER_KUAISHOU_CASH: 'fighter_kuaishou_cash',
  FIGHTER_MINE_COPY: 'fighter_mine_copy',
  FIGHTER_MINE_EDIT: 'fighter_mine_edit',
  FIGHTER_MINE_QIEPIAN: 'fighter_mine_qiepian',
  FIGHTER_MINE_PENALTY_TIP: 'fighter_mine_penalty_tip',
  FIGHTER_MINE_KEFU: 'fighter_mine_kefu',
  FIGHTER_MINE_SHANGJIA: 'fighter_mine_shangjia',
  FIGHTER_MINE_PUNISH: 'fighter_mine_punish',
  FIGHTER_MINE_MEDAL: 'fighter_mine_medal',
  FIGHTER_MINE_BOOK: 'fighter_mine_book',
  FIGHTER_MINE_RANK: 'fighter_mine_rank',
  FIGHTER_MINE_INVITE: 'fighter_mine_invite',
  FIGHTER_MINE_CONTACT: 'fighter_mine_contact',
  FIGHTER_MINE_RECORD: 'fighter_mine_record',
  FIGHTER_MINE_KAOHE_DAFEN: 'fighter_mine_kaohe_dafen',
  FIGHTER_MINE_KAOHE_JILU: 'fighter_mine_kaohe_jilu',
  FIGHTER_MINE_KAOHE_ZHONGXIN: 'fighter_mine_kaohe_zhongxin',
  FIGHTER_MINE_DASHOU_AUTH: 'fighter_mine_dashou_auth',
  FIGHTER_MINE_CLEAR: 'fighter_mine_clear',
  FIGHTER_MINE_SWITCH: 'fighter_mine_switch',
  MINE_PINDAO: 'mine_pindao',
  ICON_REFRESH: 'icon_refresh',
};

/** 仅后台上传后才展示（页面大背景），横幅/功能图标走 resolveMiniappIcon */
export const CONFIG_ONLY_ICON_KEYS = new Set([
  ICON_KEYS.FIGHTER_RECHARGE_VIP_BG,
  ICON_KEYS.FIGHTER_DEPOSIT_BG,
  ICON_KEYS.FIGHTER_DEPOSIT_HERO,
]);

export const ICON_FOLDER = 'beijing/tubiao/chengxutubiao';

/** 逍遥梦原版金牌横幅（硬编码时代 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';

/** 打手中心图标默认相对路径（后台未上传时由后端 default 下发，此处仅离线兜底） */
export function defaultIconRel(key) {
  return `${ICON_FOLDER}/${key}.png`;
}

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) {
    if (!fallback) return '';
    if (fallback.startsWith('http')) return fallback;
    const base = ossBase(app);
    return base ? base + fallback : 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: () => {} });
  });
}

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 };
}

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);
}
