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

Page({
  data: {
    order: { items: [] },
    orderNo: '',
    statusIcon: '',
    statusLabel: '',
    statusDesc: '',
    showActions: false
  },

  onLoad(options) {
    const orderNo = options.orderNo;
    if (orderNo) {
      this.setData({ orderNo });
      this.loadDetail(orderNo);
    }
  },

  async loadDetail(orderNo) {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const order = await api.getOrderDetail(orderNo);
      if (!order) {
        wx.showToast({ title: '订单不存在', icon: 'none' });
        wx.navigateBack();
        return;
      }

      const statusInfo = util.getOrderStatusInfo(order.status);
      const iconMap = {
        pending_pay: '⏳', pending_ship: '📦', shipped: '🚚',
        received: '⭐', completed: '✅', closed: '❌', refunding: '🔄'
      };
      const descMap = {
        pending_pay: '等待买家付款', pending_ship: '等待商家发货',
        shipped: '商品已发出，待收货', received: '请评价本次购物体验',
        completed: '订单已完成', closed: order.close_reason || '订单已关闭',
        refunding: '退款处理中'
      };

      this.setData({
        order: {
          ...order,
          statusInfo,
          created_at: util.formatDate(order.created_at)
        },
        statusIcon: iconMap[order.status] || '📄',
        statusLabel: statusInfo.label,
        statusDesc: descMap[order.status] || '',
        showActions: ['pending_pay', 'shipped', 'received', 'refunding'].includes(order.status)
      });
    } catch (err) {
      console.error('订单详情加载失败:', err);
    } finally {
      wx.hideLoading();
    }
  },

  async onPay() {
    try {
      await api.payOrder(this.data.orderNo, { payment_method: 'wechat' });
      wx.showToast({ title: '支付成功', icon: 'success' });
      this.loadDetail(this.data.orderNo);
    } catch (err) {}
  },

  async onCancel() {
    wx.showModal({
      title: '确认取消',
      content: '确定取消该订单？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await api.cancelOrder(this.data.orderNo, { close_reason: '用户取消' });
            wx.showToast({ title: '已取消', icon: 'success' });
            this.loadDetail(this.data.orderNo);
          } catch (err) {}
        }
      }
    });
  },

  async onConfirm() {
    try {
      await api.confirmOrder(this.data.orderNo);
      wx.showToast({ title: '已确认收货', icon: 'success' });
      this.loadDetail(this.data.orderNo);
    } catch (err) {}
  },

  onReview() {
    const order = this.data.order;
    wx.navigateTo({
      url: `/pages/review/review?mode=create&orderId=${order.id}&orderNo=${order.order_no}`
    });
  },

  onFollowUp() {
    const order = this.data.order;
    wx.navigateTo({
      url: `/pages/review/review?mode=followup&orderId=${order.id}&orderNo=${order.order_no}`
    });
  },

  onRefund() {
    const order = this.data.order;
    wx.navigateTo({
      url: `/pages/refund/refund?orderId=${order.id}&orderNo=${order.order_no}&amount=${order.pay_amount}`
    });
  },

  async onCancelRefund() {
    try {
      await api.cancelRefund(this.data.order.id);
      wx.showToast({ title: '已取消退款', icon: 'success' });
      this.loadDetail(this.data.orderNo);
    } catch (err) {}
  }
});
