import request from '../../utils/request.js';
import { getOrderStatusText } from '../../utils/api-helper.js';

const PAGE_SIZE = 15;

const TYPE_CONFIG = {
  commission: { title: '佣金记录', statuses: [3, 8] },
  settle: { title: '结算记录', statuses: [3] },
  withdraw: { title: '提现记录', api: 'withdraw' },
  deduct: { title: '扣款记录', api: 'deduct' },
};

Page({
  data: {
    pageTitle: '交易明细',
    type: 'commission',
    statusBar: 20,
    list: [],
    page: 1,
    hasMore: true,
    loading: false,
    refreshing: false,
  },

  onLoad(options) {
    const sys = wx.getSystemInfoSync();
    const type = (options.type || 'commission').trim();
    const cfg = TYPE_CONFIG[type] || TYPE_CONFIG.commission;
    this.setData({
      type,
      pageTitle: cfg.title,
      statusBar: sys.statusBarHeight || 20,
    });
    this.loadList(true);
  },

  goBack() {
    wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/fighter/fighter' }) });
  },

  onRefresh() {
    this.setData({ refreshing: true });
    this.loadList(true).finally(() => this.setData({ refreshing: false }));
  },

  onLoadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadList(false);
    }
  },

  async loadList(refresh) {
    const { type, loading } = this.data;
    if (loading) return;
    const page = refresh ? 1 : this.data.page;
    this.setData({ loading: true });
    try {
      let rows = [];
      let hasMore = false;
      if (type === 'withdraw') {
        const res = await request({
          url: '/yonghu/tixianjiluhq',
          method: 'POST',
          data: { page, limit: PAGE_SIZE },
        });
        const body = res?.data;
        if (body && (body.code === 200 || body.code === 0)) {
          const raw = body.data?.list || [];
          rows = raw.map((item, idx) => ({
            id: item.id || item.jilu_id || `${page}-${idx}`,
            title: item.beizhu || item.status_text || item.zhuangtai_text || '提现',
            time: item.creat_time || item.create_time || item.tijiao_shijian || '',
            amount: `-¥${item.jine || item.amount || item.tixian_jine || '0.00'}`,
            minus: true,
          }));
          hasMore = raw.length >= PAGE_SIZE;
        }
      } else if (type === 'deduct') {
        const res = await request({
          url: '/yonghu/dsfklbhq',
          method: 'POST',
          data: { page, page_size: PAGE_SIZE, zhuangtai: 0 },
        });
        const body = res?.data;
        if (body && (body.code === 200 || body.code === 0)) {
          const raw = body.data?.list || [];
          rows = raw.map((item, idx) => ({
            id: item.fadan_id || item.id || `${page}-${idx}`,
            title: item.yuanyin || item.beizhu || item.fakuan_yuanyin || '扣款',
            time: item.creat_time || item.create_time || '',
            amount: `-¥${item.jine || item.fakuan_jine || item.fakuanjine || '0.00'}`,
            minus: true,
          }));
          hasMore = raw.length >= PAGE_SIZE;
        }
      } else {
        const cfg = TYPE_CONFIG[type] || TYPE_CONFIG.commission;
        const res = await request({
          url: '/dingdan/dshqdingdan',
          method: 'POST',
          data: {
            zhuangtai_list: cfg.statuses,
            page,
            page_size: PAGE_SIZE,
          },
        });
        const body = res?.data;
        if (body && (body.code === 200 || body.code === 0)) {
          const raw = body.data?.list || [];
          rows = raw.map((item) => {
            const amt = item.jine || item.dashou_fencheng || '0.00';
            const brief = (item.jieshao || '').trim();
            const title = brief
              ? (brief.length > 18 ? `${brief.slice(0, 18)}…` : brief)
              : `订单 ${item.dingdan_id || ''}`;
            return {
              id: item.dingdan_id,
              title,
              time: item.wancheng_shijian || item.jiesuan_shijian || item.creat_time || getOrderStatusText(item.zhuangtai),
              amount: `+¥${amt}`,
              minus: false,
            };
          });
          hasMore = body.data?.has_more ?? raw.length >= PAGE_SIZE;
        }
      }
      const list = refresh ? rows : [...this.data.list, ...rows];
      this.setData({
        list,
        page: refresh ? 2 : page + 1,
        hasMore,
      });
    } catch (e) {
      console.error('ledger load fail', e);
    } finally {
      this.setData({ loading: false });
    }
  },
});
