import React, { useState, useEffect } from 'react';
import { Table, Button, Card, Space, Tag, Modal, Form, Input, InputNumber, Select, DatePicker, message, Descriptions, Image, Divider, AutoComplete, Tabs, Checkbox } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, UndoOutlined, PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useAuthStore } from '../store/authStore';
import FileUpload from '../components/FileUpload';

const { Option } = Select;
const { TextArea } = Input;

interface DetailItem {
  id?: string;
  description: string;
  amount: number;
  category: string;
  attachments?: string[];
}

const VerificationPage: React.FC = () => {
  const { user } = useAuthStore();
  const [records, setRecords] = useState<any[]>([]);
  const [completedRecords, setCompletedRecords] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState('active');
  const [advances, setAdvances] = useState<any[]>([]);
  const [projects, setProjects] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [selectedRecord, setSelectedRecord] = useState<any>(null);
  const [form] = Form.useForm();
  const [currentEditingStatus, setCurrentEditingStatus] = useState<string>('');
  const [detailItems, setDetailItems] = useState<DetailItem[]>([]);
  const [, setExchangeRates] = useState<Record<string, number>>({});
  const [advanceInfo, setAdvanceInfo] = useState<any>(null);

  // 监听明细项变化，自动更新结算金额
  useEffect(() => {
    if (form.getFieldValue('settlement') && advanceInfo) {
      const totalAmount = detailItems.reduce((sum, item) => sum + (item.amount || 0), 0);
      const settlementAmount = advanceInfo.remaining - totalAmount;
      form.setFieldsValue({ settlement_amount: settlementAmount });
    }
  }, [detailItems, form, advanceInfo]);

  useEffect(() => {
    fetchExchangeRates();
    fetchRecords();
    fetchAdvances();
    fetchProjects();
  }, []);

  const fetchExchangeRates = async () => {
    try {
      const res = await fetch("/api/exchange-rates/latest");
      const data = await res.json();
      if (data.success) {
        const rates: Record<string, number> = {};
        Object.keys(data.data).forEach(key => {
          rates[key] = parseFloat(data.data[key]) || 1;
        });
        setExchangeRates(rates);
      }
    } catch (error) {
      console.error('获取汇率失败:', error);
    }
  };

  const fetchRecords = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/verifications');
      const data = await res.json();
      if (data.success) {
        // 解析JSON字符串字段
        const parsedRecords = data.data.map((record: any) => ({
          ...record,
          detail_items: typeof record.detail_items === 'string' ? (JSON.parse(record.detail_items) || []) : (record.detail_items || []),
          attachments: typeof record.attachments === 'string' ? (JSON.parse(record.attachments) || []) : (record.attachments || [])
        }));
        // 分离活跃的和已完结的核销申请
        const active = parsedRecords.filter((item: any) => ['pending', 'approved', 'rejected', 'withdrawn', 'pending_edit'].includes(item.status));
        const completed = parsedRecords.filter((item: any) => ['executed', 'paid'].includes(item.status));
        setRecords(active);
        setCompletedRecords(completed);
      }
    } catch (error) {
      console.error('获取核销列表失败:', error);
      message.error('获取核销列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchAdvances = async () => {
    try {
      const res = await fetch('/api/advances?status=approved');
      const data = await res.json();
      if (data.success) {
        // 确保每个预支单都有total_reimbursed字段
        const processedAdvances = data.data.map((advance: any) => ({
          ...advance,
          total_reimbursed: advance.total_reimbursed || 0
        }));
        setAdvances(processedAdvances);
      }
    } catch (error) {
      console.error('获取预支单失败:', error);
    }
  };

  // 当关联预支单改变时，重新获取预支单信息
  useEffect(() => {
    if (form.getFieldValue('advance_code')) {
      fetchAdvances();
    }
  }, [form.getFieldValue('advance_code')]);

  const fetchProjects = async () => {
    try {
      const res = await fetch('/api/projects');
      const data = await res.json();
      if (data.success) setProjects(data.data);
    } catch (error) {
      console.error('获取项目列表失败:', error);
    }
  };

  const handleCreate = () => {
    setEditingId(null);
    setDetailItems([]);
    form.resetFields();
    form.setFieldsValue({
      verification_date: dayjs(),
      currency: 'CNY',
      expense_type: 'company',
      applicant: user?.name || user?.username || '当前用户',
      attachments: []
    });
    setModalVisible(true);
  };

  const handleEdit = (record: any) => {
    setEditingId(record.id);
    setCurrentEditingStatus(record.status);
    // 确保明细项都有字符串类型的id
    const itemsWithId = (record.detail_items || []).map((item: any, index: number) => ({
      ...item,
      id: item.id?.toString() || (Date.now().toString() + index)
    }));
    setDetailItems(itemsWithId);
    form.setFieldsValue({
      ...record,
      verification_date: record.verification_date ? dayjs(record.verification_date) : null,
      attachments: record.attachments || []
    });
    setModalVisible(true);
  };

  const handleView = (record: any) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条核销记录吗？',
      onOk: async () => {
        try {
          await fetch('/api/verifications/' + id, { method: 'DELETE' });
          message.success('删除成功');
          fetchRecords();
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  const handleWithdraw = async (id: number) => {
    Modal.confirm({
      title: '确认撤回',
      content: '撤回后可重新编辑提交，确认撤回吗？',
      onOk: async () => {
        try {
          await fetch('/api/verifications/' + id + '/withdraw', { method: 'POST' });
          message.success('已撤回，可重新编辑');
          fetchRecords();
        } catch (error) {
          message.error('撤回失败');
        }
      }
    });
  };

  // 保存操作：只保存信息，不改变状态
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      // 保存时使用编辑时的状态
      const saveStatus = currentEditingStatus || 'pending_edit';
      const data = {
        ...values,
        verification_date: values.verification_date?.format('YYYY-MM-DD'),
        detail_items: detailItems,
        amount: detailItems.reduce((sum, item) => sum + (item.amount || 0), 0),
        applicant: user?.name || user?.username,
        status: saveStatus,
        // 确保advance_amount字段存在
        advance_amount: values.advance_amount || 0
      };
      const url = editingId ? '/api/verifications/' + editingId : '/api/verifications';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      const result = await res.json();
      if (result.success) {
        message.success(editingId ? '保存成功' : '创建成功');
        setModalVisible(false);
        fetchRecords();
      } else {
        message.error(result.error || '保存失败');
      }
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 提交操作：提交到待审批状态
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // 提交时使用pending状态
      const saveStatus = 'pending';
      const data = {
        ...values,
        verification_date: values.verification_date?.format('YYYY-MM-DD'),
        detail_items: detailItems,
        amount: detailItems.reduce((sum, item) => sum + (item.amount || 0), 0),
        applicant: user?.name || user?.username,
        status: saveStatus,
        // 确保advance_amount字段存在
        advance_amount: values.advance_amount || 0
      };
      const url = editingId ? '/api/verifications/' + editingId : '/api/verifications';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      const result = await res.json();
      if (result.success) {
        message.success(editingId ? '提交成功' : '创建成功');
        setModalVisible(false);
        fetchRecords();
        // 重新获取预支单信息，确保已核销金额更新
        fetchAdvances();
      } else {
        message.error(result.error || '提交失败');
      }
    } catch (error) {
      message.error('提交失败');
    }
  };

  const handleSubmitAndSubmit = async () => {
    await handleSubmit();
  };

  const addDetailItem = () => {
    const newItem = {
      id: Date.now().toString() + Math.floor(Math.random() * 1000),
      description: '',
      amount: 0,
      category: '',
      attachments: []
    };
    const newItems = [...detailItems, newItem];
    setDetailItems(newItems);
    
    // 当添加明细项时，重新计算结算金额
    if (form.getFieldValue('settlement') && advanceInfo) {
      const totalAmount = newItems.reduce((sum, item) => sum + (item.amount || 0), 0);
      const settlementAmount = advanceInfo.remaining - totalAmount;
      form.setFieldsValue({ settlement_amount: settlementAmount });
    }
  };
  const updateDetailItem = (id: string, field: keyof DetailItem, value: any) => {
    const newItems = detailItems.map(item => 
      item.id === id ? { ...item, [field]: value } : item
    );
    setDetailItems(newItems);
    
    // 当明细金额变化时，重新计算结算金额
    if (field === 'amount' && form.getFieldValue('settlement') && advanceInfo) {
      const totalAmount = newItems.reduce((sum, item) => sum + (item.amount || 0), 0);
      const settlementAmount = advanceInfo.remaining - totalAmount;
      form.setFieldsValue({ settlement_amount: settlementAmount });
    }
  };
  const removeDetailItem = (id: string) => {
    const newItems = detailItems.filter(item => item.id !== id);
    setDetailItems(newItems);
    
    // 当删除明细项时，重新计算结算金额
    if (form.getFieldValue('settlement') && advanceInfo) {
      const totalAmount = newItems.reduce((sum, item) => sum + (item.amount || 0), 0);
      const settlementAmount = advanceInfo.remaining - totalAmount;
      form.setFieldsValue({ settlement_amount: settlementAmount });
    }
  };

  const handleAdvanceSelect = async (advanceCode: string) => {
    // 先重新获取预支单列表，确保数据最新
    await fetchAdvances();
    
    const advance = advances.find((a: any) => a.advance_code === advanceCode);
    if (advance) {
      form.setFieldsValue({
        advance_code: advance.advance_code,
        advance_amount: advance.amount,
        currency: advance.currency,
        advance_id: advance.id
      });
      // 计算已核销金额和剩余金额
      const totalReimbursed = advance.total_reimbursed || 0;
      const remaining = advance.amount - totalReimbursed;
      setAdvanceInfo({
        ...advance,
        total_reimbursed: totalReimbursed,
        remaining: remaining
      });
    }
  };

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      pending: { color: 'processing', text: '待审批' },
      approved: { color: 'success', text: '已批准' },
      rejected: { color: 'error', text: '已退回' },
      withdrawn: { color: 'default', text: '已撤回' },
      paid: { color: 'blue', text: '已付款' },
      pending_edit: { color: 'warning', text: '待编辑' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const formatAmount = (amount: number, currency: string = 'CNY') => {
    const symbols: Record<string, string> = { CNY: '¥', USD: '$', LAK: '₭', THB: '฿' };
    return (symbols[currency] || '¥') + (amount || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  };



  const columns = [
    { title: '事由', dataIndex: 'reason', key: 'reason', ellipsis: true, render: (v: string, r: any) => <a onClick={() => handleView(r)}>{v}</a> },
    { title: '申请人', dataIndex: 'applicant', key: 'applicant', width: 80 },
    { title: '关联预支', dataIndex: 'advance_code', key: 'advance_code', width: 120 },
    { title: '金额', dataIndex: 'amount', key: 'amount', width: 140, render: (v: number, r: any) => (
        <>
          <div>{formatAmount(v, r.currency)}</div>
          {r.currency !== 'CNY' && r.amount_cny && <div style={{ color: '#999', fontSize: 12 }}>≈ ¥{r.amount_cny.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</div>}
        </>
      ) },
    { title: '核销日期', dataIndex: 'verification_date', key: 'verification_date', width: 100 },
    { title: '状态', dataIndex: 'status', key: 'status', width: 100, render: (status: string) => getStatusTag(status) },
    { title: '编号', dataIndex: 'verification_code', key: 'verification_code', width: 120 },
    {
      title: '操作', key: 'action', width: 250,
      render: (_: any, record: any) => (
        <Space wrap>
          <Button size="small" icon={<EyeOutlined />} onClick={() => handleView(record)}>详情</Button>
          {record.status === 'pending' && (
            <>
              <Button size="small" icon={<UndoOutlined />} onClick={() => handleWithdraw(record.id)}>撤回</Button>
            </>
          )}
          {(record.status === 'rejected' || record.status === 'withdrawn' || record.status === 'pending_edit') && (
            <Button size="small" type="primary" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑重提</Button>
          )}
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      )
    }
  ];

  const currency = Form.useWatch('currency', form);
  const expenseType = Form.useWatch('expense_type', form);
  const totalAmount = detailItems.reduce((sum, item) => sum + (item.amount || 0), 0);

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ marginBottom: 8 }}>核销申请</h2>
        <p style={{ color: '#888', marginBottom: 0 }}>预支款项核销</p>
      </div>

      <Card extra={<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>新建核销</Button>}>
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            {
              key: 'active',
              label: '活跃申请',
              children: <Table dataSource={records} columns={columns} rowKey="id" loading={loading} pagination={{ pageSize: 20 }} size="middle" scroll={{ x: 1200 }} />
            },
            {
              key: 'completed',
              label: '已完结',
              children: <Table dataSource={completedRecords} columns={columns} rowKey="id" loading={loading} pagination={{ pageSize: 20 }} size="middle" scroll={{ x: 1200 }} />
            }
          ]}
        />
      </Card>

      <Modal 
        title={editingId ? '编辑核销' : '新建核销'} 
        open={modalVisible} 
        onCancel={() => setModalVisible(false)} 
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>取消</Button>,
          <Button key="save" onClick={handleSave}>保存</Button>,
          <Button key="submit" type="primary" onClick={handleSubmitAndSubmit}>提交</Button>
        ]} 
        width={900}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="applicant" label="申请人">
            <Input disabled style={{ color: 'rgba(0,0,0,0.85)', backgroundColor: '#f5f5f5' }} />
          </Form.Item>
          
          <Form.Item name="advance_code" label="关联预支单" rules={[{ required: true, message: '请选择关联预支单' }]}>
            <AutoComplete
              options={advances.map((a: any) => ({ 
                value: a.advance_code, 
                label: `${a.advance_code.slice(-5)} - ${a.reason?.substring(0, 15) || '无事由'}${a.reason?.length > 15 ? '...' : ''} - ${formatAmount(a.amount, a.currency)}` 
              }))}
              onSelect={handleAdvanceSelect}
              onChange={(value) => {
                // 当用户输入时，尝试根据输入值查找预支单
                const advance = advances.find((a: any) => a.advance_code === value);
                if (advance) {
                  form.setFieldsValue({
                    advance_code: advance.advance_code,
                    advance_amount: advance.amount,
                    currency: advance.currency,
                    advance_id: advance.id
                  });
                  // 计算已核销金额和剩余金额
                  const totalReimbursed = advance.total_reimbursed || 0;
                  const remaining = advance.amount - totalReimbursed;
                  setAdvanceInfo({
                    ...advance,
                    total_reimbursed: totalReimbursed,
                    remaining: remaining
                  });
                }
              }}
              placeholder="选择或输入预支单编号"
            />
          </Form.Item>

          <Form.Item name="advance_amount" label="预支金额">
            <InputNumber disabled style={{ width: 200 }} />
          </Form.Item>

          <Form.Item name="verification_date" label="核销日期" rules={[{ required: true }]}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item name="currency" label="币种">
            <Select style={{ width: 200 }} disabled>
              <Option value="CNY">人民币 (CNY)</Option>
              <Option value="USD">美元 (USD)</Option>
              <Option value="LAK">老挝基普 (LAK)</Option>
              <Option value="THB">泰铢 (THB)</Option>
            </Select>
          </Form.Item>

          {advanceInfo && (
            <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
              <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
                <div>
                  <span style={{ color: '#666' }}>已核销金额: </span>
                  <span style={{ fontWeight: 'bold' }}>{formatAmount(advanceInfo.total_reimbursed, advanceInfo.currency)}</span>
                </div>
                <div>
                  <span style={{ color: '#666' }}>剩余金额: </span>
                  <span style={{ fontWeight: 'bold' }}>{formatAmount(advanceInfo.remaining, advanceInfo.currency)}</span>
                </div>
              </div>
            </div>
          )}

          <Form.Item name="settlement" label="结算选项">
            <Form.Item name="settlement" noStyle valuePropName="checked">
              <Checkbox onChange={(e) => {
                if (e.target.checked && advanceInfo) {
                  const totalAmount = detailItems.reduce((sum, item) => sum + (item.amount || 0), 0);
                  const settlementAmount = advanceInfo.remaining - totalAmount;
                  form.setFieldsValue({ settlement_amount: settlementAmount });
                } else {
                  form.setFieldsValue({ settlement_amount: 0 });
                }
              }}>是否作为最终结算</Checkbox>
            </Form.Item>
          </Form.Item>

          <Form.Item name="settlement_amount" label="结算金额" dependencies={['settlement']}>
            <InputNumber 
              style={{ width: 200 }} 
              disabled 
              formatter={(value: any) => {
                const numValue = Number(value) || 0;
                if (numValue > 0) return `退款 ¥${numValue}`;
                if (numValue < 0) return `补款 ¥${Math.abs(numValue)}`;
                return '¥0';
              }}
            />
          </Form.Item>

          <Form.Item name="expense_type" label="支出类型" rules={[{ required: true }]}>
            <Select placeholder="选择支出类型" onChange={() => form.setFieldsValue({ project_id: undefined })}>
              <Option value="company">公司支出</Option>
              <Option value="project">项目支出</Option>
            </Select>
          </Form.Item>

          {expenseType === 'project' && (
            <Form.Item name="project_id" label="选择项目" rules={[{ required: true, message: '请选择项目' }]}>
              <Select placeholder="选择项目" showSearch optionFilterProp="children">
                {projects.map((p: any) => <Option key={p.id} value={p.id}>{p.name}</Option>)}
              </Select>
            </Form.Item>
          )}

          <Form.Item name="reason" label="核销事由" rules={[{ required: true }]}>
            <TextArea rows={2} placeholder="核销原因说明" />
          </Form.Item>

          <Divider>核销明细</Divider>
          
          <div style={{ marginBottom: 16 }}>
            <Button type="dashed" icon={<PlusCircleOutlined />} onClick={addDetailItem}>添加明细</Button>
            <span style={{ marginLeft: 16, color: '#888' }}>
              合计: {formatAmount(totalAmount, currency)}
            </span>
          </div>

          {detailItems.map((item) => (
            <Card key={item.id} size="small" style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <label style={{ display: 'block', marginBottom: 4, color: '#666' }}>费用说明</label>
                  <Input 
                    value={item.description} 
                    onChange={(e) => updateDetailItem(item.id, 'description', e.target.value)}
                    placeholder="费用说明"
                  />
                </div>
                <div style={{ width: 180 }}>
                  <label style={{ display: 'block', marginBottom: 4, color: '#666' }}>支出分类</label>
                  <Select 
                    value={item.category} 
                    onChange={(v) => updateDetailItem(item.id, 'category', v)}
                    style={{ width: '100%' }}
                    placeholder="选择支出分类"
                  >
                    {expenseType === 'project' ? (
                      <>
                        <Option value="accommodation">住宿</Option>
                        <Option value="food">餐饮</Option>
                        <Option value="fuel">加油</Option>
                        <Option value="materials">零散材料</Option>
                        <Option value="customer_relations">客户关系</Option>
                        <Option value="subcontract_relations">分包关系</Option>
                        <Option value="edl_relations">EDL关系</Option>
                        <Option value="extra_construction">额外施工</Option>
                        <Option value="other">其他</Option>
                      </>
                    ) : (
                      <>
                        <Option value="general_operations">通用运营（房租/耗材）</Option>
                        <Option value="transportation">交通通勤</Option>
                        <Option value="business_expansion">业扩营销</Option>
                        <Option value="power_system_relations">电力系统关系</Option>
                        <Option value="employee_benefits">员工福利</Option>
                        <Option value="express_logistics">快递物流</Option>
                        <Option value="other">其他</Option>
                      </>
                    )}
                  </Select>
                </div>
                <div style={{ width: 150 }}>
                  <label style={{ display: 'block', marginBottom: 4, color: '#666' }}>金额</label>
                  <InputNumber 
                    value={item.amount} 
                    onChange={(v) => updateDetailItem(item.id, 'amount', v)}
                    min={0} 
                    precision={2}
                    style={{ width: '100%' }}
                    placeholder="金额"
                  />
                </div>
                <div style={{ flex: 2, minWidth: 300 }}>
                  <label style={{ display: 'block', marginBottom: 4, color: '#666' }}>凭证附件</label>
                  <FileUpload 
                    value={item.attachments || []}
                    onChange={(urls) => updateDetailItem(item.id, 'attachments', urls)}
                    maxCount={3}
                    accept="image/*"
                  />
                </div>
                <Button type="text" danger icon={<MinusCircleOutlined />} onClick={() => removeDetailItem(item.id)} style={{ marginTop: 24 }} />
              </div>
            </Card>
          ))}

          <Divider>主附件</Divider>
          <Form.Item 
            name="attachments" 
            label={form.getFieldValue('settlement') && form.getFieldValue('settlement_amount') > 0 ? "退款凭证（必填）" : "整体凭证附件"} 
            rules={form.getFieldValue('settlement') && form.getFieldValue('settlement_amount') > 0 ? [{ required: true, message: '请上传退款凭证' }] : []}
          >
            <FileUpload 
              value={form.getFieldValue('attachments') || []} 
              onChange={(urls) => form.setFieldsValue({ attachments: urls })} 
              maxCount={9} 
              accept="image/*" 
            />
            {form.getFieldValue('settlement') && form.getFieldValue('settlement_amount') > 0 && (
              <div style={{ marginTop: 8, color: '#ff4d4f', fontSize: 12 }}>
                * 退款类型的结算核销必须上传退款凭证
              </div>
            )}
          </Form.Item>
        </Form>
      </Modal>

      <Modal title="核销详情" open={detailModalVisible} onCancel={() => setDetailModalVisible(false)} footer={null} width={900}>
        {selectedRecord && (
          <>
            <Descriptions bordered column={2} size="small">
              <Descriptions.Item label="核销编号">{selectedRecord.verification_code}</Descriptions.Item>
              <Descriptions.Item label="状态">{getStatusTag(selectedRecord.status)}</Descriptions.Item>
              <Descriptions.Item label="关联预支">{selectedRecord.advance_code}</Descriptions.Item>
              <Descriptions.Item label="申请人">{selectedRecord.applicant}</Descriptions.Item>
              <Descriptions.Item label="核销日期">{selectedRecord.verification_date}</Descriptions.Item>
              <Descriptions.Item label="币种">{selectedRecord.currency}</Descriptions.Item>
              <Descriptions.Item label="支出类型">{selectedRecord.expense_type === 'project' ? '项目支出' : '公司支出'}</Descriptions.Item>
              <Descriptions.Item label="是否结算">
                <span style={{ fontWeight: 'bold', color: selectedRecord.settlement ? '#52c41a' : '#fa8c16' }}>
                  {selectedRecord.settlement ? '是' : '否'}
                </span>
              </Descriptions.Item>
              {selectedRecord.settlement && selectedRecord.settlement_amount && (
                <Descriptions.Item label="结算金额" span={2}>
                  {selectedRecord.settlement_amount > 0 ? `退款 ${formatAmount(selectedRecord.settlement_amount, selectedRecord.currency)}` : `补款 ${formatAmount(Math.abs(selectedRecord.settlement_amount), selectedRecord.currency)}`}
                </Descriptions.Item>
              )}
              {selectedRecord.project_id && (
                <Descriptions.Item label="关联项目" span={2}>
                  {projects.find(p => p.id === selectedRecord.project_id)?.name || '未知项目'}
                </Descriptions.Item>
              )}
              <Descriptions.Item label="金额">
                {formatAmount(selectedRecord.amount, selectedRecord.currency)}
                {selectedRecord.currency !== 'CNY' && selectedRecord.amount_cny && (
                  <span style={{ color: '#999', marginLeft: 8 }}>≈ ¥{selectedRecord.amount_cny.toLocaleString('zh-CN', {minimumFractionDigits: 2})}</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="核销事由" span={2}>{selectedRecord.reason}</Descriptions.Item>
            </Descriptions>
            
            {/* 预支单信息 */}
            {selectedRecord.advance_id && (
              <div style={{ marginTop: 24 }}>
                <Divider>预支单信息</Divider>
                <Descriptions bordered column={2} size="small">
                  <Descriptions.Item label="预支单号">{selectedRecord.advance_code}</Descriptions.Item>
                  <Descriptions.Item label="预支金额">{formatAmount(selectedRecord.advance_amount || 0, selectedRecord.currency)}</Descriptions.Item>
                  <Descriptions.Item label="已核销金额">{formatAmount(selectedRecord.total_reimbursed || 0, selectedRecord.currency)}</Descriptions.Item>
                  <Descriptions.Item label="剩余金额">{formatAmount((selectedRecord.advance_amount || 0) - (selectedRecord.total_reimbursed || 0), selectedRecord.currency)}</Descriptions.Item>
                </Descriptions>
              </div>
            )}

            {Array.isArray(selectedRecord.detail_items) && selectedRecord.detail_items.length > 0 && (
              <>
                <Divider>核销明细</Divider>
                <Table 
                  dataSource={selectedRecord.detail_items} 
                  rowKey="id"
                  size="small"
                  pagination={false}
                  columns={[
                    { title: '费用说明', dataIndex: 'description', key: 'description' },
                    { 
                      title: '支出分类', 
                      dataIndex: 'category', 
                      key: 'category', 
                      render: (v: string) => {
                        const categoryMap: Record<string, string> = {
                          // Project expense categories
                          accommodation: '住宿',
                          food: '餐饮',
                          fuel: '加油',
                          materials: '零散材料',
                          customer_relations: '客户关系',
                          subcontract_relations: '分包关系',
                          edl_relations: 'EDL关系',
                          extra_construction: '额外施工',
                          // Company expense categories
                          general_operations: '通用运营（房租/耗材）',
                          transportation: '交通通勤',
                          business_expansion: '业扩营销',
                          power_system_relations: '电力系统关系',
                          employee_benefits: '员工福利',
                          express_logistics: '快递物流',
                          other: '其他'
                        };
                        return categoryMap[v] || v;
                      }
                    },
                    { title: '金额', dataIndex: 'amount', key: 'amount', render: (v: number) => formatAmount(v, selectedRecord.currency) },
                    { title: '附件', dataIndex: 'attachments', key: 'attachments', render: (v: string[]) => v?.length ? `${v.length}张` : '-' }
                  ]}
                />
              </>
            )}
            
            {Array.isArray(selectedRecord.attachments) && selectedRecord.attachments.length > 0 && (
              <>
                <Divider>{selectedRecord.settlement && selectedRecord.settlement_amount > 0 ? '退款凭证' : '整体凭证附件'}</Divider>
                <Image.PreviewGroup>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {selectedRecord.attachments.map((url: string, index: number) => (
                      <Image key={index} src={url} width={100} height={100} style={{ objectFit: 'cover', borderRadius: 4 }} />
                    ))}
                  </div>
                </Image.PreviewGroup>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default VerificationPage;
