/**
 * 装修渲染工具(v1.4.3/v1.8) — 小程序端
 * 供 首页/分类/购物车/我的 四页共用
 * v1.8 扩展: 支持瀑布流(waterfall)/优惠券墙(couponWall)/分类宫格(categoryGrid)/倒计时(countdownBanner)
 * 用法: const decor = require('../../utils/decor');
 *       onLoad 里 decor.init(this, 'category');
 */
const api = require('./api');

/**
 * 初始化装修: 拉取模板, 若enabled则设置data(触发wxml渲染装修容器并隐藏默认内容)
 */
async function init(page, pageKey) {
  try {
    const r = await api.getDecor('miniapp', pageKey);
    if (r && r.code === 0 && r.data && r.data.enabled) {
      const comps = (r.data.components || []).map(c => ({
        ...c, props: c.props || {}, products: [], coupons: [], categories: []
      }));
      const dataSet = { decorEnabled: true, decorComponents: comps };
      if (page.setData) page.setData(dataSet);
      fetchGoods(page);
      return true;
    }
  } catch (e) {}
  if (page.setData) page.setData({ decorEnabled: false });
  return false;
}

/** 为数据驱动组件拉取数据（goodsList商品 / waterfall瀑布流 / couponWall券 / categoryGrid分类） */
async function fetchGoods(page) {
  const comps = (page.data && page.data.decorComponents) || [];
  let changed = false;
  for (let i = 0; i < comps.length; i++) {
    const c = comps[i];
    // 商品类: goodsList + waterfall
    if (c.type === 'goodsList' || c.type === 'waterfall') {
      try {
        const limit = (c.props.limit || c.props.count || 6);
        const params = { pageSize: limit };
        if (c.type === 'waterfall') {
          const src = c.props.source || 'auto';
          if (src === 'hot') params.sort = 'sales';
          else if (src === 'new') params.sort = 'new';
          else if (src !== 'all') params.is_recommend = 1;
        }
        const r = await api.getProductList(params);
        if (r && r.code === 0 && r.data && r.data.list) {
          comps[i].products = r.data.list.slice(0, limit * 2); // 瀑布流两列需要2倍
          changed = true;
        }
      } catch (e) {}
    }
    // swiper 无图时用 banner
    if (c.type === 'swiper' && (!c.props.images || !c.props.images.length)) {
      try {
        const b = await api.getBanners();
        if (b && b.code === 0 && b.data && b.data.length) {
          comps[i].props = Object.assign({}, c.props, { images: b.data.map(x => ({ url: x.image, link: '' })) });
          changed = true;
        }
      } catch (e) {}
    }
    // 优惠券墙: couponWall
    if (c.type === 'couponWall') {
      try {
        const r = await api.get('/marketing/promotion-center');
        if (r && r.code === 0 && r.data && r.data.list) {
          comps[i].coupons = (r.data.list || []).filter(x => x.type === 'coupon').slice(0, (c.props.count || 4));
          comps[i].loginToken = !!wx.getStorageSync('token');
          changed = true;
        }
      } catch (e) {}
    }
    // 分类宫格: categoryGrid
    if (c.type === 'categoryGrid') {
      try {
        const r = await api.get('/category/list');
        if (r && r.code === 0 && r.data) {
          comps[i].categories = (r.data || []).slice(0, (c.props.limit || 10));
          changed = true;
        }
      } catch (e) {}
    }
  }
  if (changed && page.setData) page.setData({ decorComponents: comps });
}

/** 装修内导航点击处理 */
function onNav(page, e, defaultPages) {
  const link = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.link) || '';
  if (!link) return;
  const p = String(link).replace(/^\//, '');
  const pages = defaultPages || {};
  if (pages[p] && typeof page[pages[p]] === 'function') { page[pages[p]](); return; }
  if (typeof wx.switchTab === 'function') wx.switchTab({ url: '/pages/' + p + '/' + p });
}

/** 领取优惠券（优惠券墙） */
function claimCoupon(page, e) {
  const id = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id) || 0;
  if (!id) return;
  const token = wx.getStorageSync('token');
  if (!token) { wx.showToast({ title: '请先登录', icon: 'none' }); return; }
  api.post('/marketing/coupon/receive', { coupon_id: id })
    .then((r) => {
      if (r && r.code === 0) {
        wx.showToast({ title: '领取成功', icon: 'success' });
        fetchGoods(page);
      } else {
        wx.showToast({ title: (r && r.message) || '领取失败', icon: 'none' });
      }
    })
    .catch(() => wx.showToast({ title: '网络错误', icon: 'none' }));
}

module.exports = { init, fetchGoods, onNav, claimCoupon };
