import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Progress } from '../ui/progress';
import {
  Package,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  Calendar,
  Warehouse,
  User,
  Phone,
  Mail,
  MapPin,
  Building2,
  FileText,
  Star,
  TrendingUp,
  TrendingDown,
  Wrench,
  Tractor,
  Camera,
  Save,
  Link2,
  History,
  Clock,
  DollarSign,
  BarChart3,
  PieChart,
  ShoppingCart,
  Users,
  Award,
  Shield,
  AlertCircle,
  X,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart as RePieChart,
  Pie,
  Cell,
} from 'recharts';

interface AssetBasicInfoProps {
  activePath?: string;
}

type MaterialType = '种子' | '化肥' | '农药' | '耗材';
type MaterialStatus = '正常' | '临期预警' | '库存预警' | '已过期';
type ToolStatus = '在用' | '维修' | '报废';
type SupplierLevel = 'A级' | 'B级' | 'C级' | 'D级';

interface MaterialInventoryLocation {
  locationId: string;
  locationName: string;
  quantity: number;
}

interface Material {
  id: string;
  code: string;
  name: string;
  type: MaterialType;
  spec: string;
  model?: string;
  supplier: string;
  supplierId: string;
  manufacturer?: string;
  expiryDate: string;
  productionDate: string;
  shelfLife: string; // 有效期数量
  shelfLifeUnit: '年' | '月' | '天'; // 有效期单位
  safeStock: number;
  currentStock: number;
  unit: string;
  purchasePrice: number;
  status: MaterialStatus;
  inventoryLocations?: MaterialInventoryLocation[]; // 库存位置分布
  // 农药特殊字段
  registrationNo?: string;
  toxicityLevel?: '低毒' | '中毒' | '高毒' | '剧毒';
  safetyInterval?: number; // 安全间隔期（天）
  notes?: string;
  createdAt: string;
}

interface ToolInventoryLocation {
  locationId: string;
  locationName: string;
  quantity: number;
}

interface Tool {
  id: string;
  code: string;
  name: string;
  type: string;
  model: string;
  purchaseDate: string;
  purchasePrice: number;
  depreciation: number; // 折旧年限
  currentValue: number;
  status: ToolStatus;
  responsiblePerson?: string;
  totalQuantity: number; // 总数量
  inventoryLocations?: ToolInventoryLocation[]; // 库存位置分布
  images?: string[];
  maintenanceHistory?: MaintenanceRecord[];
  notes?: string;
  createdAt: string;
}

interface MaintenanceRecord {
  id: string;
  date: string;
  type: '保养' | '维修' | '检查';
  description: string;
  cost: number;
  technician: string;
}

interface Supplier {
  id: string;
  code: string;
  name: string;
  type: string;
  contactPerson: string;
  phone: string;
  email: string;
  address: string;
  level: SupplierLevel;
  certifications: Certification[];
  purchaseHistory: PurchaseRecord[];
  totalPurchaseAmount: number;
  cooperationYears: number;
  notes?: string;
  createdAt: string;
}

interface Certification {
  id: string;
  name: string;
  certificateNo: string;
  issueDate: string;
  expiryDate: string;
  file?: string;
}

interface PurchaseRecord {
  id: string;
  date: string;
  materialName: string;
  quantity: number;
  amount: number;
  status: '已完成' | '进行中' | '已取消';
}

interface StorageLocation {
  id: string;
  name: string;
  type: '仓库' | '车间' | '露天场地' | '其他';
  capacity?: string;
  inCharge?: string;
}

interface Customer {
  id: string;
  code: string;
  name: string;
  type: '农户' | '合作社' | '企业';
  contactPerson: string;
  phone: string;
  email?: string;
  address: string;
  creditLimit: number;
  usedCredit: number;
  purchaseHistory: CustomerPurchase[];
  totalPurchaseAmount: number;
  notes?: string;
  createdAt: string;
}

interface CustomerPurchase {
  id: string;
  date: string;
  productName: string;
  quantity: number;
  amount: number;
  paid: number;
  status: '已完成' | '待付款' | '部分付款';
}

export function AssetBasicInfo({ activePath }: AssetBasicInfoProps) {
  const [activeTab, setActiveTab] = useState('materials');
  const [showMaterialDialog, setShowMaterialDialog] = useState(false);
  const [showToolDialog, setShowToolDialog] = useState(false);
  const [showSupplierDialog, setShowSupplierDialog] = useState(false);
  const [showCustomerDialog, setShowCustomerDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [editingMaterial, setEditingMaterial] = useState<Material | null>(null);
  const [filterType, setFilterType] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  // 农资表单状态
  const [formData, setFormData] = useState({
    type: '' as MaterialType | '',
    name: '',
    spec: '',
    model: '',
    supplier: '',
    manufacturer: '',
    shelfLife: '', // 有效期数量
    shelfLifeUnit: '' as '年' | '月' | '天' | '', // 有效期单位
    safeStock: '',
    unit: '',
    purchasePrice: '',
    registrationNo: '',
    toxicityLevel: '' as '低毒' | '中毒' | '高毒' | '剧毒' | '',
    safetyInterval: '',
    notes: '',
  });

  // 农具表单状态
  const [editingTool, setEditingTool] = useState<Tool | null>(null);
  const [toolFormData, setToolFormData] = useState({
    name: '',
    type: '',
    model: '',
    purchaseDate: '',
    purchasePrice: '',
    depreciation: '',
    status: '' as ToolStatus | '',
    responsiblePerson: '',
    notes: '',
    images: [] as string[],
  });

  // 供应商表单状态
  const [editingSupplier, setEditingSupplier] = useState<Supplier | null>(null);
  const [supplierFormData, setSupplierFormData] = useState({
    name: '',
    type: '',
    contactPerson: '',
    phone: '',
    email: '',
    address: '',
    level: '' as SupplierLevel | '',
    notes: '',
  });

  // 资质证书相关状态
  const [certifications, setCertifications] = useState<Certification[]>([]);
  const [showCertDialog, setShowCertDialog] = useState(false);
  const [certFormData, setCertFormData] = useState({
    name: '',
    certificateNo: '',
    issueDate: '',
    expiryDate: '',
    file: '',
  });

  // 关联查询状态
  const [showRelatedItemsDialog, setShowRelatedItemsDialog] = useState(false);
  const [selectedSupplierForQuery, setSelectedSupplierForQuery] = useState<Supplier | null>(null);

  // 客户表单状态
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [customerFormData, setCustomerFormData] = useState({
    name: '',
    type: '' as '农户' | '合作社' | '企业' | '',
    contactPerson: '',
    phone: '',
    email: '',
    address: '',
    creditLimit: '',
    notes: '',
  });

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/materials')) {
        setActiveTab('materials');
      } else if (activePath.includes('/tools')) {
        setActiveTab('tools');
      } else if (activePath.includes('/suppliers')) {
        setActiveTab('suppliers');
      } else if (activePath.includes('/customers')) {
        setActiveTab('customers');
      }
    }
  }, [activePath]);

  // 模拟农资数据
  const [materials, setMaterials] = useState<Material[]>([
    {
      id: 'mat-1',
      code: 'SEED-2024-001',
      name: '优质水稻种子',
      type: '种子',
      spec: '25kg/袋',
      model: '龙粳31',
      supplier: '北方农资有限公司',
      supplierId: 'sup-1',
      manufacturer: '黑龙江种业集团',
      expiryDate: '2024-12-31',
      productionDate: '2023-10-01',
      shelfLife: '1',
      shelfLifeUnit: '年',
      safeStock: 100,
      currentStock: 85,
      unit: '袋',
      purchasePrice: 280,
      status: '库存预警',
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 50 },
        { locationId: 'loc-2', locationName: '2号仓库', quantity: 35 },
      ],
      createdAt: '2024-01-15',
    },
    {
      id: 'mat-2',
      code: 'FERT-2024-002',
      name: '复合肥',
      type: '化肥',
      spec: '50kg/袋',
      model: 'NPK 15-15-15',
      supplier: '中化化肥',
      supplierId: 'sup-2',
      manufacturer: '中化化肥有限公司',
      expiryDate: '2025-06-30',
      productionDate: '2024-01-01',
      shelfLife: '18',
      shelfLifeUnit: '月',
      safeStock: 200,
      currentStock: 450,
      unit: '袋',
      purchasePrice: 180,
      status: '正常',
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 200 },
        { locationId: 'loc-3', locationName: '3号仓库', quantity: 150 },
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 100 },
      ],
      createdAt: '2024-02-01',
    },
    {
      id: 'mat-3',
      code: 'PEST-2024-003',
      name: '吡虫啉可湿性粉剂',
      type: '农药',
      spec: '200g/瓶',
      model: '25%',
      supplier: '拜耳作物科学',
      supplierId: 'sup-3',
      manufacturer: '拜耳作物科学（中国）有限公司',
      expiryDate: '2024-05-31',
      productionDate: '2022-05-01',
      shelfLife: '2',
      shelfLifeUnit: '年',
      safeStock: 50,
      currentStock: 120,
      unit: '瓶',
      purchasePrice: 45,
      status: '临期预警',
      registrationNo: 'PD20210123',
      toxicityLevel: '低毒',
      safetyInterval: 15,
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 80 },
        { locationId: 'loc-2', locationName: '2号仓库', quantity: 40 },
      ],
      notes: '需在阴凉干燥处保存',
      createdAt: '2024-01-20',
    },
    {
      id: 'mat-4',
      code: 'PEST-2024-004',
      name: '草甘膦除草剂',
      type: '农药',
      spec: '500ml/瓶',
      model: '41%',
      supplier: '拜耳作物科学',
      supplierId: 'sup-3',
      manufacturer: '拜耳作物科学（中国）有限公司',
      expiryDate: '2024-11-20',
      productionDate: '2023-05-01',
      shelfLife: '18',
      shelfLifeUnit: '月',
      safeStock: 80,
      currentStock: 150,
      unit: '瓶',
      purchasePrice: 38,
      status: '临期预警',
      registrationNo: 'PD20190456',
      toxicityLevel: '中毒',
      safetyInterval: 7,
      inventoryLocations: [
        { locationId: 'loc-2', locationName: '2号仓库', quantity: 90 },
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 60 },
      ],
      notes: '使用时需佩戴防护装备',
      createdAt: '2024-03-10',
    },
    {
      id: 'mat-5',
      code: 'SEED-2024-005',
      name: '玉米杂交种子',
      type: '种子',
      spec: '10kg/袋',
      model: '先玉335',
      supplier: '北方农资有限公司',
      supplierId: 'sup-1',
      manufacturer: '登海种业',
      expiryDate: '2025-03-31',
      productionDate: '2024-04-01',
      shelfLife: '10',
      shelfLifeUnit: '月',
      safeStock: 150,
      currentStock: 60,
      unit: '袋',
      purchasePrice: 320,
      status: '库存预警',
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 40 },
        { locationId: 'loc-3', locationName: '3号仓库', quantity: 20 },
      ],
      notes: '适合春播，需低温储存',
      createdAt: '2024-05-15',
    },
    {
      id: 'mat-6',
      code: 'FERT-2024-006',
      name: '尿素',
      type: '化肥',
      spec: '50kg/袋',
      model: 'N 46%',
      supplier: '中化化肥',
      supplierId: 'sup-2',
      manufacturer: '中海化学',
      expiryDate: '2023-12-31',
      productionDate: '2022-01-01',
      shelfLife: '2',
      shelfLifeUnit: '年',
      safeStock: 100,
      currentStock: 45,
      unit: '袋',
      purchasePrice: 120,
      status: '已过期',
      inventoryLocations: [
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 45 },
      ],
      notes: '已过期，需要清理处理',
      createdAt: '2022-03-01',
    },
  ]);

  // 模拟农具数据
  const [tools, setTools] = useState<Tool[]>([
    {
      id: 'tool-1',
      code: 'TOOL-2024-001',
      name: '东方红拖拉机',
      type: '大型农机',
      model: 'LX904',
      purchaseDate: '2020-03-15',
      purchasePrice: 180000,
      depreciation: 10,
      currentValue: 108000,
      status: '在用',
      responsiblePerson: '张三',
      totalQuantity: 2,
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 1 },
        { locationId: 'loc-5', locationName: '农机车间', quantity: 1 },
      ],
      images: ['tractor1.jpg', 'tractor2.jpg'],
      maintenanceHistory: [
        {
          id: 'main-1',
          date: '2024-01-15',
          type: '保养',
          description: '更换机油和滤芯',
          cost: 800,
          technician: '李维修',
        },
      ],
      notes: '定期保养，状态良好',
      createdAt: '2020-03-15',
    },
    {
      id: 'tool-2',
      code: 'TOOL-2024-002',
      name: '旋耕机',
      type: '耕作机械',
      model: '1GQN-200',
      purchaseDate: '2021-05-20',
      purchasePrice: 12000,
      depreciation: 8,
      currentValue: 7500,
      status: '维修',
      responsiblePerson: '李四',
      totalQuantity: 1,
      inventoryLocations: [
        { locationId: 'loc-7', locationName: '维修车间', quantity: 1 },
      ],
      images: ['rotary1.jpg'],
      notes: '液压系统需要维修',
      createdAt: '2021-05-20',
    },
    {
      id: 'tool-3',
      code: 'TOOL-2024-003',
      name: '喷雾器',
      type: '植保机械',
      model: '3WX-500',
      purchaseDate: '2023-03-10',
      purchasePrice: 3500,
      depreciation: 5,
      currentValue: 2800,
      status: '在用',
      responsiblePerson: '王五',
      totalQuantity: 5,
      inventoryLocations: [
        { locationId: 'loc-2', locationName: '2号仓库', quantity: 3 },
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 2 },
      ],
      createdAt: '2023-03-10',
    },
    {
      id: 'tool-4',
      code: 'TOOL-2024-004',
      name: '收割机',
      type: '收获机械',
      model: '4LZ-5',
      purchaseDate: '2019-06-01',
      purchasePrice: 220000,
      depreciation: 12,
      currentValue: 120833,
      status: '在用',
      responsiblePerson: '赵六',
      totalQuantity: 1,
      inventoryLocations: [
        { locationId: 'loc-3', locationName: '3号仓库', quantity: 1 },
      ],
      images: ['harvester1.jpg', 'harvester2.jpg', 'harvester3.jpg'],
      maintenanceHistory: [
        {
          id: 'main-3',
          date: '2024-02-10',
          type: '保养',
          description: '更换刀片和履带',
          cost: 3500,
          technician: '李维修',
        },
        {
          id: 'main-4',
          date: '2023-08-15',
          type: '维修',
          description: '修复发动机漏油问题',
          cost: 5200,
          technician: '张师傅',
        },
      ],
      notes: '年度大修已完成，状态良好',
      createdAt: '2019-06-01',
    },
    {
      id: 'tool-5',
      code: 'TOOL-2024-005',
      name: '铁锹',
      type: '小型农具',
      model: '标准型',
      purchaseDate: '2024-01-05',
      purchasePrice: 60,
      depreciation: 3,
      currentValue: 56,
      status: '在用',
      totalQuantity: 20,
      inventoryLocations: [
        { locationId: 'loc-1', locationName: '1号仓库', quantity: 10 },
        { locationId: 'loc-2', locationName: '2号仓库', quantity: 6 },
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 4 },
      ],
      createdAt: '2024-01-05',
    },
    {
      id: 'tool-6',
      code: 'TOOL-2024-006',
      name: '播种机',
      type: '耕作机械',
      model: '2BXF-12',
      purchaseDate: '2022-04-15',
      purchasePrice: 18000,
      depreciation: 8,
      currentValue: 13500,
      status: '在用',
      responsiblePerson: '孙七',
      totalQuantity: 2,
      inventoryLocations: [
        { locationId: 'loc-4', locationName: '4号仓库', quantity: 1 },
        { locationId: 'loc-6', locationName: '露天停放区', quantity: 1 },
      ],
      images: ['seeder1.jpg'],
      notes: '春季播种时使用',
      createdAt: '2022-04-15',
    },
    {
      id: 'tool-7',
      code: 'TOOL-2024-007',
      name: '老式拖拉机',
      type: '大型农机',
      model: 'TY-504',
      purchaseDate: '2010-03-20',
      purchasePrice: 85000,
      depreciation: 10,
      currentValue: 0,
      status: '报废',
      responsiblePerson: '李四',
      totalQuantity: 1,
      inventoryLocations: [
        { locationId: 'loc-8', locationName: '报废区', quantity: 1 },
      ],
      notes: '已超过使用年限，等待报废处理',
      createdAt: '2010-03-20',
    },
  ]);

  // 模拟仓位管理数据
  const [storageLocations, setStorageLocations] = useState<StorageLocation[]>([
    {
      id: 'loc-1',
      name: '1号仓库',
      type: '仓库',
      capacity: '500平方米',
      inCharge: '张三',
    },
    {
      id: 'loc-2',
      name: '2号仓库',
      type: '仓库',
      capacity: '300平方米',
      inCharge: '李四',
    },
    {
      id: 'loc-3',
      name: '3号仓库',
      type: '仓库',
      capacity: '800平方米',
      inCharge: '王五',
    },
    {
      id: 'loc-4',
      name: '4号仓库',
      type: '仓库',
      capacity: '200平方米',
      inCharge: '赵六',
    },
    {
      id: 'loc-5',
      name: '农机车间',
      type: '车间',
      capacity: '1000平方米',
      inCharge: '孙七',
    },
    {
      id: 'loc-6',
      name: '露天停放区',
      type: '露天场地',
      capacity: '2000平方米',
      inCharge: '周八',
    },
    {
      id: 'loc-7',
      name: '维修车间',
      type: '车间',
      capacity: '400平方米',
      inCharge: '吴九',
    },
    {
      id: 'loc-8',
      name: '报废区',
      type: '其他',
      capacity: '100平方米',
      inCharge: '郑十',
    },
  ]);

  // 模拟供应商数据
  const [suppliers, setSuppliers] = useState<Supplier[]>([
    {
      id: 'sup-1',
      code: 'SUP-001',
      name: '北方农资有限公司',
      type: '种子供应商',
      contactPerson: '刘经理',
      phone: '13900001111',
      email: 'liu@northern-agri.com',
      address: '黑龙江省哈尔滨市',
      level: 'A级',
      certifications: [
        {
          id: 'cert-1',
          name: '种子经营许可证',
          certificateNo: 'SEED-2023-0001',
          issueDate: '2023-01-01',
          expiryDate: '2026-01-01',
          file: 'cert1.pdf',
        },
      ],
      purchaseHistory: [
        {
          id: 'pur-1',
          date: '2024-01-15',
          materialName: '优质水稻种子',
          quantity: 200,
          amount: 56000,
          status: '已完成',
        },
        {
          id: 'pur-2',
          date: '2024-02-20',
          materialName: '玉米种子',
          quantity: 150,
          amount: 45000,
          status: '已完成',
        },
      ],
      totalPurchaseAmount: 520000,
      cooperationYears: 3,
      notes: '长期合作伙伴，质量可靠',
      createdAt: '2021-01-01',
    },
    {
      id: 'sup-2',
      code: 'SUP-002',
      name: '中化化肥',
      type: '化肥供应商',
      contactPerson: '王总',
      phone: '13900002222',
      email: 'wang@sinochem.com',
      address: '北京市朝阳区',
      level: 'A级',
      certifications: [
        {
          id: 'cert-2',
          name: '化肥经营许可证',
          certificateNo: 'FERT-2023-0002',
          issueDate: '2023-01-01',
          expiryDate: '2026-01-01',
        },
      ],
      purchaseHistory: [
        {
          id: 'pur-3',
          date: '2024-02-01',
          materialName: '复合肥',
          quantity: 500,
          amount: 90000,
          status: '已完成',
        },
      ],
      totalPurchaseAmount: 380000,
      cooperationYears: 5,
      createdAt: '2019-01-01',
    },
    {
      id: 'sup-3',
      code: 'SUP-003',
      name: '拜耳作物科学',
      type: '农药供应商',
      contactPerson: '张经理',
      phone: '13900003333',
      email: 'zhang@bayer.com',
      address: '上海市浦东新区',
      level: 'B级',
      certifications: [
        {
          id: 'cert-3',
          name: '农药经营许可证',
          certificateNo: 'PEST-2023-0003',
          issueDate: '2023-01-01',
          expiryDate: '2026-01-01',
        },
      ],
      purchaseHistory: [
        {
          id: 'pur-4',
          date: '2024-01-20',
          materialName: '吡虫啉可湿性粉剂',
          quantity: 200,
          amount: 9000,
          status: '已完成',
        },
      ],
      totalPurchaseAmount: 125000,
      cooperationYears: 2,
      createdAt: '2022-01-01',
    },
  ]);

  // 模拟客户数据
  const [customers, setCustomers] = useState<Customer[]>([
    {
      id: 'cus-1',
      code: 'CUS-001',
      name: '李家农场',
      type: '农户',
      contactPerson: '李老板',
      phone: '13800001111',
      email: 'li@farm.com',
      address: '浙江省杭州市余杭区',
      creditLimit: 50000,
      usedCredit: 12000,
      purchaseHistory: [
        {
          id: 'sale-1',
          date: '2024-03-01',
          productName: '有机大米',
          quantity: 1000,
          amount: 18000,
          paid: 18000,
          status: '已完成',
        },
        {
          id: 'sale-2',
          date: '2024-03-15',
          productName: '有机蔬菜',
          quantity: 500,
          amount: 12000,
          paid: 0,
          status: '待付款',
        },
      ],
      totalPurchaseAmount: 185000,
      notes: '长期客户，信誉良好',
      createdAt: '2022-01-01',
    },
    {
      id: 'cus-2',
      code: 'CUS-002',
      name: '绿源合作社',
      type: '合作社',
      contactPerson: '王社长',
      phone: '13800002222',
      email: 'wang@coop.com',
      address: '浙江省杭州市萧山区',
      creditLimit: 100000,
      usedCredit: 35000,
      purchaseHistory: [
        {
          id: 'sale-3',
          date: '2024-02-15',
          productName: '有机大米',
          quantity: 2000,
          amount: 36000,
          paid: 36000,
          status: '已完成',
        },
        {
          id: 'sale-4',
          date: '2024-03-10',
          productName: '有机玉米',
          quantity: 1500,
          amount: 35000,
          paid: 15000,
          status: '部分付款',
        },
      ],
      totalPurchaseAmount: 420000,
      createdAt: '2021-06-01',
    },
    {
      id: 'cus-3',
      code: 'CUS-003',
      name: '丰收农业公司',
      type: '企业',
      contactPerson: '赵总',
      phone: '13800003333',
      email: 'zhao@harvest.com',
      address: '浙江省杭州市临安区',
      creditLimit: 200000,
      usedCredit: 80000,
      purchaseHistory: [
        {
          id: 'sale-5',
          date: '2024-01-20',
          productName: '有机大米',
          quantity: 5000,
          amount: 90000,
          paid: 90000,
          status: '已完成',
        },
      ],
      totalPurchaseAmount: 850000,
      createdAt: '2020-03-01',
    },
  ]);

  // 获取状态颜色
  const getMaterialStatusColor = (status: MaterialStatus) => {
    switch (status) {
      case '正常': return 'bg-success-muted text-success-muted-foreground';
      case '临期预警': return 'bg-warning-muted text-warning-muted-foreground';
      case '库存预警': return 'bg-warning-muted text-warning-muted-foreground';
      case '已过期': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getToolStatusColor = (status: ToolStatus) => {
    switch (status) {
      case '在用': return 'bg-success-muted text-success-muted-foreground';
      case '维修': return 'bg-warning-muted text-warning-muted-foreground';
      case '报废': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getSupplierLevelColor = (level: SupplierLevel) => {
    switch (level) {
      case 'A级': return 'bg-success-muted text-success-muted-foreground';
      case 'B级': return 'bg-info-muted text-info-muted-foreground';
      case 'C级': return 'bg-warning-muted text-warning-muted-foreground';
      case 'D级': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  // 计算临期预警
  const checkExpiry = (expiryDate: string): { isWarning: boolean; daysLeft: number } => {
    const today = new Date();
    const expiry = new Date(expiryDate);
    const daysLeft = Math.floor((expiry.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
    return {
      isWarning: daysLeft <= 90,
      daysLeft,
    };
  };

  // 生成唯一编码
  const generateCode = (type: MaterialType): string => {
    const prefix = type === '种子' ? 'SEED' : type === '化肥' ? 'FERT' : 'PEST';
    const year = new Date().getFullYear();
    const typeMatters = materials.filter(m => m.type === type);
    const nextNumber = (typeMatters.length + 1).toString().padStart(3, '0');
    return `${prefix}-${year}-${nextNumber}`;
  };

  // 计算材料状态
  const calculateMaterialStatus = (material: Partial<Material>): MaterialStatus => {
    const { expiryDate, currentStock, safeStock } = material;
    
    if (!expiryDate || currentStock === undefined || safeStock === undefined) {
      return '正常';
    }

    const expiryCheck = checkExpiry(expiryDate);
    const daysLeft = expiryCheck.daysLeft;

    // 已过期
    if (daysLeft < 0) {
      return '已过期';
    }

    // 临期预警优先级高于库存预警
    if (daysLeft <= 30) {
      return '临期预警';
    }

    if (daysLeft <= 90) {
      return '临期预警';
    }

    // 库存预警
    if (currentStock < safeStock) {
      return '库存预警';
    }

    return '正常';
  };

  // 计算有效期日期
  const calculateExpiryDate = (quantity: number, unit: '年' | '月' | '天'): string => {
    const today = new Date();
    let expiryDate = new Date(today);

    if (unit === '年') {
      expiryDate.setFullYear(expiryDate.getFullYear() + quantity);
    } else if (unit === '月') {
      expiryDate.setMonth(expiryDate.getMonth() + quantity);
    } else if (unit === '天') {
      expiryDate.setDate(expiryDate.getDate() + quantity);
    }

    return expiryDate.toISOString().split('T')[0];
  };

  // 打开新增对话框
  const handleOpenAddDialog = () => {
    setEditingMaterial(null);
    setFormData({
      type: '',
      name: '',
      spec: '',
      model: '',
      supplier: '',
      manufacturer: '',
      shelfLife: '',
      shelfLifeUnit: '',
      safeStock: '',
      unit: '',
      purchasePrice: '',
      registrationNo: '',
      toxicityLevel: '',
      safetyInterval: '',
      notes: '',
    });
    setShowMaterialDialog(true);
  };

  // 打开编辑对话框
  const handleOpenEditDialog = (material: Material) => {
    setEditingMaterial(material);
    
    // 编辑时，从现有的expiryDate反推有效期
    const today = new Date();
    const expiry = new Date(material.expiryDate);
    const diffDays = Math.ceil((expiry.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
    
    let shelfLife = '';
    let shelfLifeUnit: '年' | '月' | '天' | '' = '';
    
    if (diffDays >= 365 && diffDays % 365 === 0) {
      shelfLife = Math.floor(diffDays / 365).toString();
      shelfLifeUnit = '年';
    } else if (diffDays >= 30) {
      shelfLife = Math.floor(diffDays / 30).toString();
      shelfLifeUnit = '月';
    } else {
      shelfLife = diffDays.toString();
      shelfLifeUnit = '天';
    }
    
    setFormData({
      type: material.type,
      name: material.name,
      spec: material.spec,
      model: material.model || '',
      supplier: material.supplierId,
      manufacturer: material.manufacturer || '',
      shelfLife: shelfLife,
      shelfLifeUnit: shelfLifeUnit,
      safeStock: material.safeStock.toString(),
      unit: material.unit,
      purchasePrice: material.purchasePrice.toString(),
      registrationNo: material.registrationNo || '',
      toxicityLevel: material.toxicityLevel || '',
      safetyInterval: material.safetyInterval?.toString() || '',
      notes: material.notes || '',
    });
    setShowMaterialDialog(true);
  };

  // 保存农资
  const handleSaveMaterial = () => {
    // 验证必填字段
    if (!formData.type || !formData.name || !formData.spec || !formData.supplier || 
        !formData.shelfLife || !formData.shelfLifeUnit || 
        !formData.safeStock || !formData.unit || !formData.purchasePrice) {
      toast.error('请填写所有必填项');
      return;
    }

    // 农药特殊验证
    if (formData.type === '农药') {
      if (!formData.registrationNo || !formData.toxicityLevel || !formData.safetyInterval) {
        toast.error('农药必须填写登记证号、毒性等级和安全间隔期');
        return;
      }
    }

    const supplier = suppliers.find(s => s.id === formData.supplier);
    if (!supplier) {
      toast.error('请选择有效的供应商');
      return;
    }

    const shelfLife = parseFloat(formData.shelfLife);
    if (isNaN(shelfLife) || shelfLife <= 0) {
      toast.error('请输入有效的有效期');
      return;
    }

    const safeStock = parseFloat(formData.safeStock);

    // 计算有效期日期
    const expiryDate = calculateExpiryDate(shelfLife, formData.shelfLifeUnit as '年' | '月' | '天');
    const today = new Date().toISOString().split('T')[0];

    const materialData: Partial<Material> = {
      type: formData.type as MaterialType,
      name: formData.name,
      spec: formData.spec,
      model: formData.model,
      supplier: supplier.name,
      supplierId: supplier.id,
      manufacturer: formData.manufacturer,
      expiryDate: expiryDate,
      productionDate: today, // 使用当前日期作为生产日期
      shelfLife: formData.shelfLife, // 保存有效期数量
      shelfLifeUnit: formData.shelfLifeUnit as '年' | '月' | '天', // 保存有效期单位
      safeStock: safeStock,
      currentStock: editingMaterial ? editingMaterial.currentStock : 0, // 新增时默认库存为0，编辑时保持原值
      unit: formData.unit,
      purchasePrice: parseFloat(formData.purchasePrice),
      notes: formData.notes,
    };

    // 农药特殊字段
    if (formData.type === '农药') {
      materialData.registrationNo = formData.registrationNo;
      materialData.toxicityLevel = formData.toxicityLevel as '低毒' | '中毒' | '高毒' | '剧毒';
      materialData.safetyInterval = parseInt(formData.safetyInterval);
    }

    // 计算状态
    materialData.status = calculateMaterialStatus(materialData);

    if (editingMaterial) {
      // 更新
      setMaterials(materials.map(m =>
        m.id === editingMaterial.id
          ? { ...m, ...materialData, updatedAt: new Date().toISOString().split('T')[0] }
          : m
      ));
      toast.success('农资信息已更新');
    } else {
      // 新增
      const newMaterial: Material = {
        ...materialData as Material,
        id: `mat-${Date.now()}`,
        code: generateCode(formData.type as MaterialType),
        createdAt: new Date().toISOString().split('T')[0],
      };
      setMaterials([...materials, newMaterial]);
      toast.success('农资添加成功');
    }

    setShowMaterialDialog(false);
  };

  // 删除农资
  const handleDeleteMaterial = (id: string) => {
    if (confirm('确定要删除这条农资记录吗？')) {
      setMaterials(materials.filter(m => m.id !== id));
      toast.success('删除成功');
    }
  };

  // 查看详情
  const handleViewMaterial = (material: Material) => {
    setSelectedItem(material);
    setShowViewDialog(true);
  };

  // ==================== 农具管理功能 ====================

  // 生成农具编码
  const generateToolCode = (): string => {
    const year = new Date().getFullYear();
    const nextNumber = (tools.length + 1).toString().padStart(3, '0');
    return `TOOL-${year}-${nextNumber}`;
  };

  // 计算折旧后的当前价值
  const calculateCurrentValue = (purchasePrice: number, purchaseDate: string, depreciation: number): number => {
    const today = new Date();
    const purchase = new Date(purchaseDate);
    const yearsUsed = (today.getTime() - purchase.getTime()) / (1000 * 60 * 60 * 24 * 365);
    const depreciationPerYear = purchasePrice / depreciation;
    const depreciated = depreciationPerYear * yearsUsed;
    const currentValue = Math.max(0, purchasePrice - depreciated);
    return Math.round(currentValue);
  };

  // 打开新增农具对话框
  const handleOpenAddToolDialog = () => {
    setEditingTool(null);
    setToolFormData({
      name: '',
      type: '',
      model: '',
      purchaseDate: '',
      purchasePrice: '',
      depreciation: '',
      status: '',
      responsiblePerson: '',
      notes: '',
      images: [],
    });
    setShowToolDialog(true);
  };

  // 打开编辑农具对话框
  const handleOpenEditToolDialog = (tool: Tool) => {
    setEditingTool(tool);
    setToolFormData({
      name: tool.name,
      type: tool.type,
      model: tool.model,
      purchaseDate: tool.purchaseDate,
      purchasePrice: tool.purchasePrice.toString(),
      depreciation: tool.depreciation.toString(),
      status: tool.status,
      responsiblePerson: tool.responsiblePerson || '',
      notes: tool.notes || '',
      images: tool.images || [],
    });
    setShowToolDialog(true);
  };

  // 保存农具
  const handleSaveTool = () => {
    // 验证必填字段
    if (!toolFormData.name || !toolFormData.type || !toolFormData.model || 
        !toolFormData.purchaseDate || !toolFormData.purchasePrice || 
        !toolFormData.depreciation || !toolFormData.status) {
      toast.error('请填写所有必填项');
      return;
    }

    const purchasePrice = parseFloat(toolFormData.purchasePrice);
    const depreciation = parseFloat(toolFormData.depreciation);

    if (isNaN(purchasePrice) || purchasePrice <= 0) {
      toast.error('请输入有效的购买价格');
      return;
    }

    if (isNaN(depreciation) || depreciation <= 0) {
      toast.error('请输入有效的折旧年限');
      return;
    }

    // 计算当前价值
    const currentValue = calculateCurrentValue(purchasePrice, toolFormData.purchaseDate, depreciation);

    const toolData: Partial<Tool> = {
      name: toolFormData.name,
      type: toolFormData.type,
      model: toolFormData.model,
      purchaseDate: toolFormData.purchaseDate,
      purchasePrice: purchasePrice,
      depreciation: depreciation,
      currentValue: currentValue,
      status: toolFormData.status as ToolStatus,
      responsiblePerson: toolFormData.responsiblePerson || undefined,
      totalQuantity: editingTool ? editingTool.totalQuantity : 0, // 新增时默认数量为0，编辑时保持原值
      inventoryLocations: editingTool ? editingTool.inventoryLocations : [], // 保持库存位置不变
      images: toolFormData.images,
      notes: toolFormData.notes || undefined,
    };

    if (editingTool) {
      // 更新
      setTools(tools.map(t =>
        t.id === editingTool.id
          ? { ...t, ...toolData }
          : t
      ));
      toast.success('农具信息已更新');
    } else {
      // 新增
      const newTool: Tool = {
        ...toolData as Tool,
        id: `tool-${Date.now()}`,
        code: generateToolCode(),
        createdAt: new Date().toISOString().split('T')[0],
        maintenanceHistory: [],
      };
      setTools([...tools, newTool]);
      toast.success('农具添加成功');
    }

    setShowToolDialog(false);
  };

  // 删除农具
  const handleDeleteTool = (id: string) => {
    if (confirm('确定要删除这条农具记录吗？')) {
      setTools(tools.filter(t => t.id !== id));
      toast.success('删除成功');
    }
  };

  // 查看农具详情
  const handleViewTool = (tool: Tool) => {
    setSelectedItem(tool);
    setShowViewDialog(true);
  };

  // 处理农具图片上传
  const handleToolImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    // 模拟图片上传（实际项目中应该上传到服务器）
    const newImages: string[] = [];
    Array.from(files).forEach((file, index) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          newImages.push(event.target.result as string);
          // 当所有图片都读取完成后更新状态
          if (newImages.length === files.length) {
            setToolFormData({
              ...toolFormData,
              images: [...toolFormData.images, ...newImages],
            });
            toast.success(`已添加 ${newImages.length} 张图片`);
          }
        }
      };
      reader.readAsDataURL(file);
    });
  };

  // 删除农具图片
  const handleToolImageDelete = (index: number) => {
    const newImages = toolFormData.images.filter((_, i) => i !== index);
    setToolFormData({ ...toolFormData, images: newImages });
    toast.success('图片已删除');
  };

  // ========== 供应商管理函数 ==========
  
  // 生成供应商编码
  const generateSupplierCode = () => {
    const count = suppliers.length + 1;
    return `SUP-${count.toString().padStart(3, '0')}`;
  };

  // 打开新增供应商对话框
  const handleOpenAddSupplierDialog = () => {
    setEditingSupplier(null);
    setSupplierFormData({
      name: '',
      type: '',
      contactPerson: '',
      phone: '',
      email: '',
      address: '',
      level: '',
      notes: '',
    });
    setCertifications([]);
    setShowSupplierDialog(true);
  };

  // 打开编辑供应商对话框
  const handleOpenEditSupplierDialog = (supplier: Supplier) => {
    setEditingSupplier(supplier);
    setSupplierFormData({
      name: supplier.name,
      type: supplier.type,
      contactPerson: supplier.contactPerson,
      phone: supplier.phone,
      email: supplier.email,
      address: supplier.address,
      level: supplier.level,
      notes: supplier.notes || '',
    });
    setCertifications(supplier.certifications || []);
    setShowSupplierDialog(true);
  };

  // 保存供应商
  const handleSaveSupplier = () => {
    // 验证必填项
    if (!supplierFormData.name || !supplierFormData.type || !supplierFormData.contactPerson ||
        !supplierFormData.phone || !supplierFormData.level) {
      toast.error('请填写所有必填项');
      return;
    }

    // 验证手机号格式
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(supplierFormData.phone)) {
      toast.error('请输入有效的手机号码');
      return;
    }

    // 验证邮箱格式（如果填写了邮箱）
    if (supplierFormData.email) {
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailPattern.test(supplierFormData.email)) {
        toast.error('请输入有效的邮箱地址');
        return;
      }
    }

    const supplierData: Partial<Supplier> = {
      name: supplierFormData.name,
      type: supplierFormData.type,
      contactPerson: supplierFormData.contactPerson,
      phone: supplierFormData.phone,
      email: supplierFormData.email || '',
      address: supplierFormData.address || '',
      level: supplierFormData.level as SupplierLevel,
      certifications: certifications,
      notes: supplierFormData.notes || undefined,
    };

    if (editingSupplier) {
      // 更新供应商
      setSuppliers(suppliers.map(s =>
        s.id === editingSupplier.id
          ? {
              ...s,
              ...supplierData,
              purchaseHistory: s.purchaseHistory,
              totalPurchaseAmount: s.totalPurchaseAmount,
              cooperationYears: s.cooperationYears,
            }
          : s
      ));
      toast.success('供应商信息已更新');
    } else {
      // 新增供应商
      const newSupplier: Supplier = {
        ...supplierData as Supplier,
        id: `sup-${Date.now()}`,
        code: generateSupplierCode(),
        purchaseHistory: [],
        totalPurchaseAmount: 0,
        cooperationYears: 0,
        createdAt: new Date().toISOString().split('T')[0],
      };
      setSuppliers([...suppliers, newSupplier]);
      toast.success('供应商添加成功');
    }

    setShowSupplierDialog(false);
  };

  // 删除供应商
  const handleDeleteSupplier = (id: string) => {
    // 检查是否有关联的采购记录
    const relatedMaterials = materials.filter(m => m.supplierId === id);
    if (relatedMaterials.length > 0) {
      toast.error(`该供应商已有 ${relatedMaterials.length} 条采购记录，无法删除`);
      return;
    }

    if (confirm('确定要删除这个供应商吗？')) {
      setSuppliers(suppliers.filter(s => s.id !== id));
      toast.success('删除成功');
    }
  };

  // 查看供应商详情
  const handleViewSupplier = (supplier: Supplier) => {
    setSelectedItem(supplier);
    setShowViewDialog(true);
  };

  // 添加资质证书
  const handleAddCertification = () => {
    if (!certFormData.name || !certFormData.certificateNo || !certFormData.issueDate || !certFormData.expiryDate) {
      toast.error('请填写资质证书的所有必填项');
      return;
    }

    const newCert: Certification = {
      id: `cert-${Date.now()}`,
      ...certFormData,
    };

    setCertifications([...certifications, newCert]);
    setCertFormData({
      name: '',
      certificateNo: '',
      issueDate: '',
      expiryDate: '',
      file: '',
    });
    setShowCertDialog(false);
    toast.success('资质证书已添加');
  };

  // 删除资质证书
  const handleDeleteCertification = (id: string) => {
    setCertifications(certifications.filter(c => c.id !== id));
    toast.success('资质证书已删除');
  };

  // 处理资质文件上传
  const handleCertFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 模拟文件上传（实际项目中应该上传到服务器）
    const reader = new FileReader();
    reader.onload = (event) => {
      if (event.target?.result) {
        setCertFormData({
          ...certFormData,
          file: event.target.result as string,
        });
        toast.success('文件已上传');
      }
    };
    reader.readAsDataURL(file);
  };

  // 查看供应商关联的采购记录
  const handleViewRelatedItems = (supplier: Supplier) => {
    setSelectedSupplierForQuery(supplier);
    setShowRelatedItemsDialog(true);
  };

  // 获取某供应商的所有采购物品
  const getRelatedItemsBySupplier = (supplierId: string) => {
    return materials.filter(m => m.supplierId === supplierId);
  };

  // ========== 客户管理相关函数 ==========
  
  // 添加/编辑客户
  const handleSaveCustomer = () => {
    if (!customerFormData.name || !customerFormData.type || !customerFormData.contactPerson || 
        !customerFormData.phone || !customerFormData.address || !customerFormData.creditLimit) {
      toast.error('请填写所有必填项');
      return;
    }

    if (editingCustomer) {
      // 编辑模式
      const updatedCustomer: Customer = {
        ...editingCustomer,
        name: customerFormData.name,
        type: customerFormData.type as '农户' | '合作社' | '企业',
        contactPerson: customerFormData.contactPerson,
        phone: customerFormData.phone,
        email: customerFormData.email,
        address: customerFormData.address,
        creditLimit: parseFloat(customerFormData.creditLimit),
        notes: customerFormData.notes,
      };
      setCustomers(customers.map(c => c.id === editingCustomer.id ? updatedCustomer : c));
      toast.success('客户信息已更新');
      setEditingCustomer(null);
    } else {
      // 新增模式
      const newCustomer: Customer = {
        id: `cus-${Date.now()}`,
        code: `CUS-${String(customers.length + 1).padStart(3, '0')}`,
        name: customerFormData.name,
        type: customerFormData.type as '农户' | '合作社' | '企业',
        contactPerson: customerFormData.contactPerson,
        phone: customerFormData.phone,
        email: customerFormData.email,
        address: customerFormData.address,
        creditLimit: parseFloat(customerFormData.creditLimit),
        usedCredit: 0,
        purchaseHistory: [],
        totalPurchaseAmount: 0,
        notes: customerFormData.notes,
        createdAt: new Date().toISOString().split('T')[0],
      };
      setCustomers([...customers, newCustomer]);
      toast.success('客户添加成功');
    }

    setShowCustomerDialog(false);
    setCustomerFormData({
      name: '',
      type: '',
      contactPerson: '',
      phone: '',
      email: '',
      address: '',
      creditLimit: '',
      notes: '',
    });
  };

  // 编辑客户
  const handleEditCustomer = (customer: Customer) => {
    setEditingCustomer(customer);
    setCustomerFormData({
      name: customer.name,
      type: customer.type,
      contactPerson: customer.contactPerson,
      phone: customer.phone,
      email: customer.email || '',
      address: customer.address,
      creditLimit: customer.creditLimit.toString(),
      notes: customer.notes || '',
    });
    setShowCustomerDialog(true);
  };

  // 删除客户
  const handleDeleteCustomer = (id: string) => {
    const customer = customers.find(c => c.id === id);
    if (!customer) return;

    // 检查是否有未完成的订单
    const unpaidOrders = customer.purchaseHistory.filter(p => p.status !== '已完成');
    if (unpaidOrders.length > 0) {
      toast.error(`该客户有 ${unpaidOrders.length} 笔待付款订单，无法删除`);
      return;
    }

    if (confirm(`确定要删除客户"${customer.name}"吗？`)) {
      setCustomers(customers.filter(c => c.id !== id));
      toast.success('删除成功');
    }
  };

  // 查看客户详情
  const handleViewCustomer = (customer: Customer) => {
    setSelectedItem(customer);
    setShowViewDialog(true);
  };

  // 统计数据
  const totalMaterials = materials.length;
  const warningMaterials = materials.filter(m => m.status !== '正常').length;
  const totalTools = tools.length;
  const toolsInUse = tools.filter(t => t.status === '在用').length;
  const totalSuppliers = suppliers.length;
  const aLevelSuppliers = suppliers.filter(s => s.level === 'A级').length;
  const totalCustomers = customers.length;
  const totalCreditUsed = customers.reduce((sum, c) => sum + c.usedCredit, 0);

  // 农资类型统计
  const materialTypeStats = [
    { name: '种子', value: materials.filter(m => m.type === '种子').length },
    { name: '化肥', value: materials.filter(m => m.type === '化肥').length },
    { name: '农药', value: materials.filter(m => m.type === '农药').length },
    { name: '耗材', value: materials.filter(m => m.type === '耗材').length },
  ];

  const COLORS = ['#22c55e', '#3b82f6', '#f97316', '#8b5cf6'];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">基础信息管理</h2>
          <p className="text-muted-foreground">
            农资档案、农具档案、供应商与客户管理
          </p>
        </div>
      </div>

      {/* 统计概览 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">农资总数</p>
              <p className="mt-2 text-3xl text-success">{totalMaterials}</p>
              <p className="text-xs text-warning mt-1">
                {warningMaterials} 项预警
              </p>
            </div>
            <Package className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">农具总数</p>
              <p className="mt-2 text-3xl text-info">{totalTools}</p>
              <p className="text-xs text-success mt-1">
                {toolsInUse} 项在用
              </p>
            </div>
            <Wrench className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">供应商</p>
              <p className="mt-2 text-3xl text-foreground">{totalSuppliers}</p>
              <p className="text-xs text-success mt-1">
                {aLevelSuppliers} 家A级
              </p>
            </div>
            <Building2 className="w-12 h-12 text-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">客户数量</p>
              <p className="mt-2 text-3xl text-warning">{totalCustomers}</p>
              <p className="text-xs text-muted-foreground mt-1">
                授信: ¥{(totalCreditUsed / 10000).toFixed(1)}万
              </p>
            </div>
            <Users className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="materials">农资档案管理</TabsTrigger>
          <TabsTrigger value="tools">农具档案管理</TabsTrigger>
          <TabsTrigger value="suppliers">供应商管理</TabsTrigger>
          <TabsTrigger value="customers">客户管理</TabsTrigger>
        </TabsList>

        {/* 农资档案管理 */}
        <TabsContent value="materials" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-info-muted border-info">
            <div className="flex items-start gap-2">
              <Package className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
              <div className="text-sm text-info-muted-foreground">
                <p className="mb-2">农资档案管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>全生命周期管理</strong>: 从采购到使用的完整记录</li>
                  <li>• <strong>唯一编码</strong>: 每种农资分配唯一编码，便于追踪</li>
                  <li>• <strong>丰富属性</strong>: 名称、规格、型号、供应商、保质期、库存等</li>
                  <li>• <strong>农药特殊管理</strong>: 登记证号、毒性等级、安全间隔期（强制录入）</li>
                  <li>• <strong>临期预警</strong>: 提前3个月标黄、1个月标红</li>
                  <li>• <strong>库存预警</strong>: 低于安全库存自动预警</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="农资类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="种子">种子</SelectItem>
                  <SelectItem value="化肥">化肥</SelectItem>
                  <SelectItem value="农药">农药</SelectItem>
                  <SelectItem value="耗材">耗材</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="正常">正常</SelectItem>
                  <SelectItem value="临期预警">临期预警</SelectItem>
                  <SelectItem value="库存预警">库存预警</SelectItem>
                  <SelectItem value="已过期">已过期</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Button className="bg-success hover:bg-success/90" onClick={handleOpenAddDialog}>
              <Plus className="w-4 h-4 mr-2" />
              新增农资
            </Button>
          </div>

          {/* 农资列表 */}
          <div className="space-y-4">
            {materials
              .filter(m => filterType === 'all' || m.type === filterType)
              .filter(m => filterStatus === 'all' || m.status === filterStatus)
              .map(material => {
              const expiryCheck = checkExpiry(material.expiryDate);
              return (
                <Card key={material.id} className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-3 rounded-lg ${
                        material.type === '种子' ? 'bg-success-muted' :
                        material.type === '化肥' ? 'bg-info-muted' :
                        material.type === '农药' ? 'bg-warning-muted' :
                        'bg-muted'
                      }`}>
                        <Package className={`w-5 h-5 ${
                          material.type === '种子' ? 'text-success' :
                          material.type === '化肥' ? 'text-info' :
                          material.type === '农药' ? 'text-warning' :
                          'text-foreground'
                        }`} />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{material.name}</h4>
                          <Badge variant="outline">{material.type}</Badge>
                          <Badge className={getMaterialStatusColor(material.status)}>
                            {material.status}
                          </Badge>
                          {material.toxicityLevel && (
                            <Badge className={
                              material.toxicityLevel === '低毒' ? 'bg-success-muted text-success-muted-foreground' :
                              material.toxicityLevel === '中毒' ? 'bg-warning-muted text-warning-muted-foreground' :
                              material.toxicityLevel === '高毒' ? 'bg-warning-muted text-warning-muted-foreground' :
                              'bg-error-muted text-error-muted-foreground'
                            }>
                              {material.toxicityLevel}
                            </Badge>
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          编码: {material.code} | 规格: {material.spec} {material.model && `| 型号: ${material.model}`}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleViewMaterial(material)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleOpenEditDialog(material)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeleteMaterial(material.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4 mb-3">
                    <div className="p-3 bg-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">供应商</p>
                      <p className="mt-1">{material.supplier}</p>
                    </div>
                    <div className="p-3 bg-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">当前库存</p>
                      <p className="mt-1 font-medium">
                        {material.currentStock} {material.unit}
                      </p>
                    </div>
                    <div className="p-3 bg-muted rounded-lg">
                      <p className="text-xs text-muted-foreground">安全库存</p>
                      <p className="mt-1">{material.safeStock} {material.unit}</p>
                    </div>
                  </div>

                  {material.type === '农药' && (
                    <div className="p-3 bg-warning-muted border border-warning rounded-lg">
                      <div className="grid grid-cols-3 gap-4 text-sm">
                        <div>
                          <span className="text-muted-foreground">登记证号: </span>
                          <span className="font-medium">{material.registrationNo}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">毒性等级: </span>
                          <span className="font-medium">{material.toxicityLevel}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">安全间隔期: </span>
                          <span className="font-medium">{material.safetyInterval}天</span>
                        </div>
                      </div>
                    </div>
                  )}

                  {material.notes && (
                    <div className="mt-3 p-3 bg-info-muted rounded-lg">
                      <p className="text-xs text-info-muted-foreground">备注: {material.notes}</p>
                    </div>
                  )}
                </Card>
              );
            })}
          </div>

          {/* 农资类型统计 */}
          <Card className="p-6">
            <h3 className="mb-4">农资类型分布</h3>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <RePieChart>
                  <Pie
                    data={materialTypeStats}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {materialTypeStats.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </RePieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </TabsContent>

        {/* 农具档案管理 */}
        <TabsContent value="tools" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-success-muted border-success">
            <div className="flex items-start gap-2">
              <Wrench className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-success-muted-foreground">
                <p className="mb-2">农具档案管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>全面档案</strong>: 从锄头到拖拉机的完整记录</li>
                  <li>• <strong>基础信息</strong>: 名称、型号、编号、购买日期、价值</li>
                  <li>• <strong>折旧管理</strong>: 折旧年限、当前价值自动计算</li>
                  <li>• <strong>状态管理</strong>: 在用、维修、报废</li>
                  <li>• <strong>责任人</strong>: 指定设备责任人</li>
                  <li>• <strong>库存管理</strong>: 通过入库功能管理存放位置和数量分布</li>
                  <li>• <strong>图片上传</strong>: 支持多张设备图片上传</li>
                  <li>• <strong>维护记录</strong>: 完整的保养和维修历史</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleOpenAddToolDialog}>
              <Plus className="w-4 h-4 mr-2" />
              新增农具
            </Button>
          </div>

          {/* 农具列表 */}
          <div className="space-y-4">
            {tools.map(tool => {
              const depreciationRate = (tool.purchasePrice - tool.currentValue) / tool.purchasePrice * 100;
              return (
                <Card key={tool.id} className="p-4">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-start gap-3">
                      <div className="p-3 bg-blue-100 rounded-lg">
                        <Tractor className="w-6 h-6 text-blue-600" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{tool.name}</h4>
                          <Badge variant="outline">{tool.type}</Badge>
                          <Badge className={getToolStatusColor(tool.status)}>
                            {tool.status}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          编码: {tool.code} | 型号: {tool.model}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleViewTool(tool)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleOpenEditToolDialog(tool)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeleteTool(tool.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-5 gap-4 mb-4">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">购买日期</p>
                      <p className="mt-1">{tool.purchaseDate}</p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">购买价格</p>
                      <p className="mt-1 font-medium">¥{tool.purchasePrice.toLocaleString()}</p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">当前价值</p>
                      <p className="mt-1 font-medium text-green-600">
                        ¥{tool.currentValue.toLocaleString()}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">折旧年限</p>
                      <p className="mt-1">{tool.depreciation}年</p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground">折旧率</p>
                      <p className="mt-1">{depreciationRate.toFixed(1)}%</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <User className="w-3 h-3" />
                        责任人
                      </p>
                      <p className="mt-1 font-medium">{tool.responsiblePerson || '未指定'}</p>
                    </div>
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <History className="w-3 h-3" />
                        维护记录
                      </p>
                      <p className="mt-1 font-medium">
                        {tool.maintenanceHistory?.length || 0} 条
                      </p>
                    </div>
                  </div>

                  {tool.images && tool.images.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs text-muted-foreground mb-2">设备图片:</p>
                      <div className="flex gap-2">
                        {tool.images.map((img, i) => (
                          <div key={i} className="w-24 h-24 bg-gray-200 rounded flex items-center justify-center">
                            <Camera className="w-8 h-8 text-gray-400" />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {tool.maintenanceHistory && tool.maintenanceHistory.length > 0 && (
                    <div className="p-3 bg-purple-50 border border-purple-200 rounded-lg">
                      <p className="text-xs text-purple-900 mb-2">最近维护记录:</p>
                      {tool.maintenanceHistory.slice(0, 2).map(record => (
                        <div key={record.id} className="text-sm mb-2 last:mb-0">
                          <span className="font-medium">{record.date}</span>
                          <span className="mx-2">|</span>
                          <Badge variant="outline" className="text-xs">{record.type}</Badge>
                          <span className="mx-2">|</span>
                          <span>{record.description}</span>
                          <span className="mx-2">|</span>
                          <span className="text-green-600">¥{record.cost}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        </TabsContent>

        {/* 供应商管理 */}
        <TabsContent value="suppliers" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Building2 className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">供应商管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>基本信息</strong>: 名称、联系人、电话、邮箱、地址</li>
                  <li>• <strong>资质管理</strong>: 经营许可证、证书扫描件上传</li>
                  <li>• <strong>采购记录</strong>: 完整的历史采购记录</li>
                  <li>• <strong>信用评级</strong>: A/B/C/D四级评级体系</li>
                  <li>• <strong>关联查询</strong>: 快速查询从某供应商采购的所有物品</li>
                  <li>• <strong>统计分析</strong>: 采购金额、合作年限等统计</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleOpenAddSupplierDialog}>
              <Plus className="w-4 h-4 mr-2" />
              新增供应商
            </Button>
          </div>

          {/* 供应商列表 */}
          <div className="space-y-4">
            {suppliers.map(supplier => (
              <Card key={supplier.id} className="p-4">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 bg-purple-100 rounded-lg">
                      <Building2 className="w-6 h-6 text-purple-600" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{supplier.name}</h4>
                        <Badge variant="outline">{supplier.type}</Badge>
                        <Badge className={getSupplierLevelColor(supplier.level)}>
                          {supplier.level}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        编码: {supplier.code} | 合作{supplier.cooperationYears}年
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => handleViewSupplier(supplier)}>
                      <Eye className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => handleViewRelatedItems(supplier)} title="查看采购物品">
                      <Link2 className="w-4 h-4 mr-2" />
                      关联查询
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => handleOpenEditSupplierDialog(supplier)}>
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => handleDeleteSupplier(supplier.id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </div>

                <div className="grid grid-cols-4 gap-4 mb-4">
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <User className="w-3 h-3" />
                      联系人
                    </p>
                    <p className="mt-1 font-medium">{supplier.contactPerson}</p>
                  </div>
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Phone className="w-3 h-3" />
                      联系电话
                    </p>
                    <p className="mt-1 font-medium">{supplier.phone}</p>
                  </div>
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Mail className="w-3 h-3" />
                      邮箱
                    </p>
                    <p className="mt-1 font-medium text-xs">{supplier.email}</p>
                  </div>
                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      地址
                    </p>
                    <p className="mt-1 font-medium text-xs">{supplier.address}</p>
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-4 mb-4">
                  <div className="p-3 bg-green-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <DollarSign className="w-3 h-3" />
                      累计采购金额
                    </p>
                    <p className="mt-1 text-lg font-medium text-green-600">
                      ¥{(supplier.totalPurchaseAmount / 10000).toFixed(1)}万
                    </p>
                  </div>
                  <div className="p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <ShoppingCart className="w-3 h-3" />
                      采购次数
                    </p>
                    <p className="mt-1 text-lg font-medium text-blue-600">
                      {supplier.purchaseHistory.length} 次
                    </p>
                  </div>
                  <div className="p-3 bg-purple-50 rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Shield className="w-3 h-3" />
                      资质证书
                    </p>
                    <p className="mt-1 text-lg font-medium text-purple-600">
                      {supplier.certifications.length} 个
                    </p>
                  </div>
                </div>

                {supplier.certifications.length > 0 && (
                  <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg mb-3">
                    <p className="text-xs text-yellow-900 mb-2">资质证书:</p>
                    {supplier.certifications.map(cert => (
                      <div key={cert.id} className="text-sm mb-1 last:mb-0">
                        <span className="font-medium">{cert.name}</span>
                        <span className="mx-2">|</span>
                        <span>证书号: {cert.certificateNo}</span>
                        <span className="mx-2">|</span>
                        <span>有效期至: {cert.expiryDate}</span>
                      </div>
                    ))}
                  </div>
                )}

                {supplier.purchaseHistory.length > 0 && (
                  <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <p className="text-xs text-blue-900 mb-2">
                      最近采购记录 ({supplier.purchaseHistory.length}条):
                    </p>
                    {supplier.purchaseHistory.slice(0, 3).map(record => (
                      <div key={record.id} className="text-sm mb-1 last:mb-0">
                        <span className="font-medium">{record.date}</span>
                        <span className="mx-2">|</span>
                        <span>{record.materialName}</span>
                        <span className="mx-2">|</span>
                        <span>{record.quantity}单位</span>
                        <span className="mx-2">|</span>
                        <span className="text-green-600">¥{record.amount.toLocaleString()}</span>
                        <span className="mx-2">|</span>
                        <Badge variant="outline" className="text-xs">
                          {record.status}
                        </Badge>
                      </div>
                    ))}
                  </div>
                )}
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 客户管理 */}
        <TabsContent value="customers" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-orange-50 border-orange-200">
            <div className="flex items-start gap-2">
              <Users className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-orange-900">
                <p className="mb-2">客户管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>客户分类</strong>: 农户、合作社、企业三种类型</li>
                  <li>• <strong>基本信息</strong>: 姓名/名称、联系人、电话、地址</li>
                  <li>• <strong>信用管理</strong>: 信用额度、已用额度、剩余额度</li>
                  <li>• <strong>购买历史</strong>: 完整的购买记录和付款状态</li>
                  <li>• <strong>统计分析</strong>: 累计购买金额、欠款情况</li>
                  <li>• <strong>客户画像</strong>: 客户价值评估和分析</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex justify-end">
            <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowCustomerDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新增客户
            </Button>
          </div>

          {/* 客户列表 */}
          <div className="space-y-4">
            {customers.map(customer => {
              const remainingCredit = customer.creditLimit - customer.usedCredit;
              const creditUsageRate = (customer.usedCredit / customer.creditLimit) * 100;
              const unpaidOrders = customer.purchaseHistory.filter(p => p.status !== '已完成');
              
              return (
                <Card key={customer.id} className="p-4">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-start gap-3">
                      <div className={`p-3 rounded-lg ${
                        customer.type === '农户' ? 'bg-green-100' :
                        customer.type === '合作社' ? 'bg-blue-100' :
                        'bg-purple-100'
                      }`}>
                        <Users className={`w-6 h-6 ${
                          customer.type === '农户' ? 'text-green-600' :
                          customer.type === '合作社' ? 'text-blue-600' :
                          'text-purple-600'
                        }`} />
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{customer.name}</h4>
                          <Badge variant="outline">{customer.type}</Badge>
                          {unpaidOrders.length > 0 && (
                            <Badge className="bg-red-100 text-red-800">
                              {unpaidOrders.length}笔待付款
                            </Badge>
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          编码: {customer.code} | 联系人: {customer.contactPerson}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleViewCustomer(customer)}>
                        <Eye className="w-4 h-4 mr-2" />
                        查看详情
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEditCustomer(customer)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeleteCustomer(customer.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-4 gap-4 mb-4">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <Phone className="w-3 h-3" />
                        联系电话
                      </p>
                      <p className="mt-1 font-medium">{customer.phone}</p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <Mail className="w-3 h-3" />
                        邮箱
                      </p>
                      <p className="mt-1 font-medium text-xs">{customer.email || '未填写'}</p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg col-span-2">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        地址
                      </p>
                      <p className="mt-1 font-medium text-xs">{customer.address}</p>
                    </div>
                  </div>

                  {/* 信用额度 */}
                  <div className="p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg mb-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">信用额度使用情况</span>
                      <span className="text-sm font-medium">
                        {creditUsageRate.toFixed(1)}%
                      </span>
                    </div>
                    <Progress value={creditUsageRate} className="h-2 mb-2" />
                    <div className="grid grid-cols-3 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">总额度: </span>
                        <span className="font-medium">
                          ¥{customer.creditLimit.toLocaleString()}
                        </span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">已用: </span>
                        <span className="font-medium text-orange-600">
                          ¥{customer.usedCredit.toLocaleString()}
                        </span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">剩余: </span>
                        <span className="font-medium text-green-600">
                          ¥{remainingCredit.toLocaleString()}
                        </span>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4 mb-4">
                    <div className="p-3 bg-green-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <DollarSign className="w-3 h-3" />
                        累计购买金额
                      </p>
                      <p className="mt-1 text-lg font-medium text-green-600">
                        ¥{(customer.totalPurchaseAmount / 10000).toFixed(1)}万
                      </p>
                    </div>
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <ShoppingCart className="w-3 h-3" />
                        购买次数
                      </p>
                      <p className="mt-1 text-lg font-medium text-blue-600">
                        {customer.purchaseHistory.length} 次
                      </p>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <p className="text-xs text-muted-foreground flex items-center gap-1">
                        <Award className="w-3 h-3" />
                        客户等级
                      </p>
                      <p className="mt-1 text-lg font-medium text-purple-600">
                        {customer.totalPurchaseAmount >= 500000 ? 'VIP' :
                         customer.totalPurchaseAmount >= 200000 ? '优质' :
                         '普通'}
                      </p>
                    </div>
                  </div>

                  {customer.purchaseHistory.length > 0 && (
                    <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                      <p className="text-xs text-blue-900 mb-2">
                        最近购买记录 ({customer.purchaseHistory.length}条):
                      </p>
                      {customer.purchaseHistory.slice(0, 3).map(record => (
                        <div key={record.id} className="text-sm mb-1 last:mb-0">
                          <span className="font-medium">{record.date}</span>
                          <span className="mx-2">|</span>
                          <span>{record.productName}</span>
                          <span className="mx-2">|</span>
                          <span>{record.quantity}单位</span>
                          <span className="mx-2">|</span>
                          <span className="text-green-600">¥{record.amount.toLocaleString()}</span>
                          <span className="mx-2">|</span>
                          <span className={
                            record.status === '已完成' ? 'text-green-600' :
                            record.status === '待付款' ? 'text-red-600' :
                            'text-orange-600'
                          }>
                            {record.status === '部分付款' && `已付¥${record.paid.toLocaleString()}/`}
                            {record.status}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        </TabsContent>
      </Tabs>

      {/* 新增/编辑农资对话框 */}
      <Dialog open={showMaterialDialog} onOpenChange={setShowMaterialDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingMaterial ? '编辑农资' : '新增农资'}</DialogTitle>
            <DialogDescription>
              填写农资基本信息，农药需特殊管理
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>农资类型 <span className="text-destructive">*</span></label>
                <Select value={formData.type} onValueChange={(value) => setFormData({ ...formData, type: value as MaterialType })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="种子">种子</SelectItem>
                    <SelectItem value="化肥">化肥</SelectItem>
                    <SelectItem value="农药">农药</SelectItem>
                    <SelectItem value="耗材">耗材</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>农资名称 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="请输入名称" 
                  className="mt-2" 
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>规格 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="如: 25kg/袋" 
                  className="mt-2" 
                  value={formData.spec}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                />
              </div>
              <div>
                <label>型号</label>
                <Input 
                  placeholder="如: NPK 15-15-15" 
                  className="mt-2" 
                  value={formData.model}
                  onChange={(e) => setFormData({ ...formData, model: e.target.value })}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>供应商 <span className="text-destructive">*</span></label>
                <Select value={formData.supplier} onValueChange={(value) => setFormData({ ...formData, supplier: value })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择供应商" />
                  </SelectTrigger>
                  <SelectContent>
                    {suppliers.map(s => (
                      <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>生产厂家</label>
                <Input 
                  placeholder="请输入生产厂家" 
                  className="mt-2" 
                  value={formData.manufacturer}
                  onChange={(e) => setFormData({ ...formData, manufacturer: e.target.value })}
                />
              </div>
            </div>

            <div className="grid grid-cols-3 gap-4">
              <div>
                <label>有效期 <span className="text-destructive">*</span></label>
                <Input 
                  type="number" 
                  placeholder="如: 12" 
                  className="mt-2" 
                  value={formData.shelfLife}
                  onChange={(e) => setFormData({ ...formData, shelfLife: e.target.value })}
                />
              </div>
              <div>
                <label>有效期单位 <span className="text-destructive">*</span></label>
                <Select value={formData.shelfLifeUnit} onValueChange={(value) => setFormData({ ...formData, shelfLifeUnit: value as '年' | '月' | '天' })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择单位" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="年">年</SelectItem>
                    <SelectItem value="月">月</SelectItem>
                    <SelectItem value="天">天</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>单位 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="如: 袋" 
                  className="mt-2" 
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>安全库存 <span className="text-destructive">*</span></label>
                <Input 
                  type="number" 
                  placeholder="请输入安全库存" 
                  className="mt-2" 
                  value={formData.safeStock}
                  onChange={(e) => setFormData({ ...formData, safeStock: e.target.value })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  当前库存低于此值时将触发库存预警
                </p>
              </div>
              <div>
                <label>采购单价(元) <span className="text-destructive">*</span></label>
                <Input 
                  type="number" 
                  placeholder="请输入单价" 
                  className="mt-2" 
                  value={formData.purchasePrice}
                  onChange={(e) => setFormData({ ...formData, purchasePrice: e.target.value })}
                />
              </div>
            </div>

            {/* 农药特殊字段 */}
            {formData.type === '农药' && (
              <Card className="p-4 bg-orange-50 border-orange-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 text-orange-600" />
                  农药特殊信息（必填）
                </h4>
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label>登记证号 <span className="text-destructive">*</span></label>
                      <Input 
                        placeholder="如: PD20210123" 
                        className="mt-2" 
                        value={formData.registrationNo}
                        onChange={(e) => setFormData({ ...formData, registrationNo: e.target.value })}
                      />
                    </div>
                    <div>
                      <label>毒性等级 <span className="text-destructive">*</span></label>
                      <Select value={formData.toxicityLevel} onValueChange={(value) => setFormData({ ...formData, toxicityLevel: value as any })}>
                        <SelectTrigger className="mt-2">
                          <SelectValue placeholder="选择毒性等级" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="低毒">低毒</SelectItem>
                          <SelectItem value="中毒">中毒</SelectItem>
                          <SelectItem value="高毒">高毒</SelectItem>
                          <SelectItem value="剧毒">剧毒</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div>
                    <label>安全间隔期（天） <span className="text-destructive">*</span></label>
                    <Input 
                      type="number" 
                      placeholder="如: 15" 
                      className="mt-2" 
                      value={formData.safetyInterval}
                      onChange={(e) => setFormData({ ...formData, safetyInterval: e.target.value })}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      安全间隔期是指最后一次施药至收获农作物之间的天数
                    </p>
                  </div>
                </div>
              </Card>
            )}

            <div>
              <label>备注</label>
              <Textarea 
                placeholder="请输入备注信息" 
                className="mt-2" 
                rows={3} 
                value={formData.notes}
                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              />
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowMaterialDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveMaterial}>
                <Save className="w-4 h-4 mr-2" />
                {editingMaterial ? '更新' : '保存'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedItem?.spec ? '农资详情' : 
               selectedItem?.certifications ? '供应商详情' : 
               selectedItem?.creditLimit !== undefined ? '客户详情' : '农具详情'}
            </DialogTitle>
            <DialogDescription>
              {selectedItem?.spec ? '查看农资完整信息' : 
               selectedItem?.certifications ? '查看供应商完整信息' : 
               selectedItem?.creditLimit !== undefined ? '查看客户完整信息' : '查看农具完整信息'}
            </DialogDescription>
          </DialogHeader>
          
          {/* 供应商详情内容 */}
          {selectedItem && selectedItem.certifications && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-purple-50">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 rounded-lg bg-purple-100">
                      <Building2 className="w-6 h-6 text-purple-600" />
                    </div>
                    <div>
                      <h4 className="mb-1">{selectedItem.name}</h4>
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{selectedItem.type}</Badge>
                        <Badge className={getSupplierLevelColor(selectedItem.level)}>
                          {selectedItem.level}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground mt-1">
                        编码: {selectedItem.code} | 创建时间: {selectedItem.createdAt}
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => {
                      setShowViewDialog(false);
                      handleOpenEditSupplierDialog(selectedItem);
                    }}>
                      <Edit className="w-4 h-4 mr-2" />
                      编辑
                    </Button>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <User className="w-3 h-3" />
                      联系人
                    </p>
                    <p className="mt-1 font-medium">{selectedItem.contactPerson}</p>
                  </div>
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Phone className="w-3 h-3" />
                      联系电话
                    </p>
                    <p className="mt-1 font-medium">{selectedItem.phone}</p>
                  </div>
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <Mail className="w-3 h-3" />
                      电子邮箱
                    </p>
                    <p className="mt-1 font-medium text-sm">{selectedItem.email || '-'}</p>
                  </div>
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      地址
                    </p>
                    <p className="mt-1 font-medium text-sm">{selectedItem.address || '-'}</p>
                  </div>
                </div>
              </Card>

              {/* 统计信息 */}
              <div className="grid grid-cols-3 gap-4">
                <Card className="p-4 bg-green-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <DollarSign className="w-3 h-3" />
                    累计采购金额
                  </p>
                  <p className="text-2xl font-medium text-green-600">
                    ¥{(selectedItem.totalPurchaseAmount / 10000).toFixed(1)}万
                  </p>
                </Card>
                <Card className="p-4 bg-blue-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <ShoppingCart className="w-3 h-3" />
                    采购次数
                  </p>
                  <p className="text-2xl font-medium text-blue-600">
                    {selectedItem.purchaseHistory.length} 次
                  </p>
                </Card>
                <Card className="p-4 bg-purple-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <Clock className="w-3 h-3" />
                    合作年限
                  </p>
                  <p className="text-2xl font-medium text-purple-600">
                    {selectedItem.cooperationYears} 年
                  </p>
                </Card>
              </div>

              {/* 资质证书 */}
              {selectedItem.certifications.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Shield className="w-4 h-4 text-green-600" />
                    资质证书 ({selectedItem.certifications.length}个)
                  </h4>
                  <div className="space-y-3">
                    {selectedItem.certifications.map((cert: Certification) => (
                      <div key={cert.id} className="p-3 bg-green-50 rounded-lg">
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-2">
                              <h5 className="font-medium">{cert.name}</h5>
                              <Badge variant="outline">证书号: {cert.certificateNo}</Badge>
                            </div>
                            <div className="grid grid-cols-2 gap-2 text-sm text-muted-foreground">
                              <p>
                                <Calendar className="w-3 h-3 inline mr-1" />
                                签发日期: {cert.issueDate}
                              </p>
                              <p>
                                <Calendar className="w-3 h-3 inline mr-1" />
                                有效期至: {cert.expiryDate}
                              </p>
                            </div>
                            {cert.file && (
                              <p className="text-xs text-green-600 mt-2">
                                <FileText className="w-3 h-3 inline mr-1" />
                                已上传扫描件
                              </p>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 采购历史 */}
              {selectedItem.purchaseHistory.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-3 flex items-center gap-2">
                    <ShoppingCart className="w-4 h-4 text-blue-600" />
                    采购历史 ({selectedItem.purchaseHistory.length}条)
                  </h4>
                  <div className="space-y-3">
                    {selectedItem.purchaseHistory.map((record: PurchaseRecord) => (
                      <div key={record.id} className="p-3 bg-blue-50 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{record.materialName}</span>
                            <Badge variant="outline">{record.date}</Badge>
                          </div>
                          <span className="text-lg font-medium text-green-600">¥{record.amount.toLocaleString()}</span>
                        </div>
                        <div className="text-sm text-muted-foreground">
                          <span>数量: {record.quantity}</span>
                          <span className="mx-2">|</span>
                          <span className={
                            record.status === '已完成' ? 'text-green-600' :
                            record.status === '待付款' ? 'text-orange-600' :
                            'text-blue-600'
                          }>
                            {record.status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 备注 */}
              {selectedItem.notes && (
                <Card className="p-4 bg-yellow-50">
                  <h4 className="mb-2 flex items-center gap-2">
                    <FileText className="w-4 h-4 text-yellow-600" />
                    备注
                  </h4>
                  <p className="text-sm">{selectedItem.notes}</p>
                </Card>
              )}

              <div className="flex justify-end">
                <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}

          {/* 客户详情内容 */}
          {selectedItem && selectedItem.creditLimit !== undefined && !(selectedItem as any).certifications && !(selectedItem as any).spec && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-orange-50">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className={`p-3 rounded-lg ${
                      selectedItem.type === '农户' ? 'bg-green-100' :
                      selectedItem.type === '合作社' ? 'bg-blue-100' :
                      'bg-purple-100'
                    }`}>
                      <Users className={`w-6 h-6 ${
                        selectedItem.type === '农户' ? 'text-green-600' :
                        selectedItem.type === '合作社' ? 'text-blue-600' :
                        'text-purple-600'
                      }`} />
                    </div>
                    <div>
                      <h4 className="mb-1">{selectedItem.name}</h4>
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant="outline">{selectedItem.type}</Badge>
                        <Badge className={
                          selectedItem.totalPurchaseAmount >= 500000 ? 'bg-purple-100 text-purple-800' :
                          selectedItem.totalPurchaseAmount >= 200000 ? 'bg-blue-100 text-blue-800' :
                          'bg-gray-100 text-gray-800'
                        }>
                          {selectedItem.totalPurchaseAmount >= 500000 ? 'VIP客户' :
                           selectedItem.totalPurchaseAmount >= 200000 ? '优质客户' :
                           '普通客户'}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        编码: {selectedItem.code} | 创建时间: {selectedItem.createdAt}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-4 gap-3">
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">联系人</p>
                    <p className="font-medium">{selectedItem.contactPerson}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">联系电话</p>
                    <p className="font-medium">{selectedItem.phone}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">电子邮箱</p>
                    <p className="font-medium text-xs">{selectedItem.email || '未填写'}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">地址</p>
                    <p className="font-medium text-xs">{selectedItem.address}</p>
                  </div>
                </div>
              </Card>

              {/* 信用额度信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-purple-50">
                <h4 className="mb-3 flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-blue-600" />
                  信用额度信息
                </h4>
                <div className="mb-3">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm">额度使用率</span>
                    <span className="text-sm font-medium">
                      {((selectedItem.usedCredit / selectedItem.creditLimit) * 100).toFixed(1)}%
                    </span>
                  </div>
                  <Progress value={(selectedItem.usedCredit / selectedItem.creditLimit) * 100} className="h-2" />
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">总额度</p>
                    <p className="text-lg font-medium text-blue-600">
                      ¥{selectedItem.creditLimit.toLocaleString()}
                    </p>
                  </div>
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">已用额度</p>
                    <p className="text-lg font-medium text-orange-600">
                      ¥{selectedItem.usedCredit.toLocaleString()}
                    </p>
                  </div>
                  <div className="p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">剩余额度</p>
                    <p className="text-lg font-medium text-green-600">
                      ¥{(selectedItem.creditLimit - selectedItem.usedCredit).toLocaleString()}
                    </p>
                  </div>
                </div>
              </Card>

              {/* 统计信息 */}
              <div className="grid grid-cols-3 gap-4">
                <Card className="p-4 bg-green-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <DollarSign className="w-3 h-3" />
                    累计购买金额
                  </p>
                  <p className="text-2xl font-medium text-green-600">
                    ¥{(selectedItem.totalPurchaseAmount / 10000).toFixed(1)}万
                  </p>
                </Card>
                <Card className="p-4 bg-blue-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <ShoppingCart className="w-3 h-3" />
                    购买次数
                  </p>
                  <p className="text-2xl font-medium text-blue-600">
                    {selectedItem.purchaseHistory.length} 次
                  </p>
                </Card>
                <Card className="p-4 bg-orange-50">
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mb-2">
                    <AlertCircle className="w-3 h-3" />
                    待付款订单
                  </p>
                  <p className="text-2xl font-medium text-orange-600">
                    {selectedItem.purchaseHistory.filter((p: CustomerPurchase) => p.status !== '已完成').length} 笔
                  </p>
                </Card>
              </div>

              {/* 购买历史 */}
              {selectedItem.purchaseHistory.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-3 flex items-center gap-2">
                    <ShoppingCart className="w-4 h-4 text-blue-600" />
                    购买历史 ({selectedItem.purchaseHistory.length}条)
                  </h4>
                  <div className="space-y-3">
                    {selectedItem.purchaseHistory.map((record: CustomerPurchase) => (
                      <div key={record.id} className="p-3 bg-blue-50 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{record.productName}</span>
                            <Badge variant="outline">{record.date}</Badge>
                          </div>
                          <span className="text-lg font-medium text-green-600">¥{record.amount.toLocaleString()}</span>
                        </div>
                        <div className="text-sm text-muted-foreground">
                          <span>数量: {record.quantity}</span>
                          <span className="mx-2">|</span>
                          <span>已付: ¥{record.paid.toLocaleString()}</span>
                          <span className="mx-2">|</span>
                          <span className={
                            record.status === '已完成' ? 'text-green-600' :
                            record.status === '待付款' ? 'text-red-600' :
                            'text-orange-600'
                          }>
                            {record.status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 备注 */}
              {selectedItem.notes && (
                <Card className="p-4 bg-yellow-50">
                  <h4 className="mb-2 flex items-center gap-2">
                    <FileText className="w-4 h-4 text-yellow-600" />
                    备注
                  </h4>
                  <p className="text-sm">{selectedItem.notes}</p>
                </Card>
              )}

              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                  关闭
                </Button>
                <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
                  setShowViewDialog(false);
                  handleEditCustomer(selectedItem as Customer);
                }}>
                  <Edit className="w-4 h-4 mr-2" />
                  编辑
                </Button>
              </div>
            </div>
          )}

          {/* 农资详情内容 */}
          {selectedItem && selectedItem.spec && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-gray-50">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className={`p-3 rounded-lg ${
                      selectedItem.type === '种子' ? 'bg-green-100' :
                      selectedItem.type === '化肥' ? 'bg-blue-100' :
                      selectedItem.type === '农药' ? 'bg-orange-100' :
                      'bg-purple-100'
                    }`}>
                      <Package className={`w-6 h-6 ${
                        selectedItem.type === '种子' ? 'text-green-600' :
                        selectedItem.type === '化肥' ? 'text-blue-600' :
                        selectedItem.type === '农药' ? 'text-orange-600' :
                        'text-purple-600'
                      }`} />
                    </div>
                    <div>
                      <h4 className="mb-1">{selectedItem.name}</h4>
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{selectedItem.type}</Badge>
                        <Badge className={getMaterialStatusColor(selectedItem.status)}>
                          {selectedItem.status}
                        </Badge>
                        {selectedItem.toxicityLevel && (
                          <Badge className={
                            selectedItem.toxicityLevel === '低毒' ? 'bg-green-100 text-green-800' :
                            selectedItem.toxicityLevel === '中毒' ? 'bg-yellow-100 text-yellow-800' :
                            selectedItem.toxicityLevel === '高毒' ? 'bg-orange-100 text-orange-800' :
                            'bg-red-100 text-red-800'
                          }>
                            {selectedItem.toxicityLevel}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">唯一编码</p>
                    <p className="mt-1">{selectedItem.code}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">规格</p>
                    <p className="mt-1">{selectedItem.spec}</p>
                  </div>
                  {selectedItem.model && (
                    <div className="field-value">
                      <p className="text-xs text-muted-foreground">型号</p>
                      <p className="mt-1">{selectedItem.model}</p>
                    </div>
                  )}
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">单位</p>
                    <p className="mt-1">{selectedItem.unit}</p>
                  </div>
                </div>
              </Card>

              {/* 供应信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Building2 className="w-4 h-4 text-blue-600" />
                  供应信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">供应商</p>
                    <p className="mt-1">{selectedItem.supplier}</p>
                  </div>
                  {selectedItem.manufacturer && (
                    <div className="field-value">
                      <p className="text-xs text-muted-foreground">生产厂家</p>
                      <p className="mt-1">{selectedItem.manufacturer}</p>
                    </div>
                  )}
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">采购单价</p>
                    <p className="mt-1 text-green-600">¥{selectedItem.purchasePrice}</p>
                  </div>
                </div>
              </Card>

              {/* 库存信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Warehouse className="w-4 h-4 text-green-600" />
                  库存信息
                </h4>
                <div className="grid grid-cols-3 gap-4 mb-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">当前库存</p>
                    <p className="mt-1 text-lg text-green-600">{selectedItem.currentStock} {selectedItem.unit}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">安全库存</p>
                    <p className="mt-1">{selectedItem.safeStock} {selectedItem.unit}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">库存状态</p>
                    <p className="mt-1">
                      {selectedItem.currentStock >= selectedItem.safeStock ? (
                        <span className="text-green-600">充足</span>
                      ) : (
                        <span className="text-orange-600">预警</span>
                      )}
                    </p>
                  </div>
                </div>

                {/* 库存分布 */}
                {selectedItem.inventoryLocations && selectedItem.inventoryLocations.length > 0 && (
                  <div className="mt-4 pt-4 border-t">
                    <h5 className="text-sm mb-3 flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-green-600" />
                      库存分布
                    </h5>
                    <div className="space-y-2">
                      {selectedItem.inventoryLocations.map((loc: MaterialInventoryLocation, index: number) => (
                        <div key={index} className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                          <div className="flex items-center gap-2">
                            <MapPin className="w-4 h-4 text-green-600" />
                            <span className="text-sm">{loc.locationName}</span>
                          </div>
                          <span className="text-green-600">{loc.quantity} {selectedItem.unit}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </Card>

              {/* 有效期信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-purple-600" />
                  有效期信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">有效期</p>
                    <p className="mt-1">
                      {selectedItem.shelfLife}{selectedItem.shelfLifeUnit}
                    </p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">创建日期</p>
                    <p className="mt-1">{selectedItem.createdAt}</p>
                  </div>
                </div>
              </Card>

              {/* 农药特殊信息 */}
              {selectedItem.type === '农药' && (
                <Card className="p-4 bg-orange-50 border-orange-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Shield className="w-4 h-4 text-orange-600" />
                    农药特殊信息
                  </h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div className="field-value bg-white">
                      <p className="text-xs text-muted-foreground">登记证号</p>
                      <p className="mt-1">{selectedItem.registrationNo}</p>
                    </div>
                    <div className="field-value bg-white">
                      <p className="text-xs text-muted-foreground">毒性等级</p>
                      <p className="mt-1">
                        <Badge className={
                          selectedItem.toxicityLevel === '低毒' ? 'bg-green-100 text-green-800' :
                          selectedItem.toxicityLevel === '中毒' ? 'bg-yellow-100 text-yellow-800' :
                          selectedItem.toxicityLevel === '高毒' ? 'bg-orange-100 text-orange-800' :
                          'bg-red-100 text-red-800'
                        }>
                          {selectedItem.toxicityLevel}
                        </Badge>
                      </p>
                    </div>
                    <div className="field-value bg-white">
                      <p className="text-xs text-muted-foreground">安全间隔期</p>
                      <p className="mt-1">{selectedItem.safetyInterval} 天</p>
                    </div>
                  </div>
                </Card>
              )}

              {/* 备注 */}
              {selectedItem.notes && (
                <Card className="p-4 bg-blue-50">
                  <h4 className="mb-2 flex items-center gap-2">
                    <FileText className="w-4 h-4 text-blue-600" />
                    备注
                  </h4>
                  <p className="text-sm">{selectedItem.notes}</p>
                </Card>
              )}

              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                  关闭
                </Button>
                <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
                  setShowViewDialog(false);
                  handleOpenEditDialog(selectedItem);
                }}>
                  <Edit className="w-4 h-4 mr-2" />
                  编辑
                </Button>
              </div>
            </div>
          )}

          {/* 农具详情内容 */}
          {selectedItem && !selectedItem.spec && !selectedItem.certifications && selectedItem.purchasePrice !== undefined && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-gray-50">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="p-3 rounded-lg bg-blue-100">
                      <Tractor className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <h4 className="mb-1">{selectedItem.name}</h4>
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{selectedItem.type}</Badge>
                        <Badge className={getToolStatusColor(selectedItem.status)}>
                          {selectedItem.status}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">唯一编码</p>
                    <p className="mt-1">{selectedItem.code}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">型号</p>
                    <p className="mt-1">{selectedItem.model}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">购买日期</p>
                    <p className="mt-1">{selectedItem.purchaseDate}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">创建日期</p>
                    <p className="mt-1">{selectedItem.createdAt}</p>
                  </div>
                </div>
              </Card>

              {/* 价值信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-green-600" />
                  价值与折旧信息
                </h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">购买价格</p>
                    <p className="mt-1 text-lg text-green-600">
                      ¥{(selectedItem.purchasePrice || 0).toLocaleString()}
                    </p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">当前价值</p>
                    <p className="mt-1 text-lg text-blue-600">
                      ¥{(selectedItem.currentValue || 0).toLocaleString()}
                    </p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">折旧年限</p>
                    <p className="mt-1">{selectedItem.depreciation || 0} 年</p>
                  </div>
                </div>
                <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">累计折旧金额：</span>
                    <span className="text-orange-600">
                      ¥{((selectedItem.purchasePrice || 0) - (selectedItem.currentValue || 0)).toLocaleString()}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm mt-1">
                    <span className="text-muted-foreground">折旧率：</span>
                    <span className="text-blue-600">
                      {selectedItem.purchasePrice && selectedItem.purchasePrice > 0
                        ? (((selectedItem.purchasePrice - (selectedItem.currentValue || 0)) / selectedItem.purchasePrice * 100).toFixed(1))
                        : '0.0'}%
                    </span>
                  </div>
                </div>
              </Card>

              {/* 使用信息 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <User className="w-4 h-4 text-purple-600" />
                  使用信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">责任人</p>
                    <p className="mt-1">{selectedItem.responsiblePerson || '未指定'}</p>
                  </div>
                  <div className="field-value">
                    <p className="text-xs text-muted-foreground">当前状态</p>
                    <p className="mt-1">
                      <Badge className={getToolStatusColor(selectedItem.status)}>
                        {selectedItem.status}
                      </Badge>
                    </p>
                  </div>
                </div>
              </Card>

              {/* 库存分布 */}
              <Card className="p-4 bg-green-50 border-green-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <Warehouse className="w-4 h-4 text-green-600" />
                  库存分布
                </h4>
                <div className="mb-3 p-3 bg-white rounded-lg">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">总数量</span>
                    <span className="text-lg text-green-600">{selectedItem.totalQuantity || 0} 台/件</span>
                  </div>
                </div>
                {selectedItem.inventoryLocations && selectedItem.inventoryLocations.length > 0 ? (
                  <div className="space-y-2">
                    {selectedItem.inventoryLocations.map((loc: ToolInventoryLocation, index: number) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-white rounded-lg">
                        <div className="flex items-center gap-2">
                          <MapPin className="w-4 h-4 text-green-600" />
                          <span>{loc.locationName}</span>
                        </div>
                        <span className="text-green-600">{loc.quantity} 台/件</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-4 text-muted-foreground">
                    <p className="text-sm">暂无库存，请通过入库功能添加库存</p>
                  </div>
                )}
              </Card>

              {/* 维护记录 */}
              {selectedItem.maintenanceHistory && selectedItem.maintenanceHistory.length > 0 && (
                <Card className="p-4 bg-purple-50 border-purple-200">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Wrench className="w-4 h-4 text-purple-600" />
                    维护记录 ({selectedItem.maintenanceHistory.length}条)
                  </h4>
                  <div className="space-y-3">
                    {selectedItem.maintenanceHistory.map((record: MaintenanceRecord) => (
                      <div key={record.id} className="p-3 bg-white rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <Badge variant="outline">{record.type}</Badge>
                            <span className="text-sm">{record.date}</span>
                          </div>
                          <span className="text-sm text-green-600">¥{record.cost}</span>
                        </div>
                        <p className="text-sm">{record.description}</p>
                        <p className="text-xs text-muted-foreground mt-1">
                          技术员：{record.technician}
                        </p>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 图片 */}
              {selectedItem.images && selectedItem.images.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Camera className="w-4 h-4 text-gray-600" />
                    设备图片 ({selectedItem.images.length}张)
                  </h4>
                  <div className="grid grid-cols-4 gap-3">
                    {selectedItem.images.map((img: string, i: number) => (
                      <div key={i} className="aspect-square bg-gray-200 rounded-lg overflow-hidden">
                        {img.startsWith('data:') || img.startsWith('http') ? (
                          <img
                            src={img}
                            alt={`农具图片 ${i + 1}`}
                            className="w-full h-full object-cover cursor-pointer hover:opacity-80 transition-opacity"
                            onClick={() => window.open(img, '_blank')}
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <Camera className="w-8 h-8 text-gray-400" />
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* 备注 */}
              {selectedItem.notes && (
                <Card className="p-4 bg-blue-50">
                  <h4 className="mb-2 flex items-center gap-2">
                    <FileText className="w-4 h-4 text-blue-600" />
                    备注
                  </h4>
                  <p className="text-sm">{selectedItem.notes}</p>
                </Card>
              )}

              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                  关闭
                </Button>
                <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
                  setShowViewDialog(false);
                  handleOpenEditToolDialog(selectedItem);
                }}>
                  <Edit className="w-4 h-4 mr-2" />
                  编辑
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 新增/编辑农具对话框 */}
      <Dialog open={showToolDialog} onOpenChange={setShowToolDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingTool ? '编辑农具' : '新增农具'}</DialogTitle>
            <DialogDescription>
              填写农具基本信息，系统将自动计算折旧后的当前价值
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>农具名称 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="如：东方红拖拉机" 
                  className="mt-2" 
                  value={toolFormData.name}
                  onChange={(e) => setToolFormData({ ...toolFormData, name: e.target.value })}
                />
              </div>
              <div>
                <label>农具类型 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="如：大型农机" 
                  className="mt-2" 
                  value={toolFormData.type}
                  onChange={(e) => setToolFormData({ ...toolFormData, type: e.target.value })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  类型示例：大型农机、耕作机械、植保机械、收获机械、小型农具等
                </p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>型号 <span className="text-destructive">*</span></label>
                <Input 
                  placeholder="如：LX904" 
                  className="mt-2" 
                  value={toolFormData.model}
                  onChange={(e) => setToolFormData({ ...toolFormData, model: e.target.value })}
                />
              </div>
              <div>
                <label>购买日期 <span className="text-destructive">*</span></label>
                <Input 
                  type="date" 
                  className="mt-2" 
                  value={toolFormData.purchaseDate}
                  onChange={(e) => setToolFormData({ ...toolFormData, purchaseDate: e.target.value })}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>购买价格(元) <span className="text-destructive">*</span></label>
                <Input 
                  type="number" 
                  placeholder="如：180000" 
                  className="mt-2" 
                  value={toolFormData.purchasePrice}
                  onChange={(e) => setToolFormData({ ...toolFormData, purchasePrice: e.target.value })}
                />
              </div>
              <div>
                <label>折旧年限(年) <span className="text-destructive">*</span></label>
                <Input 
                  type="number" 
                  placeholder="如：10" 
                  className="mt-2" 
                  value={toolFormData.depreciation}
                  onChange={(e) => setToolFormData({ ...toolFormData, depreciation: e.target.value })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  系统将根据购买日期和折旧年限自动计算当前价值
                </p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>当前状态 <span className="text-destructive">*</span></label>
                <Select value={toolFormData.status} onValueChange={(value) => setToolFormData({ ...toolFormData, status: value as ToolStatus })}>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="在用">在用</SelectItem>
                    <SelectItem value="维修">维修</SelectItem>
                    <SelectItem value="报废">报废</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>责任人</label>
                <Input 
                  placeholder="如：张三" 
                  className="mt-2" 
                  value={toolFormData.responsiblePerson}
                  onChange={(e) => setToolFormData({ ...toolFormData, responsiblePerson: e.target.value })}
                />
              </div>
            </div>

            <div>
              <label>备注</label>
              <Textarea 
                placeholder="请输入备注信息，如：定期保养要求、注意事项等" 
                className="mt-2" 
                rows={3} 
                value={toolFormData.notes}
                onChange={(e) => setToolFormData({ ...toolFormData, notes: e.target.value })}
              />
            </div>

            {/* 图片上传 */}
            <div>
              <label>农具图片</label>
              <div className="mt-2">
                {/* 图片预览区 */}
                {toolFormData.images.length > 0 && (
                  <div className="grid grid-cols-4 gap-4 mb-4">
                    {toolFormData.images.map((img, index) => (
                      <div key={index} className="relative group">
                        <img
                          src={img}
                          alt={`农具图片 ${index + 1}`}
                          className="w-full h-24 object-cover rounded-lg border-2 border-gray-200"
                        />
                        <button
                          type="button"
                          onClick={() => handleToolImageDelete(index)}
                          className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                          title="删除图片"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}
                
                {/* 上传按钮 */}
                <div className="flex items-center gap-2">
                  <label className="cursor-pointer">
                    <div className="flex items-center gap-2 px-4 py-2 bg-green-50 text-green-600 rounded-lg border-2 border-green-200 hover:bg-green-100 transition-colors">
                      <Upload className="w-4 h-4" />
                      <span className="text-sm">上传图片</span>
                    </div>
                    <input
                      type="file"
                      accept="image/*"
                      multiple
                      className="hidden"
                      onChange={handleToolImageUpload}
                    />
                  </label>
                  <p className="text-xs text-muted-foreground">
                    支持上传多张图片，建议尺寸 800x600
                  </p>
                </div>
              </div>
            </div>

            {/* 重要说明 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <h4 className="mb-2 flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-blue-600" />
                重要说明
              </h4>
              <div className="text-sm text-blue-900 space-y-1">
                <p>• <strong>折旧方法</strong>：采用直线折旧法（平均年限法）</p>
                <p>• <strong>计算公式</strong>：当前价值 = 购买价格 - (购买价格 ÷ 折旧年限 × 已使用年数)</p>
                <p>• <strong>自动计算</strong>：系统会根据购买日期自动计算已使用时间和当前价值</p>
                <p>• <strong>残值处理</strong>：当前价值不会低于0</p>
                <p>• <strong>库存管理</strong>：新增后默认库存为0，需通过入库功能添加库存及存放位置</p>
              </div>
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowToolDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveTool}>
                <Save className="w-4 h-4 mr-2" />
                {editingTool ? '更新' : '保存'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 供应商新增/编辑对话框 */}
      <Dialog open={showSupplierDialog} onOpenChange={setShowSupplierDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingSupplier ? '编辑供应商' : '新增供应商'}</DialogTitle>
            <DialogDescription>
              填写供应商基本信息和资质证书
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Building2 className="w-5 h-5 text-purple-600" />
                基本信息
              </h4>
              
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>供应商名称 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：北方农资有限公司"
                      className="mt-2"
                      value={supplierFormData.name}
                      onChange={(e) => setSupplierFormData({ ...supplierFormData, name: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>供应商类型 <span className="text-destructive">*</span></label>
                    <Select value={supplierFormData.type} onValueChange={(value) => setSupplierFormData({ ...supplierFormData, type: value })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="种子供应商">种子供应商</SelectItem>
                        <SelectItem value="化肥供应商">化肥供应商</SelectItem>
                        <SelectItem value="农药供应商">农药供应商</SelectItem>
                        <SelectItem value="农机供应商">农机供应商</SelectItem>
                        <SelectItem value="综合供应商">综合供应商</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>联系人 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：张经理"
                      className="mt-2"
                      value={supplierFormData.contactPerson}
                      onChange={(e) => setSupplierFormData({ ...supplierFormData, contactPerson: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>联系电话 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：13900001111"
                      className="mt-2"
                      value={supplierFormData.phone}
                      onChange={(e) => setSupplierFormData({ ...supplierFormData, phone: e.target.value })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>电子邮箱</label>
                    <Input
                      placeholder="如：contact@supplier.com"
                      className="mt-2"
                      type="email"
                      value={supplierFormData.email}
                      onChange={(e) => setSupplierFormData({ ...supplierFormData, email: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>信用等级 <span className="text-destructive">*</span></label>
                    <Select value={supplierFormData.level} onValueChange={(value) => setSupplierFormData({ ...supplierFormData, level: value as SupplierLevel })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择等级" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="A级">A级（优秀）</SelectItem>
                        <SelectItem value="B级">B级（良好）</SelectItem>
                        <SelectItem value="C级">C级（一般）</SelectItem>
                        <SelectItem value="D级">D级（差）</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div>
                  <label>地址</label>
                  <Input
                    placeholder="如：北京市朝阳区XXX街道XXX号"
                    className="mt-2"
                    value={supplierFormData.address}
                    onChange={(e) => setSupplierFormData({ ...supplierFormData, address: e.target.value })}
                  />
                </div>

                <div>
                  <label>备注</label>
                  <Textarea
                    placeholder="如：长期合作伙伴，供货及时"
                    className="mt-2"
                    rows={2}
                    value={supplierFormData.notes}
                    onChange={(e) => setSupplierFormData({ ...supplierFormData, notes: e.target.value })}
                  />
                </div>
              </div>
            </Card>

            {/* 资质证书 */}
            <Card className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h4 className="flex items-center gap-2">
                  <Shield className="w-5 h-5 text-green-600" />
                  资质证书
                </h4>
                <Button size="sm" variant="outline" onClick={() => setShowCertDialog(true)}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加证书
                </Button>
              </div>

              {certifications.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Shield className="w-12 h-12 mx-auto mb-2 opacity-30" />
                  <p>暂无资质证书</p>
                  <p className="text-xs mt-1">点击"添加证书"按钮添加供应商资质信息</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {certifications.map(cert => (
                    <Card key={cert.id} className="p-3 bg-green-50">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h5 className="font-medium">{cert.name}</h5>
                            <Badge variant="outline">证书号: {cert.certificateNo}</Badge>
                          </div>
                          <div className="grid grid-cols-2 gap-2 text-sm">
                            <p className="text-muted-foreground">
                              <Calendar className="w-3 h-3 inline mr-1" />
                              签发日期: {cert.issueDate}
                            </p>
                            <p className="text-muted-foreground">
                              <Calendar className="w-3 h-3 inline mr-1" />
                              有效期至: {cert.expiryDate}
                            </p>
                          </div>
                          {cert.file && (
                            <p className="text-xs text-green-600 mt-2">
                              <FileText className="w-3 h-3 inline mr-1" />
                              已上传扫描件
                            </p>
                          )}
                        </div>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleDeleteCertification(cert.id)}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowSupplierDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveSupplier}>
                <Save className="w-4 h-4 mr-2" />
                {editingSupplier ? '更新' : '保存'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 添加资质证书对话框 */}
      <Dialog open={showCertDialog} onOpenChange={setShowCertDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>添加资质证书</DialogTitle>
            <DialogDescription>
              上传供应商的经营许可证、资质证书等文件
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label>证书名称 <span className="text-destructive">*</span></label>
              <Input
                placeholder="如：种子经营许可证"
                className="mt-2"
                value={certFormData.name}
                onChange={(e) => setCertFormData({ ...certFormData, name: e.target.value })}
              />
            </div>

            <div>
              <label>证书编号 <span className="text-destructive">*</span></label>
              <Input
                placeholder="如：SEED-2023-0001"
                className="mt-2"
                value={certFormData.certificateNo}
                onChange={(e) => setCertFormData({ ...certFormData, certificateNo: e.target.value })}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>签发日期 <span className="text-destructive">*</span></label>
                <Input
                  type="date"
                  className="mt-2"
                  value={certFormData.issueDate}
                  onChange={(e) => setCertFormData({ ...certFormData, issueDate: e.target.value })}
                />
              </div>
              <div>
                <label>有效期至 <span className="text-destructive">*</span></label>
                <Input
                  type="date"
                  className="mt-2"
                  value={certFormData.expiryDate}
                  onChange={(e) => setCertFormData({ ...certFormData, expiryDate: e.target.value })}
                />
              </div>
            </div>

            <div>
              <label>证书扫描件</label>
              <div className="mt-2">
                {certFormData.file ? (
                  <div className="p-4 bg-green-50 border-2 border-green-200 rounded-lg">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <FileText className="w-5 h-5 text-green-600" />
                        <span className="text-sm text-green-900">文件已上传</span>
                      </div>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => setCertFormData({ ...certFormData, file: '' })}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <label className="cursor-pointer">
                    <div className="p-6 border-2 border-dashed border-gray-300 rounded-lg hover:border-green-500 transition-colors text-center">
                      <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                      <p className="text-sm text-muted-foreground">点击上传证书扫描件</p>
                      <p className="text-xs text-muted-foreground mt-1">支持 PDF、JPG、PNG 格式</p>
                    </div>
                    <input
                      type="file"
                      accept="image/*,.pdf"
                      className="hidden"
                      onChange={handleCertFileUpload}
                    />
                  </label>
                )}
              </div>
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowCertDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleAddCertification}>
                <Plus className="w-4 h-4 mr-2" />
                添加
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 关联查询对话框 */}
      <Dialog open={showRelatedItemsDialog} onOpenChange={setShowRelatedItemsDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>采购物品关联查询</DialogTitle>
            <DialogDescription>
              {selectedSupplierForQuery && `查看从 ${selectedSupplierForQuery.name} 采购的所有物品`}
            </DialogDescription>
          </DialogHeader>
          {selectedSupplierForQuery && (
            <div className="space-y-4">
              {/* 供应商信息 */}
              <Card className="p-4 bg-purple-50">
                <div className="flex items-start gap-3">
                  <div className="p-3 bg-purple-100 rounded-lg">
                    <Building2 className="w-6 h-6 text-purple-600" />
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h4>{selectedSupplierForQuery.name}</h4>
                      <Badge variant="outline">{selectedSupplierForQuery.type}</Badge>
                      <Badge className={getSupplierLevelColor(selectedSupplierForQuery.level)}>
                        {selectedSupplierForQuery.level}
                      </Badge>
                    </div>
                    <div className="grid grid-cols-3 gap-4 text-sm">
                      <p className="text-muted-foreground">
                        <User className="w-3 h-3 inline mr-1" />
                        联系人: {selectedSupplierForQuery.contactPerson}
                      </p>
                      <p className="text-muted-foreground">
                        <Phone className="w-3 h-3 inline mr-1" />
                        电话: {selectedSupplierForQuery.phone}
                      </p>
                      <p className="text-muted-foreground">
                        <Clock className="w-3 h-3 inline mr-1" />
                        合作: {selectedSupplierForQuery.cooperationYears}年
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 采购物品列表 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Package className="w-5 h-5 text-green-600" />
                  采购物品列表 ({getRelatedItemsBySupplier(selectedSupplierForQuery.id).length} 项)
                </h4>
                
                {getRelatedItemsBySupplier(selectedSupplierForQuery.id).length === 0 ? (
                  <Card className="p-8 text-center">
                    <Package className="w-12 h-12 mx-auto mb-2 opacity-30" />
                    <p className="text-muted-foreground">暂无从该供应商采购的物品</p>
                  </Card>
                ) : (
                  <div className="space-y-3">
                    {getRelatedItemsBySupplier(selectedSupplierForQuery.id).map(item => (
                      <Card key={item.id} className="p-4">
                        <div className="flex items-start justify-between">
                          <div className="flex items-start gap-3 flex-1">
                            <div className="p-2 bg-green-100 rounded">
                              <Package className="w-5 h-5 text-green-600" />
                            </div>
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <h5 className="font-medium">{item.name}</h5>
                                <Badge variant="outline">{item.type}</Badge>
                                <Badge className={
                                  item.status === '正常' ? 'bg-green-100 text-green-700' :
                                  item.status === '临期预警' ? 'bg-yellow-100 text-yellow-700' :
                                  item.status === '库存预警' ? 'bg-orange-100 text-orange-700' :
                                  'bg-red-100 text-red-700'
                                }>
                                  {item.status}
                                </Badge>
                              </div>
                              <div className="grid grid-cols-4 gap-4 text-sm mt-2">
                                <p className="text-muted-foreground">规格: {item.spec}</p>
                                <p className="text-muted-foreground">型号: {item.model || '-'}</p>
                                <p className="text-muted-foreground">库存: {item.currentStock} {item.unit}</p>
                                <p className="text-muted-foreground">单价: ¥{item.purchasePrice}</p>
                              </div>
                              <div className="grid grid-cols-2 gap-4 text-sm mt-2">
                                <p className="text-muted-foreground">
                                  有效期: {item.shelfLife}{item.shelfLifeUnit}
                                </p>
                                <p className="text-muted-foreground">
                                  到期日期: {item.expiryDate}
                                </p>
                              </div>
                            </div>
                          </div>
                          <div className="text-right">
                            <p className="text-xs text-muted-foreground">采购日期</p>
                            <p className="text-sm">{item.createdAt}</p>
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>
                )}
              </div>

              {/* 采购统计 */}
              {getRelatedItemsBySupplier(selectedSupplierForQuery.id).length > 0 && (
                <Card className="p-4 bg-blue-50">
                  <h5 className="mb-3">采购统计</h5>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <p className="text-xs text-muted-foreground">采购品种</p>
                      <p className="text-lg font-medium text-blue-600">
                        {getRelatedItemsBySupplier(selectedSupplierForQuery.id).length} 种
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">总库存价值</p>
                      <p className="text-lg font-medium text-green-600">
                        ¥{getRelatedItemsBySupplier(selectedSupplierForQuery.id)
                          .reduce((sum, item) => sum + ((item.currentStock || 0) * (item.purchasePrice || 0)), 0)
                          .toLocaleString()}
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">异常状态物品</p>
                      <p className="text-lg font-medium text-orange-600">
                        {getRelatedItemsBySupplier(selectedSupplierForQuery.id)
                          .filter(item => item.status !== '正常').length} 项
                      </p>
                    </div>
                  </div>
                </Card>
              )}

              <div className="flex justify-end">
                <Button variant="outline" onClick={() => setShowRelatedItemsDialog(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 客户新增/编辑对话框 */}
      <Dialog open={showCustomerDialog} onOpenChange={(open) => {
        setShowCustomerDialog(open);
        if (!open) {
          setEditingCustomer(null);
          setCustomerFormData({
            name: '',
            type: '',
            contactPerson: '',
            phone: '',
            email: '',
            address: '',
            creditLimit: '',
            notes: '',
          });
        }
      }}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingCustomer ? '编辑客户' : '新增客户'}</DialogTitle>
            <DialogDescription>
              填写客户基本信息和信用额度
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Users className="w-5 h-5 text-orange-600" />
                基本信息
              </h4>
              
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>客户名称 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：张三、绿源合作社"
                      className="mt-2"
                      value={customerFormData.name}
                      onChange={(e) => setCustomerFormData({ ...customerFormData, name: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>客户类型 <span className="text-destructive">*</span></label>
                    <Select value={customerFormData.type} onValueChange={(value) => setCustomerFormData({ ...customerFormData, type: value as '农户' | '合作社' | '企业' })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="选择类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="农户">农户</SelectItem>
                        <SelectItem value="合作社">合作社</SelectItem>
                        <SelectItem value="企业">企业</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>联系人 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：张三"
                      className="mt-2"
                      value={customerFormData.contactPerson}
                      onChange={(e) => setCustomerFormData({ ...customerFormData, contactPerson: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>联系电话 <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：13800001111"
                      className="mt-2"
                      value={customerFormData.phone}
                      onChange={(e) => setCustomerFormData({ ...customerFormData, phone: e.target.value })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label>电子邮箱</label>
                    <Input
                      placeholder="如：customer@example.com"
                      className="mt-2"
                      type="email"
                      value={customerFormData.email}
                      onChange={(e) => setCustomerFormData({ ...customerFormData, email: e.target.value })}
                    />
                  </div>
                  <div>
                    <label>信用额度(元) <span className="text-destructive">*</span></label>
                    <Input
                      placeholder="如：50000"
                      className="mt-2"
                      type="number"
                      value={customerFormData.creditLimit}
                      onChange={(e) => setCustomerFormData({ ...customerFormData, creditLimit: e.target.value })}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      客户可使用的最大赊账额度
                    </p>
                  </div>
                </div>

                <div>
                  <label>地址 <span className="text-destructive">*</span></label>
                  <Input
                    placeholder="如：浙江省杭州市余杭区XXX村"
                    className="mt-2"
                    value={customerFormData.address}
                    onChange={(e) => setCustomerFormData({ ...customerFormData, address: e.target.value })}
                  />
                </div>

                <div>
                  <label>备注</label>
                  <Textarea
                    placeholder="备注信息"
                    className="mt-2"
                    rows={3}
                    value={customerFormData.notes}
                    onChange={(e) => setCustomerFormData({ ...customerFormData, notes: e.target.value })}
                  />
                </div>
              </div>
            </Card>

            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setShowCustomerDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveCustomer}>
                <Save className="w-4 h-4 mr-2" />
                {editingCustomer ? '保存' : '添加'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
