/**
 * 销售记录操作模态框组件
 * 作者: 阿瑞
 * 功能: 提供销售记录的退货、换货、退差、补发操作界面
 * 版本: 1.0.0
 */

'use client';

import React, { useState } from 'react';
import Image from 'next/image';
import Modal from '@/components/ui/Modal';
import Card from '@/components/ui/Card';
import { SalesRecord } from '@/models/team/types/old/sales';
import { MdPerson, MdPhone, MdShoppingCart, MdAttachMoney, MdCalendarToday, MdImage, MdSwapHoriz } from 'react-icons/md';
import { formatDate } from '@/utils';

/**
 * 操作类型枚举
 */
export enum OperationType {
  RETURN = 'return',    // 退货
  EXCHANGE = 'exchange', // 换货
  REFUND = 'refund',    // 退差价
  REPLENISH = 'replenish' // 补发
}

/**
 * 操作类型中文名映射
 */
const OperationNames = {
  [OperationType.RETURN]: '退货',
  [OperationType.EXCHANGE]: '换货',
  [OperationType.REFUND]: '退差',
  [OperationType.REPLENISH]: '补发'
};

/**
 * 售后处理进度枚举
 */
enum AfterSalesProgress {
  PENDING = '待处理',
  PROCESSING = '处理中',
  COMPLETED = '已处理'
}

/**
 * 交易类型枚举
 */
enum TransactionType {
  INCOME = '收入',
  EXPENSE = '支出'
}

/**
 * 格式化金额显示
 */
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined || amount === null) return '¥0.00';
  return `¥${Number(amount).toFixed(2)}`;
};

/**
 * 扩展的销售记录接口，使用与页面一致的类型
 */
interface SalesRecordWithDetails extends Omit<SalesRecord, 'products'> {
  products?: {
    productId: number;
    productName?: string;
    productCode?: string;
    price: number;
    quantity: number;
    brandName?: string;
    categoryName?: string;
    supplierName?: string;
    image?: string;
  }[];
  // 客户信息
  customerName?: string;
  customerPhone?: string;
  customerFollowDate?: string;
  customerAddress?: string;
  // 店铺信息
  sourceName?: string;
  sourceWechat?: string;
  sourcePhone?: string;
  sourceAccountNo?: string;
  // 成交店铺信息
  dealShopId?: number;
  dealShopName?: string;
  dealShopWechat?: string;
  dealShopPhone?: string;
  dealShopAccountNo?: string;
  // 导购信息
  guideName?: string;
  guideUsername?: string;
  guidePhone?: string;
  guideWechat?: string;
  // 支付平台信息
  platformName?: string;
}

/**
 * 组件Props接口
 */
interface SalesRecordModalProps {
  isOpen: boolean;
  onClose: () => void;
  salesRecord: SalesRecordWithDetails;
  operationType: OperationType;
}

/**
 * 操作信息项接口
 */
interface OperationInfoItem {
  label: string;
  value: string | number;
  valueClass?: string;
}

/**
 * 售后记录表单数据接口
 */
interface AfterSalesFormData {
  type: string;
  date: string;
  reason: string;
  progress: AfterSalesProgress;
  transactionType: TransactionType | '';
  platformId?: number;
  amount: number;
  pending: number;
  remark: string;
  selectedOriginalProducts: {
    productId: number;
    quantity: number;
  }[];
  selectedReplacementProducts: {
    productId: number;
    quantity: number;
  }[];
}

/**
 * 产品项目接口，用于渲染产品列表项
 */
interface ProductItem {
  productId: number;
  productName?: string;
  productCode?: string;
  price: number;
  quantity: number;
  brandName?: string;
  categoryName?: string;
  supplierName?: string;
  image?: string;
}

/**
 * 产品选择器组件，简化版，仅用于选择替换产品
 */
const ReplacementProductSelector: React.FC<{
  onSelectProduct: (product: ProductItem) => void;
}> = ({ onSelectProduct }) => {
  const [searchKeyword, setSearchKeyword] = useState('');
  const [searchResults, setSearchResults] = useState<ProductItem[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  
  /**
   * 处理搜索产品
   */
  const handleSearch = async () => {
    if (!searchKeyword.trim()) return;
    
    setIsSearching(true);
    
    try {
      // 模拟API调用，实际项目中应该调用真实API
      // 这里使用一些示例数据来演示
      const mockProducts: ProductItem[] = [
        {
          productId: 1001,
          productName: '示例产品 A - ' + searchKeyword,
          productCode: 'SKU001',
          price: 199,
          quantity: 10,
          brandName: '品牌A',
          categoryName: '分类A',
          image: ''
        },
        {
          productId: 1002, 
          productName: '示例产品 B - ' + searchKeyword,
          productCode: 'SKU002',
          price: 299,
          quantity: 5,
          brandName: '品牌B',
          categoryName: '分类B',
          image: ''
        }
      ];
      
      // 延迟一下模拟网络请求
      setTimeout(() => {
        setSearchResults(mockProducts);
        setIsDropdownOpen(true);
        setIsSearching(false);
      }, 500);
      
    } catch (error) {
      console.error('搜索产品失败:', error);
      setSearchResults([]);
      setIsSearching(false);
    }
  };
  
  /**
   * 处理选择产品
   */
  const handleSelectProduct = (product: ProductItem) => {
    onSelectProduct(product);
    setIsDropdownOpen(false);
    setSearchKeyword('');
  };
  
  return (
    <div className="relative">
      <div className="relative">
        <input
          type="text"
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
          placeholder="搜索要替换的产品..."
          className="w-full pl-10 pr-16 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
        />
        <MdSwapHoriz className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
        
        <button
          type="button"
          onClick={handleSearch}
          disabled={isSearching || !searchKeyword.trim()}
          className={`absolute right-2 top-1/2 transform -translate-y-1/2 px-2 py-1 text-xs rounded ${
            isSearching || !searchKeyword.trim() 
              ? 'bg-gray-300 text-gray-500 cursor-not-allowed' 
              : 'bg-blue-500 text-white hover:bg-blue-600'
          }`}
        >
          {isSearching ? '...' : '搜索'}
        </button>
      </div>
      
      {/* 搜索结果下拉菜单 */}
      {isDropdownOpen && searchResults.length > 0 && (
        <div className="absolute z-10 mt-1 w-full bg-white dark:bg-gray-800 shadow-lg border border-gray-200 dark:border-gray-700 rounded-md max-h-60 overflow-auto">
          <ul>
            {searchResults.map(product => (
              <li 
                key={product.productId}
                onClick={() => handleSelectProduct(product)}
                className="px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-0"
              >
                <div className="font-medium text-gray-800 dark:text-white flex items-center justify-between">
                  <span>{product.productName}</span>
                  <span className="text-blue-600 dark:text-blue-400">
                    {formatAmount(product.price)}
                  </span>
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-300 flex justify-between">
                  <span>{product.productCode && `编码: ${product.productCode}`}</span>
                  <span>库存: {product.quantity}</span>
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {/* 无搜索结果提示 */}
      {isDropdownOpen && searchKeyword && searchResults.length === 0 && !isSearching && (
        <div className="absolute z-10 mt-1 w-full bg-white dark:bg-gray-800 shadow-lg border border-gray-200 dark:border-gray-700 rounded-md p-4 text-center text-gray-500 dark:text-gray-400">
          未找到匹配的产品
        </div>
      )}
    </div>
  );
};

/**
 * 销售记录操作模态框组件
 */
const SalesRecordModal: React.FC<SalesRecordModalProps> = ({
  isOpen,
  onClose,
  salesRecord,
  operationType
}) => {
  // 售后记录表单数据
  const [formData, setFormData] = useState<AfterSalesFormData>({
    type: OperationNames[operationType],
    date: formatDate(new Date(), 'YYYY-MM-DD'),
    reason: '',
    progress: AfterSalesProgress.PENDING,
    transactionType: '',
    platformId: undefined,
    amount: 0,
    pending: 0,
    remark: '',
    selectedOriginalProducts: [],
    selectedReplacementProducts: []
  });

  // 已选择的原始产品
  const [selectedOriginalProducts, setSelectedOriginalProducts] = useState<Array<{
    productId: number,
    productName?: string,
    price: number,
    quantity: number,
    selected: number
  }>>([]);

  // 已选择的替换产品（仅用于换货和补发）
  const [selectedReplacementProducts, setSelectedReplacementProducts] = useState<Array<{
    productId: number,
    productName?: string,
    price: number,
    quantity: number
  }>>([]);

  /**
   * 格式化日期
   */
  const formatFriendlyDate = (dateStr: string | undefined | null): string => {
    if (!dateStr) return '-';
    return formatDate(dateStr, 'YYYY-MM-DD');
  };

  /**
   * 处理表单数据变更
   */
  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  /**
   * 处理原始产品选择变更
   */
  const handleOriginalProductSelect = (productId: number, quantity: number) => {
    // 找到对应的产品
    const product = salesRecord.products?.find(p => p.productId === productId);
    if (!product) return;

    // 更新已选产品列表
    if (quantity > 0) {
      const existingIndex = selectedOriginalProducts.findIndex(p => p.productId === productId);
      if (existingIndex >= 0) {
        // 更新已有产品
        const updatedProducts = [...selectedOriginalProducts];
        updatedProducts[existingIndex].selected = quantity;
        setSelectedOriginalProducts(updatedProducts);
      } else {
        // 添加新产品
        setSelectedOriginalProducts([
          ...selectedOriginalProducts,
          {
            productId: product.productId,
            productName: product.productName,
            price: product.price,
            quantity: product.quantity,
            selected: quantity
          }
        ]);
      }
    } else {
      // 移除产品
      setSelectedOriginalProducts(selectedOriginalProducts.filter(p => p.productId !== productId));
    }

    // 更新表单数据
    const updatedSelectedProducts = selectedOriginalProducts
      .map(p => p.productId === productId ? { ...p, selected: quantity } : p)
      .filter(p => p.selected > 0);

    if (quantity > 0 && !updatedSelectedProducts.find(p => p.productId === productId)) {
      updatedSelectedProducts.push({
        productId: product.productId,
        productName: product.productName,
        price: product.price,
        quantity: product.quantity,
        selected: quantity
      });
    }

    // 计算涉及金额
    const totalAmount = updatedSelectedProducts.reduce(
      (sum, p) => sum + (p.price * p.selected), 0
    );

    setFormData(prev => ({
      ...prev,
      amount: totalAmount,
      selectedOriginalProducts: updatedSelectedProducts.map(p => ({
        productId: p.productId,
        quantity: p.selected
      }))
    }));
  };
  
  /**
   * 渲染产品图片
   */
  const renderProductImage = (image?: string, productName?: string) => {
    if (image) {
      return (
        <div className="relative w-14 h-14 rounded-md overflow-hidden border border-gray-200 dark:border-gray-700 flex-shrink-0">
          <Image
            src={image}
            alt={productName || '产品图片'}
            fill
            sizes="56px"
            className="object-cover"
          />
        </div>
      );
    }
    
    // 没有图片时显示占位符
    return (
      <div className="w-14 h-14 rounded-md flex items-center justify-center bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex-shrink-0">
        <MdImage className="text-gray-400" size={24} />
      </div>
    );
  };
  
  /**
   * 渲染产品项目
   */
  const renderProductItem = (product: ProductItem, selected: number = 0) => {
    return (
      <div key={product.productId} className="flex items-center p-2 bg-gray-50 dark:bg-gray-800 rounded-md gap-3 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
        {/* 产品图片 */}
        {renderProductImage(product.image, product.productName)}
        
        {/* 产品信息 */}
        <div className="flex-1 min-w-0">
          <div className="font-medium text-sm truncate">{product.productName || `产品 #${product.productId}`}</div>
          <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
            <span className="inline-block px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded mr-1">
              {formatAmount(product.price)}
            </span>
            {product.brandName && (
              <span className="inline-block px-1.5 py-0.5 bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 rounded mr-1">
                {product.brandName}
              </span>
            )}
            {product.categoryName && (
              <span className="inline-block px-1.5 py-0.5 bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 rounded">
                {product.categoryName}
              </span>
            )}
          </div>
        </div>
        
        {/* 数量选择 */}
        <div className="flex items-center">
          <input
            type="number"
            min="0"
            max={product.quantity}
            value={selected}
            onChange={(e) => handleOriginalProductSelect(product.productId, Number(e.target.value))}
            className="w-16 px-2 py-1 border border-gray-300 rounded-md shadow-sm text-center focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          />
          <span className="ml-2 text-sm text-gray-500 dark:text-gray-400">/ {product.quantity}</span>
        </div>
      </div>
    );
  };
  
  /**
   * 处理替换产品选择
   */
  const handleReplacementProductSelect = (product: ProductItem) => {
    // 添加到替换产品列表
    setSelectedReplacementProducts([
      ...selectedReplacementProducts,
      {
        productId: product.productId,
        productName: product.productName,
        price: product.price,
        quantity: 1 // 默认选择1个
      }
    ]);
    
    // 更新表单数据
    setFormData(prev => ({
      ...prev,
      selectedReplacementProducts: [
        ...prev.selectedReplacementProducts,
        { productId: product.productId, quantity: 1 }
      ]
    }));
  };
  
  /**
   * 处理替换产品数量变更
   */
  const handleReplacementQuantityChange = (productId: number, quantity: number) => {
    if (quantity <= 0) {
      // 移除产品
      setSelectedReplacementProducts(
        selectedReplacementProducts.filter(p => p.productId !== productId)
      );
      setFormData(prev => ({
        ...prev,
        selectedReplacementProducts: prev.selectedReplacementProducts.filter(
          p => p.productId !== productId
        )
      }));
    } else {
      // 更新数量
      setSelectedReplacementProducts(
        selectedReplacementProducts.map(p => 
          p.productId === productId ? { ...p, quantity } : p
        )
      );
      setFormData(prev => ({
        ...prev,
        selectedReplacementProducts: prev.selectedReplacementProducts.map(p => 
          p.productId === productId ? { ...p, quantity } : p
        )
      }));
    }
  };
  
  /**
   * 移除替换产品
   */
  const handleRemoveReplacementProduct = (productId: number) => {
    setSelectedReplacementProducts(
      selectedReplacementProducts.filter(p => p.productId !== productId)
    );
    setFormData(prev => ({
      ...prev,
      selectedReplacementProducts: prev.selectedReplacementProducts.filter(
        p => p.productId !== productId
      )
    }));
  };
  
  /**
   * 渲染替换产品列表
   */
  const renderReplacementProducts = () => {
    if (selectedReplacementProducts.length === 0) {
      return (
        <div className="text-center py-4 text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 dark:border-gray-700 rounded-md">
          还没有选择替换产品
        </div>
      );
    }
    
    return (
      <div className="space-y-2 max-h-[280px] overflow-y-auto">
        {selectedReplacementProducts.map(product => (
          <div key={product.productId} className="flex items-center p-2 bg-blue-50 dark:bg-blue-900/20 rounded-md gap-3">
            <div className="flex-1 min-w-0">
              <div className="font-medium text-sm">{product.productName || `产品 #${product.productId}`}</div>
              <div className="text-sm text-gray-500 dark:text-gray-400">
                单价: {formatAmount(product.price)}
              </div>
            </div>
            
            <div className="flex items-center">
              <input
                type="number"
                min="1"
                value={product.quantity}
                onChange={(e) => handleReplacementQuantityChange(product.productId, Number(e.target.value))}
                className="w-16 px-2 py-1 border border-gray-300 rounded-md shadow-sm text-center focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
              <button
                onClick={() => handleRemoveReplacementProduct(product.productId)}
                className="ml-2 p-1 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"
              >
                ×
              </button>
            </div>
          </div>
        ))}
        
        <div className="pt-2 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <span className="text-sm">替换产品总价:</span>
          <span className="font-medium text-blue-600 dark:text-blue-400">
            {formatAmount(selectedReplacementProducts.reduce((sum, p) => sum + (p.price * p.quantity), 0))}
          </span>
        </div>
      </div>
    );
  };
  
  /**
   * 渲染客户信息卡片
   */
  const renderCustomerCard = () => {
    return (
      <Card title="客户信息" padding="medium" className="h-full flex flex-col">
        <div className="grid grid-cols-1 gap-4 flex-grow">
          <div className="flex items-center">
            <MdPerson className="text-blue-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">客户名称</div>
              <div className="font-medium">{salesRecord.customerName || '未知客户'}</div>
            </div>
          </div>
          <div className="flex items-center">
            <MdPhone className="text-green-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">联系电话</div>
              <div className="font-medium">{salesRecord.customerPhone || '-'}</div>
            </div>
          </div>
          <div className="flex items-center">
            <MdShoppingCart className="text-purple-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">商品数量</div>
              <div className="font-medium">
                {salesRecord.products ? salesRecord.products.reduce((sum, p) => sum + p.quantity, 0) : 0} 件
              </div>
            </div>
          </div>
          <div className="flex items-center">
            <MdAttachMoney className="text-yellow-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">订单总额</div>
              <div className="font-medium">
                {formatAmount(salesRecord.receivable)}
              </div>
            </div>
          </div>
          
          {/* 订单信息 */}
          <div className="flex items-center">
            <MdCalendarToday className="text-orange-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">成交日期</div>
              <div className="font-medium">{formatFriendlyDate(salesRecord.dealDate)}</div>
            </div>
          </div>
          
          {/* 导购信息 */}
          <div className="flex items-center">
            <MdPerson className="text-indigo-500 mr-2" size={20} />
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">导购信息</div>
              <div className="font-medium">{salesRecord.guideName || '-'}</div>
            </div>
          </div>
          
          {/* 总计信息 */}
          {selectedOriginalProducts.length > 0 && (
            <div className="mt-auto pt-4 border-t border-gray-200 dark:border-gray-700">
              <div className="flex justify-between items-center font-medium">
                <span>已选商品总价:</span>
                <span className="text-lg text-blue-600 dark:text-blue-400">
                  {formatAmount(selectedOriginalProducts.reduce((sum, p) => sum + (p.price * p.selected), 0))}
                </span>
              </div>
              
              {/* 换货时显示差价 */}
              {operationType === OperationType.EXCHANGE && selectedReplacementProducts.length > 0 && (
                <>
                  <div className="flex justify-between items-center text-sm mt-2">
                    <span>替换商品总价:</span>
                    <span className="text-blue-600 dark:text-blue-400">
                      {formatAmount(selectedReplacementProducts.reduce((sum, p) => sum + (p.price * p.quantity), 0))}
                    </span>
                  </div>
                  <div className="flex justify-between items-center font-medium mt-2 pt-2 border-t border-gray-200 dark:border-gray-700">
                    <span>差额:</span>
                    <span className={`text-lg ${priceDifference >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
                      {formatAmount(priceDifference)}
                    </span>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </Card>
    );
  };
  
  /**
   * 计算价格差额
   */
  const priceDifference = selectedReplacementProducts.reduce((sum, p) => sum + (p.price * p.quantity), 0) - 
                          selectedOriginalProducts.reduce((sum, p) => sum + (p.price * p.selected), 0);
  
  /**
   * 渲染操作信息卡片，根据不同操作类型显示不同内容
   */
  const renderOperationCard = () => {
    const operationName = OperationNames[operationType];
    
    // 根据操作类型添加特定字段
    const specificInfo: OperationInfoItem[] = [];
    
    switch (operationType) {
      case OperationType.RETURN:
        specificInfo.push({ label: '支付方式', value: salesRecord.platformName || '-' });
        break;
      case OperationType.EXCHANGE:
        specificInfo.push({ label: '导购', value: salesRecord.guideName || '-' });
        break;
      case OperationType.REFUND:
        specificInfo.push({ 
          label: '实收金额', 
          value: formatAmount(salesRecord.received),
          valueClass: 'font-medium text-green-600 dark:text-green-400'
        });
        break;
      case OperationType.REPLENISH:
        specificInfo.push({ label: '店铺', value: salesRecord.dealShopName || '-' });
        break;
    }
    
    return (
      <Card title={`${operationName}信息`} padding="medium">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            {/* 售后处理日期 */}
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">处理日期</div>
              <input
                type="date"
                name="date"
                value={formData.date}
                onChange={handleFormChange}
                className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
            </div>

            {/* 售后处理状态 */}
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">处理状态</div>
              <select
                name="progress"
                value={formData.progress}
                onChange={handleFormChange}
                className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              >
                <option value={AfterSalesProgress.PENDING}>{AfterSalesProgress.PENDING}</option>
                <option value={AfterSalesProgress.PROCESSING}>{AfterSalesProgress.PROCESSING}</option>
                <option value={AfterSalesProgress.COMPLETED}>{AfterSalesProgress.COMPLETED}</option>
              </select>
            </div>

            {/* 收支类型 */}
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">交易类型</div>
              <select
                name="transactionType"
                value={formData.transactionType}
                onChange={handleFormChange}
                className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              >
                <option value="">请选择交易类型</option>
                <option value={TransactionType.INCOME}>{TransactionType.INCOME}</option>
                <option value={TransactionType.EXPENSE}>{TransactionType.EXPENSE}</option>
              </select>
            </div>

            {/* 金额信息 */}
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400">
                {!formData.transactionType ? '金额' : 
                 formData.transactionType === TransactionType.INCOME ? '收入金额' : '支出金额'}
              </div>
              <input
                type="number"
                min="0"
                step="0.01"
                name="amount"
                value={formData.amount}
                onChange={handleFormChange}
                className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                placeholder={!formData.transactionType ? "请先选择交易类型" : ""}
              />
            </div>
          </div>
          
          {/* 售后原因 */}
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              {operationName}原因
            </div>
            <textarea
              name="reason"
              value={formData.reason}
              onChange={handleFormChange}
              rows={3}
              className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              placeholder={`请输入${operationName}原因...`}
            />
          </div>
          
          {/* 选择相关产品 */}
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400 mb-2 flex justify-between">
              <span>选择{operationName}商品</span>
              <span className="text-blue-500">{selectedOriginalProducts.length > 0 ? `已选${selectedOriginalProducts.length}件商品` : ''}</span>
            </div>
            {salesRecord.products && salesRecord.products.length > 0 ? (
              <div className="space-y-2 max-h-[280px] overflow-y-auto p-2 border border-gray-200 dark:border-gray-700 rounded-md">
                {salesRecord.products.map(product => (
                  renderProductItem(
                    product, 
                    selectedOriginalProducts.find(p => p.productId === product.productId)?.selected || 0
                  )
                ))}
              </div>
            ) : (
              <div className="text-center py-4 text-gray-500">没有可选的产品</div>
            )}
          </div>
          
          {/* 换货类型时，显示替换产品选择器 */}
          {operationType === OperationType.EXCHANGE && (
            <div>
              <div className="text-sm text-gray-500 dark:text-gray-400 mb-2">
                选择替换产品
              </div>
              <ReplacementProductSelector onSelectProduct={handleReplacementProductSelect} />
              
              <div className="mt-3">
                <div className="text-sm text-gray-500 dark:text-gray-400 mb-2 flex justify-between">
                  <span>已选择的替换产品</span>
                  <span className="text-blue-500">
                    {selectedReplacementProducts.length > 0 ? `${selectedReplacementProducts.length}件产品` : ''}
                  </span>
                </div>
                {renderReplacementProducts()}
              </div>
            </div>
          )}
          
          {/* 备注 */}
          <div>
            <div className="text-sm text-gray-500 dark:text-gray-400">备注</div>
            <textarea
              name="remark"
              value={formData.remark}
              onChange={handleFormChange}
              rows={2}
              className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              placeholder="其他说明..."
            />
          </div>
        </div>
      </Card>
    );
  };
  
  /**
   * 处理提交表单
   */
  const handleSubmit = () => {
    // 检查是否选择了商品
    if (selectedOriginalProducts.length === 0) {
      alert('请选择至少一件商品');
      return;
    }
    
    // 检查是否选择了交易类型
    if (!formData.transactionType) {
      alert('请选择交易类型');
      return;
    }
    
    // 如果是换货类型，检查是否选择了替换产品
    if (operationType === OperationType.EXCHANGE && selectedReplacementProducts.length === 0) {
      alert('请选择替换产品');
      return;
    }
    
    // 这里可以添加表单验证逻辑
    // 然后提交到API
    console.log('提交售后记录:', {
      ...formData,
      priceDifference: operationType === OperationType.EXCHANGE ? priceDifference : undefined
    });
    
    // 关闭模态框
    onClose();
  };
  
  /**
   * 渲染模态框页脚
   */
  const renderFooter = () => {
    return (
      <div className="flex justify-end space-x-3">
        <button
          onClick={onClose}
          className="px-4 py-2 rounded-md text-gray-700 bg-gray-200 hover:bg-gray-300 dark:text-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 transition-colors"
        >
          取消
        </button>
        <button
          onClick={handleSubmit}
          className="px-4 py-2 rounded-md text-white bg-blue-500 hover:bg-blue-600 transition-colors"
        >
          确认
        </button>
      </div>
    );
  };
  
  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={`创建${OperationNames[operationType]}记录`}
      size="xl"
      footer={renderFooter()}
      width="80%"
      className="max-w-[1400px]"
    >
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="lg:col-span-1">
          {renderCustomerCard()}
        </div>
        <div className="lg:col-span-2">
          {renderOperationCard()}
        </div>
      </div>
    </Modal>
  );
};

export default SalesRecordModal;
