const api = require('../../utils/api');

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    loading: true,
    currentTab: 'all', // all, pending, paid, completed
    list: []
  },
  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.load();
  },
  onBack() {
    wx.navigateBack({ delta: 1 });
  },
  async load(isRefresh = false) {
    if (!isRefresh) {
      this.setData({ loading: true });
    }
    try {
      // Use payment.getOrders to show the recharge/vip/etc orders
      // Pass confirm: 1 on initial load or refresh to ensure status is up to date
      const params = { page: 1, pageSize: 50, confirm: 1 };
      if (this.data.currentTab !== 'all') {
        params.status = this.data.currentTab;
      }
      const res = await api.payment.getOrders(params);
      // Get list from response structure
      let orders = [];
      if (res.data && Array.isArray(res.data.list)) {
        orders = res.data.list;
      } else if (res.data && Array.isArray(res.data.orders)) {
        orders = res.data.orders;
      } else if (Array.isArray(res.data)) {
        orders = res.data;
      }

      const list = orders.map((o) => ({
        id: o.id || o.orderNo,
        remark: this.formatOrderType(o.orderType || 'order'),
        amountText: this.formatAmount(o.amount),
        status: this.formatStatus(o.status),
        statusClass: `status-${o.status}`,
        createdAtText: this.formatDateTime(new Date(o.createdAt || o.created_at || Date.now())),
        // visual adjustment: ensure it looks like income/recharge style
        transactionType: o.orderType || 'recharge'
      }));

      this.setData({ list });
    } catch (err) {
      console.error('API failed', err);
      // Fallback empty list
      if (!isRefresh) {
        this.setData({ list: [] });
      }
    } finally {
      this.setData({ loading: false });
      if (isRefresh) {
        wx.stopPullDownRefresh();
      }
    }
  },
  onPullDownRefresh() {
    this.load(true);
  },
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.currentTab) return;
    this.setData({ currentTab: tab }, () => {
      this.load();
    });
  },
  formatOrderType(type) {
    const map = {
      'recharge': '充值',
      'vip': '会员购买',
      'agent_purchase': '智能体购买',
      'companion_chat': '陪聊服务',
      'identity_card': '身份卡'
    };
    return map[String(type)] || '订单';
  },
  formatStatus(status) {
    const map = {
      'pending': '待支付',
      'paid': '已支付',
      'refunding': '退款中',
      'refunded': '已退款',
      'cancelled': '已取消',
      'completed': '已完成'
    };
    return map[String(status)] || status;
  },
  formatDateTime(d) {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${day} ${hh}:${mm}`;
  },
  formatAmount(amount) {
    const n = Number(amount || 0);
    return `¥${n.toFixed(2)}`;
  }
});

