/**
 * 页面素材管理工具类
 * 用于小程序获取和缓存后台配置的图片资源
 */

const config = require('../config/index');
const API_BASE_URL = config.API_BASE_URL.replace('/api', ''); // 移除 /api 后缀
const CACHE_KEY = 'pageAssets';
const CACHE_DURATION = 30 * 60 * 1000; // 30分钟缓存

/**
 * 获取页面素材配置
 * @param {string|null} group - 素材分组名称，不传则获取全部
 * @param {boolean} forceRefresh - 是否强制刷新，忽略缓存
 * @returns {Promise<Object|null>} 素材配置对象
 */
async function getPageAssets(group = null, forceRefresh = false) {
  try {
    // 1. 如果不强制刷新，先尝试从缓存读取
    if (!forceRefresh) {
      const cached = getCachedAssets();
      if (cached) {
        return group ? cached[group] : cached;
      }
    }
    
    // 2. 从服务器获取
    const url = group 
      ? `${API_BASE_URL}/api/page-assets?group=${group}`
      : `${API_BASE_URL}/api/page-assets`;
      
    const res = await wx.request({
      url,
      method: 'GET',
      timeout: 10000
    });
    
    if (res.statusCode === 200 && res.data.success) {
      // 3. 更新缓存（只有获取全部时才缓存）
      if (!group) {
        setCachedAssets(res.data.data);
      }
      
      return res.data.data;
    }
    
    // 4. 请求失败，返回默认配置
    console.warn('获取素材配置失败，使用默认配置');
    return getDefaultAssets(group);
    
  } catch (error) {
    console.error('获取素材配置异常:', error);
    return getDefaultAssets(group);
  }
}

/**
 * 从缓存读取素材配置
 */
function getCachedAssets() {
  try {
    const cached = wx.getStorageSync(CACHE_KEY);
    if (cached && cached.timestamp && cached.data) {
      if (Date.now() - cached.timestamp < CACHE_DURATION) {
        return cached.data;
      }
    }
    return null;
  } catch (error) {
    console.error('读取缓存失败:', error);
    return null;
  }
}

/**
 * 保存素材配置到缓存
 */
function setCachedAssets(data) {
  try {
    wx.setStorageSync(CACHE_KEY, {
      data,
      timestamp: Date.now()
    });
  } catch (error) {
    console.error('保存缓存失败:', error);
  }
}

/**
 * 清除素材缓存
 */
function clearAssetsCache() {
  try {
    wx.removeStorageSync(CACHE_KEY);
    console.log('素材缓存已清除');
  } catch (error) {
    console.error('清除缓存失败:', error);
  }
}

/**
 * 预加载素材配置（建议在 app.js 的 onLaunch 中调用）
 */
async function preloadAssets() {
  try {
    await getPageAssets(null, false);
    console.log('素材配置预加载完成');
  } catch (error) {
    console.error('素材配置预加载失败:', error);
  }
}

/**
 * 获取默认素材配置（降级方案 - 使用CDN URL）
 */
function getDefaultAssets(group = null) {
  const cdnBase = 'https://ai-c.maimanji.com/images'
  const defaults = {
    banners: {
      companion_banner: `${cdnBase}/Header-banner.png`,
      service_banner: `${cdnBase}/service-banner-1.png`,
      home_banner: `${cdnBase}/Header-banner.png`,
      medical_banner: `${cdnBase}/service-banner-2.png`,
      housekeeping_banner: `${cdnBase}/service-banner-3.png`,
      eldercare_banner: `${cdnBase}/service-banner-4.png`,
      service_banner_5: `${cdnBase}/service-banner-5.png`,
      service_banner_6: `${cdnBase}/service-banner-6.png`,
      cooperation_banner: `${cdnBase}/Header-banner.png`,
    },
    entries: {
      entry_1: `${cdnBase}/pb01.png`,
      entry_2: `${cdnBase}/pb02.png`,
      entry_3: `${cdnBase}/pb03.png`,
      entry_4: `${cdnBase}/pb04.png`,
    },
    icons: {
      consult_button: `${cdnBase}/btn-text-consult.png`,
      gift: `${cdnBase}/icon-gift.png`,
      location: `${cdnBase}/icon-location.png`,
    },
    service_icons: {
      medical: `${cdnBase}/icon-medical.png`,
      flow: `${cdnBase}/icon-flow.png`,
      advantage: `${cdnBase}/icon-advantage.png`,
      professional: `${cdnBase}/icon-professional.png`,
      safe: `${cdnBase}/icon-safe.png`,
      efficient: `${cdnBase}/icon-efficient.png`,
      care: `${cdnBase}/icon-care.png`,
    },
    status_icons: {
      pending: `${cdnBase}/icon-pending.png`,
      success: `${cdnBase}/icon-success.png`,
      rejected: `${cdnBase}/icon-rejected.png`,
    },
    empty_states: {
      orders: `${cdnBase}/empty-orders.png`,
      messages: `${cdnBase}/empty-messages.png`,
    },
    defaults: {
      avatar: `${cdnBase}/default-avatar.png`,
      placeholder: '/images/placeholder.jpg',
    },
    tabbar: {
      listen: `${cdnBase}/tab-listen.png`,
      listen_active: `${cdnBase}/tab-listen-active.png`,
      companion: `${cdnBase}/tab-companion.png`,
      companion_active: `${cdnBase}/tab-companion-active.png`,
      service: `${cdnBase}/tab-service.png`,
      service_active: `${cdnBase}/tab-service-active.png`,
      message: `${cdnBase}/tab-message.png`,
      message_unread: `${cdnBase}/tab-message-nodot.png`,
      message_active: `${cdnBase}/tab-message-active.png`,
      profile: `${cdnBase}/tab-profile.png`,
      profile_active: `${cdnBase}/tab-profile-active.png`,
      square: `${cdnBase}/tab-compass.png`,
      square_active: `${cdnBase}/tab-compass-active.png`,
    },
    workbench: {
      orders: `${cdnBase}/icon-orders.png`,
      customers: `${cdnBase}/icon-customers.png`,
      withdraw: `${cdnBase}/icon-withdraw.png`,
      commission: `${cdnBase}/icon-commission.png`,
    },
  };
  
  return group ? defaults[group] : defaults;
}

module.exports = {
  getPageAssets,
  clearAssetsCache,
  preloadAssets
};
