import { createPage, request } from '../../utils/base-page.js';
import { fetchMerchantOrderStats, applyOrderStatsToPage } from '../../utils/merchant-order-stats.js';

Page(createPage({
  data: {
    statusBar: 20,
    loading: true,
    canViewFinance: true,
    orderStats: {
      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',
    },
    penaltyStats: {
      fakuan_pending: 0,
      fakuan_pending_amount: '0.00',
      jifen_pending: 0,
    },
    jinriliushui: '0.00',
    jinyueliushui: '0.00',
    jinridingdan: 0,
    jinrituikuan: 0,
  },

  onLoad() {
    const sys = wx.getSystemInfoSync();
    this.setData({ statusBar: sys.statusBarHeight || 20 });
    this.loadData();
  },

  onPullDownRefresh() {
    this.loadData().finally(() => wx.stopPullDownRefresh());
  },

  async loadData() {
    this.setData({ loading: true });
    try {
      const statsData = await fetchMerchantOrderStats(request, {});
      applyOrderStatsToPage(this, statsData);
      try {
        const res = await request({ url: '/yonghu/shangjiaxinxi', method: 'POST' });
        if (res.data && res.data.code === 200) {
          const d = res.data.data || {};
          this.setData({
            jinriliushui: d.jinriliushui || '0.00',
            jinyueliushui: d.jinyueliushui || '0.00',
            jinridingdan: d.jinripaidan || 0,
            jinrituikuan: d.jinrituikuan || 0,
          });
        }
      } catch (e) {
        console.warn('商家流水加载失败', e);
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  goBack() {
    wx.navigateBack();
  },
}));
