/**
 * 积分商城
 * 商品列表 / 详情兑换 / 兑换记录
 * 对齐后端 /api/exchange/*
 */
const api = require('../../utils/api');

Page({
  data: {
    loading: true,
    products: [],
    myPoints: 0,
    orders: [],
    activeTab: 'shop', // shop | orders
    // 兑换弹窗
    showExchange: false,
    current: null,
    qty: 1,
    recipient: { name: '', phone: '', address: '', remark: '' },
    submitting: false
  },

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

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

  async loadMyPoints() {
    try {
      const u = await api.getUserInfo();
      this.setData({ myPoints: (u && u.experience) || 0 });
    } catch (e) {}
  },

  async loadProducts() {
    this.setData({ loading: true });
    const res = await api.getExchangeProducts({ status: 1 }).catch(() => []);
    this.setData({ products: (res && res.list) || res || [], loading: false });
  },

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

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

  openExchange(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.products.find(p => p.id == id);
    if (!item) return;
    this.setData({
      showExchange: true,
      current: item,
      qty: 1,
      recipient: { name: '', phone: '', address: '', remark: '' }
    });
  },
  closeExchange() {
    this.setData({ showExchange: false });
  },
  onQtySub() {
    if (this.data.qty > 1) this.setData({ qty: this.data.qty - 1 });
  },
  onQtyAdd() {
    const max = this.data.current.stock || 99;
    if (this.data.qty < max) this.setData({ qty: this.data.qty + 1 });
  },
  onRecipient(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({ ['recipient.' + key]: e.detail.value });
  },
  async submitExchange() {
    const { current, qty, recipient } = this.data;
    if (!recipient.name || !recipient.phone) {
      wx.showToast({ title: '请填写收货人', icon: 'none' });
      return;
    }
    const need = (current.points || 0) * qty;
    if (this.data.myPoints < need) {
      wx.showToast({ title: '积分不足', icon: 'none' });
      return;
    }
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const res = await api.createExchangeOrder({
        product_id: current.id,
        quantity: qty,
        recipient_name: recipient.name,
        recipient_phone: recipient.phone,
        recipient_address: recipient.address,
        remark: recipient.remark
      });
      this.setData({ showExchange: false });
      wx.showToast({ title: '兑换成功', icon: 'success' });
      this.loadMyPoints();
      this.loadOrders();
    } catch (e) {}
    finally {
      this.setData({ submitting: false });
    }
  }
});
