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

Page({
  data: {
    activeTab: 'all',
    orders: [],
    page: 1,
    pageSize: 10,
    total: 0,
    loading: true,
    loadStatus: 'loading'
  },

  onLoad(options) {
    if (options.status) {
      this.setData({ activeTab: options.status });
    }
    this.loadOrders(true);
  },

  onPullDownRefresh() {
    this.loadOrders(true).then(() => wx.stopPullDownRefresh());
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab, orders: [], page: 1 });
    this.loadOrders(true);
  },

  async loadOrders(reset = false) {
    if (reset) {
      this.setData({ page: 1, loading: true, loadStatus: 'loading' });
    }

    const { activeTab, page, pageSize } = this.data;
    const params = { page, pageSize };
    if (activeTab !== 'all') {
      params.status = activeTab;
    }

    try {
      const result = await api.getOrderList(params);
      const list = result.list || [];
      const total = result.total || 0;

      // 处理订单状态信息
      const orders = list.map(o => ({
        ...o,
        statusInfo: util.getOrderStatusInfo(o.status),
        created_at: util.formatDate(o.created_at, 'MM-DD HH:mm')
      }));

      this.setData({
        orders: reset ? orders : this.data.orders.concat(orders),
        total,
        loading: false,
        loadStatus: this.data.orders.length + list.length >= total ? 'nomore' : 'loading'
      });
    } catch (err) {
      this.setData({ loading: false, loadStatus: 'error' });
    }
  },

  onLoadMore() {
    const { loadStatus, page, total, orders } = this.data;
    if (loadStatus === 'loading' && orders.length < total) {
      this.setData({ page: page + 1 });
      this.loadOrders();
    }
  },

  goDetail(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    wx.navigateTo({ url: `/pages/order-detail/order-detail?orderNo=${orderNo}` });
  },

  async onPay(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    try {
      await api.payOrder(orderNo, { payment_method: 'wechat' });
      wx.showToast({ title: '支付成功', icon: 'success' });
      this.loadOrders(true);
    } catch (err) {}
  },

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

  async onConfirm(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    try {
      await api.confirmOrder(orderNo);
      wx.showToast({ title: '已确认收货', icon: 'success' });
      this.loadOrders(true);
    } catch (err) {}
  },

  onReview(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    wx.navigateTo({ url: `/pages/order-detail/order-detail?orderNo=${orderNo}` });
  },

  goHome() {
    wx.switchTab({ url: '/pages/index/index' });
  }
});
