/**
 * 余额充值
 * 套餐 / 我的余额 / 充值记录
 * 对齐后端 /api/recharge/*
 */
const api = require('../../utils/api');

Page({
  data: {
    loading: true,
    plans: [],
    balance: 0,
    orders: [],
    activeTab: 'shop', // shop | orders
    submitting: false
  },

  onShow() {
    this.loadBalance();
  },

  onLoad() {
    this.loadPlans();
    this.loadOrders();
  },

  async loadBalance() {
    try {
      const b = await api.getBalance();
      this.setData({ balance: (b && b.balance) || 0 });
    } catch (e) {}
  },

  async loadPlans() {
    this.setData({ loading: true });
    const plans = await api.getRechargePlans().catch(() => []);
    this.setData({ plans: Array.isArray(plans) ? plans : [], loading: false });
  },

  async loadOrders() {
    const res = await api.getRechargeOrders({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ orders: (res && res.list) || res || [] });
  },

  switchTab(e) {
    this.setData({ activeTab: e.currentTarget.dataset.tab });
  },

  async onRecharge(e) {
    const id = e.currentTarget.dataset.id;
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const res = await api.createRechargeOrder({ plan_id: id, payment_method: 'wechat' });
      if (res && res.order_no) {
        wx.showModal({
          title: '下单成功',
          content: `充值订单 ${res.order_no}，金额 ¥${Number(res.amount).toFixed(2)}。支付请前往 H5 充值页完成。`,
          confirmText: '去支付',
          cancelText: '稍后',
          success: (m) => {
            if (m.confirm) {
              const base = getApp().globalData.baseUrl || 'https://ssypco.com';
              wx.navigateTo({
                url: '/pages/webview/webview?url=' + encodeURIComponent(base + '/mobile/#/recharge/pay?order_no=' + res.order_no)
              });
            }
          }
        });
      }
    } catch (e) { /* 门控/错误由接口 toast */ }
    finally {
      this.setData({ submitting: false });
    }
  }
});
