/**
 * 售后页面（统一售后）
 * 支持查看售后列表、申请退款(仅退款/退货退款)、提交退货物流、取消售后
 */
const api = require('../../utils/api');

const TYPE_LABEL = { only_refund: '仅退款', refund_and_return: '退货退款', exchange: '换货' };
const STATUS_LABEL = {
  pending: '待审核', approved: '已通过(待寄回)', shipped_back: '已寄回(待确认)',
  completed: '已完成', rejected: '已拒绝', cancelled: '已取消'
};

Page({
  data: {
    mode: 'list', // list | apply | return
    refunds: [],
    reasonIndex: 0,
    reasons: ['七天无理由', '质量问题', '商品破损', '发错货', '其他'],
    reason: '七天无理由',
    orderId: '',
    orderNo: '',
    maxAmount: 0,
    curRefund: null,   // 当前操作中的售后单
    type: 'only_refund',
    shippingCompany: '',
    shippingNo: '',
    shippingCompanies: ['顺丰速运', '中通快递', '圆通速递', '韵达快递', '邮政EMS', '京东物流', '其他'],
    loading: true,
    submitting: false
  },

  onLoad(options) {
    if (options.orderId) {
      this.setData({
        mode: 'apply',
        orderId: options.orderId,
        orderNo: options.orderNo || '',
        maxAmount: options.amount || 0
      });
    } else {
      this.loadRefunds();
    }
  },

  async loadRefunds() {
    this.setData({ loading: true });
    try {
      const result = await api.getRefundList();
      const list = (result.list || []).map(r => Object.assign({}, r, {
        type_label: TYPE_LABEL[r.type] || r.type || '仅退款',
        status_label: this.refundStatusLabel(r.status)
      }));
      this.setData({ refunds: list });
    } catch (err) {
      console.error('售后列表加载失败:', err);
    } finally {
      this.setData({ loading: false });
    }
  },

  refundStatusLabel(status) {
    return STATUS_LABEL[status] || status;
  },

  onTypeChange(e) {
    this.setData({ type: e.detail.value === 0 ? 'only_refund' : 'refund_and_return' });
  },

  onReasonChange(e) {
    const i = Number(e.detail.value) || 0;
    this.setData({ reasonIndex: i, reason: this.data.reasons[i] });
  },

  onReasonInput(e) {
    this.setData({ reason: e.detail.value });
  },

  onCompanyChange(e) {
    const i = Number(e.detail.value) || 0;
    this.setData({ shippingCompany: this.data.shippingCompanies[i] });
  },

  onCompanyInput(e) {
    this.setData({ shippingCompany: e.detail.value });
  },

  onShippingNoInput(e) {
    this.setData({ shippingNo: e.detail.value });
  },

  async onSubmitRefund() {
    const { orderId, reason, maxAmount, type, submitting } = this.data;
    if (submitting) return;
    if (!reason || !reason.trim()) {
      wx.showToast({ title: '请填写退款原因', icon: 'none' });
      return;
    }
    if (!orderId) {
      wx.showToast({ title: '缺少订单信息', icon: 'none' });
      return;
    }

    this.setData({ submitting: true });
    try {
      await api.applyRefund({
        order_id: orderId,
        reason,
        amount: maxAmount,
        type
      });
      wx.showToast({ title: '申请成功', icon: 'success' });
      wx.navigateBack({ delta: 1 });
    } catch (err) {
      console.error('申请售后失败:', err);
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 打开退货物流填写
  onOpenReturn(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.refunds.find(r => r.id === id);
    if (!item) return;
    this.setData({ mode: 'return', curRefund: item, shippingCompany: this.data.shippingCompanies[0], shippingNo: '' });
  },

  async onSubmitReturn() {
    const { curRefund, shippingCompany, shippingNo, submitting } = this.data;
    if (submitting) return;
    if (!shippingNo || !shippingNo.trim()) {
      wx.showToast({ title: '请填写退货物流单号', icon: 'none' });
      return;
    }
    this.setData({ submitting: true });
    try {
      await api.submitReturnRefund(curRefund.id, {
        shipping_company: shippingCompany || '其他',
        shipping_no: shippingNo.trim()
      });
      wx.showToast({ title: '已提交退货信息', icon: 'success' });
      this.setData({ mode: 'list' });
      this.loadRefunds();
    } catch (err) {
      console.error('提交退货失败:', err);
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 取消售后
  async onCancelRefund(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '取消售后',
      content: '确定取消该售后申请吗？',
      success: async (res) => {
        if (!res.confirm) return;
        try {
          await api.cancelRefund(id);
          wx.showToast({ title: '已取消', icon: 'success' });
          this.loadRefunds();
        } catch (err) {
          console.error('取消失败:', err);
        }
      }
    });
  },

  goBack() {
    if (this.data.mode !== 'list') {
      this.setData({ mode: 'list', curRefund: null });
    } else {
      wx.navigateBack({ delta: 1 });
    }
  }
});
