import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Row,
  Col,
  Statistic,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Tabs,
  Tooltip,
  Badge,
  message,
  Descriptions,
  Divider,
  Alert,
  Popconfirm,
  Rate,
  Progress,
  Drawer,
  List,
  Avatar,
  Timeline,
  ShoppingOutlined,
  TeamOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SearchOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  CarOutlined,
  InboxOutlined,
  DollarOutlined,
  StarOutlined,
  PhoneOutlined,
  MailOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  Option,
  RangePicker,
  TextArea,
  FC,
} from '@/imports';
import type { TabsProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import {
  procurementDataSource,
  SUPPLIER_STATUS_COLORS,
  SUPPLIER_LEVEL_COLORS,
  PROCUREMENT_STATUS_COLORS,
  PROCUREMENT_STATUS_TEXT,
  PAYMENT_STATUS_COLORS,
  QUALITY_STATUS_COLORS,
} from '@/services/procurementDataSource';
import {
  Supplier,
  ProcurementRecord,
  ProcurementStats,
  ProcurementStatus,
  SupplierStatus,
  QualityStatus,
} from '@/types/procurement';

const ProcurementManagement: FC = () => {
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [procurementRecords, setProcurementRecords] = useState<ProcurementRecord[]>([]);
  const [stats, setStats] = useState<ProcurementStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('records');
  
  const [supplierModalVisible, setSupplierModalVisible] = useState(false);
  const [procurementModalVisible, setProcurementModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [receiveModalVisible, setReceiveModalVisible] = useState(false);
  
  const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
  const [selectedRecord, setSelectedRecord] = useState<ProcurementRecord | null>(null);
  const [editingSupplier, setEditingSupplier] = useState<Supplier | null>(null);
  
  const [supplierForm] = Form.useForm();
  const [procurementForm] = Form.useForm();
  const [receiveForm] = Form.useForm();
  
  const [statusFilter, setStatusFilter] = useState<ProcurementStatus | 'all'>('all');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [suppliersData, recordsData, statsData] = await Promise.all([
        procurementDataSource.fetchSuppliers('tenant-001'),
        procurementDataSource.fetchProcurementRecords('tenant-001'),
        procurementDataSource.fetchProcurementStats('tenant-001'),
      ]);
      setSuppliers(suppliersData);
      setProcurementRecords(recordsData);
      setStats(statsData);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateSupplier = async (values: any) => {
    try {
      await procurementDataSource.createSupplier({
        name: values.name,
        code: values.code,
        contact_person: values.contact_person,
        phone: values.phone,
        email: values.email,
        address: values.address,
        category: values.category || [],
        payment_terms: values.payment_terms,
        credit_limit: values.credit_limit,
        lead_time_days: values.lead_time_days,
        min_order_amount: values.min_order_amount,
        remarks: values.remarks,
      });
      message.success('供应商创建成功');
      setSupplierModalVisible(false);
      supplierForm.resetFields();
      loadData();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleCreateProcurement = async (values: any) => {
    try {
      const items = values.items.map((item: any) => ({
        product_id: item.product_id || `PROD-${Date.now()}`,
        product_name: item.product_name,
        sku: item.sku,
        quantity: item.quantity,
        unit: item.unit,
        unit_price: item.unit_price,
      }));

      await procurementDataSource.createProcurement({
        supplier_id: values.supplier_id,
        items,
        expected_date: values.expected_date?.format('YYYY-MM-DD'),
        warehouse_id: values.warehouse_id,
        remarks: values.remarks,
      });
      message.success('采购单创建成功');
      setProcurementModalVisible(false);
      procurementForm.resetFields();
      loadData();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleApproveProcurement = async (recordId: string) => {
    try {
      await procurementDataSource.approveProcurement(recordId);
      message.success('采购单已确认');
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleCancelProcurement = async (recordId: string, reason: string) => {
    try {
      await procurementDataSource.cancelProcurement(recordId, reason);
      message.success('采购单已取消');
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleReceiveProcurement = async (values: any) => {
    if (!selectedRecord) return;
    
    try {
      const items = selectedRecord.items.map(item => ({
        item_id: item.id,
        received_quantity: values[`received_${item.id}`] || 0,
        quality_status: values[`quality_${item.id}`] || 'PENDING',
      }));

      await procurementDataSource.receiveProcurement(selectedRecord.id, items);
      message.success('收货成功');
      setReceiveModalVisible(false);
      receiveForm.resetFields();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleDeleteSupplier = async (supplierId: string) => {
    try {
      await procurementDataSource.deleteSupplier(supplierId);
      message.success('供应商已删除');
      loadData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const filteredRecords = procurementRecords.filter(record => {
    if (statusFilter !== 'all' && record.status !== statusFilter) return false;
    if (dateRange) {
      const recordDate = dayjs(record.created_at);
      if (recordDate.isBefore(dateRange[0]) || recordDate.isAfter(dateRange[1])) return false;
    }
    return true;
  });

  const supplierColumns: ColumnsType<Supplier> = [
    {
      title: '供应商编码',
      dataIndex: 'code',
      key: 'code',
      width: 120,
      render: (code: string) => <code>{code}</code>,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level: string) => (
        <Tag color={SUPPLIER_LEVEL_COLORS[level]} icon={<StarOutlined />}>
          {level}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: SupplierStatus) => (
        <Tag color={SUPPLIER_STATUS_COLORS[status]}>
          {status === 'ACTIVE' ? '合作中' : status === 'INACTIVE' ? '暂停合作' : '黑名单'}
        </Tag>
      ),
    },
    {
      title: '联系人',
      dataIndex: 'contact_person',
      key: 'contact_person',
      width: 100,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 120,
      render: (rating: number) => <Rate disabled defaultValue={rating} allowHalf />,
    },
    {
      title: '准时率',
      dataIndex: 'on_time_rate',
      key: 'on_time_rate',
      width: 100,
      render: (rate: number) => (
        <Progress
          percent={rate}
          size="small"
          status={rate >= 90 ? 'success' : rate >= 70 ? 'normal' : 'exception'}
        />
      ),
    },
    {
      title: '合格率',
      dataIndex: 'quality_pass_rate',
      key: 'quality_pass_rate',
      width: 100,
      render: (rate: number) => (
        <Progress
          percent={rate}
          size="small"
          status={rate >= 95 ? 'success' : rate >= 85 ? 'normal' : 'exception'}
        />
      ),
    },
    {
      title: '累计金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (amount: number) => `¥${amount.toLocaleString()}`,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedSupplier(record);
                setDetailDrawerVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                setEditingSupplier(record);
                supplierForm.setFieldsValue(record);
                setSupplierModalVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定删除此供应商？"
            onConfirm={() => handleDeleteSupplier(record.id)}
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const procurementColumns: ColumnsType<ProcurementRecord> = [
    {
      title: '采购单号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 140,
      render: (no: string) => <code>{no}</code>,
    },
    {
      title: '供应商',
      dataIndex: 'supplier_name',
      key: 'supplier_name',
      width: 180,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: ProcurementStatus) => (
        <Tag color={PROCUREMENT_STATUS_COLORS[status]}>
          {PROCUREMENT_STATUS_TEXT[status]}
        </Tag>
      ),
    },
    {
      title: '商品数量',
      dataIndex: 'total_quantity',
      key: 'total_quantity',
      width: 100,
      render: (qty: number) => <Badge count={qty} showZero color="blue" />,
    },
    {
      title: '总金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (amount: number) => (
        <strong style={{ color: '#1890ff' }}>¥{amount.toLocaleString()}</strong>
      ),
    },
    {
      title: '付款状态',
      dataIndex: 'payment_status',
      key: 'payment_status',
      width: 100,
      render: (status: string) => (
        <Tag color={PAYMENT_STATUS_COLORS[status as keyof typeof PAYMENT_STATUS_COLORS]}>
          {status === 'UNPAID' ? '未付款' : status === 'PARTIAL' ? '部分付款' : '已付款'}
        </Tag>
      ),
    },
    {
      title: '预计到货',
      dataIndex: 'expected_date',
      key: 'expected_date',
      width: 110,
      render: (date: string) => date || '-',
    },
    {
      title: '采购员',
      dataIndex: 'purchaser',
      key: 'purchaser',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedRecord(record);
                setDetailDrawerVisible(true);
              }}
            />
          </Tooltip>
          {record.status === 'PENDING' && (
            <Tooltip title="确认">
              <Button
                type="link"
                size="small"
                style={{ color: '#52c41a' }}
                icon={<CheckCircleOutlined />}
                onClick={() => handleApproveProcurement(record.id)}
              >
                确认
              </Button>
            </Tooltip>
          )}
          {record.status === 'CONFIRMED' && (
            <Tooltip title="标记发货">
              <Button
                type="link"
                size="small"
                icon={<CarOutlined />}
                onClick={() => {
                  setSelectedRecord(record);
                  procurementDataSource.updateProcurementStatus(record.id, 'IN_TRANSIT');
                  loadData();
                }}
              >
                发货
              </Button>
            </Tooltip>
          )}
          {record.status === 'IN_TRANSIT' && (
            <Tooltip title="收货">
              <Button
                type="link"
                size="small"
                icon={<InboxOutlined />}
                onClick={() => {
                  setSelectedRecord(record);
                  record.items.forEach(item => {
                    receiveForm.setFieldsValue({
                      [`received_${item.id}`]: item.quantity,
                      [`quality_${item.id}`]: 'PASSED',
                    });
                  });
                  setReceiveModalVisible(true);
                }}
              >
                收货
              </Button>
            </Tooltip>
          )}
          {['PENDING', 'CONFIRMED'].includes(record.status) && (
            <Popconfirm
              title="确定取消此采购单？"
              onConfirm={() => handleCancelProcurement(record.id, '用户取消')}
            >
              <Button type="link" size="small" danger icon={<CloseCircleOutlined />}>
                取消
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  const tabItems: TabsProps['items'] = [
    {
      key: 'records',
      label: (
        <span>
          <ShoppingOutlined />
          采购记录
          <Badge count={procurementRecords.length} style={{ marginLeft: 8 }} />
        </span>
      ),
      children: (
        <Card>
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={6}>
              <Select
                value={statusFilter}
                onChange={setStatusFilter}
                style={{ width: '100%' }}
              >
                <Option value="all">全部状态</Option>
                <Option value="PENDING">待确认</Option>
                <Option value="CONFIRMED">已确认</Option>
                <Option value="IN_TRANSIT">运输中</Option>
                <Option value="RECEIVED">已收货</Option>
                <Option value="CANCELLED">已取消</Option>
              </Select>
            </Col>
            <Col span={8}>
              <RangePicker
                value={dateRange}
                onChange={(dates) => setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
                style={{ width: '100%' }}
              />
            </Col>
            <Col span={10} style={{ textAlign: 'right' }}>
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    procurementForm.resetFields();
                    setProcurementModalVisible(true);
                  }}
                >
                  新建采购单
                </Button>
                <Button icon={<SearchOutlined />} onClick={loadData}>
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>

          <Table
            columns={procurementColumns}
            dataSource={filteredRecords}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1600 }}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条`,
            }}
          />
        </Card>
      ),
    },
    {
      key: 'suppliers',
      label: (
        <span>
          <TeamOutlined />
          供应商管理
          <Badge count={suppliers.filter(s => s.status === 'ACTIVE').length} style={{ marginLeft: 8 }} />
        </span>
      ),
      children: (
        <Card>
          <div style={{ marginBottom: 16, textAlign: 'right' }}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  setEditingSupplier(null);
                  supplierForm.resetFields();
                  setSupplierModalVisible(true);
                }}
              >
                新建供应商
              </Button>
              <Button icon={<SearchOutlined />} onClick={loadData}>
                刷新
              </Button>
            </Space>
          </div>

          <Table
            columns={supplierColumns}
            dataSource={suppliers}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1400 }}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条`,
            }}
          />
        </Card>
      ),
    },
  ];

  return (
    <div className="procurement-management">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="采购单总数"
              value={stats?.total_orders || 0}
              prefix={<ShoppingOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="待处理"
              value={stats?.pending_orders || 0}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="运输中"
              value={stats?.in_transit_orders || 0}
              valueStyle={{ color: '#1890ff' }}
              prefix={<CarOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="采购总额"
              value={stats?.total_amount || 0}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="待付款"
              value={stats?.pending_amount || 0}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="合作供应商"
              value={stats?.active_supplier_count || 0}
              suffix={`/ ${stats?.supplier_count || 0}`}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />

      <Modal
        title={editingSupplier ? '编辑供应商' : '新建供应商'}
        open={supplierModalVisible}
        onCancel={() => {
          setSupplierModalVisible(false);
          setEditingSupplier(null);
          supplierForm.resetFields();
        }}
        footer={null}
        width={700}
      >
        <Form form={supplierForm} layout="vertical" onFinish={handleCreateSupplier}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="供应商名称"
                rules={[{ required: true, message: '请输入供应商名称' }]}
              >
                <Input placeholder="请输入供应商名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="供应商编码"
                rules={[{ required: true, message: '请输入供应商编码' }]}
              >
                <Input placeholder="请输入供应商编码" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="contact_person"
                label="联系人"
                rules={[{ required: true, message: '请输入联系人' }]}
              >
                <Input placeholder="请输入联系人" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="联系电话"
                rules={[{ required: true, message: '请输入联系电话' }]}
              >
                <Input placeholder="请输入联系电话" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="email" label="邮箱">
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="address"
                label="地址"
                rules={[{ required: true, message: '请输入地址' }]}
              >
                <Input placeholder="请输入地址" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="payment_terms" label="付款条件">
                <Select placeholder="请选择付款条件">
                  <Option value="现结">现结</Option>
                  <Option value="月结15天">月结15天</Option>
                  <Option value="月结30天">月结30天</Option>
                  <Option value="月结60天">月结60天</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="credit_limit" label="信用额度">
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  placeholder="请输入信用额度"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="lead_time_days" label="交货周期(天)">
                <InputNumber style={{ width: '100%' }} min={1} placeholder="请输入交货周期" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="min_order_amount" label="最小订单金额">
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  placeholder="请输入最小订单金额"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="remarks" label="备注">
            <TextArea rows={2} placeholder="请输入备注" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingSupplier ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setSupplierModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="新建采购单"
        open={procurementModalVisible}
        onCancel={() => {
          setProcurementModalVisible(false);
          procurementForm.resetFields();
        }}
        footer={null}
        width={900}
      >
        <Form form={procurementForm} layout="vertical" onFinish={handleCreateProcurement}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="supplier_id"
                label="供应商"
                rules={[{ required: true, message: '请选择供应商' }]}
              >
                <Select placeholder="请选择供应商" showSearch>
                  {suppliers.filter(s => s.status === 'ACTIVE').map(s => (
                    <Option key={s.id} value={s.id}>
                      {s.name} ({s.code})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="expected_date" label="预计到货日期">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.List name="items" initialValue={[{}]}>
            {(fields, { add, remove }) => (
              <>
                <div style={{ marginBottom: 8 }}>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加采购商品
                  </Button>
                </div>
                {fields.map(({ key, name, ...restField }) => (
                  <Card key={key} size="small" style={{ marginBottom: 8 }}>
                    <Row gutter={16}>
                      <Col span={8}>
                        <Form.Item
                          {...restField}
                          name={[name, 'product_name']}
                          label="商品名称"
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="商品名称" />
                        </Form.Item>
                      </Col>
                      <Col span={6}>
                        <Form.Item
                          {...restField}
                          name={[name, 'sku']}
                          label="SKU"
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="SKU" />
                        </Form.Item>
                      </Col>
                      <Col span={4}>
                        <Form.Item
                          {...restField}
                          name={[name, 'quantity']}
                          label="数量"
                          rules={[{ required: true }]}
                        >
                          <InputNumber min={1} style={{ width: '100%' }} />
                        </Form.Item>
                      </Col>
                      <Col span={4}>
                        <Form.Item
                          {...restField}
                          name={[name, 'unit_price']}
                          label="单价"
                          rules={[{ required: true }]}
                        >
                          <InputNumber min={0} precision={2} style={{ width: '100%' }} />
                        </Form.Item>
                      </Col>
                      <Col span={2}>
                        <Form.Item label=" ">
                          <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => remove(name)}
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Card>
                ))}
              </>
            )}
          </Form.List>

          <Form.Item name="remarks" label="备注">
            <TextArea rows={2} placeholder="请输入备注" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建采购单
              </Button>
              <Button onClick={() => setProcurementModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="收货确认"
        open={receiveModalVisible}
        onCancel={() => {
          setReceiveModalVisible(false);
          receiveForm.resetFields();
        }}
        footer={null}
        width={800}
      >
        {selectedRecord && (
          <Form form={receiveForm} layout="vertical" onFinish={handleReceiveProcurement}>
            <Alert
              message={`采购单: ${selectedRecord.order_no}`}
              description={`供应商: ${selectedRecord.supplier_name}`}
              type="info"
              style={{ marginBottom: 16 }}
            />
            
            {selectedRecord.items.map(item => (
              <Card key={item.id} size="small" style={{ marginBottom: 8 }}>
                <Row gutter={16} align="middle">
                  <Col span={8}>
                    <strong>{item.product_name}</strong>
                    <br />
                    <small>{item.sku}</small>
                  </Col>
                  <Col span={4}>
                    订购: {item.quantity} {item.unit}
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      name={`received_${item.id}`}
                      label="实收数量"
                      style={{ marginBottom: 0 }}
                    >
                      <InputNumber min={0} max={item.quantity} style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      name={`quality_${item.id}`}
                      label="质检状态"
                      style={{ marginBottom: 0 }}
                    >
                      <Select style={{ width: '100%' }}>
                        <Option value="PENDING">待检</Option>
                        <Option value="PASSED">合格</Option>
                        <Option value="FAILED">不合格</Option>
                        <Option value="PARTIAL">部分合格</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
            ))}

            <Form.Item style={{ marginTop: 16 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  确认收货
                </Button>
                <Button onClick={() => setReceiveModalVisible(false)}>取消</Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>

      <Drawer
        title={activeTab === 'suppliers' ? '供应商详情' : '采购单详情'}
        placement="right"
        width={600}
        onClose={() => {
          setDetailDrawerVisible(false);
          setSelectedSupplier(null);
          setSelectedRecord(null);
        }}
        open={detailDrawerVisible}
      >
        {selectedSupplier && (
          <div>
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="编码">{selectedSupplier.code}</Descriptions.Item>
              <Descriptions.Item label="名称">{selectedSupplier.name}</Descriptions.Item>
              <Descriptions.Item label="等级">
                <Tag color={SUPPLIER_LEVEL_COLORS[selectedSupplier.level]}>{selectedSupplier.level}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={SUPPLIER_STATUS_COLORS[selectedSupplier.status]}>
                  {selectedSupplier.status === 'ACTIVE' ? '合作中' : '暂停合作'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="联系人">{selectedSupplier.contact_person}</Descriptions.Item>
              <Descriptions.Item label="电话">{selectedSupplier.phone}</Descriptions.Item>
              <Descriptions.Item label="邮箱" span={2}>{selectedSupplier.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="地址" span={2}>{selectedSupplier.address}</Descriptions.Item>
              <Descriptions.Item label="付款条件">{selectedSupplier.payment_terms || '-'}</Descriptions.Item>
              <Descriptions.Item label="交货周期">{selectedSupplier.lead_time_days}天</Descriptions.Item>
            </Descriptions>

            <Divider>绩效指标</Divider>

            <Row gutter={16}>
              <Col span={12}>
                <Card>
                  <Statistic
                    title="准时交货率"
                    value={selectedSupplier.on_time_rate}
                    suffix="%"
                    valueStyle={{ color: selectedSupplier.on_time_rate >= 90 ? '#52c41a' : '#faad14' }}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card>
                  <Statistic
                    title="质量合格率"
                    value={selectedSupplier.quality_pass_rate}
                    suffix="%"
                    valueStyle={{ color: selectedSupplier.quality_pass_rate >= 95 ? '#52c41a' : '#faad14' }}
                  />
                </Card>
              </Col>
            </Row>

            <Divider>历史记录</Divider>

            <Descriptions column={2} size="small">
              <Descriptions.Item label="总订单数">{selectedSupplier.total_orders}</Descriptions.Item>
              <Descriptions.Item label="累计金额">¥{selectedSupplier.total_amount.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="信用额度">¥{(selectedSupplier.credit_limit || 0).toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="已用额度">¥{(selectedSupplier.credit_used || 0).toLocaleString()}</Descriptions.Item>
            </Descriptions>
          </div>
        )}

        {selectedRecord && (
          <div>
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="采购单号">{selectedRecord.order_no}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={PROCUREMENT_STATUS_COLORS[selectedRecord.status]}>
                  {PROCUREMENT_STATUS_TEXT[selectedRecord.status]}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="供应商" span={2}>{selectedRecord.supplier_name}</Descriptions.Item>
              <Descriptions.Item label="采购员">{selectedRecord.purchaser}</Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {new Date(selectedRecord.created_at).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="预计到货">{selectedRecord.expected_date || '-'}</Descriptions.Item>
              <Descriptions.Item label="实际到货">{selectedRecord.actual_date || '-'}</Descriptions.Item>
            </Descriptions>

            <Divider>商品明细</Divider>

            <Table
              dataSource={selectedRecord.items}
              rowKey="id"
              size="small"
              pagination={false}
              columns={[
                { title: '商品', dataIndex: 'product_name', key: 'product_name' },
                { title: 'SKU', dataIndex: 'sku', key: 'sku' },
                { title: '数量', dataIndex: 'quantity', key: 'quantity' },
                { title: '单价', dataIndex: 'unit_price', key: 'unit_price', render: (v) => `¥${v}` },
                { title: '金额', dataIndex: 'total_price', key: 'total_price', render: (v) => `¥${v}` },
                {
                  title: '质检',
                  dataIndex: 'quality_status',
                  key: 'quality_status',
                  render: (status: QualityStatus) => (
                    <Tag color={QUALITY_STATUS_COLORS[status]}>
                      {status === 'PENDING' ? '待检' : status === 'PASSED' ? '合格' : status === 'FAILED' ? '不合格' : '部分合格'}
                    </Tag>
                  ),
                },
              ]}
            />

            <Divider>付款信息</Divider>

            <Descriptions column={2} size="small">
              <Descriptions.Item label="总金额">¥{selectedRecord.total_amount.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="已付款">¥{selectedRecord.paid_amount.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="付款状态">
                <Tag color={PAYMENT_STATUS_COLORS[selectedRecord.payment_status]}>
                  {selectedRecord.payment_status === 'UNPAID' ? '未付款' : 
                   selectedRecord.payment_status === 'PARTIAL' ? '部分付款' : '已付款'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="仓库">{selectedRecord.warehouse_name || '-'}</Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default ProcurementManagement;
