/**
 * 订单结算页
 */
const api = require('../../utils/api');
const util = require('../../utils/util');

Page({
  data: {
    items: [],
    address: null,
    addressList: [],
    remark: '',
    paymentMethod: 'wechat',
    totalAmount: 0,
    discountAmount: 0,
    payAmount: 0,
    submitting: false
  },

  onLoad(options) {
    let items = [];
    try {
      items = JSON.parse(decodeURIComponent(options.items || '[]'));
    } catch(e) {
      wx.showToast({ title: '参数错误', icon: 'none' });
      wx.navigateBack();
      return;
    }
    this.setData({ items });
    this.loadAddress();
    this.calcAmount(items);
  },

  async loadAddress() {
    try {
      const list = await api.getAddressList();
      if (Array.isArray(list)) {
        const defaultAddr = list.find(a => a.is_default) || list[0];
        this.setData({ addressList: list, address: defaultAddr });
      }
    } catch(e) {}
  },

  async calcAmount(items) {
    try {
      const orderItems = items.map(i => ({
        product_id: i.product_id,
        sku_id: i.sku_id,
        quantity: i.quantity
      }));
      const result = await api.calcAmount({ items: orderItems });
      if (result) {
        this.setData({
          totalAmount: result.total_amount || 0,
          discountAmount: result.discount_amount || 0,
          payAmount: result.pay_amount || 0
        });
      }
    } catch(e) {
      // 如果估算失败，手动计算
      const total = items.reduce((s, i) => s + parseFloat(i.price) * i.quantity, 0);
      this.setData({ totalAmount: total, payAmount: total });
    }
  },

  formatPrice(v) {
    return parseFloat(v || 0).toFixed(2);
  },

  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },

  selectPayment(e) {
    this.setData({ paymentMethod: e.currentTarget.dataset.method });
  },

  onSelectAddress() {
    const { addressList, address } = this.data;
    if (addressList.length === 0) {
      wx.navigateTo({ url: '/pages/address-form/address-form' });
      return;
    }
    
    wx.showActionSheet({
      itemList: addressList.map(a => `${a.name} ${a.phone} ${a.detail}`),
      success: (res) => {
        this.setData({ address: addressList[res.tapIndex] });
      }
    });
  },

  async onSubmit() {
    const { items, address, remark, paymentMethod, payAmount, submitting } = this.data;
    if (submitting) return;
    if (!address) {
      wx.showToast({ title: '请选择收货地址', icon: 'none' });
      return;
    }

    this.setData({ submitting: true });
    try {
      const orderItems = items.map(i => ({
        product_id: i.product_id,
        sku_id: i.sku_id,
        quantity: i.quantity,
        cart_id: i.cart_id
      }));

      const result = await api.createOrder({
        items: orderItems,
        address_id: address.id,
        remark
      });

      // 创建成功，跳转支付或订单详情
      wx.showToast({ title: '下单成功', icon: 'success' });
      
      if (result && result.orderNo) {
        // 自动发起支付
        try {
          await api.payOrder(result.orderNo, { payment_method: paymentMethod });
          wx.showToast({ title: '支付成功', icon: 'success' });
          setTimeout(() => {
            wx.redirectTo({ url: `/pages/order-detail/order-detail?orderNo=${result.orderNo}` });
          }, 1500);
        } catch (payErr) {
          // 支付失败，跳转到订单详情
          setTimeout(() => {
            wx.redirectTo({ url: `/pages/order-detail/order-detail?orderNo=${result.orderNo}` });
          }, 500);
        }
      }
    } catch (err) {
      console.error('提交订单失败:', err);
    } finally {
      this.setData({ submitting: false });
    }
  }
});
