/**
 * 采购订单页面
 * 遵循设计方案：采购-付款-物流-退库一体化流程设计方案.md
 * 章节：三、采购订单页面设计
 * 
 * 多TAB设计：
 * - 订单列表：显示所有采购订单
 * - 订单详情：多TAB（基本信息、商品明细、付款信息、物流信息、验收记录）
 */
import React, { useState, useEffect } from 'react'
import {
  Table, Button, Modal, Form, Input, Select, message, Space, Tag, Card,
  Row, Col, DatePicker, InputNumber, Popconfirm, Tabs, Descriptions, Upload, Divider
} from 'antd'
import {
  PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, CheckOutlined,
  UploadOutlined, FileTextOutlined, CarOutlined, SafetyCertificateOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'

interface PurchaseOrder {
  id: number
  code: string
  purchase_request_id: number
  project_id: number
  project_name: string
  supplier_id: number
  supplier_name: string
  supplier_country: string
  estimated_amount: number
  total_amount: number
  paid_amount: number
  currency: string
  status: string
  contract_url: string
  quotation_url: string
  remark: string
  created_at: string
  items: OrderItem[]
  payment_plans: PaymentPlan[]
  logistics: LogisticsRecord[]
  verifications: VerificationRecord[]
}

interface OrderItem {
  id: number
  product_id: number
  product_name: string
  specification: string
  unit: string
  quantity: number
  unit_price: number
  total_price: number
  received_quantity: number
  verified_quantity: number
}

interface PaymentPlan {
  id: number
  stage: string
  planned_date: string
  planned_amount: number
  planned_percentage: number
  actual_amount: number
  actual_date: string
  status: string
  remark: string
}

interface LogisticsRecord {
  id: number
  code: string
  ship_from: string
  logistics_company_name: string
  tracking_number: string
  ship_date: string
  status: string
  primary_freight: number
  secondary_freight: number
}

interface VerificationRecord {
  id: number
  code: string
  verification_date: string
  verifier: string
  total_verified: number
  status: string
}

interface Project { id: number; name: string }
interface Supplier { id: number; name: string; country: string }
interface Product { id: number; name: string; specification: string; unit: string }

const PurchaseOrdersPage: React.FC = () => {
  const [orders, setOrders] = useState<PurchaseOrder[]>([])
  const [loading, setLoading] = useState(false)
  const [projects, setProjects] = useState<Project[]>([])
  const [suppliers, setSuppliers] = useState<Supplier[]>([])
  const [products, setProducts] = useState<Product[]>([])
  
  const [selectedProjectId, setSelectedProjectId] = useState<number | null>(null)
  const [selectedStatus, setSelectedStatus] = useState<string | null>(null)
  
  const [detailModalVisible, setDetailModalVisible] = useState(false)
  const [currentOrder, setCurrentOrder] = useState<PurchaseOrder | null>(null)
  const [activeDetailTab, setActiveDetailTab] = useState('basic')
  
  const [itemModalVisible, setItemModalVisible] = useState(false)
  const [editingItem, setEditingItem] = useState<OrderItem | null>(null)
  const [itemForm] = Form.useForm()
  
  const [paymentModalVisible, setPaymentModalVisible] = useState(false)
  const [editingPayment, setEditingPayment] = useState<PaymentPlan | null>(null)
  const [paymentForm] = Form.useForm()

  const fetchOrders = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (selectedProjectId) params.append('project_id', selectedProjectId.toString())
      if (selectedStatus) params.append('status', selectedStatus)
      
      const response = await fetch(`/api/purchase-orders?${params}`)
      const data = await response.json()
      
      if (data.success) {
        setOrders(data.data)
      } else {
        message.error('获取采购订单列表失败')
      }
    } catch (error) {
      console.error('获取采购订单列表失败:', error)
      message.error('获取采购订单列表失败')
    } finally {
      setLoading(false)
    }
  }
  
  const fetchProjects = async () => {
    try {
      const response = await fetch('/api/projects')
      const data = await response.json()
      if (data.success) setProjects(data.data)
    } catch (error) {
      console.error('获取项目列表失败:', error)
    }
  }
  
  const fetchSuppliers = async () => {
    try {
      const response = await fetch('/api/suppliers')
      const data = await response.json()
      if (data.success) setSuppliers(data.data)
    } catch (error) {
      console.error('获取供应商列表失败:', error)
    }
  }
  
  const fetchProducts = async () => {
    try {
      const response = await fetch('/api/products')
      const data = await response.json()
      if (data.success) setProducts(data.data)
    } catch (error) {
      console.error('获取商品列表失败:', error)
    }
  }
  
  const fetchOrderDetail = async (id: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${id}`)
      const data = await response.json()
      if (data.success) {
        setCurrentOrder(data.data)
        setDetailModalVisible(true)
        setActiveDetailTab('basic')
      } else {
        message.error('获取订单详情失败')
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      message.error('获取订单详情失败')
    }
  }
  
  useEffect(() => {
    fetchProjects()
    fetchSuppliers()
    fetchProducts()
  }, [])
  
  useEffect(() => {
    fetchOrders()
  }, [selectedProjectId, selectedStatus])

  const handleConfirmOrder = async (id: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${id}/confirm`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({})
      })
      const data = await response.json()
      if (data.success) {
        message.success('订单确认成功')
        fetchOrders()
      } else {
        message.error(data.message || '订单确认失败')
      }
    } catch (error) {
      console.error('订单确认失败:', error)
      message.error('订单确认失败')
    }
  }
  
  const handleCancelOrder = async (id: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${id}/cancel`, { method: 'POST' })
      const data = await response.json()
      if (data.success) {
        message.success('订单已取消')
        fetchOrders()
      } else {
        message.error('取消订单失败')
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      message.error('取消订单失败')
    }
  }
  
  const handleDeleteOrder = async (id: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${id}`, { method: 'DELETE' })
      const data = await response.json()
      if (data.success) {
        message.success('订单删除成功')
        fetchOrders()
      } else {
        message.error('删除订单失败')
      }
    } catch (error) {
      console.error('删除订单失败:', error)
      message.error('删除订单失败')
    }
  }

  const handleAddItem = () => {
    setEditingItem(null)
    itemForm.resetFields()
    setItemModalVisible(true)
  }
  
  const handleEditItem = (item: OrderItem) => {
    setEditingItem(item)
    itemForm.setFieldsValue(item)
    setItemModalVisible(true)
  }
  
  const handleSaveItem = async () => {
    try {
      const values = await itemForm.validateFields()
      const url = editingItem 
        ? `/api/purchase-orders/${currentOrder?.id}/items/${editingItem.id}`
        : `/api/purchase-orders/${currentOrder?.id}/items`
      const method = editingItem ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values)
      })
      const data = await response.json()
      
      if (data.success) {
        message.success(editingItem ? '商品更新成功' : '商品添加成功')
        setItemModalVisible(false)
        fetchOrderDetail(currentOrder!.id)
      } else {
        message.error('操作失败')
      }
    } catch (error) {
      console.error('保存商品失败:', error)
    }
  }
  
  const handleDeleteItem = async (itemId: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${currentOrder?.id}/items/${itemId}`, {
        method: 'DELETE'
      })
      const data = await response.json()
      if (data.success) {
        message.success('商品删除成功')
        fetchOrderDetail(currentOrder!.id)
      } else {
        message.error('删除失败')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }

  const handleAddPayment = () => {
    setEditingPayment(null)
    paymentForm.resetFields()
    setPaymentModalVisible(true)
  }
  
  const handleEditPayment = (plan: PaymentPlan) => {
    setEditingPayment(plan)
    paymentForm.setFieldsValue({
      ...plan,
      planned_date: plan.planned_date ? dayjs(plan.planned_date) : null
    })
    setPaymentModalVisible(true)
  }
  
  const handleSavePayment = async () => {
    try {
      const values = await paymentForm.validateFields()
      const submitData = {
        ...values,
        planned_date: values.planned_date?.format('YYYY-MM-DD')
      }
      const url = editingPayment
        ? `/api/purchase-orders/${currentOrder?.id}/payment-plans/${editingPayment.id}`
        : `/api/purchase-orders/${currentOrder?.id}/payment-plans`
      const method = editingPayment ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submitData)
      })
      const data = await response.json()
      
      if (data.success) {
        message.success(editingPayment ? '付款计划更新成功' : '付款计划添加成功')
        setPaymentModalVisible(false)
        fetchOrderDetail(currentOrder!.id)
      } else {
        message.error('操作失败')
      }
    } catch (error) {
      console.error('保存付款计划失败:', error)
    }
  }
  
  const handleDeletePayment = async (planId: number) => {
    try {
      const response = await fetch(`/api/purchase-orders/${currentOrder?.id}/payment-plans/${planId}`, {
        method: 'DELETE'
      })
      const data = await response.json()
      if (data.success) {
        message.success('付款计划删除成功')
        fetchOrderDetail(currentOrder!.id)
      } else {
        message.error('删除失败')
      }
    } catch (error) {
      console.error('删除付款计划失败:', error)
    }
  }

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      draft: { color: 'default', text: '草稿' },
      confirmed: { color: 'blue', text: '已确认' },
      partial_paid: { color: 'orange', text: '部分付款' },
      paid: { color: 'green', text: '已付清' },
      shipping: { color: 'cyan', text: '物流中' },
      verified: { color: 'purple', text: '已验收' },
      closed: { color: 'success', text: '已关闭' },
      cancelled: { color: 'error', text: '已取消' }
    }
    const info = statusMap[status] || { color: 'default', text: status }
    return <Tag color={info.color}>{info.text}</Tag>
  }
  
  const getAmountColor = (status: string) => {
    if (status === 'draft') return '#999'
    if (status === 'cancelled') return '#ff4d4f'
    if (['verified', 'closed'].includes(status)) return '#52c41a'
    return '#1890ff'
  }
  
  const columns: ColumnsType<PurchaseOrder> = [
    {
      title: '订单号',
      dataIndex: 'code',
      key: 'code',
      width: 150,
      render: (v: string, r: PurchaseOrder) => (
        <a onClick={() => fetchOrderDetail(r.id)} style={{ fontWeight: 500 }}>{v}</a>
      )
    },
    {
      title: '供应商',
      dataIndex: 'supplier_name',
      key: 'supplier_name',
      width: 140,
      render: (v: string) => v || '-'
    },
    {
      title: '项目',
      dataIndex: 'project_name',
      key: 'project_name',
      width: 120,
      render: (v: string) => v || '-'
    },
    {
      title: '金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 140,
      align: 'right',
      render: (amount: number, r: PurchaseOrder) => {
        const displayAmount = r.status === 'draft' ? r.estimated_amount : amount
        return (
          <span style={{ fontWeight: 500, color: getAmountColor(r.status) }}>
            {r.currency} {(displayAmount || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}
          </span>
        )
      }
    },
    {
      title: '已付',
      dataIndex: 'paid_amount',
      key: 'paid_amount',
      width: 120,
      align: 'right',
      render: (v: number, r: PurchaseOrder) => (
        <span style={{ color: '#52c41a' }}>
          {(v || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}
        </span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: getStatusTag
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 100,
      render: (v: string) => v ? dayjs(v).format('MM-DD') : '-'
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size={4}>
          <Button size="small" type="text" icon={<EyeOutlined />} onClick={() => fetchOrderDetail(record.id)} />
          {record.status === 'draft' && (
            <>
              <Button size="small" type="text" icon={<CheckOutlined />} style={{ color: '#52c41a' }} onClick={() => handleConfirmOrder(record.id)}>确认</Button>
              <Popconfirm title="确定要取消吗？" onConfirm={() => handleCancelOrder(record.id)}>
                <Button size="small" type="text" danger>取消</Button>
              </Popconfirm>
            </>
          )}
          {record.status === 'cancelled' && (
            <Popconfirm title="确定要删除吗？" onConfirm={() => handleDeleteOrder(record.id)}>
              <Button size="small" type="text" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          )}
        </Space>
      )
    }
  ]
  
  const itemColumns: ColumnsType<OrderItem> = [
    { title: '商品名称', dataIndex: 'product_name', key: 'product_name', width: 150 },
    { title: '规格', dataIndex: 'specification', key: 'specification', width: 100 },
    { title: '单位', dataIndex: 'unit', key: 'unit', width: 60 },
    { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80, align: 'right' },
    { title: '单价', dataIndex: 'unit_price', key: 'unit_price', width: 100, align: 'right', render: (v: number) => v?.toFixed(2) },
    { title: '小计', dataIndex: 'total_price', key: 'total_price', width: 120, align: 'right', render: (v: number) => <strong>{v?.toFixed(2)}</strong> },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render: (_, record) => currentOrder?.status === 'draft' && (
        <Space size={4}>
          <Button size="small" type="text" icon={<EditOutlined />} onClick={() => handleEditItem(record)} />
          <Popconfirm title="确定删除？" onConfirm={() => handleDeleteItem(record.id)}>
            <Button size="small" type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      )
    }
  ]
  
  const paymentColumns: ColumnsType<PaymentPlan> = [
    { title: '阶段', dataIndex: 'stage', key: 'stage', width: 80 },
    { title: '计划日期', dataIndex: 'planned_date', key: 'planned_date', width: 100 },
    { title: '计划金额', dataIndex: 'planned_amount', key: 'planned_amount', width: 120, align: 'right', render: (v: number) => v?.toFixed(2) },
    { title: '比例%', dataIndex: 'planned_percentage', key: 'planned_percentage', width: 80, align: 'right' },
    { title: '实际金额', dataIndex: 'actual_amount', key: 'actual_amount', width: 120, align: 'right', render: (v: number) => v?.toFixed(2) || '-' },
    { title: '状态', dataIndex: 'status', key: 'status', width: 80, render: (s: string) => {
      const map: Record<string, { color: string; text: string }> = {
        pending: { color: 'default', text: '待付款' },
        requested: { color: 'blue', text: '已申请' },
        paid: { color: 'green', text: '已支付' }
      }
      const info = map[s] || { color: 'default', text: s }
      return <Tag color={info.color}>{info.text}</Tag>
    }},
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render: (_, record) => record.status === 'pending' && (
        <Space size={4}>
          <Button size="small" type="text" icon={<EditOutlined />} onClick={() => handleEditPayment(record)} />
          <Popconfirm title="确定删除？" onConfirm={() => handleDeletePayment(record.id)}>
            <Button size="small" type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      )
    }
  ]
  
  const logisticsColumns: ColumnsType<LogisticsRecord> = [
    { title: '物流单号', dataIndex: 'code', key: 'code', width: 120 },
    { title: '发货地', dataIndex: 'ship_from', key: 'ship_from', width: 80, render: (v: string) => v === 'China' ? '中国' : '老挝' },
    { title: '物流公司', dataIndex: 'logistics_company_name', key: 'logistics_company_name', width: 120 },
    { title: '发货日期', dataIndex: 'ship_date', key: 'ship_date', width: 100 },
    { title: '一次运费', dataIndex: 'primary_freight', key: 'primary_freight', width: 100, align: 'right', render: (v: number) => v?.toFixed(2) || '-' },
    { title: '二次运费', dataIndex: 'secondary_freight', key: 'secondary_freight', width: 100, align: 'right', render: (v: number) => v?.toFixed(2) || '-' },
    { title: '状态', dataIndex: 'status', key: 'status', width: 80, render: getStatusTag }
  ]
  
  const verificationColumns: ColumnsType<VerificationRecord> = [
    { title: '验收单号', dataIndex: 'code', key: 'code', width: 120 },
    { title: '验收日期', dataIndex: 'verification_date', key: 'verification_date', width: 100 },
    { title: '验收人', dataIndex: 'verifier', key: 'verifier', width: 80 },
    { title: '验收数量', dataIndex: 'total_verified', key: 'total_verified', width: 100, align: 'right' },
    { title: '状态', dataIndex: 'status', key: 'status', width: 80, render: getStatusTag }
  ]

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ marginBottom: 8 }}>采购订单</h2>
        <p style={{ color: '#888', marginBottom: 0 }}>管理采购订单（多TAB：基本信息、商品明细、付款信息、物流信息、验收记录）</p>
      </div>

      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Select placeholder="选择项目筛选" allowClear style={{ width: '100%' }} onChange={(v) => setSelectedProjectId(v)}>
              {projects.map(p => <Select.Option key={p.id} value={p.id}>{p.name}</Select.Option>)}
            </Select>
          </Col>
          <Col span={6}>
            <Select placeholder="选择状态筛选" allowClear style={{ width: '100%' }} onChange={(v) => setSelectedStatus(v)}>
              <Select.Option value="draft">草稿</Select.Option>
              <Select.Option value="confirmed">已确认</Select.Option>
              <Select.Option value="partial_paid">部分付款</Select.Option>
              <Select.Option value="paid">已付清</Select.Option>
              <Select.Option value="shipping">物流中</Select.Option>
              <Select.Option value="verified">已验收</Select.Option>
              <Select.Option value="cancelled">已取消</Select.Option>
            </Select>
          </Col>
        </Row>
        <Table columns={columns} dataSource={orders} rowKey="id" loading={loading} pagination={{ pageSize: 20 }} size="small" scroll={{ x: 1200 }} />
      </Card>
      
      {/* 订单详情弹窗 - 多TAB */}
      <Modal
        title={`采购订单详情 - ${currentOrder?.code || ''}`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={1000}
      >
        {currentOrder && (
          <Tabs activeKey={activeDetailTab} onChange={setActiveDetailTab}>
            {/* TAB1: 基本信息 */}
            <Tabs.TabPane tab={<span><FileTextOutlined /> 基本信息</span>} key="basic">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="订单号">{currentOrder.code}</Descriptions.Item>
                <Descriptions.Item label="状态">{getStatusTag(currentOrder.status)}</Descriptions.Item>
                <Descriptions.Item label="供应商">{currentOrder.supplier_name || '-'}</Descriptions.Item>
                <Descriptions.Item label="供应商国家">{currentOrder.supplier_country === 'China' ? '中国' : (currentOrder.supplier_country || '老挝')}</Descriptions.Item>
                <Descriptions.Item label="项目">{currentOrder.project_name || '-'}</Descriptions.Item>
                <Descriptions.Item label="币种">{currentOrder.currency}</Descriptions.Item>
                <Descriptions.Item label="预计金额">
                  <span style={{ color: '#999' }}>{currentOrder.estimated_amount?.toFixed(2) || '0.00'}</span>
                </Descriptions.Item>
                <Descriptions.Item label="订单金额">
                  <span style={{ fontWeight: 'bold', color: getAmountColor(currentOrder.status) }}>
                    {currentOrder.total_amount?.toFixed(2) || '0.00'}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="已付金额">
                  <span style={{ color: '#52c41a' }}>{currentOrder.paid_amount?.toFixed(2) || '0.00'}</span>
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">{currentOrder.created_at}</Descriptions.Item>
                {currentOrder.remark && <Descriptions.Item label="备注" span={2}>{currentOrder.remark}</Descriptions.Item>}
              </Descriptions>
            </Tabs.TabPane>
            
            {/* TAB2: 商品明细 */}
            <Tabs.TabPane tab={<span><FileTextOutlined /> 商品明细</span>} key="items">
              {currentOrder.status === 'draft' && (
                <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddItem} style={{ marginBottom: 16 }}>添加商品</Button>
              )}
              <Table columns={itemColumns} dataSource={currentOrder.items || []} rowKey="id" pagination={false} size="small" />
              <div style={{ marginTop: 16, textAlign: 'right' }}>
                <strong>商品总计：{currentOrder.currency} {(currentOrder.items || []).reduce((sum, item) => sum + (item.total_price || 0), 0).toFixed(2)}</strong>
              </div>
            </Tabs.TabPane>
            
            {/* TAB3: 付款信息 */}
            <Tabs.TabPane tab={<span><FileTextOutlined /> 付款信息</span>} key="payment">
              {currentOrder.status !== 'draft' && currentOrder.status !== 'cancelled' && (
                <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddPayment} style={{ marginBottom: 16 }}>添加付款计划</Button>
              )}
              <Table columns={paymentColumns} dataSource={currentOrder.payment_plans || []} rowKey="id" pagination={false} size="small" />
            </Tabs.TabPane>
            
            {/* TAB4: 物流信息 */}
            <Tabs.TabPane tab={<span><CarOutlined /> 物流信息</span>} key="logistics">
              <Table columns={logisticsColumns} dataSource={currentOrder.logistics || []} rowKey="id" pagination={false} size="small" />
              {(currentOrder.logistics || []).length === 0 && <div style={{ textAlign: 'center', color: '#999', padding: 20 }}>暂无物流信息</div>}
            </Tabs.TabPane>
            
            {/* TAB5: 验收记录 */}
            <Tabs.TabPane tab={<span><SafetyCertificateOutlined /> 验收记录</span>} key="verification">
              <Table columns={verificationColumns} dataSource={currentOrder.verifications || []} rowKey="id" pagination={false} size="small" />
              {(currentOrder.verifications || []).length === 0 && <div style={{ textAlign: 'center', color: '#999', padding: 20 }}>暂无验收记录</div>}
            </Tabs.TabPane>
          </Tabs>
        )}
      </Modal>
      
      {/* 商品明细编辑弹窗 */}
      <Modal
        title={editingItem ? '编辑商品' : '添加商品'}
        open={itemModalVisible}
        onOk={handleSaveItem}
        onCancel={() => setItemModalVisible(false)}
        width={600}
      >
        <Form form={itemForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="product_id" label="选择商品">
                <Select placeholder="选择商品" allowClear showSearch optionFilterProp="children" onChange={(v) => {
                  const product = products.find(p => p.id === v)
                  if (product) {
                    itemForm.setFieldsValue({
                      product_name: product.name,
                      specification: product.specification,
                      unit: product.unit
                    })
                  }
                }}>
                  {products.map(p => <Select.Option key={p.id} value={p.id}>{p.name}</Select.Option>)}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="product_name" label="商品名称" rules={[{ required: true }]}>
                <Input placeholder="商品名称" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="specification" label="规格">
                <Input placeholder="规格" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="unit" label="单位">
                <Input placeholder="单位" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="quantity" label="数量" rules={[{ required: true }]}>
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="unit_price" label="单价" rules={[{ required: true }]}>
                <InputNumber min={0} precision={2} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      
      {/* 付款计划编辑弹窗 */}
      <Modal
        title={editingPayment ? '编辑付款计划' : '添加付款计划'}
        open={paymentModalVisible}
        onOk={handleSavePayment}
        onCancel={() => setPaymentModalVisible(false)}
        width={500}
      >
        <Form form={paymentForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="stage" label="阶段" rules={[{ required: true }]}>
                <Select placeholder="选择阶段">
                  <Select.Option value="预付款">预付款</Select.Option>
                  <Select.Option value="发货款">发货款</Select.Option>
                  <Select.Option value="验收款">验收款</Select.Option>
                  <Select.Option value="尾款">尾款</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="planned_date" label="计划日期">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="planned_amount" label="计划金额" rules={[{ required: true }]}>
                <InputNumber min={0} precision={2} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="planned_percentage" label="比例(%)">
                <InputNumber min={0} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default PurchaseOrdersPage
