/**
 * 预售（定金+尾款）
 * 对齐后端 /api/presale/*
 * 视图：list(活动列表) / detail(活动详情+定金下单) / orders(我的预售单+付尾款)
 * 三端对齐版：定金/尾款均走真实支付链（下单生成 payment_records，支付入口在 H5）
 */
const api = require('../../utils/api');

Page({
  data: {
    view: 'list',        // list | detail | orders
    loading: true,
    list: [],
    detail: {},
    qty: 1,
    orders: [],
    submitting: false
  },

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

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

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

  async loadOrders() {
    const t = wx.getStorageSync('token');
    if (!t) return;
    const res = await api.getPresaleOrders({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ orders: (res && res.list) || res || [] });
  },

  switchView(e) {
    const v = e.currentTarget.dataset.view;
    this.setData({ view: v });
    if (v === 'list') this.loadList();
    if (v === 'orders') this.loadOrders();
  },

  async openDetail(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({ loading: true, view: 'detail' });
    try {
      const d = await api.getPresaleDetail(id);
      if (d && d.id) {
        this.setData({ detail: d, qty: 1 });
      } else {
        wx.showToast({ title: '获取详情失败', icon: 'none' });
        this.setData({ view: 'list' });
      }
    } catch (err) {
      wx.showToast({ title: '获取详情失败', icon: 'none' });
      this.setData({ view: 'list' });
    }
    this.setData({ loading: false });
  },

  backToList() {
    this.setData({ view: 'list' });
  },

  changeQty(e) {
    let v = Number(e.detail.value) || 1;
    if (v < 1) v = 1;
    if (v > 999) v = 999;
    this.setData({ qty: v });
  },

  async submitDeposit() {
    const t = wx.getStorageSync('token');
    if (!t) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    if (!this.data.detail.id) {
      wx.showToast({ title: '请先选择预售活动', icon: 'none' });
      return;
    }
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const res = await api.createPresaleOrder({
        presale_id: this.data.detail.id,
        product_id: this.data.detail.product_id,
        quantity: this.data.qty,
        payment_method: 'wechat'
      });
      const orderNo = res && res.order_no;
      if (orderNo) {
        const depositAmt = Number(this.data.detail.deposit * this.data.qty).toFixed(2);
        this.setData({ submitting: false });
        // P1：优先小程序原生拉起定金支付；失败则回退 H5
        try {
          const naturalPay = require('../../utils/native-pay');
          const p = await naturalPay.nativePay({ order_no: orderNo, amount: depositAmt, subject: '预售定金' });
          if (p.mode === 'jsapi' && !p.completed) {
            wx.showToast({ title: '已下单，可继续支付定金', icon: 'none', duration: 2200 });
          }
          this.setData({ view: 'orders' });
          this.loadOrders();
        } catch (e) {
          const base = getApp().globalData.baseUrl || 'https://ssypco.com';
          wx.navigateTo({ url: '/pages/webview/webview?url=' + encodeURIComponent(base + '/mobile/#/presale/pay?order_no=' + orderNo + '&stage=deposit') });
        }
        return;
      } else {
        const msg = (res && res.message) || '提交失败';
        wx.showToast({ title: msg, icon: 'none', duration: 2500 });
      }
    } catch (e) {
      wx.showToast({ title: '提交失败', icon: 'none' });
    }
    this.setData({ submitting: false });
  },

  async payFinal(e) {
    const orderNo = e.currentTarget.dataset.no;
    const t = wx.getStorageSync('token');
    if (!t) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    try {
      const res = await api.payFinalAmount(orderNo);
      if (res && res.pay_url) {
        const base = getApp().globalData.baseUrl || 'https://ssypco.com';
        wx.showModal({
          title: '尾款支付已发起',
          content: `请前往 H5 完成尾款支付。`,
          confirmText: '去支付',
          cancelText: '稍后',
          success: (m) => {
            if (m.confirm) {
              wx.navigateTo({
                url: '/pages/webview/webview?url=' +
                  encodeURIComponent(base + '/mobile/#/presale/pay?order_no=' + orderNo + '&stage=final')
              });
            }
          }
        });
      } else {
        wx.showToast({ title: (res && res.message) || '支付失败', icon: 'none', duration: 2500 });
        this.loadOrders();
      }
    } catch (e) {
      wx.showToast({ title: '支付失败', icon: 'none' });
    }
  },

  statusLabel(s) {
    const m = { deposit_pending: '待付定金', deposit_paid: '待付尾款', final_paid: '已付尾款', cancelled: '已取消' };
    return m[s] || s || '';
  },

  // 详情定金按钮文案
  get depositText() {
    return Number(this.data.detail.deposit * this.data.qty).toFixed(2);
  }
});
