/**
 * 商家订单统计：优先新接口，失败时回退订单列表中的 pending 字段
 */
import { STAFF_API, isStaffMode } from './staff-api.js';

const EMPTY_ORDER = {
  pending_count: 0,
  pending_amount: '0.00',
  completed_count: 0,
  completed_amount: '0.00',
  refund_count: 0,
  refund_amount: '0.00',
  dispatch_count: 0,
  dispatch_amount: '0.00',
};

export async function fetchMerchantOrderStats(request, params = {}) {
  const statsUrl = isStaffMode() ? STAFF_API.orderStats : '/dingdan/sjshujutj';
  try {
    const res = await request({ url: statsUrl, method: 'POST', data: params });
    if (res.statusCode === 200 && res.data && (res.data.code === 0 || res.data.code === 200)) {
      return res.data.data || {};
    }
  } catch (e) {
    console.warn('统计接口失败，尝试回退', e);
  }

  try {
    const listUrl = isStaffMode() ? STAFF_API.orderList : '/dingdan/sjdingdanhq';
    const fb = await request({
      url: listUrl,
      method: 'POST',
      data: { zhuangtai_list: [8], page: 1, page_size: 1, ...params },
    });
    if (fb.statusCode === 200 && fb.data && fb.data.code === 0) {
      const d = fb.data.data || {};
      return {
        order: {
          ...EMPTY_ORDER,
          pending_count: d.pending_count || 0,
          pending_amount: d.pending_amount || '0.00',
        },
        can_view_finance: true,
      };
    }
  } catch (e) {
    console.warn('统计回退失败', e);
  }
  return { order: { ...EMPTY_ORDER }, can_view_finance: true };
}

export function applyOrderStatsToPage(page, data) {
  const order = data.order || data || {};
  const penalty = data.penalty || {};
  const fakuanP = penalty.fakuan_pending || 0;
  const jifenP = penalty.jifen_pending || 0;
  page.setData({
    canViewFinance: data.can_view_finance !== false,
    orderStats: {
      pending_count: order.pending_count || 0,
      pending_amount: order.pending_amount || '0.00',
      completed_count: order.completed_count || 0,
      completed_amount: order.completed_amount || '0.00',
      refund_count: order.refund_count || 0,
      refund_amount: order.refund_amount || '0.00',
      dispatch_count: order.dispatch_count || 0,
      dispatch_amount: order.dispatch_amount || '0.00',
    },
    penaltyStats: {
      fakuan_pending: fakuanP,
      fakuan_pending_amount: penalty.fakuan_pending_amount || '0.00',
      jifen_pending: jifenP,
    },
    pendingCount: order.pending_count || 0,
    punishPending: fakuanP + jifenP,
  });
}

export function applyOrderStatsToHome(page, data, statsKey = 'stats') {
  const order = data.order || data || {};
  const base = page.data[statsKey] || {};
  page.setData({
    [statsKey]: {
      ...base,
      pendingCount: order.pending_count || 0,
      pendingAmount: order.pending_amount || '0.00',
      completedCount: order.completed_count || 0,
      completedAmount: order.completed_amount || '0.00',
      refundCount: order.refund_count || 0,
      refundAmount: order.refund_amount || '0.00',
      dispatchCount: order.dispatch_count || 0,
      dispatchAmount: order.dispatch_amount || '0.00',
    },
  });
}
