/**
 * 销售记录创建页面
 * 作者: 阿瑞
 * 功能: 提供创建销售记录的表单界面
 * 版本: 1.6.0
 */

'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import { useTeam } from '@/hooks/useTeam';
import { useThemeMode } from '@/store/settingStore';
import { useUserProfile } from '@/hooks/useUser';
import { ThemeMode } from '@/types/enum';
import { formatDate } from '@/utils';
import { PaymentType } from '@/models/team/types/old/sales';
import { Customer } from '@/models/team/types/old/customer';
import { Product } from '@/models/team/types/old/product';
import { Shop } from '@/models/team/types/old/shop';
import { PaymentPlatform } from '@/models/team/types/old/payment-platform';
import { MdShoppingCart, MdAddCircleOutline, MdPerson } from 'react-icons/md';
import Card from '@/components/ui/Card';
import CustomerSelector from './components/CustomerSelector';
import CustomerSelectorInfo from './components/CustomerSelectorInfo';
import ProductSelector from './components/ProductSelector';
import SelectedProductList from './components/SelectedProductList';
import ProductModalAdapter from './components/ProductModalAdapter';
import Button from '@/components/ui/Button';

/**
 * 销售记录创建页面组件
 * 布局分为上下两部分，上部分为产品选择和已选产品列表，下部分为客户信息和详细信息
 */
export default function SalesPage() {
  const params = useParams();
  const teamCode = params?.teamCode as string;
  useTeam();
  const themeMode = useThemeMode();
  const isDarkMode = themeMode === ThemeMode.Dark;
  const userProfile = useUserProfile(); // 获取用户信息

  // 表单数据状态
  const [formData, setFormData] = useState({
    customerId: 0,
    sourceId: undefined as number | undefined,
    paymentType: undefined as PaymentType | undefined,
    dealDate: formatDate(new Date(), 'YYYY-MM-DD'),
    receivable: 0,
    received: 0,
    pending: 0,
    platformId: undefined as number | undefined,
    dealShopId: undefined as number | undefined,
    remark: '',
    products: [] as {
      productId: number;
      name: string;
      price: number;
      quantity: number;
      total: number;
      image?: string;
      supplierName?: string;
      brandName?: string;
      code?: string;
      sku?: string;
      stock?: number;
    }[]
  });

  // 选择器数据状态
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [, setSelectedProduct] = useState<Product | null>(null);

  // 加载状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // 数据列表
  const [shops, setShops] = useState<Shop[]>([]);
  const [platforms, setPlatforms] = useState<PaymentPlatform[]>([]);

  // 新增产品模态框状态
  const [isProductModalOpen, setIsProductModalOpen] = useState(false);
  const [suppliers, setSuppliers] = useState<{ id: number; name: string }[]>([]);
  const [brands, setBrands] = useState<{ id: number; name: string }[]>([]);
  const [categories, setCategories] = useState<{ id: number; name: string }[]>([]);
  const [availableLevels, setAvailableLevels] = useState<string[]>([]);

  // 视图状态
  const [isPageLoading, setIsPageLoading] = useState(true);

  /**
   * 加载支付平台数据
   */
  const fetchPaymentPlatforms = useCallback(async () => {
    if (!teamCode) return;

    try {
      const response = await fetch(`/api/team/${teamCode}/payment-platforms`);

      if (response.ok) {
        const data = await response.json();
        setPlatforms(data.paymentPlatforms || []);
      }
    } catch (error) {
      console.error('加载支付平台失败:', error);
    }
  }, [teamCode]);

  /**
   * 加载店铺数据
   */
  const fetchShops = useCallback(async () => {
    if (!teamCode) return;

    try {
      const response = await fetch(`/api/team/${teamCode}/shops`);

      if (response.ok) {
        const data = await response.json();
        setShops(data.shops || []);
      }
    } catch (error) {
      console.error('加载店铺失败:', error);
    }
  }, [teamCode]);

  /**
   * 加载产品相关数据（供应商、品牌、品类）
   */
  const fetchProductRelatedData = useCallback(async () => {
    if (!teamCode) return;

    try {
      // 加载供应商
      const suppliersResponse = await fetch(`/api/team/${teamCode}/suppliers?pageSize=100`);

      if (suppliersResponse.ok) {
        const data = await suppliersResponse.json();
        setSuppliers(data.suppliers.map((s: { id: number; name: string }) => ({ id: s.id, name: s.name })));
      }

      // 加载品牌
      const brandsResponse = await fetch(`/api/team/${teamCode}/brands?pageSize=100`);

      if (brandsResponse.ok) {
        const data = await brandsResponse.json();
        setBrands(data.brands.map((b: { id: number; name: string }) => ({ id: b.id, name: b.name })));
      }

      // 加载品类
      const categoriesResponse = await fetch(`/api/team/${teamCode}/categories?pageSize=100`);

      if (categoriesResponse.ok) {
        const data = await categoriesResponse.json();
        setCategories(data.categories.map((c: { id: number; name: string }) => ({ id: c.id, name: c.name })));
      }

      // 设置可用级别
      setAvailableLevels(['初级', '中级', '高级', '奢华']);
    } catch (error) {
      console.error('加载产品相关数据失败:', error);
    }
  }, [teamCode]);

  /**
   * 初始加载数据
   */
  useEffect(() => {
    if (teamCode) {
      setIsPageLoading(true);
      Promise.all([
        fetchPaymentPlatforms(),
        fetchShops(),
        fetchProductRelatedData()
      ]).finally(() => {
        setIsPageLoading(false);
      });
    }
  }, [teamCode, fetchPaymentPlatforms, fetchShops, fetchProductRelatedData]);

  /**
   * 处理表单输入变化
   */
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;

    // 处理数字类型字段
    if (name === 'receivable' || name === 'received') {
      const numValue = value === '' ? 0 : parseFloat(value);

      // 更新表单数据
      setFormData(prev => {
        const newData = {
          ...prev,
          [name]: numValue
        };

        // 如果修改了应收或实收金额，自动计算待收金额
        if (name === 'receivable' || name === 'received') {
          newData.pending = Math.max(0, newData.receivable - newData.received);
        }

        return newData;
      });
      return;
    }

    // 处理支付类型
    if (name === 'paymentType') {
      setFormData(prev => ({
        ...prev,
        [name]: value === '' ? undefined : parseInt(value, 10)
      }));
      return;
    }

    // 处理其他字段
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  /**
   * 处理选择客户
   */
  const handleSelectCustomer = (customer: Customer) => {
    setSelectedCustomer(customer);
    setFormData(prev => ({
      ...prev,
      customerId: customer.id
    }));
  };

  /**
   * 处理选择产品
   */
  const handleSelectProduct = (product: Product) => {
    setSelectedProduct(product);
    
    // 直接添加产品到列表中
    const numPrice = product.price;
    const quantity = 1;
    const total = numPrice * quantity;

    // 检查是否已存在该产品
    const existingProductIndex = formData.products.findIndex(p => p.productId === product.id);

    if (existingProductIndex >= 0) {
      // 更新现有产品
      setFormData(prev => {
        const updatedProducts = [...prev.products];
        const existingProduct = updatedProducts[existingProductIndex];

        updatedProducts[existingProductIndex] = {
          ...existingProduct,
          quantity: existingProduct.quantity + quantity,
          price: numPrice,
          total: existingProduct.total + total
        };

        // 重新计算总金额
        const newReceivable = updatedProducts.reduce((sum, p) => sum + p.total, 0);

        return {
          ...prev,
          products: updatedProducts,
          receivable: newReceivable,
          pending: Math.max(0, newReceivable - prev.received)
        };
      });
    } else {
      // 添加新产品
      setFormData(prev => {
        const newProducts = [
          ...prev.products,
          {
            productId: product.id,
            name: product.name,
            price: numPrice,
            quantity: quantity,
            total,
            // 添加更多产品信息
            image: product.image,
            supplierName: product.supplier?.name,
            brandName: product.brand?.name,
            code: product.code,
            sku: product.sku,
            stock: product.stock
          }
        ];

        // 重新计算总金额
        const newReceivable = newProducts.reduce((sum, p) => sum + p.total, 0);

        return {
          ...prev,
          products: newProducts,
          receivable: newReceivable,
          pending: Math.max(0, newReceivable - prev.received)
        };
      });
    }
    
    setError(null);
  };

  /**
   * 处理移除产品
   */
  const handleRemoveProduct = (index: number) => {
    setFormData(prev => {
      const updatedProducts = prev.products.filter((_, i) => i !== index);

      // 重新计算总金额
      const newReceivable = updatedProducts.reduce((sum, p) => sum + p.total, 0);

      return {
        ...prev,
        products: updatedProducts,
        receivable: newReceivable,
        pending: Math.max(0, newReceivable - prev.received)
      };
    });
  };

  /**
   * 表单提交处理
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 基本验证
    if (!formData.customerId) {
      setError('请选择客户');
      return;
    }

    if (!formData.dealDate) {
      setError('请选择成交日期');
      return;
    }

    if (formData.products.length === 0) {
      setError('请至少添加一个产品');
      return;
    }

    if (formData.paymentType === undefined) {
      setError('请选择收款类型');
      return;
    }

    if (formData.platformId === undefined) {
      setError('请选择支付平台');
      return;
    }

    setIsSubmitting(true);
    setError(null);

    try {
      // 准备提交数据，确保所有数值字段都是数字类型
      const submitData = {
        customerId: Number(formData.customerId),
        sourceId: formData.sourceId ? Number(formData.sourceId) : undefined,
        paymentType: Number(formData.paymentType),
        dealDate: formData.dealDate,
        receivable: Number(formData.receivable),
        received: Number(formData.received),
        pending: Number(formData.pending),
        platformId: formData.platformId ? Number(formData.platformId) : undefined,
        dealShop: formData.dealShopId ? Number(formData.dealShopId) : undefined,
        remark: formData.remark || null,
        guideId: userProfile.userId, // 直接使用当前用户ID作为导购ID
        products: formData.products.map(p => ({
          productId: Number(p.productId),
          quantity: Number(p.quantity),
          price: Number(p.price)
        }))
      };

      // 发送请求
      const response = await fetch(`/api/team/${teamCode}/sales-records`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || '创建销售记录失败');
      }

      // 显示成功消息
      setSuccessMessage('销售记录创建成功！');

      // 清空表单
      setFormData({
        customerId: 0,
        sourceId: undefined,
        paymentType: undefined,
        dealDate: formatDate(new Date(), 'YYYY-MM-DD'),
        receivable: 0,
        received: 0,
        pending: 0,
        platformId: undefined,
        dealShopId: undefined,
        remark: '',
        products: []
      });

      setSelectedCustomer(null);
      setSelectedProduct(null);
    } catch (err) {
      console.error('创建销售记录失败:', err);
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setIsSubmitting(false);
    }
  };

  /**
   * 渲染支付类型选项
   */
  const renderPaymentTypeOptions = () => {
    return (
      <>
        <option value="">请选择</option>
        <option value={PaymentType.FULL_PAYMENT}>全款</option>
        <option value={PaymentType.DEPOSIT}>定金</option>
        <option value={PaymentType.UNPAID}>未付</option>
        <option value={PaymentType.FREE}>赠送</option>
        <option value={PaymentType.OTHER}>其他</option>
      </>
    );
  };

  /**
   * 获取支付类型标签颜色
   */
  const getPaymentTypeColor = (type: PaymentType | undefined) => {
    if (type === undefined) return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';

    switch (type) {
      case PaymentType.FULL_PAYMENT:
        return 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300';
      case PaymentType.DEPOSIT:
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-300';
      case PaymentType.UNPAID:
        return 'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300';
      case PaymentType.FREE:
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900/50 dark:text-purple-300';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  /**
   * 处理产品模态框关闭
   */
  const handleProductModalClose = () => {
    setIsProductModalOpen(false);
  };

  /**
   * 处理产品创建成功
   */
  const handleProductSuccess = () => {
    setIsProductModalOpen(false);
    // 这里可以添加提示或其他操作
  };

  return (
    <div className="w-full mb-10">
      {/* 页面标题 */}
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center">
          <MdShoppingCart className="mr-2 text-blue-500" size={24} />
          创建销售记录
        </h1>
      </div>

      {/* 加载状态显示 */}
      {isPageLoading ? (
        <Card
          glassEffect={isDarkMode ? "medium" : "light"}
          padding="large"
          className="flex justify-center items-center py-20"
          isLoading={true}
          loadingText="正在加载数据..."
        >
          <div></div>
        </Card>
      ) : (
        <>
          {/* 成功消息 */}
          {successMessage && (
            <div className={`
              mb-4 p-3 rounded-lg border-l-4 border-green-500 
              ${isDarkMode ? 'bg-green-900/20' : 'bg-green-50'} 
              text-green-700 dark:text-green-300
              animate-fadeIn
            `}>
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2 text-green-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
                <p>{successMessage}</p>
              </div>
            </div>
          )}

          {/* 错误提示 */}
          {error && (
            <div className={`
              mb-4 p-3 rounded-lg border-l-4 border-red-500 
              ${isDarkMode ? 'bg-red-900/20' : 'bg-red-50'} 
              text-red-700 dark:text-red-300
              animate-fadeIn
            `}>
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <p>{error}</p>
              </div>
            </div>
          )}

          <form onSubmit={handleSubmit}>

            {/* 产品列表部分 - 始终显示，无论是否有产品 */}
            <div className="mb-4">

              <SelectedProductList
                products={formData.products}
                onRemove={handleRemoveProduct}
              />
            </div>

            {/* 客户选择部分 */}
            <Card
              glassEffect={isDarkMode ? "medium" : "light"}
              padding="medium"
              title="客户信息"
              className="mb-4"
            >
              <div className="mb-5 pb-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
                      客户信息 <span className="text-red-500">*</span>
                    </label>

                    {/* 客户选择器 */}
                    <CustomerSelector
                      teamCode={teamCode}
                      selectedCustomer={selectedCustomer}
                      onSelectCustomer={handleSelectCustomer}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
                      选择添加产品 <span className="text-red-500">*</span>
                    </label>

                    <div className="flex items-center space-x-2">
                      {/* 产品选择器 - 直接添加产品 */}
                      <div className="flex-grow">
                        <ProductSelector
                          teamCode={teamCode}
                          onSelectProduct={handleSelectProduct}
                        />
                      </div>
                      
                      {/* 新增产品按钮 */}
                      <Button
                        variant="primary"
                        size="md"
                        icon={<MdAddCircleOutline size={16} />}
                        onClick={() => setIsProductModalOpen(true)}
                        className="flex-shrink-0"
                      >
                        新增
                      </Button>
                    </div>
                  </div>
                </div>

                {/* 客户详细信息展示 */}
                {selectedCustomer && (
                  <div className="mt-3">
                    <CustomerSelectorInfo customer={selectedCustomer} />
                  </div>
                )}
              </div>
            </Card>

            {/* 订单详细信息 */}
            <Card
              glassEffect={isDarkMode ? "medium" : "light"}
              padding="medium"
              title="订单详细信息"
            >
              <div className="grid grid-cols-1 md:grid-cols-4 gap-x-6 gap-y-4">
                {/* 第一列 */}
                <div className="space-y-3">
                  {/* 成交店铺 */}
                  <div>
                    <label htmlFor="dealShopId" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      成交店铺
                    </label>
                    <select
                      id="dealShopId"
                      name="dealShopId"
                      value={formData.dealShopId || ''}
                      onChange={handleChange}
                      className={`
                        w-full px-3 py-1.5 rounded-md text-sm
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                      `}
                    >
                      <option value="">请选择成交店铺</option>
                      {shops.map(shop => (
                        <option key={shop.id} value={shop.id}>
                          {shop.nickname || shop.wechat || shop.accountNo || `店铺ID: ${shop.id}`}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* 成交日期 */}
                  <div>
                    <label htmlFor="dealDate" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      成交日期 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="date"
                      id="dealDate"
                      name="dealDate"
                      value={formData.dealDate}
                      onChange={handleChange}
                      className={`
                        w-full px-3 py-1.5 rounded-md text-sm
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                      `}
                      required
                    />
                  </div>
                </div>

                {/* 第二列 */}
                <div className="space-y-3">
                  {/* 收款类型 */}
                  <div>
                    <label htmlFor="paymentType" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      收款类型 <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <select
                        id="paymentType"
                        name="paymentType"
                        value={formData.paymentType === undefined ? '' : formData.paymentType}
                        onChange={handleChange}
                        className={`
                          w-full pl-3 pr-10 py-1.5 rounded-md text-sm appearance-none
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                      `}
                        required
                      >
                        {renderPaymentTypeOptions()}
                      </select>
                      <div className="absolute top-1/2 right-3 transform -translate-y-1/2 pointer-events-none">
                        {formData.paymentType !== undefined && (
                          <span className={`inline-flex items-center px-2 py-0.5 text-xs rounded-full ${getPaymentTypeColor(formData.paymentType)}`}>
                            {formData.paymentType === PaymentType.FULL_PAYMENT && "全款"}
                            {formData.paymentType === PaymentType.DEPOSIT && "定金"}
                            {formData.paymentType === PaymentType.UNPAID && "未付"}
                            {formData.paymentType === PaymentType.FREE && "赠送"}
                            {formData.paymentType === PaymentType.OTHER && "其他"}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 支付平台 */}
                  <div>
                    <label htmlFor="platformId" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      支付平台 <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="platformId"
                      name="platformId"
                      value={formData.platformId || ''}
                      onChange={handleChange}
                      className={`
                        w-full px-3 py-1.5 rounded-md text-sm
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                      `}
                      required
                    >
                      <option value="">请选择支付平台</option>
                      {platforms.map(platform => (
                        <option key={platform.id} value={platform.id}>
                          {platform.name}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* 第三列 */}
                <div className="space-y-3">
                  {/* 金额信息 */}
                  <div>
                    <label htmlFor="receivable" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      应收金额 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="number"
                      id="receivable"
                      name="receivable"
                      value={formData.receivable}
                      onChange={handleChange}
                      step="0.01"
                      min="0"
                      className={`
                        w-full px-3 py-1.5 rounded-md text-sm
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                      `}
                      required
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label htmlFor="received" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        实收金额 <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="number"
                        id="received"
                        name="received"
                        value={formData.received}
                        onChange={handleChange}
                        step="0.01"
                        min="0"
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                          backdrop-blur-sm border border-white/20 dark:border-white/10
                          focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                          text-gray-800 dark:text-white
                        `}
                        required
                      />
                    </div>

                    <div>
                      <label htmlFor="pending" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                        待收金额
                      </label>
                      <input
                        type="number"
                        id="pending"
                        name="pending"
                        value={formData.pending}
                        readOnly
                        className={`
                          w-full px-3 py-1.5 rounded-md text-sm
                          ${isDarkMode ? 'bg-gray-700/50' : 'bg-gray-100/70'}
                          backdrop-blur-sm border border-white/10 dark:border-white/5
                          focus:outline-none
                          text-gray-700 dark:text-gray-300
                        `}
                      />
                    </div>
                  </div>
                </div>

                {/* 第四列 */}
                <div className="space-y-3">
                  {/* 当前用户信息 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      <MdPerson className="inline mr-1" size={14} />
                      创建人信息
                    </label>
                    <div className={`
                      w-full px-3 py-2 rounded-md text-sm
                      ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                      backdrop-blur-sm border border-white/20 dark:border-white/10
                      text-gray-800 dark:text-white
                    `}>
                      <div className="flex flex-col space-y-1">
                        <div className="flex justify-between">
                          <span className="text-gray-600 dark:text-gray-400">用户名:</span>
                          <span className="font-medium">{userProfile.username}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600 dark:text-gray-400">用户ID:</span>
                          <span className="font-medium">{userProfile.userId}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* 备注 */}
                  <div>
                    <label htmlFor="remark" className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                      备注
                    </label>
                    <textarea
                      id="remark"
                      name="remark"
                      value={formData.remark}
                      onChange={handleChange}
                      rows={4}
                      placeholder="请输入备注信息"
                      className={`
                        w-full px-3 py-1.5 rounded-md text-sm
                        ${isDarkMode ? 'bg-slate-800/50' : 'bg-white/50'}
                        backdrop-blur-sm border border-white/20 dark:border-white/10
                        focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-transparent
                        text-gray-800 dark:text-white
                        resize-none
                      `}
                    />
                  </div>
                </div>
              </div>

              {/* 提交按钮 */}
              <div className="flex justify-end mt-4">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className={`
                    px-5 py-2 rounded-lg text-white font-medium text-sm
                    flex items-center justify-center
                    transition-all duration-200
                    ${isSubmitting
                      ? 'bg-blue-400/80 cursor-not-allowed'
                      : `${isDarkMode ? 'bg-blue-600/80 hover:bg-blue-500/80' : 'bg-blue-500 hover:bg-blue-600'} 
                        hover:shadow-md hover:scale-[1.02] active:scale-[0.98]`
                    }
                    backdrop-blur-md border border-white/20
                  `}
                >
                  {isSubmitting ? (
                    <div className="flex items-center">
                      <svg className="animate-spin h-4 w-4 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      提交中...
                    </div>
                  ) : '创建销售记录'}
                </button>
              </div>
            </Card>
          </form>

          {/* 产品创建模态框 */}
          <ProductModalAdapter
            isOpen={isProductModalOpen}
            onClose={handleProductModalClose}
            product={null}
            onSuccess={handleProductSuccess}
            suppliers={suppliers}
            brands={brands}
            categories={categories}
            availableLevels={availableLevels}
            onSelectProduct={handleSelectProduct}
          />
        </>
      )}
    </div>
  );
} 