/**
 * 会员中心（VIP）
 * 套餐列表 / 我的会员 / 购买 / 购买记录
 * 对齐后端 /api/membership/*
 */
const api = require('../../utils/api');

Page({
  data: {
    loading: true,
    plans: [],
    myMembership: null,
    level: null,
    experience: 0,
    history: [],
    buyLoading: false
  },

  onLoad() {
    this.loadAll();
  },

  async loadAll() {
    this.setData({ loading: true });
    try {
      const plans = await api.getMembershipPlans().catch(() => []);
      const myRes = await api.getMyMembership().catch(() => null);
      this.setData({
        plans: Array.isArray(plans) ? plans : [],
        myMembership: (myRes && myRes.membership) ? myRes.membership : null,
        level: (myRes && myRes.level) ? myRes.level : null,
        experience: (myRes && myRes.experience) ? myRes.experience : 0
      });
      const history = await api.getMembershipHistory().catch(() => []);
      this.setData({ history: Array.isArray(history) ? history : [] });
    } catch (e) {
      console.error('会员信息加载失败', e);
    } finally {
      this.setData({ loading: false });
    }
  },

  async onBuy(e) {
    const id = e.currentTarget.dataset.id;
    if (this.data.buyLoading) return;
    this.setData({ buyLoading: true });
    try {
      const res = await api.buyMembership({ plan_id: id, payment_method: 'wechat' });
      if (res && res.order_no) {
        wx.showModal({
          title: '下单成功',
          content: `订单号：${res.order_no}，需支付 ¥${Number(res.amount).toFixed(2)}，请前往订单列表完成支付`,
          showCancel: false,
          confirmText: '去支付',
          success: () => {
            wx.redirectTo({ url: `/pages/order-detail/order-detail?orderNo=${res.order_no}` });
          }
        });
      }
    } catch (err) {
      // 接口已内部 toast
    } finally {
      this.setData({ buyLoading: false });
    }
  },

  goOrderList() {
    wx.navigateTo({ url: '/pages/order/order?status=pending_pay' });
  }
});
