import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import { Input } from '@tarojs/components';
import {
  confirmPlatformInvoicePayment,
  createPlatformInvoiceFromSubscription,
  createPlatformInvoicesBatchFromSubscriptions,
  createPlatformInvoicesFromUsageOverage,
  createPlatformSubscription,
  loadPlatformInvoiceReminders,
  loadPlatformInvoices,
  loadPlatformPlans,
  loadPlatformSubscriptionInvoiceCandidates,
  loadPlatformUsageOverageInvoiceCandidates,
  loadPlatformUsage,
  processPlatformOverdueInvoices,
  recordPlatformUsage,
  type PlatformInvoiceReminderItem,
  type PlatformInvoiceItem,
  type PlatformSaasPlan,
  type PlatformSubscriptionInvoiceCandidate,
  type PlatformUsageOverageInvoiceCandidate,
  type PlatformUsageItem,
} from '@/services/platformAdmin';
import '../platform.css';

function money(cents: unknown, currency = 'CNY') {
  const symbol = currency === 'CNY' ? '¥' : `${currency} `;
  return `${symbol}${(Number(cents || 0) / 100).toFixed(2)}`;
}

function todayText() {
  return new Date().toISOString().slice(0, 10);
}

function monthStartText() {
  const now = new Date();
  return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString().slice(0, 10);
}

function centsFromYuan(value: string) {
  const amount = Number(value || 0);
  if (!Number.isFinite(amount) || amount <= 0) return 0;
  return Math.round(amount * 100);
}

export default function PlatformBillingPage() {
  const [status, setStatus] = useState('');
  const [plans, setPlans] = useState<PlatformSaasPlan[]>([]);
  const [invoices, setInvoices] = useState<PlatformInvoiceItem[]>([]);
  const [reminders, setReminders] = useState<PlatformInvoiceReminderItem[]>([]);
  const [usage, setUsage] = useState<PlatformUsageItem[]>([]);
  const [candidates, setCandidates] = useState<PlatformSubscriptionInvoiceCandidate[]>([]);
  const [overageCandidates, setOverageCandidates] = useState<PlatformUsageOverageInvoiceCandidate[]>([]);
  const [batchResult, setBatchResult] = useState('');
  const [subscriptionForm, setSubscriptionForm] = useState({
    tenantId: '',
    planCode: '',
    status: 'active',
    amountYuan: '',
  });
  const [invoiceForm, setInvoiceForm] = useState({
    tenantId: '',
    dueDate: '',
    note: '',
  });
  const [paymentForm, setPaymentForm] = useState({
    tenantId: '',
    invoiceId: '',
    amountYuan: '',
    providerTradeNo: '',
  });
  const [usageForm, setUsageForm] = useState({
    tenantId: '',
    metricKey: 'students',
    metricValue: '',
    periodStart: todayText(),
    periodEnd: todayText(),
  });
  const [batchInvoiceForm, setBatchInvoiceForm] = useState({
    daysAhead: '45',
    dueDate: '',
    note: '',
  });
  const [overageForm, setOverageForm] = useState({
    periodStart: monthStartText(),
    periodEnd: todayText(),
    dueDate: '',
    note: '',
  });
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  function reload(nextStatus = status) {
    Promise.all([
      loadPlatformPlans(true).catch(() => ({ items: [] })),
      loadPlatformInvoices({ status: nextStatus || undefined, limit: 100 }),
      loadPlatformInvoiceReminders({ limit: 80 }).catch(() => ({ items: [] })),
      loadPlatformUsage({ limit: 80 }).catch(() => ({ items: [] })),
      loadPlatformSubscriptionInvoiceCandidates({ daysAhead: Number(batchInvoiceForm.daysAhead || 45), limit: 100 }).catch(() => ({ items: [] })),
      loadPlatformUsageOverageInvoiceCandidates({
        periodStart: overageForm.periodStart,
        periodEnd: overageForm.periodEnd,
        limit: 100,
      }).catch(() => ({ items: [] })),
    ]).then(([planPayload, invoicePayload, reminderPayload, usagePayload, candidatePayload, overagePayload]) => {
      const nextPlans = planPayload.items || [];
      setPlans(nextPlans);
      setSubscriptionForm(current => ({ ...current, planCode: current.planCode || nextPlans[0]?.code || '' }));
      setInvoices(invoicePayload.items || []);
      setReminders(reminderPayload.items || []);
      setUsage(usagePayload.items || []);
      setCandidates(candidatePayload.items || []);
      setOverageCandidates(overagePayload.items || []);
    }).catch(nextError => setError(nextError instanceof Error ? nextError.message : '账务数据加载失败'));
  }

  useEffect(() => {
    reload('');
  }, []);

  function chooseStatus(nextStatus: string) {
    setStatus(nextStatus);
    reload(nextStatus);
  }

  const unpaidCents = invoices.reduce((sum, item) => sum + Number(item.balanceCents || 0), 0);
  const paidCents = invoices.reduce((sum, item) => sum + Number(item.paidCents || 0), 0);

  function updateSubscriptionForm(key: keyof typeof subscriptionForm, value: string) {
    setSubscriptionForm(current => ({ ...current, [key]: value }));
  }

  function updateInvoiceForm(key: keyof typeof invoiceForm, value: string) {
    setInvoiceForm(current => ({ ...current, [key]: value }));
  }

  function updatePaymentForm(key: keyof typeof paymentForm, value: string) {
    setPaymentForm(current => ({ ...current, [key]: value }));
  }

  function updateUsageForm(key: keyof typeof usageForm, value: string) {
    setUsageForm(current => ({ ...current, [key]: value }));
  }

  function updateBatchInvoiceForm(key: keyof typeof batchInvoiceForm, value: string) {
    setBatchInvoiceForm(current => ({ ...current, [key]: value }));
  }

  function updateOverageForm(key: keyof typeof overageForm, value: string) {
    setOverageForm(current => ({ ...current, [key]: value }));
  }

  async function confirm(title: string, content: string) {
    const result = await Taro.showModal({ title, content, confirmText: '确认', cancelText: '取消' });
    return result.confirm;
  }

  async function submitSubscription() {
    setError('');
    if (!subscriptionForm.tenantId || !subscriptionForm.planCode) {
      setError('开通订阅需要填写租户 ID 和套餐编码。');
      return;
    }
    const ok = await confirm('开通订阅', `确认给租户 ${subscriptionForm.tenantId} 开通 ${subscriptionForm.planCode}？`);
    if (!ok) return;
    setBusy('subscription');
    try {
      await createPlatformSubscription({
        tenantId: subscriptionForm.tenantId,
        planCode: subscriptionForm.planCode,
        status: subscriptionForm.status || 'active',
        amountCents: subscriptionForm.amountYuan ? centsFromYuan(subscriptionForm.amountYuan) : undefined,
      });
      Taro.showToast({ title: '已开通', icon: 'success' });
      reload(status);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '订阅开通失败');
    } finally {
      setBusy('');
    }
  }

  async function submitInvoiceFromSubscription() {
    setError('');
    if (!invoiceForm.tenantId) {
      setError('生成账单需要填写租户 ID。');
      return;
    }
    const ok = await confirm('生成账单', `确认按租户 ${invoiceForm.tenantId} 最新订阅生成服务费账单？`);
    if (!ok) return;
    setBusy('invoice');
    try {
      await createPlatformInvoiceFromSubscription({
        tenantId: invoiceForm.tenantId,
        status: 'issued',
        dueDate: invoiceForm.dueDate || undefined,
        note: invoiceForm.note.trim() || undefined,
      });
      Taro.showToast({ title: '已生成', icon: 'success' });
      reload(status);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '账单生成失败');
    } finally {
      setBusy('');
    }
  }

  async function submitPaymentConfirm() {
    setError('');
    const amountCents = centsFromYuan(paymentForm.amountYuan);
    if (!paymentForm.tenantId || !paymentForm.invoiceId || amountCents <= 0) {
      setError('确认收款需要填写租户 ID、账单 ID 和正数金额。');
      return;
    }
    const ok = await confirm('确认收款', `确认登记线下收款 ${money(amountCents)}？该动作会影响租户账务状态。`);
    if (!ok) return;
    setBusy('payment');
    try {
      await confirmPlatformInvoicePayment({
        tenantId: paymentForm.tenantId,
        invoiceId: paymentForm.invoiceId,
        amountCents,
        provider: 'manual',
        method: 'manual',
        providerTradeNo: paymentForm.providerTradeNo.trim() || undefined,
      });
      Taro.showToast({ title: '已确认', icon: 'success' });
      reload(status);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '收款确认失败');
    } finally {
      setBusy('');
    }
  }

  async function submitUsageRecord() {
    setError('');
    const metricValue = Number(usageForm.metricValue || 0);
    if (!usageForm.tenantId || !usageForm.metricKey || !usageForm.periodStart || !usageForm.periodEnd || metricValue < 0) {
      setError('记录用量需要填写租户、指标、数值和账期。');
      return;
    }
    const ok = await confirm('记录用量', `确认写入 ${usageForm.metricKey} = ${metricValue} 的账期用量？`);
    if (!ok) return;
    setBusy('usage');
    try {
      await recordPlatformUsage({
        tenantId: usageForm.tenantId,
        metricKey: usageForm.metricKey,
        metricValue,
        periodStart: usageForm.periodStart,
        periodEnd: usageForm.periodEnd,
      });
      Taro.showToast({ title: '已记录', icon: 'success' });
      reload(status);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '用量记录失败');
    } finally {
      setBusy('');
    }
  }

  async function loadSubscriptionCandidates() {
    setError('');
    setBusy('candidates');
    try {
      const payload = await loadPlatformSubscriptionInvoiceCandidates({
        daysAhead: Number(batchInvoiceForm.daysAhead || 45),
        limit: 100,
      });
      setCandidates(payload.items || []);
      setBatchResult('');
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '订阅账单候选加载失败');
    } finally {
      setBusy('');
    }
  }

  async function submitBatchInvoices(dryRun: boolean) {
    setError('');
    const daysAhead = Number(batchInvoiceForm.daysAhead || 45);
    if (!Number.isFinite(daysAhead) || daysAhead < 0) {
      setError('请填写有效的候选天数。');
      return;
    }
    const ok = dryRun
      ? true
      : await confirm('批量生成账单', `确认给 ${candidates.length} 个候选订阅批量生成服务费账单？后端会跳过已存在账单的订阅。`);
    if (!ok) return;
    setBusy(dryRun ? 'batch-dry-run' : 'batch-create');
    try {
      const payload = await createPlatformInvoicesBatchFromSubscriptions({
        daysAhead,
        dueDate: batchInvoiceForm.dueDate || undefined,
        note: batchInvoiceForm.note.trim() || undefined,
        status: 'issued',
        dryRun,
      });
      const item = payload.item || {};
      setBatchResult(`${dryRun ? '预览' : '生成'}完成：创建 ${item.createdCount || 0}，跳过 ${item.skippedCount || 0}`);
      if (dryRun) {
        setCandidates((item.items || []).map(candidate => ({ ...candidate, wouldCreate: true })));
      } else {
        Taro.showToast({ title: '已批量生成', icon: 'success' });
        reload(status);
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '批量账单处理失败');
    } finally {
      setBusy('');
    }
  }

  async function loadUsageOverageCandidates() {
    setError('');
    if (!overageForm.periodStart || !overageForm.periodEnd) {
      setError('请填写超额计费账期。');
      return;
    }
    setBusy('overage-candidates');
    try {
      const payload = await loadPlatformUsageOverageInvoiceCandidates({
        periodStart: overageForm.periodStart,
        periodEnd: overageForm.periodEnd,
        limit: 100,
      });
      setOverageCandidates(payload.items || []);
      setBatchResult('');
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '超额账单候选加载失败');
    } finally {
      setBusy('');
    }
  }

  async function submitUsageOverageInvoices(dryRun: boolean) {
    setError('');
    if (!overageForm.periodStart || !overageForm.periodEnd) {
      setError('请填写超额计费账期。');
      return;
    }
    const ok = dryRun
      ? true
      : await confirm('生成超额账单', `确认按 ${overageForm.periodStart} 至 ${overageForm.periodEnd} 的后端用量快照生成超额服务费账单？`);
    if (!ok) return;
    setBusy(dryRun ? 'overage-dry-run' : 'overage-create');
    try {
      const payload = await createPlatformInvoicesFromUsageOverage({
        periodStart: overageForm.periodStart,
        periodEnd: overageForm.periodEnd,
        dueDate: overageForm.dueDate || undefined,
        note: overageForm.note.trim() || undefined,
        status: 'issued',
        dryRun,
      });
      const item = payload.item || {};
      setBatchResult(`${dryRun ? '超额预览' : '超额账单生成'}完成：创建 ${item.createdCount || 0}，跳过 ${item.skippedCount || 0}，金额 ${money(item.totalCents || 0)}`);
      setOverageCandidates((item.items || []).map(candidate => ({ ...candidate, wouldCreate: dryRun ? true : candidate.wouldCreate })));
      if (!dryRun) {
        Taro.showToast({ title: '已生成', icon: 'success' });
        reload(status);
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '超额账单处理失败');
    } finally {
      setBusy('');
    }
  }

  async function submitOverdueProcess(dryRun: boolean) {
    setError('');
    const ok = dryRun
      ? true
      : await confirm('处理逾期账单', '确认扫描已过期未结清的平台服务费账单，并生成内部催缴记录？该动作不会自动停用租户。');
    if (!ok) return;
    setBusy(dryRun ? 'overdue-dry-run' : 'overdue-process');
    try {
      const payload = await processPlatformOverdueInvoices({
        dryRun,
        channel: 'internal',
        limit: 100,
      });
      const item = payload.item || {};
      setBatchResult(`${dryRun ? '逾期预览' : '逾期处理'}完成：处理 ${item.processed || 0}，标记 ${item.markedOverdue || 0}，催缴 ${item.reminderCreated || 0}，跳过 ${item.skippedReminder || 0}`);
      if (!dryRun) {
        Taro.showToast({ title: '已处理', icon: 'success' });
        reload(status);
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '逾期处理失败');
    } finally {
      setBusy('');
    }
  }

  return (
    <View className='platform-page'>
      <View className='platform-shell'>
        <View className='platform-header'>
          <Text className='platform-kicker'>Billing</Text>
          <Text className='platform-title'>账务中心</Text>
          <Text className='platform-subtitle'>平台 SaaS 套餐、租户服务费账单、收款状态和近期待计费用量。</Text>
        </View>

        <View className='platform-tabs'>
          {[
            { label: '全部', value: '' },
            { label: 'issued', value: 'issued' },
            { label: 'overdue', value: 'overdue' },
            { label: 'paid', value: 'paid' },
          ].map(item => (
            <Button key={item.label} className={`platform-button ${status === item.value ? 'active' : ''}`} onClick={() => chooseStatus(item.value)}>{item.label}</Button>
          ))}
        </View>

        <View className='platform-grid'>
          <View className='platform-metric'><Text className='platform-metric-label'>套餐数</Text><Text className='platform-metric-value'>{String(plans.length)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>未收余额</Text><Text className='platform-metric-value'>{money(unpaidCents)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>已收金额</Text><Text className='platform-metric-value'>{money(paidCents)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>用量记录</Text><Text className='platform-metric-value'>{String(usage.length)}</Text></View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>订阅与账单操作</Text>
          <View className='platform-form compact'>
            <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' placeholder='tenantId' value={subscriptionForm.tenantId} onInput={event => updateSubscriptionForm('tenantId', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>套餐编码</Text><Input className='platform-input' placeholder={plans[0]?.code || 'plan_code'} value={subscriptionForm.planCode} onInput={event => updateSubscriptionForm('planCode', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>订阅状态</Text><Input className='platform-input' placeholder='active / trial' value={subscriptionForm.status} onInput={event => updateSubscriptionForm('status', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>订阅金额</Text><Input className='platform-input' placeholder='元，可留空用套餐价' type='digit' value={subscriptionForm.amountYuan} onInput={event => updateSubscriptionForm('amountYuan', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'subscription'} onClick={submitSubscription}>开通订阅</Button>
          </View>

          <View className='platform-form compact'>
            <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' placeholder='tenantId' value={invoiceForm.tenantId} onInput={event => updateInvoiceForm('tenantId', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>到期日</Text><Input className='platform-input' placeholder='YYYY-MM-DD' value={invoiceForm.dueDate} onInput={event => updateInvoiceForm('dueDate', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>备注</Text><Input className='platform-input' placeholder='账单说明，可选' value={invoiceForm.note} onInput={event => updateInvoiceForm('note', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'invoice'} onClick={submitInvoiceFromSubscription}>生成订阅账单</Button>
          </View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>收款与用量</Text>
          <View className='platform-form compact'>
            <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' placeholder='tenantId' value={paymentForm.tenantId} onInput={event => updatePaymentForm('tenantId', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>账单 ID</Text><Input className='platform-input' placeholder='invoiceId' value={paymentForm.invoiceId} onInput={event => updatePaymentForm('invoiceId', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>收款金额</Text><Input className='platform-input' placeholder='元' type='digit' value={paymentForm.amountYuan} onInput={event => updatePaymentForm('amountYuan', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>流水号</Text><Input className='platform-input' placeholder='可选' value={paymentForm.providerTradeNo} onInput={event => updatePaymentForm('providerTradeNo', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'payment'} onClick={submitPaymentConfirm}>确认收款</Button>
          </View>

          <View className='platform-form compact'>
            <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' placeholder='tenantId' value={usageForm.tenantId} onInput={event => updateUsageForm('tenantId', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>指标</Text><Input className='platform-input' placeholder='students / questions / storage_gb' value={usageForm.metricKey} onInput={event => updateUsageForm('metricKey', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>数值</Text><Input className='platform-input' placeholder='0' type='digit' value={usageForm.metricValue} onInput={event => updateUsageForm('metricValue', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>开始</Text><Input className='platform-input' placeholder='YYYY-MM-DD' value={usageForm.periodStart} onInput={event => updateUsageForm('periodStart', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>结束</Text><Input className='platform-input' placeholder='YYYY-MM-DD' value={usageForm.periodEnd} onInput={event => updateUsageForm('periodEnd', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'usage'} onClick={submitUsageRecord}>记录用量</Button>
          </View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>批量订阅账单</Text>
          <View className='platform-form compact'>
            <View className='platform-field'><Text className='platform-field-label'>候选天数</Text><Input className='platform-input' placeholder='45' type='number' value={batchInvoiceForm.daysAhead} onInput={event => updateBatchInvoiceForm('daysAhead', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>到期日</Text><Input className='platform-input' placeholder='YYYY-MM-DD，可选' value={batchInvoiceForm.dueDate} onInput={event => updateBatchInvoiceForm('dueDate', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>批量备注</Text><Input className='platform-input' placeholder='账单说明，可选' value={batchInvoiceForm.note} onInput={event => updateBatchInvoiceForm('note', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button' loading={busy === 'candidates'} onClick={loadSubscriptionCandidates}>刷新候选</Button>
            <Button className='platform-button' loading={busy === 'batch-dry-run'} onClick={() => submitBatchInvoices(true)}>预览批量</Button>
            <Button className='platform-button primary' loading={busy === 'batch-create'} onClick={() => submitBatchInvoices(false)}>批量生成账单</Button>
          </View>
          {batchResult ? <Text className='platform-row-meta'>{batchResult}</Text> : null}
          <View className='platform-list'>
            {candidates.slice(0, 12).map(item => (
              <View className='platform-row' key={item.subscriptionId}>
                <Text className='platform-row-main'>{item.tenantName || item.tenantSlug || item.tenantId}</Text>
                <Text className='platform-row-meta'>{item.planName || item.planCode || 'plan'} · {item.status || '-'} · {money(item.amountCents)} · 到期 {String(item.expiresAt || '').slice(0, 10) || '-'}</Text>
                <Text className='platform-row-meta'>{item.hasExistingInvoice ? `已有账单 ${item.existingInvoiceNo || item.existingInvoiceId}` : item.wouldCreate ? '预览会生成' : '可生成订阅服务费账单'}</Text>
              </View>
            ))}
          </View>
          {!candidates.length ? <View className='platform-empty'>暂无即将到期且未开票的订阅。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>用量超额账单</Text>
          <View className='platform-form compact'>
            <View className='platform-field'><Text className='platform-field-label'>账期开始</Text><Input className='platform-input' placeholder='YYYY-MM-DD' value={overageForm.periodStart} onInput={event => updateOverageForm('periodStart', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>账期结束</Text><Input className='platform-input' placeholder='YYYY-MM-DD' value={overageForm.periodEnd} onInput={event => updateOverageForm('periodEnd', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>到期日</Text><Input className='platform-input' placeholder='YYYY-MM-DD，可选' value={overageForm.dueDate} onInput={event => updateOverageForm('dueDate', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>备注</Text><Input className='platform-input' placeholder='超额服务费说明，可选' value={overageForm.note} onInput={event => updateOverageForm('note', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button' loading={busy === 'overage-candidates'} onClick={loadUsageOverageCandidates}>刷新超额候选</Button>
            <Button className='platform-button' loading={busy === 'overage-dry-run'} onClick={() => submitUsageOverageInvoices(true)}>预览超额</Button>
            <Button className='platform-button primary' loading={busy === 'overage-create'} onClick={() => submitUsageOverageInvoices(false)}>生成超额账单</Button>
          </View>
          <View className='platform-list'>
            {overageCandidates.slice(0, 12).map(item => (
              <View className='platform-row' key={`${item.tenantId}-${item.periodStart}-${item.periodEnd}`}>
                <Text className='platform-row-main'>{item.tenantName || item.tenantSlug || item.tenantId}</Text>
                <Text className='platform-row-meta'>{item.planName || item.planCode || 'plan'} · {item.periodStart || '-'} 至 {item.periodEnd || '-'} · {money(item.totalCents)}</Text>
                {(item.items || []).map(overage => (
                  <Text className='platform-row-meta' key={`${item.tenantId}-${overage.description}`}>{overage.description || '超额项'} · {String(overage.quantity || 0)} × {money(overage.unitAmountCents)}</Text>
                ))}
                <Text className='platform-row-meta'>{item.hasExistingInvoice ? `已有超额账单 ${item.existingInvoiceNo || item.existingInvoiceId}` : item.wouldCreate ? '预览会生成超额账单' : '可生成超额账单'}</Text>
              </View>
            ))}
          </View>
          {!overageCandidates.length ? <View className='platform-empty'>当前账期暂无超过套餐额度的租户。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>逾期与催缴</Text>
          <View className='platform-actions'>
            <Button className='platform-button' loading={busy === 'overdue-dry-run'} onClick={() => submitOverdueProcess(true)}>预览逾期</Button>
            <Button className='platform-button primary' loading={busy === 'overdue-process'} onClick={() => submitOverdueProcess(false)}>生成催缴</Button>
          </View>
          <View className='platform-list'>
            {reminders.slice(0, 12).map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.invoiceNo || item.invoiceId}</Text>
                <Text className='platform-row-meta'>{item.tenantName || item.tenantSlug || item.tenantId} · {item.reminderType || 'reminder'} · {item.channel || 'internal'} · {item.status || '-'}</Text>
                <Text className='platform-row-meta'>第 {String(item.reminderLevel || 1)} 次 · 账单到期 {item.dueDate ? String(item.dueDate).slice(0, 10) : '-'} · 快照余额 {money(item.balanceCentsSnapshot)}</Text>
                <Text className='platform-row-meta'>{item.message || '暂无催缴备注'}</Text>
              </View>
            ))}
          </View>
          {!reminders.length ? <View className='platform-empty'>暂无催缴记录。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>SaaS 套餐</Text>
          <View className='platform-list'>
            {plans.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.name}</Text>
                <Text className='platform-row-meta'>{item.code} · {item.billingCycle || 'cycle'} · {money(item.baseAmountCents, item.currency || 'CNY')} · {item.status || 'active'}</Text>
                <Text className='platform-row-meta'>{item.description || '暂无说明'}</Text>
              </View>
            ))}
          </View>
          {!plans.length ? <View className='platform-empty'>暂无套餐配置。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>服务费账单</Text>
          <View className='platform-list'>
            {invoices.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.invoiceNo || item.id}</Text>
                <Text className='platform-row-meta'>{item.tenantName || item.tenantSlug || item.tenantId} · {item.invoiceType || 'invoice'} · {item.status || '-'}</Text>
                <Text className='platform-row-meta'>总额 {money(item.totalCents, item.currency || 'CNY')} · 已收 {money(item.paidCents, item.currency || 'CNY')} · 余额 {money(item.balanceCents, item.currency || 'CNY')}</Text>
                <Text className='platform-row-meta'>到期 {item.dueDate ? String(item.dueDate).slice(0, 10) : '-'}</Text>
                <View className='platform-row-actions'>
                  <Button className='platform-mini-button' onClick={() => {
                    setPaymentForm(current => ({
                      ...current,
                      tenantId: item.tenantId,
                      invoiceId: item.id,
                      amountYuan: Number(item.balanceCents || 0) > 0 ? String(Number(item.balanceCents || 0) / 100) : current.amountYuan,
                    }));
                    setInvoiceForm(current => ({ ...current, tenantId: item.tenantId }));
                    setSubscriptionForm(current => ({ ...current, tenantId: item.tenantId }));
                    setUsageForm(current => ({ ...current, tenantId: item.tenantId }));
                  }}>选择</Button>
                </View>
              </View>
            ))}
          </View>
          {!invoices.length ? <View className='platform-empty'>暂无账单。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>近期待计费用量</Text>
          <View className='platform-list'>
            {usage.slice(0, 12).map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.tenantName || item.tenantSlug || item.tenantId}</Text>
                <Text className='platform-row-meta'>{item.metricKey || 'metric'} · {String(item.metricValue || 0)} · {String(item.periodStart || '').slice(0, 10)} 至 {String(item.periodEnd || '').slice(0, 10)}</Text>
              </View>
            ))}
          </View>
        </View>
        {error ? <Text className='platform-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
