/**
 * 销售记录列表页面
 * 作者: 阿瑞
 * 功能: 提供销售记录数据的展示和查询功能
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useTeam } from '@/hooks/useTeam';
import { useThemeMode } from '@/store/settingStore';
import { useAccessToken } from '@/store/userStore';
import { ThemeMode, PaymentTypeNames, PaymentTypeColors } from '@/types/enum';
import {
  MdAdd,
  MdSearch,
  MdRefresh,
  MdPerson,
  MdCalendarMonth,
  MdPayment,
  MdStore,
  MdEdit,
  MdOutlineAssignment,
  MdCompareArrows,
  MdAddShoppingCart,
  MdAttachMoney,
  MdLocalShipping
} from 'react-icons/md';
import { SalesRecord, PaymentType, SalesRecordProduct } from '@/models/team/types/old/sales';
import { formatDate } from '@/utils';
import styles from './page.module.css';
import ProductInfoModal from './ProductInfoModal';
import SalesRecordModal from './components/SalesRecordModal';
import ShipModal from './components/ShipModal';
import { OperationType } from './components/SalesRecordModal';

/**
 * 扩展的销售记录产品接口，包含API返回的额外字段
 */
interface SalesRecordProductWithDetails extends SalesRecordProduct {
  productName?: string;
  productCode?: string;
  productSku?: string;
  brandId?: number;
  brandName?: string;
  categoryId?: number;
  categoryName?: string;
  supplierId?: number;
  supplierName?: string;
  image?: string;
  description?: string;
}

/**
 * 扩展的销售记录接口，使用扩展的产品接口
 */
interface SalesRecordWithDetails extends Omit<SalesRecord, 'products'> {
  products?: SalesRecordProductWithDetails[];
  // 客户信息
  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;
  guideId?: number;
  guidePhone?: string;
  guideWechat?: string;
  // 支付平台信息
  platformName?: string;
  // 订单信息
  remark?: string;
  // 物流信息
  logisticsStatus?: string;
  logisticsTrackingNumber?: string;
  logisticsCompany?: string;
  logisticsCustomerTailNumber?: string;
  logisticsIsQueryable?: boolean;
  logisticsDetails?: string;
}

/**
 * 销售记录列表页面组件
 */
export default function SalesRecordsPage() {
  const params = useParams();
  const router = useRouter();
  const teamCode = params?.teamCode as string;
  const { currentTeam } = useTeam();
  const accessToken = useAccessToken();
  const themeMode = useThemeMode();
  const isDarkMode = themeMode === ThemeMode.Dark;

  // 销售记录数据状态
  const [salesRecords, setSalesRecords] = useState<SalesRecordWithDetails[]>([]);
  const [totalRecords, setTotalRecords] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 搜索和筛选状态
  const [searchKeyword, setSearchKeyword] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [filterPaymentType, setFilterPaymentType] = useState<string>('');
  const [isAdvancedFilterOpen, setIsAdvancedFilterOpen] = useState(false);

  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);

  // 操作模态框状态
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<SalesRecordWithDetails | null>(null);
  const [operationType, setOperationType] = useState<OperationType>(OperationType.RETURN);
  
  // 发货模态框状态
  const [shipModalOpen, setShipModalOpen] = useState(false);

  /**
   * 获取销售记录列表数据
   */
  const fetchSalesRecords = useCallback(async () => {
    if (!currentTeam || !teamCode) return;

    setIsLoading(true);
    setError(null);

    try {
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: currentPage.toString(),
        pageSize: pageSize.toString()
      });

      if (searchKeyword) queryParams.append('keyword', searchKeyword);
      if (startDate) queryParams.append('startDate', startDate);
      if (endDate) queryParams.append('endDate', endDate);
      if (filterPaymentType) queryParams.append('paymentType', filterPaymentType);

      const response = await fetch(`/api/team/${teamCode}/sales-records?${queryParams.toString()}`, {
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      });

      if (!response.ok) {
        throw new Error('获取销售记录列表失败');
      }

      const data = await response.json();

      // 调试输出，查看API返回的数据结构
      console.log('API返回的销售记录数据:', data.salesRecords);

      setSalesRecords(data.salesRecords || []);
      setTotalRecords(data.total || 0);
    } catch (err) {
      console.error('获取销售记录列表失败:', err);
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  }, [currentTeam, teamCode, accessToken, currentPage, pageSize, searchKeyword, startDate, endDate, filterPaymentType]);

  /**
   * 初始加载和依赖变化时获取数据
   */
  useEffect(() => {
    if (accessToken && teamCode) {
      fetchSalesRecords();
    }
  }, [accessToken, teamCode, currentPage, fetchSalesRecords]);

  /**
   * 处理搜索
   */
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1); // 重置到第一页
    fetchSalesRecords();
  };

  /**
   * 清空筛选条件
   */
  const handleClearFilters = () => {
    setSearchKeyword('');
    setStartDate('');
    setEndDate('');
    setFilterPaymentType('');
    setCurrentPage(1);
    fetchSalesRecords();
  };

  /**
   * 处理高级筛选切换
   */
  const toggleAdvancedFilter = () => {
    setIsAdvancedFilterOpen(!isAdvancedFilterOpen);
  };

  /**
   * 处理添加销售记录按钮点击
   */
  const handleAddSalesRecord = () => {
    router.push(`/team/${teamCode}/sales`);
  };

  /**
   * 处理编辑销售记录
   */
  const handleEditSalesRecord = (salesRecord: SalesRecordWithDetails) => {
    router.push(`/team/${teamCode}/sales/${salesRecord.id}`);
  };

  /**
   * 处理页码变更
   */
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  /**
   * 计算总页数
   */
  const totalPages = Math.ceil(totalRecords / pageSize);

  /**
   * 格式化金额显示
   */
  const formatAmount = (amount: number | undefined) => {
    if (amount === undefined || amount === null) return '¥0.00';
    // 确保 amount 是数字类型
    const numAmount = Number(amount);
    // 检查是否为有效数字
    if (isNaN(numAmount)) return '¥0.00';
    return `¥${numAmount.toFixed(2)}`;
  };

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

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

  /**
   * 格式化电话号码，添加隐私保护
   */
  const formatPhone = (phone: string | undefined | null): string => {
    if (!phone || phone.length < 7) return phone || '-';
    // 只显示前3位和后4位，中间用星号代替
    return `${phone.substring(0, 3)}****${phone.substring(phone.length - 4)}`;
  };

  /**
   * 截断长文本并添加省略号
   */
  const truncateText = (text: string | undefined | null, maxLength: number = 20): string => {
    if (!text) return '-';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };

  /**
   * 渲染分页控件
   */
  const renderPagination = () => {
    const pages = [];
    const maxPagesToShow = 5; // 最多显示的页码数

    let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
    const endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);

    if (endPage - startPage + 1 < maxPagesToShow) {
      startPage = Math.max(1, endPage - maxPagesToShow + 1);
    }

    // 首页
    if (startPage > 1) {
      pages.push(
        <button
          key="first"
          onClick={() => handlePageChange(1)}
          className={`${styles.paginationButton} ${isDarkMode ? styles.dark : styles.light}`}
        >
          1
        </button>
      );

      if (startPage > 2) {
        pages.push(
          <span key="dots1" className="mx-1">...</span>
        );
      }
    }

    // 页码按钮
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          onClick={() => handlePageChange(i)}
          className={currentPage === i
            ? styles.paginationButtonCurrent
            : `${styles.paginationButton} ${isDarkMode ? styles.dark : styles.light}`}
        >
          {i}
        </button>
      );
    }

    // 末页
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        pages.push(
          <span key="dots2" className="mx-1">...</span>
        );
      }

      pages.push(
        <button
          key="last"
          onClick={() => handlePageChange(totalPages)}
          className={`${styles.paginationButton} ${isDarkMode ? styles.dark : styles.light}`}
        >
          {totalPages}
        </button>
      );
    }

    return (
      <div className={styles.paginationContainer}>
        <button
          onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
          disabled={currentPage === 1}
          className={`${styles.paginationButton} ${isDarkMode ? styles.dark : styles.light}`}
          style={{ opacity: currentPage === 1 ? 0.5 : 1, cursor: currentPage === 1 ? 'not-allowed' : 'pointer' }}
        >
          上一页
        </button>

        {pages}

        <button
          onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
          disabled={currentPage === totalPages || totalPages === 0}
          className={`${styles.paginationButton} ${isDarkMode ? styles.dark : styles.light}`}
          style={{ opacity: (currentPage === totalPages || totalPages === 0) ? 0.5 : 1, cursor: (currentPage === totalPages || totalPages === 0) ? 'not-allowed' : 'pointer' }}
        >
          下一页
        </button>
      </div>
    );
  };

  /**
   * 处理退货操作
   */
  const handleReturn = (record: SalesRecordWithDetails) => {
    setSelectedRecord(record);
    setOperationType(OperationType.RETURN);
    setModalOpen(true);
  };

  /**
   * 处理换货操作
   */
  const handleExchange = (record: SalesRecordWithDetails) => {
    setSelectedRecord(record);
    setOperationType(OperationType.EXCHANGE);
    setModalOpen(true);
  };

  /**
   * 处理退差价操作
   */
  const handleRefund = (record: SalesRecordWithDetails) => {
    setSelectedRecord(record);
    setOperationType(OperationType.REFUND);
    setModalOpen(true);
  };

  /**
   * 处理补发操作
   */
  const handleReplenish = (record: SalesRecordWithDetails) => {
    setSelectedRecord(record);
    setOperationType(OperationType.REPLENISH);
    setModalOpen(true);
  };

  /**
   * 处理发货操作
   */
  const handleShip = (record: SalesRecordWithDetails) => {
    setSelectedRecord(record);
    setShipModalOpen(true);
  };

  /**
   * 关闭操作模态框
   */
  const handleCloseModal = () => {
    setModalOpen(false);
    setSelectedRecord(null);
  };

  return (
    <div className={`${styles.pageContainer}`}>
      <h1 className={styles.pageTitle}>销售记录管理</h1>

      {/* 搜索和筛选区域 */}
      <div className={`${styles.searchContainer} ${isDarkMode ? styles.dark : styles.light}`}>
        <form onSubmit={handleSearch} className={styles.searchForm}>
          {/* 基本搜索栏 */}
          <div className={styles.searchRow}>
            <div className={styles.searchInputContainer}>
              <input
                type="text"
                placeholder="搜索客户名称、电话、备注..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className={`${styles.searchInput} ${isDarkMode ? styles.dark : styles.light}`}
              />
              <MdSearch className={styles.searchIcon} size={20} />
            </div>

            <div className={styles.filterGroup}>
              <input
                type="date"
                placeholder="开始日期"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className={`${styles.dateInput} ${isDarkMode ? styles.dark : styles.light}`}
              />
              <input
                type="date"
                placeholder="结束日期"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className={`${styles.dateInput} ${isDarkMode ? styles.dark : styles.light}`}
              />

              <select
                value={filterPaymentType}
                onChange={(e) => setFilterPaymentType(e.target.value)}
                className={`${styles.select} ${isDarkMode ? styles.dark : styles.light}`}
              >
                <option value="">所有支付类型</option>
                <option value={PaymentType.FULL_PAYMENT.toString()}>全款</option>
                <option value={PaymentType.DEPOSIT.toString()}>定金</option>
                <option value={PaymentType.UNPAID.toString()}>未付</option>
                <option value={PaymentType.FREE.toString()}>赠送</option>
                <option value={PaymentType.OTHER.toString()}>其他</option>
              </select>
            </div>

            <div className={styles.buttonGroup}>
              <button
                type="submit"
                className={styles.searchButton}
              >
                <MdSearch className="mr-1" />
                搜索
              </button>
              <button
                type="button"
                onClick={toggleAdvancedFilter}
                className={`${styles.secondaryButton} ${isDarkMode ? styles.dark : styles.light}`}
              >
                {isAdvancedFilterOpen ? '收起筛选' : '高级筛选'}
              </button>
              <button
                type="button"
                onClick={handleClearFilters}
                className={`${styles.secondaryButton} ${isDarkMode ? styles.dark : styles.light}`}
              >
                <MdRefresh className="mr-1" />
                重置
              </button>
              <button
                type="button"
                onClick={handleAddSalesRecord}
                className={styles.addButton}
              >
                <MdAdd className="mr-1" />
                新增
              </button>
            </div>
          </div>

          {/* 高级筛选选项 */}
          {isAdvancedFilterOpen && (
            <div className={`${styles.advancedFiltersContainer} ${isDarkMode ? styles.dark : styles.light}`}>
              <div className={styles.filterItem}>
                <label className={styles.filterLabel}>筛选范围</label>
                <div className={styles.quickFilterButtons}>
                  <button
                    type="button"
                    onClick={() => {
                      // 设置为过去7天
                      const endDate = new Date();
                      const startDate = new Date();
                      startDate.setDate(startDate.getDate() - 7);
                      setStartDate(formatDate(startDate, 'YYYY-MM-DD'));
                      setEndDate(formatDate(endDate, 'YYYY-MM-DD'));
                    }}
                    className={`${styles.quickFilterButton} ${isDarkMode ? styles.dark : styles.light}`}
                  >
                    最近7天
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      // 设置为过去30天
                      const endDate = new Date();
                      const startDate = new Date();
                      startDate.setDate(startDate.getDate() - 30);
                      setStartDate(formatDate(startDate, 'YYYY-MM-DD'));
                      setEndDate(formatDate(endDate, 'YYYY-MM-DD'));
                    }}
                    className={`${styles.quickFilterButton} ${isDarkMode ? styles.dark : styles.light}`}
                  >
                    最近30天
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      // 设置为本月
                      const now = new Date();
                      const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                      setStartDate(formatDate(startDate, 'YYYY-MM-DD'));
                      setEndDate(formatDate(now, 'YYYY-MM-DD'));
                    }}
                    className={`${styles.quickFilterButton} ${isDarkMode ? styles.dark : styles.light}`}
                  >
                    本月
                  </button>
                </div>
              </div>

              {/* 更多高级筛选选项可以添加在这里 */}
            </div>
          )}
        </form>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className={`${styles.errorMessage} ${isDarkMode ? styles.dark : styles.light}`}>
          <p>{error}</p>
        </div>
      )}

      {/* 加载状态 */}
      {isLoading && (
        <div className={styles.loaderContainer}>
          <div className={styles.loader}></div>
        </div>
      )}

      {/* 销售记录列表 */}
      {!isLoading && salesRecords.length === 0 ? (
        <div className={`${styles.emptyState} ${isDarkMode ? styles.dark : styles.light}`}>
          <p className={`${styles.emptyStateText} ${isDarkMode ? styles.dark : ''}`}>暂无销售记录数据</p>
          <button
            onClick={handleAddSalesRecord}
            className={styles.addButton}
          >
            <MdAdd className="mr-1" />
            创建销售记录
          </button>
        </div>
      ) : (
        !isLoading && (
          <div className={styles.tableContainer}>
            <table className={`${styles.table} ${isDarkMode ? styles.dark : styles.light}`}>
              <thead className={`${styles.tableHead} ${isDarkMode ? styles.dark : styles.light}`}>
                <tr>
                  <th className={styles.tableHeadCell} style={{ width: '10%' }}>客户信息</th>
                  <th className={styles.tableHeadCell} style={{ width: '12%' }}>日期信息</th>
                  <th className={styles.tableHeadCell} style={{ width: '14%' }}>店铺/导购</th>
                  <th className={styles.tableHeadCell} style={{ width: '16%' }}>支付信息</th>
                  <th className={styles.tableHeadCell} style={{ width: '22%' }}>产品信息</th>
                  <th className={styles.tableHeadCell} style={{ width: '12%' }}>备注</th>
                  <th className={styles.tableHeadCell} style={{ textAlign: 'center', width: '16%' }}>操作</th>
                </tr>
              </thead>
              <tbody>
                {salesRecords.map(record => (
                  <tr
                    key={record.id}
                    className={`${styles.tableRow} ${isDarkMode ? styles.dark : styles.light}`}
                  >
                    {/* 客户信息 - 优化显示内容 */}
                    <td className={styles.tableCell}>
                      <div className={styles.infoColumn}>
                        <div className={styles.infoItemWithIcon}>
                          <MdPerson className={styles.iconBlue} size={18} />
                          <span className={styles.infoLabel}>ID:</span> {record.customerId || '-'}
                        </div>
                        <div className={styles.infoContent}>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`} title={record.customerName || '-'}>
                            <span className={styles.infoLabel}>姓名:</span> {truncateText(record.customerName, 10) || '-'}
                          </div>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`}>
                            <span className={styles.infoLabel}>电话:</span> {formatPhone(record.customerPhone)}
                          </div>
                          {record.customerAddress && (
                            <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`} title={record.customerAddress}>
                              <span className={styles.infoLabel}>地址:</span> {truncateText(record.customerAddress, 15)}
                            </div>
                          )}
                        </div>
                      </div>
                    </td>

                    {/* 日期信息 */}
                    <td className={styles.tableCell}>
                      <div className={styles.infoColumn}>
                        <div className={styles.infoItemWithIcon}>
                          <MdCalendarMonth className={styles.iconGreen} size={16} />
                          <span className={styles.infoLabel}>成交日期</span>
                        </div>
                        <div className={styles.infoContent}>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`}>
                            {formatFriendlyDate(record.dealDate)}
                          </div>
                        </div>

                        <div className={styles.infoItemWithIcon} style={{ marginTop: '8px' }}>
                          <MdCalendarMonth className={styles.iconGray} size={16} />
                          <span className={styles.infoLabel}>创建时间</span>
                        </div>
                        <div className={styles.infoContent}>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`}>
                            {formatDateTime(record.createdAt)}
                          </div>
                        </div>
                      </div>
                    </td>

                    {/* 店铺/导购信息 */}
                    <td className={styles.tableCell}>
                      <div className={styles.infoColumn}>
                        <div className={styles.infoItemWithIcon}>
                          <MdStore className={styles.iconBlue} size={16} />
                          <span className={styles.infoLabel}>成交店铺</span>
                        </div>
                        <div className={styles.infoContent}>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`} title={record.dealShopName || '-'}>
                            {record.dealShopName || '-'}
                          </div>
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`}>
                            <span className={styles.infoLabel}>微信:</span> {record.dealShopWechat || '-'}
                          </div>
                        </div>

                        {/* 导购信息 */}
                        <div className={styles.infoItemWithIcon} style={{ marginTop: '8px' }}>
                          <MdPerson className={styles.iconGreen} size={16} />
                          <span className={styles.infoLabel}>导购</span>
                          <span className={styles.infoLabel}>ID: {record.guideId || '-'}</span>
                        </div>
                      </div>
                    </td>

                    {/* 支付信息 */}
                    <td className={styles.tableCell}>
                      <div className={styles.infoColumn}>
                        <div className={styles.infoItemWithIcon}>
                          <MdPayment className={styles.iconYellow} size={16} />
                          <span className={styles.infoLabel} style={{ color: PaymentTypeColors[record.paymentType] }}>
                            {PaymentTypeNames[record.paymentType] || '未知'}
                          </span>
                          <span className={styles.infoLabel}>平台:</span> {record.platformName || '-'}
                        </div>

                        <div className={styles.infoContent}>
                          <div style={{ marginTop: '8px' }} className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`}>
                            <div className="flex justify-between items-center">
                              <span className={styles.infoLabel}>应收:</span>
                              <span style={{ fontWeight: '500' }}>{formatAmount(record.receivable)}</span>
                            </div>
                            <div className="flex justify-between items-center">
                              <span className={styles.infoLabel}>实收:</span>
                              <span style={{ color: PaymentTypeColors[record.paymentType], fontWeight: '500' }}>
                                {formatAmount(record.received)}
                              </span>
                            </div>
                            {record.pending > 0 && (
                              <div className="flex justify-between items-center">
                                <span className={styles.infoLabel}>待收:</span>
                                <span style={{ color: '#ef4444', fontWeight: '500' }}>
                                  {formatAmount(record.pending)}
                                </span>
                              </div>
                            )}
                          </div>
                        </div>
                        {record.products && record.products.length > 0 && (
                          <div className={`${styles.productSummaryInfo} ${isDarkMode ? styles.dark : styles.light}`}>
                            <div>共 {record.products.reduce((sum, p) => sum + p.quantity, 0)} 件商品</div>
                            <div className={`${styles.productTotalInline} ${isDarkMode ? styles.dark : ''}`}>
                              总价: {formatAmount(record.products.reduce((sum, p) => sum + (p.price * p.quantity), 0))}
                            </div>
                          </div>
                        )}
                      </div>
                    </td>

                    {/* 产品信息 */}
                    <td className={styles.tableCell}>
                      <div className={styles.infoColumn}>
                        {record.products && record.products.length > 0 ? (
                          <div className={styles.productListContainer}>
                            <div className={styles.productGridScroll}>
                              {record.products.map((product, idx) => (
                                <ProductInfoModal
                                  key={idx}
                                  productId={product.productId}
                                  productName={product.productName}
                                  productCode={product.productCode}
                                  price={product.price}
                                  quantity={product.quantity}
                                  brandName={product.brandName}
                                  categoryName={product.categoryName}
                                  supplierName={product.supplierName}
                                  image={product.image}
                                  logisticsStatus={record.logisticsStatus}
                                  logisticsDetails={record.logisticsDetails}
                                  logisticsTrackingNumber={record.logisticsTrackingNumber}
                                  logisticsCompany={record.logisticsCompany}
                                />
                              ))}
                            </div>
                          </div>
                        ) : (
                          <div className={`${styles.subInfoItem} ${isDarkMode ? styles.dark : styles.light}`} style={{ marginLeft: '0.5rem', marginTop: '0.25rem', fontSize: '0.8rem' }}>
                            无产品信息
                          </div>
                        )}
                      </div>
                    </td>

                    {/* 备注 */}
                    <td className={styles.tableCell}>
                      <div className={styles.remarkContent}>
                        <p className={`${styles.remarkText} ${isDarkMode ? styles.dark : styles.light}`} title={record.remark || '-'}>
                          {truncateText(record.remark, 10) || '-'}
                        </p>
                      </div>
                    </td>

                    {/* 操作按钮 */}
                    <td className={styles.tableCell}>
                      <div className={styles.actionsColumn}>
                        <button
                          onClick={() => handleEditSalesRecord(record)}
                          className={`${styles.actionButton} ${styles.editButton} ${isDarkMode ? styles.dark : ''}`}
                          title="编辑"
                        >
                          <MdEdit size={18} />
                          <span>编辑</span>
                        </button>
                        <button
                          onClick={() => handleReturn(record)}
                          className={`${styles.actionButton} ${styles.returnButton} ${isDarkMode ? styles.dark : ''}`}
                          title="退货"
                        >
                          <MdOutlineAssignment size={18} />
                          <span>退货</span>
                        </button>
                        <button
                          onClick={() => handleExchange(record)}
                          className={`${styles.actionButton} ${styles.exchangeButton} ${isDarkMode ? styles.dark : ''}`}
                          title="换货"
                        >
                          <MdCompareArrows size={18} />
                          <span>换货</span>
                        </button>
                        <button
                          onClick={() => handleRefund(record)}
                          className={`${styles.actionButton} ${styles.priceDiffButton} ${isDarkMode ? styles.dark : ''}`}
                          title="退差"
                        >
                          <MdAttachMoney size={18} />
                          <span>退差</span>
                        </button>
                        <button
                          onClick={() => handleReplenish(record)}
                          className={`${styles.actionButton} ${styles.replenishButton} ${isDarkMode ? styles.dark : ''}`}
                          title="补发"
                        >
                          <MdAddShoppingCart size={18} />
                          <span>补发</span>
                        </button>
                        <button
                          onClick={() => handleShip(record)}
                          className={`${styles.actionButton} ${styles.shipButton} ${isDarkMode ? styles.dark : ''}`}
                          title="发货"
                        >
                          <MdLocalShipping size={18} />
                          <span>发货</span>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )
      )}

      {/* 分页控件 */}
      {!isLoading && salesRecords.length > 0 && renderPagination()}

      {/* 操作模态框 */}
      {selectedRecord && (
        <>
        <SalesRecordModal
          isOpen={modalOpen}
          onClose={handleCloseModal}
          salesRecord={selectedRecord}
          operationType={operationType}
        />
          <ShipModal
            isOpen={shipModalOpen}
            onClose={() => setShipModalOpen(false)}
            salesRecord={selectedRecord}
          />
        </>
      )}
    </div>
  );
} 