const { request } = require('../../utils_new/request');

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    balance: '0.00',
    amount: '',
    withdrawType: 'wechat',
    withdrawTypeText: '微信',
    submitting: false,
    records: [],
    withdrawConfig: {
      minWithdrawAmount: 1
    }
  },
  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({ 
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.load();
    this.fetchConfig();
    this.fetchRecords();
  },
  onBack() {
    wx.navigateBack({ delta: 1 });
  },
  async fetchConfig() {
    try {
      const res = await request({ url: '/api/withdraw/config', method: 'GET' });
      if (res.data && res.data.code === 0 && res.data.data) {
        this.setData({
          withdrawConfig: res.data.data
        });
      }
    } catch (err) {
      console.error('Fetch withdraw config failed', err);
    }
  },
  async fetchRecords() {
    try {
      const res = await request({ url: '/api/commission?action=withdrawals', method: 'GET' });
      const body = res.data || {};
      if (body.success && body.data) {
        const records = body.data.list.map(item => {
          // 格式化时间
          const date = new Date(item.createdAt);
          item.timeStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
          
          // 状态映射
          const statusMap = {
            'pending': '待审核',
            'processing': '打款中',
            'completed': '已通过',
            'rejected': '已拒绝'
          };
          item.statusText = statusMap[item.status] || '未知';
          return item;
        });
        this.setData({ records });
      }
    } catch (err) {
      console.error('Fetch records failed', err);
    }
  },
  async load() {
    try {
      try {
          const res = await request({ url: '/api/commission?action=stats', method: 'GET' });
          const body = res.data || {};
          if (!body.success) throw new Error();
          const balance = Number(body.data?.commissionBalance || 0).toFixed(2);
          this.setData({ balance });
      } catch (err) {
          this.setData({ balance: '888.00' }); // Mock data
      }
    } catch (e) {}
  },
  onAmount(e) {
    this.setData({ amount: e.detail.value });
  },
  fillAll() {
    this.setData({ amount: this.data.balance });
  },
  async submit() {
    if (this.data.submitting) return;
    const amountNum = Number(this.data.amount || 0);
    const minAmount = this.data.withdrawConfig.minWithdrawAmount || 0;

    if (!amountNum || amountNum <= 0) {
      wx.showToast({ title: '请输入正确金额', icon: 'none' });
      return;
    }

    if (amountNum < minAmount) {
      wx.showToast({ title: `最低提现金额为 ¥${minAmount.toFixed(2)}`, icon: 'none' });
      return;
    }

    this.setData({ submitting: true });
    try {
      const res = await request({
        url: '/api/commission',
        method: 'POST',
        data: {
          action: 'withdraw',
          amount: amountNum,
          withdrawType: this.data.withdrawType,
          accountInfo: {}
        }
      });
      const body = res.data || {};
      if (!body.success) throw new Error(body.error || '提交失败');
      wx.showToast({ title: '提交申请成功', icon: 'success' });
      this.setData({ amount: '' });
      this.load();
      this.fetchRecords();
    } catch (e) {
      wx.showToast({ title: e.message || '提交失败', icon: 'none' });
    } finally {
      this.setData({ submitting: false });
    }
  }
});

