import { useEffect, useMemo, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import {
  createAdjustmentVoucher,
  createReconciliationIssue,
  createTenantRefund,
  loadAdjustmentVoucherReport,
  loadAdjustmentVouchers,
  loadCommerceOperationAnomalies,
  loadProviderBillJobs,
  loadReconciliationBatches,
  loadReconciliationIssues,
  loadReconciliationItems,
  loadTenantRefunds,
  requestProviderBillDownload,
  updateAdjustmentVoucherStatus,
  updateReconciliationIssueStatus,
  updateTenantRefundStatus,
  type AdjustmentVoucherItem,
  type AdjustmentVoucherReport,
  type CommerceOperationAnomaly,
  type ProviderBillJobItem,
  type ReconciliationBatchItem,
  type ReconciliationIssueItem,
  type ReconciliationItem,
  type TenantRefundItem,
} from '@/services/tenantFinance';
import '../admin.css';

type ProviderFilter = '' | 'wechat_pay' | 'alipay';

function money(cents: unknown) {
  return `¥${(Number(cents || 0) / 100).toFixed(2)}`;
}

function yuanToCents(value: string) {
  const parsed = Number(value || 0);
  return Number.isFinite(parsed) ? Math.max(0, Math.round(parsed * 100)) : 0;
}

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

function monthStart() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;
}

function statusText(value: unknown) {
  return String(value || '-').replace(/_/g, ' ');
}

function firstNonEmpty(...values: Array<unknown>) {
  for (const value of values) {
    if (value !== undefined && value !== null && String(value).trim()) return String(value);
  }
  return '-';
}

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

export default function TenantFinancePage() {
  const [provider, setProvider] = useState<ProviderFilter>('');
  const [billDate, setBillDate] = useState(today());
  const [billType, setBillType] = useState<'payment' | 'refund' | 'combined'>('combined');
  const [refundStatus, setRefundStatus] = useState('');
  const [issueStatus, setIssueStatus] = useState('');
  const [voucherStatus, setVoucherStatus] = useState('');
  const [selectedBatchId, setSelectedBatchId] = useState('');
  const [selectedItemId, setSelectedItemId] = useState('');
  const [selectedIssueId, setSelectedIssueId] = useState('');
  const [selectedRefundId, setSelectedRefundId] = useState('');
  const [selectedVoucherId, setSelectedVoucherId] = useState('');
  const [reportRange, setReportRange] = useState({ startDate: monthStart(), endDate: today() });
  const [refundForm, setRefundForm] = useState({
    orderNo: '',
    amountYuan: '',
    reason: '用户申请退款',
    providerNotifyUrl: '',
    note: '',
  });
  const [voucherForm, setVoucherForm] = useState({
    title: '',
    amountYuan: '',
    adjustmentType: 'manual_payment_confirm',
    direction: 'none',
    externalUrl: '',
    note: '',
    reviewNote: '',
  });
  const [anomalies, setAnomalies] = useState<CommerceOperationAnomaly[]>([]);
  const [anomalySummary, setAnomalySummary] = useState<Record<string, unknown>>({});
  const [refunds, setRefunds] = useState<TenantRefundItem[]>([]);
  const [billJobs, setBillJobs] = useState<ProviderBillJobItem[]>([]);
  const [batches, setBatches] = useState<ReconciliationBatchItem[]>([]);
  const [items, setItems] = useState<ReconciliationItem[]>([]);
  const [issues, setIssues] = useState<ReconciliationIssueItem[]>([]);
  const [vouchers, setVouchers] = useState<AdjustmentVoucherItem[]>([]);
  const [voucherReport, setVoucherReport] = useState<AdjustmentVoucherReport | null>(null);
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  const selectedIssue = useMemo(() => issues.find(item => item.id === selectedIssueId) || null, [issues, selectedIssueId]);
  const selectedVoucher = useMemo(() => vouchers.find(item => item.id === selectedVoucherId) || null, [vouchers, selectedVoucherId]);

  async function reloadAll() {
    setBusy('reload');
    setError('');
    try {
      const [
        anomalyPayload,
        refundPayload,
        jobPayload,
        batchPayload,
        itemPayload,
        issuePayload,
        voucherPayload,
        reportPayload,
      ] = await Promise.all([
        loadCommerceOperationAnomalies({ provider: provider || undefined, limit: 40 }).catch(() => ({ items: [], summary: {} })),
        loadTenantRefunds({ status: refundStatus || undefined, limit: 40 }).catch(() => ({ items: [] })),
        loadProviderBillJobs({ provider: provider || undefined, billDate: billDate || undefined, limit: 30 }).catch(() => ({ items: [] })),
        loadReconciliationBatches({ provider: provider || undefined, billDate: billDate || undefined, limit: 30 }).catch(() => ({ items: [] })),
        loadReconciliationItems({
          batchId: selectedBatchId || undefined,
          matchStatus: selectedBatchId ? undefined : 'amount_mismatch',
          limit: 60,
        }).catch(() => ({ items: [] })),
        loadReconciliationIssues({ status: issueStatus || undefined, limit: 40 }).catch(() => ({ items: [] })),
        loadAdjustmentVouchers({ status: voucherStatus || undefined, limit: 40 }).catch(() => ({ items: [] })),
        loadAdjustmentVoucherReport(reportRange).catch(() => ({ item: null })),
      ]);
      setAnomalies(anomalyPayload.items || []);
      setAnomalySummary(anomalyPayload.summary || {});
      setRefunds(refundPayload.items || []);
      setBillJobs(jobPayload.items || []);
      setBatches(batchPayload.items || []);
      setItems(itemPayload.items || []);
      setIssues(issuePayload.items || []);
      setVouchers(voucherPayload.items || []);
      setVoucherReport(reportPayload.item || null);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '财务运营数据加载失败');
    } finally {
      setBusy('');
    }
  }

  useEffect(() => {
    void reloadAll();
  }, []);

  async function reloadBatches(nextBatchId = selectedBatchId) {
    setBusy('reconciliation');
    setError('');
    try {
      const [batchPayload, itemPayload] = await Promise.all([
        loadReconciliationBatches({ provider: provider || undefined, billDate: billDate || undefined, limit: 50 }),
        loadReconciliationItems({ batchId: nextBatchId || undefined, matchStatus: nextBatchId ? undefined : 'amount_mismatch', limit: 80 }),
      ]);
      setBatches(batchPayload.items || []);
      setItems(itemPayload.items || []);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '对账数据加载失败');
    } finally {
      setBusy('');
    }
  }

  async function requestProviderBill() {
    if (!provider) {
      Taro.showToast({ title: '请选择微信或支付宝', icon: 'none' });
      return;
    }
    if (!billDate) {
      Taro.showToast({ title: '请填写账单日期', icon: 'none' });
      return;
    }
    const confirmed = await confirmAction('创建官方账单任务', `${provider} ${billDate} ${billType}，任务由后端 worker 下载并导入对账。`);
    if (!confirmed) return;
    setBusy('provider-bill');
    setError('');
    try {
      await requestProviderBillDownload({
        provider,
        billDate,
        billType,
        metadata: { source: 'taro-tenant-finance' },
      });
      Taro.showToast({ title: '账单任务已创建', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '官方账单任务创建失败');
    } finally {
      setBusy('');
    }
  }

  async function submitRefund() {
    if (!refundForm.orderNo.trim()) {
      Taro.showToast({ title: '请填写订单号', icon: 'none' });
      return;
    }
    const amountCents = yuanToCents(refundForm.amountYuan);
    const confirmed = await confirmAction('创建退款申请', `${refundForm.orderNo} · ${amountCents ? money(amountCents) : '剩余可退金额'} · 退款成功后可按规则撤销权益`, '创建');
    if (!confirmed) return;
    setBusy('refund-create');
    setError('');
    try {
      const payload = await createTenantRefund({
        orderNo: refundForm.orderNo.trim(),
        amountCents: amountCents || undefined,
        reason: refundForm.reason.trim() || null,
        entitlementAction: 'revoke_on_success',
        metadata: { source: 'taro-tenant-finance' },
      });
      setSelectedRefundId(payload.item?.id || selectedRefundId);
      Taro.showToast({ title: '退款申请已创建', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '退款申请失败');
    } finally {
      setBusy('');
    }
  }

  async function updateRefund(item: TenantRefundItem, action: string) {
    const labels: Record<string, string> = {
      approve: '审核通过',
      reject: '驳回',
      submit_provider_refund: '提交供应商退款',
      query_provider_refund: '查询供应商退款',
      mark_succeeded: '手工标记成功',
      mark_failed: '手工标记失败',
      cancel: '取消',
    };
    const confirmed = await confirmAction(labels[action] || '更新退款', `${item.refundNo || item.id} · ${item.orderNo || '-'} · ${money(item.amountCents)}`, labels[action] || '确认');
    if (!confirmed) return;
    setBusy(`refund:${item.id}:${action}`);
    setError('');
    try {
      await updateTenantRefundStatus({
        refundId: item.id,
        action,
        note: refundForm.note || `${labels[action] || action} by Taro`,
        providerNotifyUrl: action === 'submit_provider_refund' ? refundForm.providerNotifyUrl || null : undefined,
        metadata: { source: 'taro-tenant-finance' },
      });
      Taro.showToast({ title: '退款状态已更新', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '退款状态更新失败');
    } finally {
      setBusy('');
    }
  }

  async function createIssue(item: ReconciliationItem) {
    const confirmed = await confirmAction('创建差错工单', `${item.orderNo || item.refundNo || item.id} · ${item.matchStatus || '-'} · ${item.issueCode || '-'}`, '创建');
    if (!confirmed) return;
    setBusy(`issue-create:${item.id}`);
    setError('');
    try {
      const payload = await createReconciliationIssue({
        itemId: item.id,
        summary: `${item.issueCode || item.matchStatus || '对账异常'} ${item.orderNo || item.refundNo || ''}`.trim(),
        note: 'Taro 财务运营台创建',
        metadata: { source: 'taro-tenant-finance' },
      });
      setSelectedIssueId(payload.item?.id || selectedIssueId);
      Taro.showToast({ title: payload.idempotent ? '已有工单' : '工单已创建', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '差错工单创建失败');
    } finally {
      setBusy('');
    }
  }

  async function updateIssue(item: ReconciliationIssueItem, action: 'start' | 'resolve' | 'ignore' | 'escalate' | 'reopen') {
    const labels: Record<string, string> = {
      start: '开始处理',
      resolve: '解决工单',
      ignore: '忽略工单',
      escalate: '升级工单',
      reopen: '重开工单',
    };
    const confirmed = await confirmAction(labels[action], `${item.issueNo || item.id} · ${item.summary || item.issueCode || '-'}`, labels[action]);
    if (!confirmed) return;
    setBusy(`issue:${item.id}:${action}`);
    setError('');
    try {
      await updateReconciliationIssueStatus({
        issueId: item.id,
        action,
        resolutionType: action === 'resolve' ? 'manual_adjustment' : action === 'ignore' ? 'false_positive' : undefined,
        note: `${labels[action]} by Taro`,
        metadata: { source: 'taro-tenant-finance' },
      });
      Taro.showToast({ title: '工单已更新', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '工单更新失败');
    } finally {
      setBusy('');
    }
  }

  async function submitVoucher() {
    const amountCents = yuanToCents(voucherForm.amountYuan);
    const source = selectedIssue
      ? { reconciliationIssueId: selectedIssue.id }
      : selectedItemId
        ? { reconciliationItemId: selectedItemId }
        : refundForm.orderNo.trim()
          ? { orderNo: refundForm.orderNo.trim() }
          : { sourceType: 'manual' };
    const confirmed = await confirmAction('提交调整凭证', `${voucherForm.title || '财务调整凭证'} · ${money(amountCents)}`, '提交');
    if (!confirmed) return;
    setBusy('voucher-create');
    setError('');
    try {
      const payload = await createAdjustmentVoucher({
        ...source,
        adjustmentType: voucherForm.adjustmentType,
        direction: voucherForm.direction,
        amountCents,
        status: 'submitted',
        title: voucherForm.title.trim() || null,
        description: voucherForm.note.trim() || null,
        externalUrl: voucherForm.externalUrl.trim() || null,
        note: 'Taro 财务运营台提交',
        metadata: { source: 'taro-tenant-finance' },
      });
      setSelectedVoucherId(payload.item?.id || selectedVoucherId);
      Taro.showToast({ title: '调整凭证已提交', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '调整凭证提交失败');
    } finally {
      setBusy('');
    }
  }

  async function updateVoucher(item: AdjustmentVoucherItem, status: 'approved' | 'rejected' | 'voided') {
    const labels = { approved: '审批通过', rejected: '驳回', voided: '作废' };
    const confirmed = await confirmAction(labels[status], `${item.voucherNo || item.id} · ${money(item.amountCents)} · 审批不会直接修改订单/支付/权益`, labels[status]);
    if (!confirmed) return;
    setBusy(`voucher:${item.id}:${status}`);
    setError('');
    try {
      await updateAdjustmentVoucherStatus({
        voucherId: item.id,
        status,
        reviewNote: voucherForm.reviewNote || `${labels[status]} by Taro`,
        metadata: { source: 'taro-tenant-finance' },
      });
      Taro.showToast({ title: '凭证状态已更新', icon: 'success' });
      await reloadAll();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '凭证状态更新失败');
    } finally {
      setBusy('');
    }
  }

  return (
    <View className='admin-page'>
      <View className='admin-shell'>
        <View className='admin-header'>
          <Text className='admin-kicker'>Finance Ops</Text>
          <Text className='admin-title'>财务运营</Text>
          <Text className='admin-subtitle'>退款、官方账单、资金对账、差错工单和人工调整凭证统一在这里处理。</Text>
        </View>

        <View className='admin-actions compact'>
          {[
            { value: '', label: '全部渠道' },
            { value: 'wechat_pay', label: '微信支付' },
            { value: 'alipay', label: '支付宝' },
          ].map(item => (
            <Button key={item.value || 'all'} className={`admin-button ${provider === item.value ? 'active' : ''}`} onClick={() => setProvider(item.value as ProviderFilter)}>
              {item.label}
            </Button>
          ))}
          <Button className='admin-button primary' loading={busy === 'reload'} onClick={reloadAll}>刷新</Button>
        </View>

        <View className='admin-grid'>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>异常总数</Text>
            <Text className='admin-metric-value'>{String(anomalySummary.total || anomalies.length || 0)}</Text>
          </View>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>待退款</Text>
            <Text className='admin-metric-value'>{String(refunds.filter(item => ['requested', 'approved', 'processing'].includes(String(item.status))).length)}</Text>
          </View>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>差错工单</Text>
            <Text className='admin-metric-value'>{String(issues.filter(item => !['resolved', 'ignored'].includes(String(item.status))).length)}</Text>
          </View>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>待复核凭证</Text>
            <Text className='admin-metric-value'>{String(voucherReport?.pendingReviewCount || 0)}</Text>
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>异常订单运营台</Text>
          <View className='admin-list'>
            {anomalies.slice(0, 12).map(item => (
              <View className='admin-row' key={`${item.type}:${item.id}`}>
                <Text className='admin-row-main'>{item.title || item.type || '异常事件'}</Text>
                <Text className='admin-row-meta'>{statusText(item.severity)} · {statusText(item.status)} · {firstNonEmpty(item.provider, '未知渠道')} · {money(item.amountCents)}</Text>
                <Text className='admin-row-meta'>订单 {firstNonEmpty(item.orderNo)} · 退款 {firstNonEmpty(item.refundNo)} · {firstNonEmpty(item.updatedAt, item.createdAt)}</Text>
              </View>
            ))}
          </View>
          {!anomalies.length ? <View className='admin-empty'>暂无需要处理的支付/对账/退款异常。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>退款状态机</Text>
          <View className='admin-form-grid'>
            <Input className='admin-input' placeholder='订单号，用于创建退款申请或筛选关联凭证' value={refundForm.orderNo} onInput={event => setRefundForm(prev => ({ ...prev, orderNo: String(event.detail.value || '') }))} />
            <Input className='admin-input' type='digit' placeholder='退款金额，单位元；留空则退剩余可退金额' value={refundForm.amountYuan} onInput={event => setRefundForm(prev => ({ ...prev, amountYuan: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='退款原因' value={refundForm.reason} onInput={event => setRefundForm(prev => ({ ...prev, reason: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='供应商退款通知 URL，可选' value={refundForm.providerNotifyUrl} onInput={event => setRefundForm(prev => ({ ...prev, providerNotifyUrl: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='退款审核/处理备注' value={refundForm.note} onInput={event => setRefundForm(prev => ({ ...prev, note: String(event.detail.value || '') }))} />
          </View>
          <View className='admin-actions compact'>
            {['', 'requested', 'approved', 'processing', 'succeeded', 'failed', 'rejected', 'cancelled'].map(status => (
              <Button key={status || 'all'} className={`admin-button ${refundStatus === status ? 'active' : ''}`} onClick={() => setRefundStatus(status)}>{status || '全部退款'}</Button>
            ))}
            <Button className='admin-button primary' loading={busy === 'refund-create'} onClick={submitRefund}>创建退款</Button>
          </View>
          <View className='admin-list'>
            {refunds.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.refundNo || item.id} · {statusText(item.status)} · {money(item.amountCents)}</Text>
                <Text className='admin-row-meta'>{item.orderNo || '-'} · {item.provider || item.paymentProvider || '-'} · {item.reason || '-'}</Text>
                <Text className='admin-row-meta'>申请 {firstNonEmpty(item.requestedAt, item.createdAt)} · 成功 {firstNonEmpty(item.succeededAt)} · 失败 {firstNonEmpty(item.failureReason)}</Text>
                <View className='admin-row-actions'>
                  <Button className={`admin-mini-button ${selectedRefundId === item.id ? 'primary' : ''}`} onClick={() => setSelectedRefundId(item.id)}>选择</Button>
                  {item.status === 'requested' ? <Button className='admin-mini-button primary' loading={busy === `refund:${item.id}:approve`} onClick={() => updateRefund(item, 'approve')}>审核通过</Button> : null}
                  {['requested', 'approved'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `refund:${item.id}:reject`} onClick={() => updateRefund(item, 'reject')}>驳回</Button> : null}
                  {item.status === 'approved' ? <Button className='admin-mini-button primary' loading={busy === `refund:${item.id}:submit_provider_refund`} onClick={() => updateRefund(item, 'submit_provider_refund')}>提交供应商</Button> : null}
                  {item.status === 'processing' ? <Button className='admin-mini-button primary' loading={busy === `refund:${item.id}:query_provider_refund`} onClick={() => updateRefund(item, 'query_provider_refund')}>查询供应商</Button> : null}
                  {['requested', 'approved', 'processing'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `refund:${item.id}:mark_succeeded`} onClick={() => updateRefund(item, 'mark_succeeded')}>手工成功</Button> : null}
                  {['approved', 'processing'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `refund:${item.id}:mark_failed`} onClick={() => updateRefund(item, 'mark_failed')}>手工失败</Button> : null}
                </View>
              </View>
            ))}
          </View>
          {!refunds.length ? <View className='admin-empty'>暂无退款记录，或当前角色缺少 `tenant:refund:read` 权限。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>官方账单下载</Text>
          <View className='admin-form-grid'>
            <Input className='admin-input' placeholder='账单日期 YYYY-MM-DD' value={billDate} onInput={event => setBillDate(String(event.detail.value || ''))} />
          </View>
          <View className='admin-actions compact'>
            {(['combined', 'payment', 'refund'] as const).map(item => (
              <Button key={item} className={`admin-button ${billType === item ? 'active' : ''}`} onClick={() => setBillType(item)}>{item}</Button>
            ))}
            <Button className='admin-button primary' loading={busy === 'provider-bill'} onClick={requestProviderBill}>创建下载任务</Button>
            <Button className='admin-button' loading={busy === 'reconciliation'} onClick={() => reloadBatches()}>刷新对账</Button>
          </View>
          <View className='admin-list'>
            {billJobs.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.provider || '-'} · {item.billDate || '-'} · {statusText(item.status)}</Text>
                <Text className='admin-row-meta'>类型 {item.billType || 'combined'} · 行数 {item.rowCount || 0} · 下载域 {item.downloadUrlHost || '未返回'}</Text>
                <Text className='admin-row-meta break-line'>hash {item.downloadHashType || '-'}:{item.downloadHashValue || '-'} · 批次 {item.reconciliationBatchId || '-'}</Text>
                {item.errorMessage ? <Text className='admin-error'>{item.errorCode || 'FAILED'} · {item.errorMessage}</Text> : null}
              </View>
            ))}
          </View>
          {!billJobs.length ? <View className='admin-empty'>暂无官方账单任务。任务创建后由 provider-bills worker 下载和导入，前端不会拿到供应商下载 URL 或密钥。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>对账批次</Text>
          <View className='admin-list'>
            {batches.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.provider || '-'} · {item.billDate || '-'} · {statusText(item.status)}</Text>
                <Text className='admin-row-meta'>总 {item.totalCount || 0} · 匹配 {item.matchedCount || 0} · 金额/状态差异 {item.mismatchCount || 0} · 供应商缺失 {item.missingProviderCount || 0} · 本地缺失 {item.missingLocalCount || 0}</Text>
                <Text className='admin-row-meta'>收入 {money(item.amountCents)} · 退款 {money(item.refundAmountCents)} · 手续费 {money(item.feeCents)}</Text>
                <View className='admin-row-actions'>
                  <Button
                    className={`admin-mini-button ${selectedBatchId === item.id ? 'primary' : ''}`}
                    loading={busy === 'reconciliation'}
                    onClick={() => {
                      const nextId = selectedBatchId === item.id ? '' : item.id;
                      setSelectedBatchId(nextId);
                      void reloadBatches(nextId);
                    }}
                  >
                    {selectedBatchId === item.id ? '取消筛选' : '查看明细'}
                  </Button>
                </View>
              </View>
            ))}
          </View>
          {!batches.length ? <View className='admin-empty'>暂无对账批次。可以先创建官方账单任务，或后续从文件导入账单。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>异常明细</Text>
          <View className='admin-list'>
            {items.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.orderNo || item.refundNo || item.providerTradeNo || item.id} · {statusText(item.matchStatus)}</Text>
                <Text className='admin-row-meta'>{item.transactionType || '-'} · {item.issueCode || '-'} · {statusText(item.severity)} · provider {item.providerStatus || '-'} · local {item.localStatus || '-'}</Text>
                <Text className='admin-row-meta'>支付 {money(item.amountCents)} · 退款 {money(item.refundAmountCents)} · row {item.rowNo || '-'}</Text>
                <View className='admin-row-actions'>
                  <Button className={`admin-mini-button ${selectedItemId === item.id ? 'primary' : ''}`} onClick={() => setSelectedItemId(selectedItemId === item.id ? '' : item.id)}>选择明细</Button>
                  {!['matched', 'ignored'].includes(String(item.matchStatus)) ? <Button className='admin-mini-button primary' loading={busy === `issue-create:${item.id}`} onClick={() => createIssue(item)}>创建工单</Button> : null}
                </View>
              </View>
            ))}
          </View>
          {!items.length ? <View className='admin-empty'>当前筛选下暂无异常明细。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>差错工单</Text>
          <View className='admin-actions compact'>
            {['', 'open', 'investigating', 'escalated', 'resolved', 'ignored'].map(status => (
              <Button key={status || 'all'} className={`admin-button ${issueStatus === status ? 'active' : ''}`} onClick={() => setIssueStatus(status)}>{status || '全部工单'}</Button>
            ))}
          </View>
          <View className='admin-list'>
            {issues.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.issueNo || item.id} · {statusText(item.status)} · {statusText(item.severity)}</Text>
                <Text className='admin-row-meta'>{item.summary || item.issueCode || '-'} · 订单 {firstNonEmpty(item.orderNo)} · 退款 {firstNonEmpty(item.refundNo)}</Text>
                <Text className='admin-row-meta'>处理人 {firstNonEmpty(item.assignedToName, item.assignedTo)} · 结论 {statusText(item.resolutionType)}</Text>
                <View className='admin-row-actions'>
                  <Button className={`admin-mini-button ${selectedIssueId === item.id ? 'primary' : ''}`} onClick={() => setSelectedIssueId(selectedIssueId === item.id ? '' : item.id)}>选择工单</Button>
                  {['open', 'escalated'].includes(String(item.status)) ? <Button className='admin-mini-button primary' loading={busy === `issue:${item.id}:start`} onClick={() => updateIssue(item, 'start')}>开始</Button> : null}
                  {!['resolved', 'ignored'].includes(String(item.status)) ? <Button className='admin-mini-button primary' loading={busy === `issue:${item.id}:resolve`} onClick={() => updateIssue(item, 'resolve')}>解决</Button> : null}
                  {!['resolved', 'ignored'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `issue:${item.id}:ignore`} onClick={() => updateIssue(item, 'ignore')}>忽略</Button> : null}
                  {!['resolved', 'ignored'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `issue:${item.id}:escalate`} onClick={() => updateIssue(item, 'escalate')}>升级</Button> : null}
                  {['resolved', 'ignored'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `issue:${item.id}:reopen`} onClick={() => updateIssue(item, 'reopen')}>重开</Button> : null}
                </View>
              </View>
            ))}
          </View>
          {!issues.length ? <View className='admin-empty'>暂无差错工单。</View> : null}
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>人工调整凭证</Text>
          <View className='admin-form-grid'>
            <Input className='admin-input' placeholder='凭证标题' value={voucherForm.title} onInput={event => setVoucherForm(prev => ({ ...prev, title: String(event.detail.value || '') }))} />
            <Input className='admin-input' type='digit' placeholder='调整金额，单位元' value={voucherForm.amountYuan} onInput={event => setVoucherForm(prev => ({ ...prev, amountYuan: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='外部凭证 URL，可选' value={voucherForm.externalUrl} onInput={event => setVoucherForm(prev => ({ ...prev, externalUrl: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='凭证说明' value={voucherForm.note} onInput={event => setVoucherForm(prev => ({ ...prev, note: String(event.detail.value || '') }))} />
            <Input className='admin-input' placeholder='复核备注' value={voucherForm.reviewNote} onInput={event => setVoucherForm(prev => ({ ...prev, reviewNote: String(event.detail.value || '') }))} />
          </View>
          <View className='admin-actions compact'>
            {['manual_payment_confirm', 'refund_correction', 'provider_confirmed', 'local_corrected', 'write_off', 'duplicate', 'other'].map(item => (
              <Button key={item} className={`admin-button ${voucherForm.adjustmentType === item ? 'active' : ''}`} onClick={() => setVoucherForm(prev => ({ ...prev, adjustmentType: item }))}>{item}</Button>
            ))}
          </View>
          <View className='admin-actions compact'>
            {['none', 'increase', 'decrease'].map(item => (
              <Button key={item} className={`admin-button ${voucherForm.direction === item ? 'active' : ''}`} onClick={() => setVoucherForm(prev => ({ ...prev, direction: item }))}>{item}</Button>
            ))}
            <Button className='admin-button primary' loading={busy === 'voucher-create'} onClick={submitVoucher}>提交凭证</Button>
          </View>
          <View className='admin-actions compact'>
            {['', 'draft', 'submitted', 'approved', 'rejected', 'voided'].map(status => (
              <Button key={status || 'all'} className={`admin-button ${voucherStatus === status ? 'active' : ''}`} onClick={() => setVoucherStatus(status)}>{status || '全部凭证'}</Button>
            ))}
            <Input className='admin-input compact' placeholder='报表开始日期' value={reportRange.startDate} onInput={event => setReportRange(prev => ({ ...prev, startDate: String(event.detail.value || '') }))} />
            <Input className='admin-input compact' placeholder='报表结束日期' value={reportRange.endDate} onInput={event => setReportRange(prev => ({ ...prev, endDate: String(event.detail.value || '') }))} />
          </View>
          <View className='admin-grid'>
            <View className='admin-metric'><Text className='admin-metric-label'>凭证数</Text><Text className='admin-metric-value'>{String(voucherReport?.totalCount || 0)}</Text></View>
            <View className='admin-metric'><Text className='admin-metric-label'>凭证金额</Text><Text className='admin-metric-value'>{money(voucherReport?.totalAmountCents)}</Text></View>
          </View>
          <View className='admin-list'>
            {vouchers.map(item => (
              <View className='admin-row' key={item.id}>
                <Text className='admin-row-main'>{item.voucherNo || item.id} · {statusText(item.status)} · {money(item.amountCents)}</Text>
                <Text className='admin-row-meta'>{item.adjustmentType || '-'} · {item.direction || 'none'} · {item.title || '-'}</Text>
                <Text className='admin-row-meta'>来源 {item.sourceType || '-'} · 工单 {item.reconciliationIssueId || '-'} · 订单 {item.orderNo || '-'}</Text>
                {item.externalUrl ? <Text className='admin-row-meta break-line'>{item.externalUrl}</Text> : null}
                <View className='admin-row-actions'>
                  <Button className={`admin-mini-button ${selectedVoucher?.id === item.id ? 'primary' : ''}`} onClick={() => setSelectedVoucherId(selectedVoucherId === item.id ? '' : item.id)}>选择凭证</Button>
                  {item.status === 'submitted' ? <Button className='admin-mini-button primary' loading={busy === `voucher:${item.id}:approved`} onClick={() => updateVoucher(item, 'approved')}>审批通过</Button> : null}
                  {item.status === 'submitted' ? <Button className='admin-mini-button' loading={busy === `voucher:${item.id}:rejected`} onClick={() => updateVoucher(item, 'rejected')}>驳回</Button> : null}
                  {['draft', 'submitted'].includes(String(item.status)) ? <Button className='admin-mini-button' loading={busy === `voucher:${item.id}:voided`} onClick={() => updateVoucher(item, 'voided')}>作废</Button> : null}
                </View>
              </View>
            ))}
          </View>
          {!vouchers.length ? <View className='admin-empty'>暂无人工调整凭证。凭证审批只写财务审计，不直接修改订单、支付、退款或权益。</View> : null}
        </View>

        {error ? <Text className='admin-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
