// AssetEquipment.tsx - v2.0
import { useState, useEffect, useRef } 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, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import {
  Activity,
  AlertCircle,
  AlertTriangle,
  Archive,
  BarChart3,
  Box,
  Calculator,
  Calendar,
  CheckCircle,
  CircleDot,
  Clock,
  Cpu,
  DollarSign,
  Download,
  Edit,
  Eye,
  FileText,
  Filter,
  Gauge,
  Link2,
  MapPin,
  Package,
  PauseCircle,
  PieChart as PieChartIcon,
  Play,
  PlayCircle,
  Plus,
  Printer,
  RefreshCcw,
  Search,
  Send,
  Settings,
  Star,
  Tag,
  Timer,
  Trash2,
  TrendingDown,
  TrendingUp,
  Upload,
  User,
  Wrench,
  XCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  Area,
  AreaChart,
} from 'recharts';

interface AssetEquipmentProps {
  activePath?: string;
  onNavigate?: (path: string) => void;
}

type EquipmentStatus = '空闲' | '使用中' | '维修中' | '已调度' | '报废';
type MaintenanceType = '定期保养' | '故障维修' | '预防性维护';
type DepreciationMethod = '直线法' | '工作量法';
type DisposalStatus = '待申请' | '待审批' | '已批准' | '已驳回' | '已报废';

interface Equipment {
  id: string;
  code: string;
  name: string;
  category: string;
  model: string;
  manufacturer: string;
  purchaseDate: string;
  purchasePrice: number;
  depreciationYears: number;
  usageHours: number;
  currentValue: number;
  status: EquipmentStatus;
  location?: string;
  assignedTo?: string;
  lastMaintenanceDate?: string;
  nextMaintenanceDate?: string;
  specifications?: string;
  serialNumber?: string;
}

interface DispatchRecord {
  id: string;
  equipmentCode: string;
  equipmentName: string;
  status: EquipmentStatus;
  currentLocation: string;
  assignedTask?: string;
  assignedTo?: string;
  startTime?: string;
  estimatedEndTime?: string;
  actualUsageHours?: number;
  notes?: string;
}

interface MaintenancePlan {
  id: string;
  equipmentCode: string;
  equipmentName: string;
  planType: '按时间' | '按工作量';
  interval: number;
  intervalUnit: '天' | '小时';
  lastMaintenanceDate: string;
  nextMaintenanceDate: string;
  status: '正常' | '即将到期' | '逾期';
  autoRemind: boolean;
  currentUsage?: number;
  maintenanceItems?: string[];
  maintenanceHistory?: MaintenanceHistoryRecord[];
}

interface MaintenanceHistoryRecord {
  id: string;
  maintenanceDate: string;
  technician: string;
  technicianPhone?: string;
  duration: number;
  completedItems: string[];
  usedParts: {
    name: string;
    quantity: number;
    cost: number;
  }[];
  laborCost: number;
  totalCost: number;
  notes?: string;
  qualityRating?: '优秀' | '良好' | '合格';
}

interface MaintenanceRecord {
  id: string;
  workOrderNo: string;
  equipmentCode: string;
  equipmentName: string;
  maintenanceType: '定期保养' | '紧急维修' | '预防性维修';
  description: string;
  faultLevel?: '轻微' | '一般' | '严重';
  technician: string;
  technicianPhone?: string;
  startTime: string;
  endTime?: string;
  duration: number;
  parts: {
    name: string;
    quantity: number;
    cost: number;
  }[];
  laborCost: number;
  totalCost: number;
  paymentStatus?: '未结算' | '已结算';
  status: '待处理' | '进行中' | '已完成';
}

interface DepreciationRecord {
  id: string;
  equipmentCode: string;
  equipmentName: string;
  purchaseDate: string;
  purchasePrice: number;
  depreciationMethod: DepreciationMethod;
  depreciationYears: number;
  usedMonths: number;
  usageHours?: number;
  totalWorkload?: number;
  annualDepreciation: number;
  accumulatedDepreciation: number;
  currentValue: number;
  depreciationRate: number;
}

interface DisposalRequest {
  id: string;
  requestNo: string;
  equipmentCode: string;
  equipmentName: string;
  applicant: string;
  applyDate: string;
  reason: string;
  photos: string[];
  purchasePrice: number;
  currentValue: number;
  usageYears: number;
  status: DisposalStatus;
  approver?: string;
  approveDate?: string;
  approvalComments?: string;
}

// 基础设备数据（不包含折旧计算结果）- 组件外部常量
const baseEquipmentData = [
  {
    id: 'dep-1',
    equipmentCode: 'TOOL-2024-001',
    equipmentName: '拖拉机',
    purchaseDate: '2022-03-15',
    purchasePrice: 280000,
    depreciationYears: 10,
    usedMonths: 31,
    usageHours: 1250,
    totalWorkload: 10000,
  },
  {
    id: 'dep-2',
    equipmentCode: 'TOOL-2024-002',
    equipmentName: '喷雾器',
    purchaseDate: '2023-05-20',
    purchasePrice: 15000,
    depreciationYears: 5,
    usedMonths: 17,
    usageHours: 320,
    totalWorkload: 5000,
  },
  {
    id: 'dep-3',
    equipmentCode: 'TOOL-2024-003',
    equipmentName: '收割机',
    purchaseDate: '2021-06-10',
    purchasePrice: 350000,
    depreciationYears: 10,
    usedMonths: 40,
    usageHours: 2180,
    totalWorkload: 10000,
  },
];

export function AssetEquipment({ activePath, onNavigate }: AssetEquipmentProps) {
  const [activeTab, setActiveTab] = useState('archive');
  const [showEquipmentDialog, setShowEquipmentDialog] = useState(false);
  const [showMaintenanceDialog, setShowMaintenanceDialog] = useState(false);
  const [showPlanDialog, setShowPlanDialog] = useState(false);
  const [showPlanDetailDialog, setShowPlanDetailDialog] = useState(false);
  const [showPlanEditDialog, setShowPlanEditDialog] = useState(false);
  const [showExecuteMaintenanceDialog, setShowExecuteMaintenanceDialog] = useState(false);
  const [showWorkOrderDetailDialog, setShowWorkOrderDetailDialog] = useState(false);
  const [showProcessWorkOrderDialog, setShowProcessWorkOrderDialog] = useState(false);
  const [showCompleteWorkOrderDialog, setShowCompleteWorkOrderDialog] = useState(false);
  const [showDisposalDialog, setShowDisposalDialog] = useState(false);
  const [showDisposalDetailDialog, setShowDisposalDetailDialog] = useState(false);
  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [selectedEquipment, setSelectedEquipment] = useState<Equipment | null>(null);
  const [selectedPlan, setSelectedPlan] = useState<MaintenancePlan | null>(null);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState<MaintenanceRecord | null>(null);
  const [selectedDisposal, setSelectedDisposal] = useState<DisposalRequest | null>(null);
  const [showDispatchDetailDialog, setShowDispatchDetailDialog] = useState(false);
  const [selectedDispatchRecord, setSelectedDispatchRecord] = useState<DispatchRecord | null>(null);
  const [showDepreciationDetailDialog, setShowDepreciationDetailDialog] = useState(false);
  const [showDepreciationViewDialog, setShowDepreciationViewDialog] = useState(false);
  const [selectedDepreciationRecord, setSelectedDepreciationRecord] = useState<DepreciationRecord | null>(null);
  const [selectedCalculationMethod, setSelectedCalculationMethod] = useState<'直线法' | '工作量法'>('直线法');
  const [disposalFormData, setDisposalFormData] = useState({
    equipmentId: '',
    reason: '',
    photos: [] as string[],
  });

  // 维修工单配件管理
  const [maintenanceParts, setMaintenanceParts] = useState<{ name: string; quantity: number; cost: number }[]>([]);
  const [newPart, setNewPart] = useState({ name: '', quantity: 0, cost: 0 });
  const [laborCost, setLaborCost] = useState(0);

  // 保养计划表单数据
  const [planFormData, setPlanFormData] = useState({
    equipmentId: '',
    planType: '按时间' as '按时间' | '按工作量',
    interval: 0,
    intervalUnit: '天' as '天' | '小时',
    autoRemind: true,
    maintenanceItems: [] as string[],
    newItem: '',
  });

  // 农资物料列表 - 用于配件选择
  const [materialList] = useState([
    { id: '1', code: 'M001', name: '机油', type: '耗材' as const, spec: '5W-40', unit: '升', purchasePrice: 45, currentStock: 120 },
    { id: '2', code: 'M002', name: '空气滤芯', type: '耗材' as const, spec: 'A-123', unit: '个', purchasePrice: 35, currentStock: 50 },
    { id: '3', code: 'M003', name: '机油滤芯', type: '耗材' as const, spec: 'OF-456', unit: '个', purchasePrice: 28, currentStock: 60 },
    { id: '4', code: 'M004', name: '液压油', type: '耗材' as const, spec: 'HM-68', unit: '升', purchasePrice: 38, currentStock: 80 },
    { id: '5', code: 'M005', name: '刹车片', type: '耗材' as const, spec: 'BP-789', unit: '套', purchasePrice: 180, currentStock: 25 },
    { id: '6', code: 'M006', name: '轮胎', type: '耗材' as const, spec: '16.9-30', unit: '条', purchasePrice: 850, currentStock: 12 },
    { id: '7', code: 'M007', name: '润滑脂', type: '耗材' as const, spec: '通用型', unit: '千克', purchasePrice: 22, currentStock: 40 },
    { id: '8', code: 'M008', name: '传动皮带', type: '耗材' as const, spec: 'B-456', unit: '条', purchasePrice: 65, currentStock: 30 },
    { id: '9', code: 'M009', name: '火花塞', type: '耗材' as const, spec: 'SP-123', unit: '个', purchasePrice: 15, currentStock: 100 },
    { id: '10', code: 'M010', name: '冷却液', type: '耗材' as const, spec: '防冻型', unit: '升', purchasePrice: 18, currentStock: 90 },
  ]);
  const [selectedMaterialId, setSelectedMaterialId] = useState('');

  // 编辑保养计划表单数据
  const [editPlanFormData, setEditPlanFormData] = useState({
    equipmentId: '',
    planType: '按时间' as '按时间' | '按工作量',
    interval: 0,
    intervalUnit: '天' as '天' | '小时',
    autoRemind: true,
    maintenanceItems: [] as string[],
    newItem: '',
  });

  // 执行保养表单数据
  const [executeFormData, setExecuteFormData] = useState({
    technician: '',
    technicianPhone: '',
    actualStartTime: '',
    actualEndTime: '',
    completedItems: [] as string[],
    usedParts: [] as { name: string; quantity: number; cost: number }[],
    laborCost: 0,
    notes: '',
  });

  // 处理维修工单表单数据（开始维修）
  const [processFormData, setProcessFormData] = useState({
    actualStartTime: '',
    estimatedDuration: 0,
    processNotes: '',
  });

  // 完成维修工单表单数据
  const [completeFormData, setCompleteFormData] = useState({
    actualEndTime: '',
    actualDuration: 0,
    additionalParts: [] as { name: string; quantity: number; cost: number }[],
    additionalLaborCost: 0,
    solutionNotes: '',
    qualityCheck: false,
  });

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/equipment/archive')) {
        setActiveTab('archive');
      } else if (activePath.includes('/equipment/dispatch')) {
        setActiveTab('dispatch');
      } else if (activePath.includes('/equipment/maintenance')) {
        setActiveTab('maintenance');
      } else if (activePath.includes('/equipment/depreciation')) {
        setActiveTab('depreciation');
      } else if (activePath.includes('/equipment/disposal')) {
        setActiveTab('disposal');
      }
    }
  }, [activePath]);

  // 模拟数据
  const [equipmentList] = useState<Equipment[]>([
    {
      id: 'eq-1',
      code: 'TOOL-2024-001',
      name: '拖拉机',
      category: '动力机械',
      model: 'JD-6130M',
      manufacturer: '约翰迪尔',
      purchaseDate: '2022-03-15',
      purchasePrice: 280000,
      depreciationYears: 10,
      usageHours: 1250,
      currentValue: 224000,
      status: '使用中',
      location: '1号机库',
      assignedTo: '张师傅',
      lastMaintenanceDate: '2024-09-15',
      nextMaintenanceDate: '2024-12-15',
      serialNumber: 'JD2022031501',
    },
    {
      id: 'eq-2',
      code: 'TOOL-2024-002',
      name: '喷雾器',
      category: '植保机械',
      model: 'SP-300',
      manufacturer: '绿田农机',
      purchaseDate: '2023-05-20',
      purchasePrice: 15000,
      depreciationYears: 5,
      usageHours: 320,
      currentValue: 10500,
      status: '空闲',
      location: '2号仓库',
      lastMaintenanceDate: '2024-08-10',
      nextMaintenanceDate: '2024-11-10',
      serialNumber: 'LT2023052001',
    },
    {
      id: 'eq-3',
      code: 'TOOL-2024-003',
      name: '收割机',
      category: '收获机械',
      model: 'XG-988',
      manufacturer: '星光农机',
      purchaseDate: '2021-06-10',
      purchasePrice: 350000,
      depreciationYears: 10,
      usageHours: 2180,
      currentValue: 227500,
      status: '维修中',
      location: '维修车间',
      assignedTo: '维修组',
      lastMaintenanceDate: '2024-10-01',
      serialNumber: 'XG2021061001',
    },
  ]);

  const [dispatchRecords] = useState<DispatchRecord[]>([
    {
      id: 'dis-1',
      equipmentCode: 'TOOL-2024-001',
      equipmentName: '拖拉机',
      status: '使用中',
      currentLocation: '1号田块',
      assignedTask: '耕地作业',
      assignedTo: '张师傅',
      startTime: '2024-10-15 08:00',
      estimatedEndTime: '2024-10-15 17:00',
      actualUsageHours: 5.5,
      notes: '正常作业中',
    },
    {
      id: 'dis-2',
      equipmentCode: 'TOOL-2024-002',
      equipmentName: '喷雾器',
      status: '空闲',
      currentLocation: '2号仓库',
      notes: '可调度',
    },
    {
      id: 'dis-3',
      equipmentCode: 'TOOL-2024-003',
      equipmentName: '收割机',
      status: '维修中',
      currentLocation: '维修车间',
      assignedTo: '维修组',
      startTime: '2024-10-10 09:00',
      notes: '液压系统故障维修中',
    },
  ]);

  const [maintenancePlans] = useState<MaintenancePlan[]>([
    {
      id: 'plan-1',
      equipmentCode: 'TOOL-2024-001',
      equipmentName: '拖拉机',
      planType: '按时间',
      interval: 90,
      intervalUnit: '天',
      lastMaintenanceDate: '2024-09-15',
      nextMaintenanceDate: '2024-12-15',
      status: '正常',
      autoRemind: true,
      maintenanceItems: ['更换机油', '检查刹车系统', '清洁空滤', '润滑传动部件'],
      maintenanceHistory: [
        {
          id: 'hist-1',
          maintenanceDate: '2024-09-15',
          technician: '王师傅',
          technicianPhone: '13900139002',
          duration: 4,
          completedItems: ['更换机油', '检查刹车系统', '清洁空滤', '润滑传动部件'],
          usedParts: [
            { name: '机油 (5W-40)', quantity: 15, cost: 45 },
            { name: '机油滤芯 (OF-456)', quantity: 1, cost: 28 },
            { name: '空气滤芯 (A-123)', quantity: 1, cost: 35 },
          ],
          laborCost: 400,
          totalCost: 1063,
          notes: '按计划完成定期保养，设备运行正常',
          qualityRating: '优秀',
        },
        {
          id: 'hist-2',
          maintenanceDate: '2024-06-15',
          technician: '李师傅',
          technicianPhone: '13800138001',
          duration: 3.5,
          completedItems: ['更换机油', '检查刹车系统', '清洁空滤'],
          usedParts: [
            { name: '机油 (5W-40)', quantity: 15, cost: 45 },
            { name: '机油滤芯 (OF-456)', quantity: 1, cost: 28 },
          ],
          laborCost: 350,
          totalCost: 1053,
          notes: '定期保养，发现刹车片磨损轻微，建议下次保养更换',
          qualityRating: '良好',
        },
        {
          id: 'hist-3',
          maintenanceDate: '2024-03-15',
          technician: '王师傅',
          technicianPhone: '13900139002',
          duration: 4,
          completedItems: ['更换机油', '检查刹车系统', '清洁空滤', '润滑传动部件'],
          usedParts: [
            { name: '机油 (5W-40)', quantity: 15, cost: 45 },
            { name: '机油滤芯 (OF-456)', quantity: 1, cost: 28 },
            { name: '空气滤芯 (A-123)', quantity: 1, cost: 35 },
            { name: '润滑脂 (通用型)', quantity: 2, cost: 22 },
          ],
          laborCost: 400,
          totalCost: 1107,
          notes: '春季保养完成，设备状态良好',
          qualityRating: '优秀',
        },
      ],
    },
    {
      id: 'plan-2',
      equipmentCode: 'TOOL-2024-002',
      equipmentName: '喷雾器',
      planType: '按时间',
      interval: 60,
      intervalUnit: '天',
      lastMaintenanceDate: '2024-09-20',
      nextMaintenanceDate: '2024-10-28',
      status: '即将到期',
      autoRemind: true,
      maintenanceItems: ['清洗喷头', '检查管路', '更换滤网'],
      maintenanceHistory: [
        {
          id: 'hist-4',
          maintenanceDate: '2024-09-20',
          technician: '张技师',
          technicianPhone: '13700137003',
          duration: 2,
          completedItems: ['清洗喷头', '检查管路', '更换滤网'],
          usedParts: [
            { name: '滤网套装', quantity: 1, cost: 65 },
          ],
          laborCost: 200,
          totalCost: 265,
          notes: '喷雾器保养完成，喷雾效果正常',
          qualityRating: '优秀',
        },
        {
          id: 'hist-5',
          maintenanceDate: '2024-07-20',
          technician: '张技师',
          technicianPhone: '13700137003',
          duration: 1.5,
          completedItems: ['清洗喷头', '检查管路'],
          usedParts: [],
          laborCost: 150,
          totalCost: 150,
          notes: '常规清洗维护',
          qualityRating: '良好',
        },
      ],
    },
    {
      id: 'plan-3',
      equipmentCode: 'TOOL-2024-003',
      equipmentName: '收割机',
      planType: '按工作量',
      interval: 500,
      intervalUnit: '小时',
      lastMaintenanceDate: '2024-07-20',
      nextMaintenanceDate: '2024-10-15',
      status: '逾期',
      autoRemind: true,
      currentUsage: 580,
      maintenanceItems: ['检查液压系统', '更换刀片', '清洁除尘系统', '润滑轴承'],
      maintenanceHistory: [
        {
          id: 'hist-6',
          maintenanceDate: '2024-07-20',
          technician: '赵师傅',
          technicianPhone: '13600136000',
          duration: 6,
          completedItems: ['检查液压系统', '更换刀片', '清洁除尘系统', '润滑轴承'],
          usedParts: [
            { name: '液压油 (HM-68)', quantity: 20, cost: 38 },
            { name: '收割刀片', quantity: 8, cost: 120 },
            { name: '润滑脂 (通用型)', quantity: 3, cost: 22 },
          ],
          laborCost: 600,
          totalCost: 2386,
          notes: '夏季保养完成，更换磨损刀片，液压系统正常',
          qualityRating: '优秀',
        },
        {
          id: 'hist-7',
          maintenanceDate: '2024-04-10',
          technician: '赵师傅',
          technicianPhone: '13600136000',
          duration: 5,
          completedItems: ['检查液压系统', '清洁除尘系统', '润滑轴承'],
          usedParts: [
            { name: '液压油 (HM-68)', quantity: 15, cost: 38 },
            { name: '润滑脂 (通用型)', quantity: 2, cost: 22 },
          ],
          laborCost: 500,
          totalCost: 1114,
          notes: '春季保养完成，为农忙做准备',
          qualityRating: '良好',
        },
        {
          id: 'hist-8',
          maintenanceDate: '2023-12-15',
          technician: '李师傅',
          technicianPhone: '13800138001',
          duration: 7,
          completedItems: ['检查液压系统', '更换刀片', '清洁除尘系统', '润滑轴承'],
          usedParts: [
            { name: '液压油 (HM-68)', quantity: 20, cost: 38 },
            { name: '收割刀片', quantity: 10, cost: 120 },
            { name: '润滑脂 (通用型)', quantity: 4, cost: 22 },
            { name: '传动皮带 (B-456)', quantity: 2, cost: 65 },
          ],
          laborCost: 700,
          totalCost: 3218,
          notes: '年度大保养，更换多个易损件',
          qualityRating: '优秀',
        },
      ],
    },
  ]);

  const [maintenanceRecords] = useState<MaintenanceRecord[]>([
    {
      id: 'maint-1',
      workOrderNo: 'WO202410150001',
      equipmentCode: 'TOOL-2024-003',
      equipmentName: '收割机',
      maintenanceType: '紧急维修',
      description: '液压系统压力不足，工作时出现异响，检查发现密封圈老化导致漏油，需更换密封圈套装和液压油',
      faultLevel: '严重',
      technician: '李维修',
      technicianPhone: '13800138001',
      startTime: '2024-10-10 09:00',
      endTime: undefined,
      duration: 14,
      parts: [
        { name: '液压密封圈套装', quantity: 1, cost: 350 },
        { name: '液压油', quantity: 20, cost: 600 },
        { name: '油管接头', quantity: 2, cost: 80 },
      ],
      laborCost: 1400,
      totalCost: 2430,
      paymentStatus: '未结算',
      status: '进行中',
    },
    {
      id: 'maint-2',
      workOrderNo: 'WO202409150001',
      equipmentCode: 'TOOL-2024-001',
      equipmentName: '拖拉机',
      maintenanceType: '定期保养',
      description: '按照保养计划进行定期保养：更换机油、机滤、空滤，检查刹车系统、传动系统、电气系统等各部件',
      faultLevel: undefined,
      technician: '王师傅',
      technicianPhone: '13900139002',
      startTime: '2024-09-15 08:00',
      endTime: '2024-09-15 12:00',
      duration: 4,
      parts: [
        { name: '机油', quantity: 15, cost: 450 },
        { name: '机滤', quantity: 1, cost: 80 },
        { name: '空滤', quantity: 1, cost: 60 },
      ],
      laborCost: 400,
      totalCost: 990,
      paymentStatus: '已结算',
      status: '已完成',
    },
    {
      id: 'maint-3',
      workOrderNo: 'WO202410010001',
      equipmentCode: 'TOOL-2024-002',
      equipmentName: '喷雾器',
      maintenanceType: '预防性维修',
      description: '喷雾器喷头出现轻微堵塞现象，进行预防性清洁和检查',
      faultLevel: '轻微',
      technician: '张技师',
      technicianPhone: '13700137003',
      startTime: '2024-10-01 14:00',
      endTime: '2024-10-01 16:30',
      duration: 2.5,
      parts: [
        { name: '喷头滤网', quantity: 3, cost: 45 },
        { name: '密封垫圈', quantity: 5, cost: 25 },
      ],
      laborCost: 200,
      totalCost: 270,
      paymentStatus: '已结算',
      status: '已完成',
    },
    {
      id: 'maint-4',
      workOrderNo: 'WO202409200001',
      equipmentCode: 'TOOL-2024-001',
      equipmentName: '拖拉机',
      maintenanceType: '紧急维修',
      description: '发动机启动困难，检查后发现启动马达故障，需更换启动马达总成',
      faultLevel: '一般',
      technician: '刘师傅',
      technicianPhone: '13600136004',
      startTime: '2024-09-20 10:00',
      endTime: '2024-09-20 15:00',
      duration: 5,
      parts: [
        { name: '启动马达总成', quantity: 1, cost: 1200 },
        { name: '电瓶接线柱', quantity: 2, cost: 40 },
      ],
      laborCost: 500,
      totalCost: 1740,
      paymentStatus: '已结算',
      status: '已完成',
    },
    {
      id: 'maint-5',
      workOrderNo: 'WO202408150001',
      equipmentCode: 'TOOL-2024-002',
      equipmentName: '喷雾器',
      maintenanceType: '定期保养',
      description: '按计划进行定期保养，清洗喷头、检查管路、更换滤网',
      technician: '张技师',
      technicianPhone: '13700137003',
      startTime: '2024-08-15 09:00',
      endTime: '2024-08-15 11:00',
      duration: 2,
      parts: [
        { name: '滤网', quantity: 2, cost: 60 },
        { name: '喷头', quantity: 1, cost: 120 },
      ],
      laborCost: 200,
      totalCost: 380,
      paymentStatus: '已结算',
      status: '已完成',
    },
    {
      id: 'maint-6',
      workOrderNo: 'WO202407280001',
      equipmentCode: 'TOOL-2024-003',
      equipmentName: '收割机',
      maintenanceType: '定期保养',
      description: '收获季前大保养，全面检查各系统，更换易损件',
      technician: '李维修',
      technicianPhone: '13800138001',
      startTime: '2024-07-28 08:00',
      endTime: '2024-07-29 17:00',
      duration: 16,
      parts: [
        { name: '刀片组', quantity: 1, cost: 800 },
        { name: '传动皮带', quantity: 2, cost: 240 },
        { name: '轴承套装', quantity: 1, cost: 450 },
        { name: '机油', quantity: 20, cost: 600 },
      ],
      laborCost: 1600,
      totalCost: 3690,
      paymentStatus: '已结算',
      status: '已完成',
    },
    {
      id: 'maint-7',
      workOrderNo: 'WO202410180001',
      equipmentCode: 'TOOL-2024-001',
      equipmentName: '拖拉机',
      maintenanceType: '预防性维修',
      description: '发现轮胎磨损严重，进行预防性检查和轮胎更换',
      faultLevel: '一般',
      technician: '王师傅',
      technicianPhone: '13900139002',
      startTime: '2024-10-18 13:00',
      endTime: undefined,
      duration: 0,
      parts: [],
      laborCost: 0,
      totalCost: 0,
      paymentStatus: '未结算',
      status: '待处理',
    },
  ]);

  const [depreciationRecords, setDepreciationRecords] = useState<DepreciationRecord[]>(() => {
    // 初始使用直线法计算
    return baseEquipmentData.map(equipment => {
      const annualDepreciation = equipment.purchasePrice / equipment.depreciationYears;
      const accumulatedDepreciation = (annualDepreciation / 12) * equipment.usedMonths;
      const currentValue = equipment.purchasePrice - accumulatedDepreciation;
      const depreciationRate = (accumulatedDepreciation / equipment.purchasePrice) * 100;

      return {
        ...equipment,
        depreciationMethod: '直线法' as DepreciationMethod,
        annualDepreciation,
        accumulatedDepreciation,
        currentValue,
        depreciationRate,
      };
    });
  });

  const [disposalRequests] = useState<DisposalRequest[]>([
    {
      id: 'disp-1',
      requestNo: 'DISP202410010001',
      equipmentCode: 'TOOL-2020-015',
      equipmentName: '老式拖拉机',
      applicant: '资产管理员',
      applyDate: '2024-10-01',
      reason: '设备老化严重，维修成本过高，已超过使用年限，申请报废',
      photos: ['old-tractor-1.jpg', 'old-tractor-2.jpg'],
      purchasePrice: 180000,
      currentValue: 5000,
      usageYears: 12,
      status: '待审批',
    },
    {
      id: 'disp-2',
      requestNo: 'DISP202409150001',
      equipmentCode: 'TOOL-2019-008',
      equipmentName: '播种机',
      applicant: '张主管',
      applyDate: '2024-09-15',
      reason: '设备严重损坏，无维修价值',
      photos: ['seeder-damage.jpg'],
      purchasePrice: 45000,
      currentValue: 2000,
      usageYears: 5,
      status: '已批准',
      approver: '李经理',
      approveDate: '2024-09-20',
      approvalComments: '同意报废，按流程处理',
    },
  ]);

  // 统计数据
  const totalEquipment = equipmentList.length;
  const inUse = equipmentList.filter(e => e.status === '使用中').length;
  const idle = equipmentList.filter(e => e.status === '空闲').length;
  const underMaintenance = equipmentList.filter(e => e.status === '维修中').length;
  const totalValue = equipmentList.reduce((sum, e) => sum + e.currentValue, 0);

  // 报废统计
  const pendingDisposal = disposalRequests.filter(r => r.status === '待审批').length;
  const approvedDisposal = disposalRequests.filter(r => r.status === '已批准').length;
  const rejectedDisposal = disposalRequests.filter(r => r.status === '已驳回').length;
  const completedDisposal = disposalRequests.filter(r => r.status === '已报废').length;
  const totalDisposalValue = disposalRequests.reduce((sum, r) => sum + r.currentValue, 0);

  // 图表数据
  const statusChartData = [
    { name: '空闲', value: idle, color: '#10b981' },
    { name: '使用中', value: inUse, color: '#3b82f6' },
    { name: '维修中', value: underMaintenance, color: '#f59e0b' },
    { name: '已调度', value: 0, color: '#8b5cf6' },
  ];

  const valueChartData = equipmentList.map(eq => ({
    name: eq.name,
    原值: eq.purchasePrice,
    现值: eq.currentValue,
    折旧: eq.purchasePrice - eq.currentValue,
  }));

  const maintenanceCostData = [
    { month: '6月', cost: 4500 },
    { month: '7月', cost: 3200 },
    { month: '8月', cost: 5800 },
    { month: '9月', cost: 990 },
    { month: '10月', cost: 2350 },
  ];

  const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6'];

  const getStatusColor = (status: EquipmentStatus) => {
    switch (status) {
      case '空闲': return 'bg-success-muted text-success-muted-foreground';
      case '使用中': return 'bg-info-muted text-info-muted-foreground';
      case '维修中': return 'bg-warning-muted text-warning-muted-foreground';
      case '已调度': return 'bg-accent-muted text-accent-foreground';
      case '报废': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getMaintenanceStatusColor = (status: string) => {
    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 getDisposalStatusColor = (status: DisposalStatus) => {
    switch (status) {
      case '待申请': return 'bg-muted text-muted-foreground';
      case '待审批': return 'bg-warning-muted text-warning-muted-foreground';
      case '已批准': return 'bg-success-muted text-success-muted-foreground';
      case '已驳回': return 'bg-error-muted text-error-muted-foreground';
      case '已报废': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const calculateDepreciation = (equipment: Equipment) => {
    const monthsUsed = Math.floor(
      (new Date().getTime() - new Date(equipment.purchaseDate).getTime()) / (1000 * 60 * 60 * 24 * 30)
    );
    const annualDepreciation = equipment.purchasePrice / equipment.depreciationYears;
    const accumulatedDepreciation = (annualDepreciation / 12) * monthsUsed;
    return {
      monthsUsed,
      annualDepreciation,
      accumulatedDepreciation,
      currentValue: equipment.purchasePrice - accumulatedDepreciation,
      depreciationRate: (accumulatedDepreciation / equipment.purchasePrice) * 100,
    };
  };

  // 根据选择的折旧方法重新计算所有设备
  const recalculateDepreciation = (method: '直线法' | '工作量法') => {
    const newRecords = baseEquipmentData.map(equipment => {
      let annualDepreciation: number;
      let accumulatedDepreciation: number;
      let currentValue: number;
      let depreciationRate: number;

      if (method === '直线法') {
        // 直线法：年折旧额 = 原值 / 预计使用年限
        annualDepreciation = equipment.purchasePrice / equipment.depreciationYears;
        accumulatedDepreciation = (annualDepreciation / 12) * equipment.usedMonths;
        currentValue = equipment.purchasePrice - accumulatedDepreciation;
        depreciationRate = (accumulatedDepreciation / equipment.purchasePrice) * 100;
      } else {
        // 工作量法：单位折旧额 = 原值 / 预计总工作量
        const unitDepreciation = equipment.purchasePrice / equipment.totalWorkload;
        accumulatedDepreciation = unitDepreciation * equipment.usageHours;
        currentValue = equipment.purchasePrice - accumulatedDepreciation;
        depreciationRate = (accumulatedDepreciation / equipment.purchasePrice) * 100;
        // 工作量法的年折旧额以实际使用情况估算
        annualDepreciation = (accumulatedDepreciation / equipment.usedMonths) * 12;
      }

      return {
        ...equipment,
        depreciationMethod: method,
        annualDepreciation,
        accumulatedDepreciation,
        currentValue,
        depreciationRate,
      };
    });

    setDepreciationRecords(newRecords);
    toast.success(`已使用${method}重新计算所有设备折旧`);
  };

  // 监听计算方法变化，自动重新计算（跳过初始渲染）
  const isFirstRender = useRef(true);
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    recalculateDepreciation(selectedCalculationMethod);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedCalculationMethod]);

  const handleSaveEquipment = () => {
    toast.success('设备信息保存成功');
    setShowEquipmentDialog(false);
  };

  const handleAddPart = () => {
    if (!selectedMaterialId) {
      toast.error('请选择配件');
      return;
    }
    if (!newPart.quantity || newPart.quantity <= 0) {
      toast.error('请输入配件数量');
      return;
    }

    const selectedMaterial = materialList.find(m => m.id === selectedMaterialId);
    if (!selectedMaterial) {
      toast.error('配件信息不存在');
      return;
    }

    // 检查库存
    if (newPart.quantity > selectedMaterial.currentStock) {
      toast.error(`库存不足！当前库存：${selectedMaterial.currentStock}${selectedMaterial.unit}`);
      return;
    }

    // 使用物料的名称和单价
    setMaintenanceParts([...maintenanceParts, { 
      name: `${selectedMaterial.name} (${selectedMaterial.spec})`,
      quantity: newPart.quantity,
      cost: selectedMaterial.purchasePrice,
    }]);
    
    setNewPart({ name: '', quantity: 0, cost: 0 });
    setSelectedMaterialId('');
    toast.success('配件添加成功');
  };

  const handleRemovePart = (index: number) => {
    setMaintenanceParts(maintenanceParts.filter((_, i) => i !== index));
    toast.success('配件已移除');
  };

  const calculateTotalCost = () => {
    const partsCost = maintenanceParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0);
    return partsCost + laborCost;
  };

  const handleSaveMaintenance = () => {
    toast.success('维修工单创建成功');
    setShowMaintenanceDialog(false);
    // 重置表单
    setMaintenanceParts([]);
    setNewPart({ name: '', quantity: 0, cost: 0 });
    setLaborCost(0);
  };

  const handleAddMaintenanceItem = () => {
    if (!planFormData.newItem.trim()) {
      toast.error('请输入保养项目');
      return;
    }
    setPlanFormData({
      ...planFormData,
      maintenanceItems: [...planFormData.maintenanceItems, planFormData.newItem.trim()],
      newItem: '',
    });
    toast.success('保养项目已添加');
  };

  const handleRemoveMaintenanceItem = (index: number) => {
    setPlanFormData({
      ...planFormData,
      maintenanceItems: planFormData.maintenanceItems.filter((_, i) => i !== index),
    });
    toast.success('保养项目已移除');
  };

  const handleSavePlan = () => {
    if (!planFormData.equipmentId) {
      toast.error('请选择设备');
      return;
    }
    if (!planFormData.interval || planFormData.interval <= 0) {
      toast.error('请设置有效的保养间隔');
      return;
    }
    if (planFormData.maintenanceItems.length === 0) {
      toast.error('请至少添加一项保养内容');
      return;
    }
    
    toast.success('保养计划创建成功');
    setShowPlanDialog(false);
    // 重置表单
    setPlanFormData({
      equipmentId: '',
      planType: '按时间',
      interval: 0,
      intervalUnit: '天',
      autoRemind: true,
      maintenanceItems: [],
      newItem: '',
    });
  };

  // 查看保养计划详情
  const handleViewPlanDetail = (plan: MaintenancePlan) => {
    setSelectedPlan(plan);
    setShowPlanDetailDialog(true);
  };

  // 编辑保养计划
  const handleEditPlan = (plan: MaintenancePlan) => {
    setSelectedPlan(plan);
    const equipment = equipmentList.find(e => e.code === plan.equipmentCode);
    setEditPlanFormData({
      equipmentId: equipment?.id || '',
      planType: plan.planType,
      interval: plan.interval,
      intervalUnit: plan.intervalUnit,
      autoRemind: plan.autoRemind,
      maintenanceItems: plan.maintenanceItems || [],
      newItem: '',
    });
    setShowPlanEditDialog(true);
  };

  const handleSaveEditPlan = () => {
    if (!editPlanFormData.interval || editPlanFormData.interval <= 0) {
      toast.error('请设置有效的保养间隔');
      return;
    }
    if (editPlanFormData.maintenanceItems.length === 0) {
      toast.error('请至少添加一项保养内容');
      return;
    }
    
    toast.success('保养计划更新成功');
    setShowPlanEditDialog(false);
    setSelectedPlan(null);
  };

  // 执行保养
  const handleExecuteMaintenance = (plan: MaintenancePlan) => {
    setSelectedPlan(plan);
    const currentDate = new Date().toISOString().slice(0, 16);
    setExecuteFormData({
      technician: '',
      technicianPhone: '',
      actualStartTime: currentDate,
      actualEndTime: '',
      completedItems: [],
      usedParts: [],
      laborCost: 0,
      notes: '',
    });
    setShowExecuteMaintenanceDialog(true);
  };

  const handleSaveExecuteMaintenance = () => {
    if (!executeFormData.technician) {
      toast.error('请输入维护人员');
      return;
    }
    if (!executeFormData.actualStartTime || !executeFormData.actualEndTime) {
      toast.error('请填写保养起止时间');
      return;
    }
    if (executeFormData.completedItems.length === 0) {
      toast.error('请至少完成一项保养内容');
      return;
    }

    toast.success('保养任务已完成，已生成维修工单记录');
    setShowExecuteMaintenanceDialog(false);
    setSelectedPlan(null);
  };

  // 查看维修工单详情
  const handleViewWorkOrderDetail = (record: MaintenanceRecord) => {
    setSelectedWorkOrder(record);
    setShowWorkOrderDetailDialog(true);
  };

  // 开始处理维修工单
  const handleProcessWorkOrder = (record: MaintenanceRecord) => {
    if (record.status !== '待处理') {
      toast.error('只能处理待处理状态的工单');
      return;
    }
    setSelectedWorkOrder(record);
    const currentDate = new Date().toISOString().slice(0, 16);
    setProcessFormData({
      actualStartTime: currentDate,
      estimatedDuration: 0,
      processNotes: '',
    });
    setShowProcessWorkOrderDialog(true);
  };

  const handleSaveProcessWorkOrder = () => {
    if (!processFormData.actualStartTime) {
      toast.error('请选择开始时间');
      return;
    }
    if (!processFormData.estimatedDuration || processFormData.estimatedDuration <= 0) {
      toast.error('请输入预计耗时');
      return;
    }

    toast.success('工单已开始处理，状态已更新为"进行中"');
    setShowProcessWorkOrderDialog(false);
    setSelectedWorkOrder(null);
  };

  // 完成维修工单
  const handleCompleteWorkOrder = (record: MaintenanceRecord) => {
    if (record.status !== '进行中') {
      toast.error('只能完成进行中的工单');
      return;
    }
    setSelectedWorkOrder(record);
    const currentDate = new Date().toISOString().slice(0, 16);
    setCompleteFormData({
      actualEndTime: currentDate,
      actualDuration: record.duration,
      additionalParts: [],
      additionalLaborCost: 0,
      solutionNotes: '',
      qualityCheck: false,
    });
    setShowCompleteWorkOrderDialog(true);
  };

  const handleSaveCompleteWorkOrder = () => {
    if (!completeFormData.actualEndTime) {
      toast.error('请选择完成时间');
      return;
    }
    if (!completeFormData.actualDuration || completeFormData.actualDuration <= 0) {
      toast.error('请输入实际耗时');
      return;
    }
    if (!completeFormData.qualityCheck) {
      toast.error('请完成质量检查后再提交');
      return;
    }
    if (!completeFormData.solutionNotes.trim()) {
      toast.error('请填写解决方案说明');
      return;
    }

    toast.success('维修工单已完成，设备可正常使用');
    setShowCompleteWorkOrderDialog(false);
    setSelectedWorkOrder(null);
  };

  const handleSubmitDisposal = () => {
    if (!disposalFormData.equipmentId || !disposalFormData.reason) {
      toast.error('请填写完整信息');
      return;
    }
    toast.success('报废申请已提交，等待审批');
    setShowDisposalDialog(false);
    setDisposalFormData({ equipmentId: '', reason: '', photos: [] });
  };

  const handleApproveDisposal = () => {
    toast.success('报废申请已批准，资产状态已更新为"报废"');
    setShowApprovalDialog(false);
    setSelectedDisposal(null);
  };

  const handleRejectDisposal = () => {
    toast.info('报废申请已驳回');
    setShowApprovalDialog(false);
    setSelectedDisposal(null);
  };

  const handleViewDisposal = (request: DisposalRequest) => {
    setSelectedDisposal(request);
    setShowDisposalDetailDialog(true);
  };

  const handleStartApproval = (request: DisposalRequest) => {
    setSelectedDisposal(request);
    setShowApprovalDialog(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>农资农具管理</h2>
          <p className="text-sm text-muted-foreground mt-1">
            固定资产全生命周期管理：档案、调度、维修、折旧与报废
          </p>
        </div>
        <div className="flex items-center gap-3">
          <div className="text-right text-sm">
            <p className="text-muted-foreground">
              物资档案数据来源于基础信息管理-农具档案
            </p>
            <p className="text-xs text-info">
              新增/编辑请前往基础信息管理-农具档案
            </p>
          </div>
          <Button 
            variant="outline" 
            className="border-info text-info hover:bg-info-muted"
            onClick={() => {
              if (onNavigate) {
                onNavigate('/asset/basic/tools');
                toast.success('已跳转到基础信息管理-农具档案');
              } else {
                toast.info('请点击顶部导航栏「基础信息管理」，然后选择「农具档案」进行编辑', {
                  duration: 4000,
                });
              }
            }}
          >
            <Link2 className="w-4 h-4 mr-2" />
            前往农具档案
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 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">{totalEquipment}</p>
              <p className="text-xs text-success mt-1">在册设备</p>
            </div>
            <Box 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">{inUse}</p>
              <p className="text-xs text-info mt-1">作业中设备</p>
            </div>
            <PlayCircle 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-success">{idle}</p>
              <p className="text-xs text-success mt-1">可调度</p>
            </div>
            <PauseCircle 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-warning">{underMaintenance}</p>
              <p className="text-xs text-warning mt-1">暂不可用</p>
            </div>
            <Wrench className="w-12 h-12 text-warning 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">
                {(totalValue / 10000).toFixed(1)}
              </p>
              <p className="text-xs text-foreground mt-1">万元</p>
            </div>
            <DollarSign className="w-12 h-12 text-foreground opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="archive">物资档案</TabsTrigger>
          <TabsTrigger value="dispatch">使用调度与状态</TabsTrigger>
          <TabsTrigger value="maintenance">维修保养</TabsTrigger>
          <TabsTrigger value="depreciation">折旧计算</TabsTrigger>
          <TabsTrigger value="disposal">报废处理</TabsTrigger>
        </TabsList>

        {/* 物资档案 */}
        <TabsContent value="archive" className="space-y-4">
          <Card className="p-4 bg-success-muted border-success">
            <div className="flex items-start gap-2">
              <Box 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"><strong>物资档案功能说明</strong></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>
                </ul>
              </div>
            </div>
          </Card>

          {/* 数据来源提示 */}
          <Card className="p-4 bg-info-muted border-info">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <AlertCircle className="w-5 h-5 text-info" />
                <div className="text-sm text-info-muted-foreground">
                  <p className="font-medium">数据来源</p>
                  <p className="text-xs mt-1">
                    本页面数据来自<strong>"基础信息管理 → 农具档案管理"</strong>。
                    如需新增或编辑农具信息，请前往基础信息管理模块的农具档案。
                  </p>
                </div>
              </div>
              <Button 
                variant="outline" 
                className="text-info border-info hover:bg-info-muted"
                onClick={() => {
                  if (onNavigate) {
                    onNavigate('/asset/basic/tools');
                    toast.success('已跳转到基础信息管理-农具档案');
                  } else {
                    toast.info('请点击顶部导航栏「基础信息管理」，然后选择「农具档案」进行编辑', {
                      duration: 4000,
                    });
                  }
                }}
              >
                <Link2 className="w-4 h-4 mr-2" />
                前往农具档案
              </Button>
            </div>
          </Card>

          {/* 搜索和筛选 */}
          <Card className="p-4">
            <div className="flex gap-4">
              <div className="flex-1 relative">
                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
                <Input placeholder="搜索设备编号、名称、型号..." className="pl-9" />
              </div>
              <Select defaultValue="all-category">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="设备分类" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-category">全部分类</SelectItem>
                  <SelectItem value="power">动力机械</SelectItem>
                  <SelectItem value="plant-protection">植保机械</SelectItem>
                  <SelectItem value="harvest">收获机械</SelectItem>
                  <SelectItem value="tillage">耕整机械</SelectItem>
                  <SelectItem value="sowing">播种机械</SelectItem>
                </SelectContent>
              </Select>
              <Select defaultValue="all-status">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="使用状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-status">全部状态</SelectItem>
                  <SelectItem value="idle">空闲</SelectItem>
                  <SelectItem value="in-use">使用中</SelectItem>
                  <SelectItem value="maintenance">维修中</SelectItem>
                  <SelectItem value="dispatched">已调度</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 设备列表 */}
          <Card>
            <div className="p-4 border-b bg-muted">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <Package className="w-5 h-5 text-success" />
                  物资档案清单
                </h3>
                <div className="text-sm text-muted-foreground">
                  共 <span className="text-success font-medium">{equipmentList.length}</span> 条记录
                </div>
              </div>
            </div>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-32">设备编号</TableHead>
                    <TableHead className="w-48">设备名称</TableHead>
                    <TableHead className="w-32">分类</TableHead>
                    <TableHead className="w-36">型号/规格</TableHead>
                    <TableHead className="w-36">购买日期</TableHead>
                    <TableHead className="w-28">折旧年限</TableHead>
                    <TableHead className="w-32">购买价值</TableHead>
                    <TableHead className="w-32">当前价值</TableHead>
                    <TableHead className="w-28">使用次数</TableHead>
                    <TableHead className="w-28">使用状态</TableHead>
                    <TableHead className="w-32">存放位置</TableHead>
                    <TableHead className="w-28">责任人</TableHead>
                    <TableHead className="w-28">序列号</TableHead>
                    <TableHead className="w-24">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {equipmentList.map((equipment) => {
                    const depInfo = calculateDepreciation(equipment);
                    return (
                      <TableRow key={equipment.id}>
                        <TableCell className="font-medium text-info">{equipment.code}</TableCell>
                        <TableCell>
                          <div>
                            <div className="font-medium">{equipment.name}</div>
                            <div className="text-xs text-muted-foreground">{equipment.manufacturer}</div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="bg-muted text-foreground border-border">
                            {equipment.category}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm">{equipment.model}</TableCell>
                        <TableCell>
                          <div className="text-sm flex items-center gap-1">
                            <Calendar className="w-3 h-3 text-muted-foreground" />
                            {equipment.purchaseDate}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm">
                            <div className="font-medium">{equipment.depreciationYears}年</div>
                            <div className="text-xs text-muted-foreground">
                              已用{depInfo.monthsUsed}月
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm font-medium text-info">
                            ¥{equipment.purchasePrice.toLocaleString()}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm">
                            <div className="font-medium text-success">
                              ¥{equipment.currentValue.toLocaleString()}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              折旧{depInfo.depreciationRate.toFixed(1)}%
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm flex items-center gap-1">
                            <Timer className="w-3 h-3 text-muted-foreground" />
                            {equipment.usageHours}次
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge className={getStatusColor(equipment.status)}>{equipment.status}</Badge>
                        </TableCell>
                        <TableCell>
                          {equipment.location ? (
                            <div className="text-sm flex items-center gap-1">
                              <MapPin className="w-3 h-3 text-muted-foreground" />
                              {equipment.location}
                            </div>
                          ) : (
                            <span className="text-xs text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {equipment.assignedTo ? (
                            <div className="text-sm flex items-center gap-1">
                              <User className="w-3 h-3 text-muted-foreground" />
                              {equipment.assignedTo}
                            </div>
                          ) : (
                            <span className="text-xs text-muted-foreground">未分配</span>
                          )}
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {equipment.serialNumber || '-'}
                        </TableCell>
                        <TableCell>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                              setSelectedEquipment(equipment);
                              setShowEquipmentDialog(true);
                            }}
                            title="查看详情"
                          >
                            <Eye className="w-3 h-3" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          </Card>

          {/* 统计汇总 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-lg bg-success-muted flex items-center justify-center">
                  <DollarSign className="w-6 h-6 text-success" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">总购买价值</p>
                  <p className="text-xl font-medium text-success">
                    ¥{equipmentList.reduce((sum, e) => sum + e.purchasePrice, 0).toLocaleString()}
                  </p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-lg bg-info-muted flex items-center justify-center">
                  <TrendingDown className="w-6 h-6 text-info" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">总当前价值</p>
                  <p className="text-xl font-medium text-info">
                    ¥{totalValue.toLocaleString()}
                  </p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-lg bg-warning-muted flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-warning" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">累计折旧</p>
                  <p className="text-xl font-medium text-warning">
                    ¥{(equipmentList.reduce((sum, e) => sum + e.purchasePrice, 0) - totalValue).toLocaleString()}
                  </p>
                </div>
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 使用调度与状态 */}
        <TabsContent value="dispatch" className="space-y-4">
          {/* 功能说明 */}
          <Card className="p-4 bg-info-muted border-info">
            <div className="flex items-start gap-2">
              <Activity 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"><strong>使用调度与状态功能说明</strong></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>
                </ul>
              </div>
            </div>
          </Card>

          {/* 快速调度操作区 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 cursor-pointer hover:shadow-md transition-shadow bg-success-muted border-success">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-success flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-success">{idle}</p>
                  <p className="text-xs text-success">空闲可调度</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-success-muted-foreground">
                点击查看可用设备列表
              </div>
            </Card>

            <Card className="p-4 cursor-pointer hover:shadow-md transition-shadow bg-info-muted border-info">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-info flex items-center justify-center">
                  <PlayCircle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-info">{inUse}</p>
                  <p className="text-xs text-info">使用中</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-info-muted-foreground">
                正在执行作业任务
              </div>
            </Card>

            <Card className="p-4 cursor-pointer hover:shadow-md transition-shadow bg-warning-muted border-warning">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-warning flex items-center justify-center">
                  <Wrench className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-warning">{underMaintenance}</p>
                  <p className="text-xs text-warning">维修中</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-warning-muted-foreground">
                暂时不可调度
              </div>
            </Card>

            <Card className="p-4 cursor-pointer hover:shadow-md transition-shadow bg-muted border-border">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-foreground flex items-center justify-center">
                  <Send className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-foreground">{dispatchRecords.filter(r => r.status === '已调度').length}</p>
                  <p className="text-xs text-foreground">已调度</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-muted-foreground">
                任务已分配待执行
              </div>
            </Card>
          </div>

          {/* 数据可视化区 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <CircleDot className="w-4 h-4" />
                设备状态分布
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={statusChartData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, value }) => `${name}: ${value}`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {statusChartData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Gauge className="w-4 h-4" />
                设备使用率统计
              </h4>
              <div className="space-y-4">
                {equipmentList.map((eq) => (
                  <div key={eq.id}>
                    <div className="flex justify-between text-sm mb-1">
                      <span>{eq.name}</span>
                      <span>{((eq.usageHours / (calculateDepreciation(eq).monthsUsed * 30 * 8)) * 100).toFixed(1)}%</span>
                    </div>
                    <Progress value={(eq.usageHours / (calculateDepreciation(eq).monthsUsed * 30 * 8)) * 100} />
                  </div>
                ))}
              </div>
            </Card>
          </div>

          {/* 状态筛选器 */}
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm font-medium">状态筛选</span>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" className="text-xs">
                  全部状态
                </Button>
                <Button variant="outline" size="sm" className="text-xs border-success text-success hover:bg-success-muted">
                  <CheckCircle className="w-3 h-3 mr-1" />
                  空闲 ({idle})
                </Button>
                <Button variant="outline" size="sm" className="text-xs border-info text-info hover:bg-info-muted">
                  <PlayCircle className="w-3 h-3 mr-1" />
                  使用中 ({inUse})
                </Button>
                <Button variant="outline" size="sm" className="text-xs border-warning text-warning hover:bg-warning-muted">
                  <Wrench className="w-3 h-3 mr-1" />
                  维修中 ({underMaintenance})
                </Button>
                <Button variant="outline" size="sm" className="text-xs border-border text-foreground hover:bg-muted">
                  <Send className="w-3 h-3 mr-1" />
                  已调度
                </Button>
              </div>
            </div>
          </Card>

          {/* 设备调度状态表格 */}
          <Card>
            <div className="p-4 border-b bg-muted">
              <h3 className="flex items-center gap-2">
                <Settings className="w-5 h-5 text-info" />
                设备调度状态管理
              </h3>
            </div>
            <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-32">设备编号</TableHead>
                    <TableHead className="w-36">设备名称</TableHead>
                    <TableHead className="w-28">当前状态</TableHead>
                    <TableHead className="w-36">当前位置</TableHead>
                    <TableHead className="w-48">关联任务</TableHead>
                    <TableHead className="w-28">责任人</TableHead>
                    <TableHead className="w-48">时间信息</TableHead>
                    <TableHead className="w-48">备注说明</TableHead>
                    <TableHead className="w-24">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {dispatchRecords.map((record) => (
                    <TableRow key={record.id} className="hover:bg-muted/50">
                      <TableCell className="font-medium text-info">{record.equipmentCode}</TableCell>
                      <TableCell>
                        <div className="font-medium">{record.equipmentName}</div>
                      </TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(record.status)}>{record.status}</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1 text-sm">
                          <MapPin className="w-3 h-3 text-muted-foreground" />
                          {record.currentLocation}
                        </div>
                      </TableCell>
                      <TableCell>
                        {record.assignedTask ? (
                          <div className="text-sm">
                            <div className="font-medium text-info">{record.assignedTask}</div>
                            {record.startTime && (
                              <div className="text-xs text-muted-foreground mt-1">
                                开始于 {record.startTime}
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-muted-foreground text-sm">无任务</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {record.assignedTo ? (
                          <div className="flex items-center gap-1 text-sm">
                            <User className="w-3 h-3 text-muted-foreground" />
                            {record.assignedTo}
                          </div>
                        ) : (
                          <span className="text-muted-foreground text-sm">未分配</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="text-xs space-y-1">
                          {record.startTime && (
                            <div className="flex items-center gap-1">
                              <Clock className="w-3 h-3 text-success" />
                              <span>开始: {record.startTime}</span>
                            </div>
                          )}
                          {record.estimatedEndTime && (
                            <div className="flex items-center gap-1 text-muted-foreground">
                              <Calendar className="w-3 h-3" />
                              <span>预计: {record.estimatedEndTime}</span>
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {record.notes || '-'}
                      </TableCell>
                      <TableCell>
                        <Button 
                          size="sm" 
                          variant="outline" 
                          title="查看详情"
                          onClick={() => {
                            setSelectedDispatchRecord(record);
                            setShowDispatchDetailDialog(true);
                          }}
                        >
                          <Eye className="w-3 h-3" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 维修保养 */}
        <TabsContent value="maintenance" className="space-y-4">
          {/* 功能说明 */}
          <Card className="p-4 bg-warning-muted border-warning">
            <div className="flex items-start gap-2">
              <Wrench className="w-5 h-5 text-warning flex-shrink-0 mt-0.5" />
              <div className="text-sm text-warning-muted-foreground">
                <p className="mb-2"><strong>维修保养功能说明</strong></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>
                </ul>
              </div>
            </div>
          </Card>

          {/* 维修保养概览 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 bg-error-muted border-error">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-error flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-error">
                    {maintenancePlans.filter(p => p.status === '逾期').length}
                  </p>
                  <p className="text-xs text-error">逾期保养</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-error-muted-foreground">
                需立即处理
              </div>
            </Card>

            <Card className="p-4 bg-warning-muted border-warning">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-warning flex items-center justify-center">
                  <Clock className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-warning">
                    {maintenancePlans.filter(p => p.status === '即将到期').length}
                  </p>
                  <p className="text-xs text-warning">即将到期</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-warning-muted-foreground">
                7天内需保养
              </div>
            </Card>

            <Card className="p-4 bg-info-muted border-info">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-info flex items-center justify-center">
                  <Wrench className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-info">
                    {maintenanceRecords.filter(r => r.status === '进行中').length}
                  </p>
                  <p className="text-xs text-info">维修中</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-info-muted-foreground">
                正在维修处理
              </div>
            </Card>

            <Card className="p-4 bg-success-muted border-success">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-success flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-success">
                    {maintenanceRecords.filter(r => r.status === '已完成').length}
                  </p>
                  <p className="text-xs text-success">本月完成</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-success-muted-foreground">
                维修保养记录
              </div>
            </Card>
          </div>

          {/* 快捷操作 */}
          <div className="flex flex-wrap gap-4">
            <Button className="bg-warning hover:bg-warning/90" onClick={() => setShowMaintenanceDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              创建维修工单
            </Button>
            <Button className="bg-info hover:bg-info/90" onClick={() => setShowPlanDialog(true)}>
              <Calendar className="w-4 h-4 mr-2" />
              新建保养计划
            </Button>
          </div>

          {/* 保养计划管理 */}
          <Card>
            <div className="p-4 border-b bg-muted">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <Calendar className="w-5 h-5 text-info" />
                  保养计划管理
                </h3>
                <div className="flex items-center gap-2">
                  <Button variant="outline" size="sm">
                    <Filter className="w-3 h-3 mr-1" />
                    筛选
                  </Button>
                  <Button variant="outline" size="sm">
                    <RefreshCcw className="w-3 h-3 mr-1" />
                    刷新
                  </Button>
                </div>
              </div>
            </div>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-32">设备编号</TableHead>
                    <TableHead className="w-36">设备名称</TableHead>
                    <TableHead className="w-28">计划类型</TableHead>
                    <TableHead className="w-36">保养间隔</TableHead>
                    <TableHead className="w-32">上次保养</TableHead>
                    <TableHead className="w-32">下次保养</TableHead>
                    <TableHead className="w-28">剩余天数</TableHead>
                    <TableHead className="w-28">计划状态</TableHead>
                    <TableHead className="w-28">自动提醒</TableHead>
                    <TableHead className="w-48">保养内容</TableHead>
                    <TableHead className="w-36">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {maintenancePlans.map((plan) => {
                    // 计算剩余天数
                    const daysLeft = Math.ceil((new Date(plan.nextMaintenanceDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
                    
                    return (
                      <TableRow key={plan.id} className="hover:bg-muted/50">
                        <TableCell className="font-medium text-info">{plan.equipmentCode}</TableCell>
                        <TableCell>
                          <div className="font-medium">{plan.equipmentName}</div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className={
                            plan.planType === '按时间' ? 'border-info text-info' :
                            'border-border text-foreground'
                          }>
                            {plan.planType}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm">
                            <div className="font-medium">
                              每 {plan.interval}{plan.intervalUnit}
                            </div>
                            {plan.planType === '按工作量' && (
                              <div className="text-xs text-muted-foreground mt-1">
                                当前: {plan.currentUsage || 0}小时
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-sm">
                          {plan.lastMaintenanceDate ? (
                            <div>
                              <div>{plan.lastMaintenanceDate}</div>
                              <div className="text-xs text-muted-foreground mt-1">
                                {Math.ceil((new Date().getTime() - new Date(plan.lastMaintenanceDate).getTime()) / (1000 * 60 * 60 * 24))}天前
                              </div>
                            </div>
                          ) : (
                            <span className="text-muted-foreground">未保养</span>
                          )}
                        </TableCell>
                        <TableCell className="text-sm">
                          <div>{plan.nextMaintenanceDate}</div>
                          {daysLeft > 0 && daysLeft <= 7 && (
                            <div className="text-xs text-warning mt-1 flex items-center gap-1">
                              <AlertTriangle className="w-3 h-3" />
                              即将到期
                            </div>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className={`text-sm font-medium ${
                            daysLeft < 0 ? 'text-error' :
                            daysLeft <= 7 ? 'text-warning' :
                            'text-success'
                          }`}>
                            {daysLeft < 0 ? `逾期${Math.abs(daysLeft)}天` :
                             daysLeft === 0 ? '今天' :
                             `${daysLeft}天`}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge className={getMaintenanceStatusColor(plan.status)}>
                            {plan.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            {plan.autoRemind ? (
                              <>
                                <CheckCircle className="w-4 h-4 text-success" />
                                <span className="text-xs text-success">已启用</span>
                              </>
                            ) : (
                              <>
                                <XCircle className="w-4 h-4 text-muted-foreground" />
                                <span className="text-xs text-muted-foreground">未启用</span>
                              </>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm">
                            {plan.maintenanceItems?.slice(0, 2).map((item, idx) => (
                              <div key={idx} className="text-xs text-muted-foreground">
                                • {item}
                              </div>
                            )) || <span className="text-muted-foreground">-</span>}
                            {(plan.maintenanceItems?.length || 0) > 2 && (
                              <div className="text-xs text-info mt-1">
                                +{plan.maintenanceItems!.length - 2}项
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            <Button 
                              size="sm" 
                              variant="outline" 
                              title="查看详情"
                              onClick={() => handleViewPlanDetail(plan)}
                            >
                              <Eye className="w-3 h-3" />
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline" 
                              title="编辑计划"
                              onClick={() => handleEditPlan(plan)}
                            >
                              <Edit className="w-3 h-3" />
                            </Button>
                            {daysLeft <= 7 && (
                              <Button 
                                size="sm" 
                                className="bg-success hover:bg-success/90" 
                                title="执行保养"
                                onClick={() => handleExecuteMaintenance(plan)}
                              >
                                <Play className="w-3 h-3" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          </Card>

          {/* 维修工单记录 */}
          <Card>
            <div className="p-4 border-b bg-muted">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-warning" />
                  维修工单记录
                </h3>
                <div className="flex items-center gap-2">
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" className="text-xs">
                      全部工单
                    </Button>
                    <Button variant="outline" size="sm" className="text-xs border-warning text-warning hover:bg-warning-muted">
                      待处理 ({maintenanceRecords.filter(r => r.status === '待处理').length})
                    </Button>
                    <Button variant="outline" size="sm" className="text-xs border-info text-info hover:bg-info-muted">
                      进行中 ({maintenanceRecords.filter(r => r.status === '进行中').length})
                    </Button>
                    <Button variant="outline" size="sm" className="text-xs border-success text-success hover:bg-success-muted">
                      已完成 ({maintenanceRecords.filter(r => r.status === '已完成').length})
                    </Button>
                  </div>
                </div>
              </div>
            </div>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-24">工单号</TableHead>
                    <TableHead className="w-32">设备信息</TableHead>
                    <TableHead className="w-24">维修类型</TableHead>
                    <TableHead className="w-28">故障描述</TableHead>
                    <TableHead className="w-24">维修人员</TableHead>
                    <TableHead className="w-40">维修时间</TableHead>
                    <TableHead className="w-20">耗时</TableHead>
                    <TableHead className="w-36">费用明细</TableHead>
                    <TableHead className="w-24">总费用</TableHead>
                    <TableHead className="w-24">工单状态</TableHead>
                    <TableHead className="w-32">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {maintenanceRecords.map((record) => (
                    <TableRow key={record.id} className="hover:bg-muted/50">
                      <TableCell className="font-medium text-warning">{record.workOrderNo}</TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div className="font-medium">{record.equipmentName}</div>
                          <div className="text-xs text-muted-foreground">{record.equipmentCode}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className={
                          record.maintenanceType === '紧急维修' ? 'border-error text-error' :
                          record.maintenanceType === '定期保养' ? 'border-info text-info' :
                          'border-warning text-warning'
                        }>
                          {record.maintenanceType}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div className="line-clamp-2">{record.description}</div>
                          {record.faultLevel && (
                            <Badge variant="outline" className="mt-1 text-xs">
                              {record.faultLevel}
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div className="flex items-center gap-1">
                            <User className="w-3 h-3 text-muted-foreground" />
                            {record.technician}
                          </div>
                          {record.technicianPhone && (
                            <div className="text-xs text-muted-foreground mt-1">
                              {record.technicianPhone}
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm space-y-1">
                          <div className="flex items-center gap-1">
                            <Clock className="w-3 h-3 text-success" />
                            <span className="text-xs">开始: {record.startTime}</span>
                          </div>
                          {record.endTime ? (
                            <div className="flex items-center gap-1">
                              <CheckCircle className="w-3 h-3 text-info" />
                              <span className="text-xs">结束: {record.endTime}</span>
                            </div>
                          ) : (
                            <div className="text-xs text-warning">
                              维修中...
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm font-medium flex items-center gap-1">
                          <Timer className="w-3 h-3 text-info" />
                          {record.duration}h
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm space-y-1">
                          <div className="font-medium text-muted-foreground text-xs">配件费用:</div>
                          {record.parts.slice(0, 2).map((part, idx) => (
                            <div key={idx} className="text-xs">
                              • {part.name} x{part.quantity}: ¥{part.cost}
                            </div>
                          ))}
                          {record.parts.length > 2 && (
                            <div className="text-xs text-info">
                              +{record.parts.length - 2}项配件
                            </div>
                          )}
                          <div className="text-xs text-muted-foreground border-t pt-1 mt-1">
                            人工费: ¥{record.laborCost}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="font-medium text-warning text-base">
                          ¥{record.totalCost.toLocaleString()}
                        </div>
                        <div className="text-xs text-muted-foreground mt-1">
                          {record.paymentStatus || '未结算'}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={
                          record.status === '已完成' ? 'bg-success-muted text-success' :
                          record.status === '进行中' ? 'bg-info-muted text-info' :
                          'bg-warning-muted text-warning'
                        }>
                          {record.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button 
                            size="sm" 
                            variant="outline" 
                            title="查看详情"
                            onClick={() => handleViewWorkOrderDetail(record)}
                          >
                            <Eye className="w-3 h-3" />
                          </Button>
                          {record.status === '待处理' && (
                            <Button 
                              size="sm" 
                              className="bg-info hover:bg-info/90" 
                              title="开始处理"
                              onClick={() => handleProcessWorkOrder(record)}
                            >
                              <Play className="w-3 h-3" />
                            </Button>
                          )}
                          {record.status === '进行中' && (
                            <Button 
                              size="sm" 
                              className="bg-success hover:bg-success/90" 
                              title="完成工单"
                              onClick={() => handleCompleteWorkOrder(record)}
                            >
                              <CheckCircle className="w-3 h-3" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>

        {/* 折旧计算 */}
        <TabsContent value="depreciation" className="space-y-4">
          {/* 功能说明 */}
          <Card className="p-4 bg-muted border-border">
            <div className="flex items-start gap-2">
              <TrendingDown className="w-5 h-5 text-foreground flex-shrink-0 mt-0.5" />
              <div className="text-sm text-muted-foreground">
                <p className="mb-2"><strong>折旧计算功能说明</strong></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>
                </ul>
              </div>
            </div>
          </Card>

          {/* 折旧概览 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 bg-info-muted border-info">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-info flex items-center justify-center">
                  <DollarSign className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-info">
                    ¥{depreciationRecords.reduce((sum, r) => sum + r.purchasePrice, 0).toLocaleString()}
                  </p>
                  <p className="text-xs text-info">资产总原值</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-info-muted-foreground">
                在用设备原值
              </div>
            </Card>

            <Card className="p-4 bg-error-muted border-error">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-error flex items-center justify-center">
                  <TrendingDown className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-error">
                    ¥{depreciationRecords.reduce((sum, r) => sum + r.accumulatedDepreciation, 0).toLocaleString()}
                  </p>
                  <p className="text-xs text-error">累计折旧</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-error-muted-foreground">
                已计提折旧额
              </div>
            </Card>

            <Card className="p-4 bg-success-muted border-success">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-success flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-success">
                    ¥{depreciationRecords.reduce((sum, r) => sum + r.currentValue, 0).toLocaleString()}
                  </p>
                  <p className="text-xs text-success">资产净值</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-success-muted-foreground">
                当前账面价值
              </div>
            </Card>

            <Card className="p-4 bg-muted border-border">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-foreground flex items-center justify-center">
                  <BarChart3 className="w-6 h-6 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-medium text-foreground">
                    {depreciationRecords.length > 0 
                      ? ((depreciationRecords.reduce((sum, r) => sum + r.accumulatedDepreciation, 0) / 
                         depreciationRecords.reduce((sum, r) => sum + r.purchasePrice, 0)) * 100).toFixed(1)
                      : 0}%
                  </p>
                  <p className="text-xs text-foreground">平均折旧率</p>
                </div>
              </div>
              <div className="mt-3 text-xs text-muted-foreground">
                整体折旧水平
              </div>
            </Card>
          </div>

          {/* 折旧计算方法选择 */}
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-indigo-50 border-purple-200">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-lg bg-purple-600 flex items-center justify-center flex-shrink-0">
                <Calculator className="w-5 h-5 text-white" />
              </div>
              <div className="flex-1">
                <h4 className="font-medium text-purple-900 mb-3">💡 选择折旧计算方法</h4>
                <div className="flex items-center gap-4">
                  <label className="flex items-center gap-2 cursor-pointer group">
                    <input
                      type="radio"
                      name="depreciationMethod"
                      value="直线法"
                      checked={selectedCalculationMethod === '直线法'}
                      onChange={(e) => setSelectedCalculationMethod(e.target.value as '直线法' | '工作量法')}
                      className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                    />
                    <div className="flex items-center gap-2">
                      <Cpu className="w-4 h-4 text-blue-600" />
                      <span className="text-sm font-medium text-gray-900 group-hover:text-blue-600">直线法（平均年限法）</span>
                    </div>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer group">
                    <input
                      type="radio"
                      name="depreciationMethod"
                      value="工作量法"
                      checked={selectedCalculationMethod === '工作量法'}
                      onChange={(e) => setSelectedCalculationMethod(e.target.value as '直线法' | '工作量法')}
                      className="w-4 h-4 text-green-600 focus:ring-green-500"
                    />
                    <div className="flex items-center gap-2">
                      <Timer className="w-4 h-4 text-green-600" />
                      <span className="text-sm font-medium text-gray-900 group-hover:text-green-600">工作量法</span>
                    </div>
                  </label>
                </div>
                <div className="mt-3 text-xs text-purple-700 bg-white p-3 rounded-lg border border-purple-200">
                  <p className="flex items-center gap-2">
                    <AlertCircle className="w-4 h-4 flex-shrink-0" />
                    <span>
                      当前使用 <strong className={selectedCalculationMethod === '直线法' ? 'text-blue-600' : 'text-green-600'}>{selectedCalculationMethod}</strong> 计算所有设备的折旧。
                      切换方法后，系统会自动重新计算所有设备的折旧数据。
                    </span>
                  </p>
                </div>
              </div>
            </div>
          </Card>

          {/* 折旧方法说明 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-600 flex items-center justify-center flex-shrink-0">
                  <Cpu className="w-5 h-5 text-white" />
                </div>
                <div className="flex-1">
                  <h4 className="font-medium text-blue-900 mb-2">直线法（平均年限法）</h4>
                  <div className="bg-white p-3 rounded-lg border border-blue-200 mb-3">
                    <p className="text-sm font-medium text-blue-900 mb-2">计算公式：</p>
                    <div className="text-xs space-y-1">
                      <p>年折旧额 = 原值 / 预计使用年限</p>
                      <p>月折旧额 = 年折旧额 / 12</p>
                    </div>
                  </div>
                  <div className="text-xs">
                    <p className="font-medium text-blue-900 mb-1">适用场景：</p>
                    <ul className="space-y-1 text-muted-foreground">
                      <li>• 使用价值均匀递减的资产</li>
                      <li>• 工作负荷较为均衡的设备</li>
                      <li>• 最常用、最简单的折旧方法</li>
                      <li>• 适用于大部分农机设备</li>
                    </ul>
                  </div>
                </div>
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 border-green-200">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-lg bg-green-600 flex items-center justify-center flex-shrink-0">
                  <Timer className="w-5 h-5 text-white" />
                </div>
                <div className="flex-1">
                  <h4 className="font-medium text-green-900 mb-2">工作量法</h4>
                  <div className="bg-white p-3 rounded-lg border border-green-200 mb-3">
                    <p className="text-sm font-medium text-green-900 mb-2">计算公式：</p>
                    <div className="text-xs space-y-1">
                      <p>单位折旧额 = 原值 / 预计总工作量</p>
                      <p>折旧额 = 单位折旧额 × 实际工作量</p>
                      <p className="text-muted-foreground mt-2">工作量单位：工作小时、公里数等</p>
                    </div>
                  </div>
                  <div className="text-xs">
                    <p className="font-medium text-green-900 mb-1">适用场景：</p>
                    <ul className="space-y-1 text-muted-foreground">
                      <li>• 使用程度很不均匀的资产</li>
                      <li>• 按工作量折旧更合理</li>
                      <li>• 如拖拉机按工作小时计算</li>
                      <li>• 更能反映资产实际损耗</li>
                    </ul>
                  </div>
                </div>
              </div>
            </Card>
          </div>

          {/* 折旧计算明细表 */}
          <Card>
            <div className="p-4 border-b bg-gray-50">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <BarChart3 className="w-5 h-5 text-purple-600" />
                  资产折旧明细表
                </h3>
                <div className="flex items-center gap-2">
                  <Select defaultValue="all-equipment">
                    <SelectTrigger className="w-48">
                      <SelectValue placeholder="按设备名称筛选" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all-equipment">全部设备</SelectItem>
                      {depreciationRecords.map((record) => (
                        <SelectItem key={record.id} value={record.equipmentName}>
                          {record.equipmentName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-32">设备编号</TableHead>
                    <TableHead className="w-36">设备名称</TableHead>
                    <TableHead className="w-28">购买日期</TableHead>
                    <TableHead className="w-32">资产原值</TableHead>
                    <TableHead className="w-28">折旧方法</TableHead>
                    <TableHead className="w-24">折旧年限</TableHead>
                    <TableHead className="w-28">已使用时间</TableHead>
                    <TableHead className="w-32">工作量</TableHead>
                    <TableHead className="w-32">年折旧额</TableHead>
                    <TableHead className="w-32">月折旧额</TableHead>
                    <TableHead className="w-32">累计折旧</TableHead>
                    <TableHead className="w-32">资产净值</TableHead>
                    <TableHead className="w-32">折旧进度</TableHead>
                    <TableHead className="w-28">残值率</TableHead>
                    <TableHead className="w-36">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {depreciationRecords.map((record) => {
                    const monthlyDepreciation = record.annualDepreciation / 12;
                    const salvageRate = 5; // 残值率5%
                    
                    return (
                      <TableRow key={record.id} className="hover:bg-gray-50">
                        <TableCell className="font-medium text-purple-600">{record.equipmentCode}</TableCell>
                        <TableCell>
                          <div className="font-medium">{record.equipmentName}</div>
                        </TableCell>
                        <TableCell className="text-sm">{record.purchaseDate}</TableCell>
                        <TableCell>
                          <div className="font-medium text-blue-600">
                            ¥{record.purchasePrice.toLocaleString()}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className={
                            record.depreciationMethod === '直线法' ? 'border-blue-300 text-blue-600' :
                            'border-green-300 text-green-600'
                          }>
                            {record.depreciationMethod}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm">
                          <div className="font-medium">{record.depreciationYears}年</div>
                        </TableCell>
                        <TableCell className="text-sm">
                          <div>
                            <div className="font-medium">{record.usedMonths}个月</div>
                            <div className="text-xs text-muted-foreground">
                              ({(record.usedMonths / 12).toFixed(1)}年)
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="text-sm">
                          {record.usageHours ? (
                            <div>
                              <div className="font-medium">{record.usageHours}h</div>
                              <div className="text-xs text-muted-foreground">
                                / {record.totalWorkload}h
                              </div>
                              <Progress 
                                value={(record.usageHours / (record.totalWorkload || 1)) * 100} 
                                className="w-16 h-1 mt-1" 
                              />
                            </div>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="font-medium text-orange-600">
                            ¥{record.annualDepreciation.toLocaleString()}
                          </div>
                          <div className="text-xs text-muted-foreground mt-1">
                            {((record.annualDepreciation / record.purchasePrice) * 100).toFixed(1)}%
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="font-medium text-orange-600">
                            ¥{monthlyDepreciation.toLocaleString()}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="font-medium text-red-600">
                            ¥{record.accumulatedDepreciation.toLocaleString()}
                          </div>
                          <div className="text-xs text-muted-foreground mt-1">
                            {record.depreciationRate}%
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="font-medium text-green-600 text-base">
                            ¥{record.currentValue.toLocaleString()}
                          </div>
                          <div className="text-xs text-muted-foreground mt-1">
                            剩余{((record.currentValue / record.purchasePrice) * 100).toFixed(1)}%
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="space-y-2">
                            <div className="flex items-center gap-2">
                              <Progress value={record.depreciationRate} className="w-20 h-2" />
                              <span className="text-sm font-medium">{record.depreciationRate}%</span>
                            </div>
                            <div className="text-xs">
                              {record.depreciationRate >= 80 ? (
                                <span className="text-red-600">⚠️ 接近报废</span>
                              ) : record.depreciationRate >= 50 ? (
                                <span className="text-yellow-600">⚠️ 过半折旧</span>
                              ) : (
                                <span className="text-green-600">✓ 状态良好</span>
                              )}
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm font-medium text-blue-600">{salvageRate}%</div>
                          <div className="text-xs text-muted-foreground mt-1">
                            ¥{(record.purchasePrice * salvageRate / 100).toLocaleString()}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            <Button 
                              size="sm" 
                              variant="outline" 
                              title="查看详情"
                              onClick={() => {
                                setSelectedDepreciationRecord(record);
                                setShowDepreciationViewDialog(true);
                              }}
                            >
                              <Eye className="w-3 h-3" />
                            </Button>
                            <Button 
                              size="sm" 
                              className="bg-blue-600 hover:bg-blue-700"
                              title="折旧明细"
                              onClick={() => {
                                setSelectedDepreciationRecord(record);
                                setShowDepreciationDetailDialog(true);
                              }}
                            >
                              <FileText className="w-3 h-3" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          </Card>

          {/* 折旧明细弹窗 */}
          <Dialog open={showDepreciationDetailDialog} onOpenChange={setShowDepreciationDetailDialog}>
            <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-blue-600" />
                  折旧明细详情
                </DialogTitle>
                <DialogDescription>
                  查看资产的完整折旧计算明细和历史记录
                </DialogDescription>
              </DialogHeader>

              {selectedDepreciationRecord && (
                <div className="space-y-6">
                  {/* 设备基本信息 */}
                  <Card className="p-4 bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200">
                    <h4 className="mb-3 flex items-center gap-2">
                      <Box className="w-4 h-4 text-blue-600" />
                      设备基本信息
                    </h4>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <div className="text-muted-foreground mb-1">设备编号</div>
                        <div className="font-medium">{selectedDepreciationRecord.equipmentCode}</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">设备名称</div>
                        <div className="font-medium">{selectedDepreciationRecord.equipmentName}</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">购买日期</div>
                        <div className="font-medium">{selectedDepreciationRecord.purchaseDate}</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">购买原值</div>
                        <div className="font-medium text-blue-600">¥{selectedDepreciationRecord.purchasePrice.toLocaleString()}</div>
                      </div>
                    </div>
                  </Card>

                  {/* 折旧计算参数 */}
                  <Card className="p-4">
                    <h4 className="mb-3 flex items-center gap-2">
                      <Calculator className="w-4 h-4 text-purple-600" />
                      折旧计算参数
                    </h4>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <div className="text-muted-foreground mb-1">折旧方法</div>
                        <Badge className="bg-purple-600">{selectedDepreciationRecord.depreciationMethod}</Badge>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">折旧年限</div>
                        <div className="font-medium">{selectedDepreciationRecord.depreciationYears}年</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">已使用时间</div>
                        <div className="font-medium">{selectedDepreciationRecord.usedMonths}个月</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">年折旧额</div>
                        <div className="font-medium text-orange-600">¥{selectedDepreciationRecord.annualDepreciation.toLocaleString()}/年</div>
                      </div>
                      {selectedDepreciationRecord.depreciationMethod === '工作量法' && (
                        <>
                          <div>
                            <div className="text-muted-foreground mb-1">累计工作量</div>
                            <div className="font-medium">{selectedDepreciationRecord.usageHours || 0}小时</div>
                          </div>
                          <div>
                            <div className="text-muted-foreground mb-1">预计总工作量</div>
                            <div className="font-medium">{selectedDepreciationRecord.totalWorkload || 0}小时</div>
                          </div>
                          <div>
                            <div className="text-muted-foreground mb-1">单位折旧额</div>
                            <div className="font-medium text-green-600">
                              ¥{selectedDepreciationRecord.totalWorkload 
                                ? (selectedDepreciationRecord.purchasePrice / selectedDepreciationRecord.totalWorkload).toFixed(2)
                                : '0'}/小时
                            </div>
                          </div>
                        </>
                      )}
                    </div>
                  </Card>

                  {/* 折旧状态总览 */}
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-blue-600 flex items-center justify-center">
                          <DollarSign className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">累计折旧</div>
                          <div className="text-xl font-medium text-blue-600">
                            ¥{selectedDepreciationRecord.accumulatedDepreciation.toLocaleString()}
                          </div>
                        </div>
                      </div>
                    </Card>

                    <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 border-green-200">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-green-600 flex items-center justify-center">
                          <TrendingUp className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">资产净值</div>
                          <div className="text-xl font-medium text-green-600">
                            ¥{selectedDepreciationRecord.currentValue.toLocaleString()}
                          </div>
                        </div>
                      </div>
                    </Card>

                    <Card className="p-4 bg-gradient-to-br from-orange-50 to-orange-100 border-orange-200">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-orange-600 flex items-center justify-center">
                          <TrendingDown className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">折旧率</div>
                          <div className="text-xl font-medium text-orange-600">
                            {selectedDepreciationRecord.depreciationRate.toFixed(1)}%
                          </div>
                        </div>
                      </div>
                    </Card>

                    <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-purple-600 flex items-center justify-center">
                          <Timer className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">使用进度</div>
                          <div className="text-xl font-medium text-purple-600">
                            {((selectedDepreciationRecord.usedMonths / (selectedDepreciationRecord.depreciationYears * 12)) * 100).toFixed(1)}%
                          </div>
                        </div>
                      </div>
                    </Card>
                  </div>

                  {/* 折旧趋势图表 */}
                  <Card className="p-4">
                    <h4 className="mb-4 flex items-center gap-2">
                      <BarChart3 className="w-4 h-4 text-blue-600" />
                      折旧趋势分析
                    </h4>
                    <ResponsiveContainer width="100%" height={250}>
                      <AreaChart
                        data={Array.from({ length: Math.min(selectedDepreciationRecord.usedMonths + 1, 13) }, (_, i) => {
                          const monthlyDepreciation = selectedDepreciationRecord.annualDepreciation / 12;
                          const accumulated = monthlyDepreciation * i;
                          return {
                            month: `第${i}月`,
                            累计折旧: Math.round(accumulated),
                            资产净值: Math.round(selectedDepreciationRecord.purchasePrice - accumulated),
                          };
                        })}
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="month" />
                        <YAxis />
                        <RechartsTooltip />
                        <Legend />
                        <Area 
                          type="monotone" 
                          dataKey="累计折旧" 
                          stackId="1"
                          stroke="#ef4444" 
                          fill="#fecaca" 
                        />
                        <Area 
                          type="monotone" 
                          dataKey="资产净值" 
                          stackId="1"
                          stroke="#10b981" 
                          fill="#86efac" 
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  </Card>

                  {/* 月度折旧明细表 */}
                  {selectedDepreciationRecord.depreciationMethod === '直线法' && (
                    <Card className="p-4">
                      <h4 className="mb-4 flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-green-600" />
                        月度折旧明细（最近12个月）
                      </h4>
                      <div className="overflow-x-auto">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>期数</TableHead>
                              <TableHead>月份</TableHead>
                              <TableHead className="text-right">月折旧额</TableHead>
                              <TableHead className="text-right">累计折旧</TableHead>
                              <TableHead className="text-right">账面净值</TableHead>
                              <TableHead className="text-right">折旧率</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {Array.from({ length: Math.min(selectedDepreciationRecord.usedMonths, 12) }, (_, i) => {
                              const monthlyDepreciation = selectedDepreciationRecord.annualDepreciation / 12;
                              const period = i + 1;
                              const accumulated = monthlyDepreciation * period;
                              const netValue = selectedDepreciationRecord.purchasePrice - accumulated;
                              const rate = (accumulated / selectedDepreciationRecord.purchasePrice) * 100;
                              
                              // 计算日期
                              const purchaseDate = new Date(selectedDepreciationRecord.purchaseDate);
                              const currentDate = new Date(purchaseDate);
                              currentDate.setMonth(currentDate.getMonth() + period);
                              const dateStr = `${currentDate.getFullYear()}年${currentDate.getMonth() + 1}月`;

                              return (
                                <TableRow key={i}>
                                  <TableCell>{period}</TableCell>
                                  <TableCell>{dateStr}</TableCell>
                                  <TableCell className="text-right">¥{monthlyDepreciation.toLocaleString()}</TableCell>
                                  <TableCell className="text-right text-orange-600">¥{accumulated.toLocaleString()}</TableCell>
                                  <TableCell className="text-right text-green-600">¥{netValue.toLocaleString()}</TableCell>
                                  <TableCell className="text-right">
                                    <Badge variant="outline">{rate.toFixed(2)}%</Badge>
                                  </TableCell>
                                </TableRow>
                              );
                            })}
                          </TableBody>
                        </Table>
                      </div>
                    </Card>
                  )}

                  {/* 工作量折旧明细 */}
                  {selectedDepreciationRecord.depreciationMethod === '工作量法' && (
                    <Card className="p-4">
                      <h4 className="mb-4 flex items-center gap-2">
                        <Gauge className="w-4 h-4 text-green-600" />
                        工作量折旧明细
                      </h4>
                      <div className="space-y-4">
                        <div className="grid grid-cols-2 md:grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">单位折旧额</div>
                            <div className="font-medium text-blue-600">
                              ¥{selectedDepreciationRecord.totalWorkload 
                                ? (selectedDepreciationRecord.purchasePrice / selectedDepreciationRecord.totalWorkload).toFixed(2)
                                : '0'}/小时
                            </div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">累计工作量</div>
                            <div className="font-medium">{selectedDepreciationRecord.usageHours || 0}小时</div>
                          </div>
                          <div>
                            <div className="text-xs text-muted-foreground mb-1">工作量完成度</div>
                            <div className="font-medium text-purple-600">
                              {selectedDepreciationRecord.totalWorkload
                                ? ((selectedDepreciationRecord.usageHours || 0) / selectedDepreciationRecord.totalWorkload * 100).toFixed(1)
                                : '0'}%
                            </div>
                          </div>
                        </div>
                        
                        <div className="space-y-2">
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">工作量进度</span>
                            <span className="font-medium">
                              {selectedDepreciationRecord.usageHours || 0} / {selectedDepreciationRecord.totalWorkload || 0} 小时
                            </span>
                          </div>
                          <Progress 
                            value={selectedDepreciationRecord.totalWorkload
                              ? ((selectedDepreciationRecord.usageHours || 0) / selectedDepreciationRecord.totalWorkload * 100)
                              : 0
                            } 
                            className="h-3"
                          />
                        </div>

                        <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                          <div className="flex items-start gap-2 text-sm">
                            <AlertCircle className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                            <div>
                              <div className="font-medium text-blue-900 mb-1">工作量法说明</div>
                              <div className="text-blue-700 text-xs">
                                工作量法根据实际使用时间计算折旧，每工作1小时折旧
                                ¥{selectedDepreciationRecord.totalWorkload 
                                  ? (selectedDepreciationRecord.purchasePrice / selectedDepreciationRecord.totalWorkload).toFixed(2)
                                  : '0'}，
                                当前已累计折旧¥{selectedDepreciationRecord.accumulatedDepreciation.toLocaleString()}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </Card>
                  )}

                  {/* 残值信息 */}
                  <Card className="p-4 bg-gradient-to-r from-gray-50 to-gray-100 border-gray-200">
                    <h4 className="mb-3 flex items-center gap-2">
                      <Archive className="w-4 h-4 text-gray-600" />
                      残值信息
                    </h4>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <div className="text-muted-foreground mb-1">残值率</div>
                        <div className="font-medium">5%</div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">预计残值</div>
                        <div className="font-medium text-gray-600">
                          ¥{(selectedDepreciationRecord.purchasePrice * 0.05).toLocaleString()}
                        </div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">剩余年限</div>
                        <div className="font-medium">
                          {Math.max(0, selectedDepreciationRecord.depreciationYears - Math.floor(selectedDepreciationRecord.usedMonths / 12))}年
                          {selectedDepreciationRecord.usedMonths % 12}个月
                        </div>
                      </div>
                      <div>
                        <div className="text-muted-foreground mb-1">预计报废日期</div>
                        <div className="font-medium">
                          {(() => {
                            const date = new Date(selectedDepreciationRecord.purchaseDate);
                            date.setFullYear(date.getFullYear() + selectedDepreciationRecord.depreciationYears);
                            return date.toLocaleDateString('zh-CN');
                          })()}
                        </div>
                      </div>
                    </div>
                  </Card>
                </div>
              )}

              <DialogFooter>
                <Button variant="outline" onClick={() => setShowDepreciationDetailDialog(false)}>
                  关闭
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          {/* 查看详情弹窗 */}
          <Dialog open={showDepreciationViewDialog} onOpenChange={setShowDepreciationViewDialog}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <Eye className="w-5 h-5 text-green-600" />
                  资产详情
                </DialogTitle>
                <DialogDescription>
                  查看资产的完整信息和当前状态
                </DialogDescription>
              </DialogHeader>

              {selectedDepreciationRecord && (
                <div className="space-y-6">
                  {/* 设备基本信息 */}
                  <Card className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
                    <h4 className="mb-4 flex items-center gap-2">
                      <Box className="w-4 h-4 text-green-600" />
                      设备基本信息
                    </h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                      <div className="flex items-start gap-3 p-3 bg-white rounded-lg border border-green-100">
                        <div className="w-8 h-8 rounded-lg bg-green-100 flex items-center justify-center flex-shrink-0">
                          <Tag className="w-4 h-4 text-green-600" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">设备编号</div>
                          <div className="font-medium text-green-900">{selectedDepreciationRecord.equipmentCode}</div>
                        </div>
                      </div>

                      <div className="flex items-start gap-3 p-3 bg-white rounded-lg border border-green-100">
                        <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0">
                          <Package className="w-4 h-4 text-blue-600" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">设备名称</div>
                          <div className="font-medium text-blue-900">{selectedDepreciationRecord.equipmentName}</div>
                        </div>
                      </div>

                      <div className="flex items-start gap-3 p-3 bg-white rounded-lg border border-green-100">
                        <div className="w-8 h-8 rounded-lg bg-purple-100 flex items-center justify-center flex-shrink-0">
                          <Calendar className="w-4 h-4 text-purple-600" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">购买日期</div>
                          <div className="font-medium text-purple-900">{selectedDepreciationRecord.purchaseDate}</div>
                        </div>
                      </div>

                      <div className="flex items-start gap-3 p-3 bg-white rounded-lg border border-green-100">
                        <div className="w-8 h-8 rounded-lg bg-orange-100 flex items-center justify-center flex-shrink-0">
                          <DollarSign className="w-4 h-4 text-orange-600" />
                        </div>
                        <div className="flex-1">
                          <div className="text-xs text-muted-foreground mb-1">购买原值</div>
                          <div className="text-xl font-medium text-orange-600">¥{selectedDepreciationRecord.purchasePrice.toLocaleString()}</div>
                        </div>
                      </div>
                    </div>
                  </Card>

                  {/* 折旧信息概览 */}
                  <Card className="p-4">
                    <h4 className="mb-4 flex items-center gap-2">
                      <Calculator className="w-4 h-4 text-purple-600" />
                      折旧信息概览
                    </h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-3">
                        <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg border border-purple-100">
                          <span className="text-sm text-muted-foreground">折旧方法</span>
                          <Badge className="bg-purple-600">{selectedDepreciationRecord.depreciationMethod}</Badge>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100">
                          <span className="text-sm text-muted-foreground">折旧年限</span>
                          <span className="font-medium text-blue-900">{selectedDepreciationRecord.depreciationYears}年</span>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100">
                          <span className="text-sm text-muted-foreground">已使用时间</span>
                          <span className="font-medium text-green-900">
                            {Math.floor(selectedDepreciationRecord.usedMonths / 12)}年{selectedDepreciationRecord.usedMonths % 12}个月
                          </span>
                        </div>
                        {selectedDepreciationRecord.depreciationMethod === '工作量法' && (
                          <div className="flex items-center justify-between p-3 bg-orange-50 rounded-lg border border-orange-100">
                            <span className="text-sm text-muted-foreground">累计工作量</span>
                            <span className="font-medium text-orange-900">{selectedDepreciationRecord.usageHours || 0}小时</span>
                          </div>
                        )}
                      </div>

                      <div className="space-y-3">
                        <div className="flex items-center justify-between p-3 bg-orange-50 rounded-lg border border-orange-100">
                          <span className="text-sm text-muted-foreground">年折旧额</span>
                          <span className="font-medium text-orange-600">¥{selectedDepreciationRecord.annualDepreciation.toLocaleString()}</span>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-red-50 rounded-lg border border-red-100">
                          <span className="text-sm text-muted-foreground">累计折旧</span>
                          <span className="font-medium text-red-600">¥{selectedDepreciationRecord.accumulatedDepreciation.toLocaleString()}</span>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100">
                          <span className="text-sm text-muted-foreground">资产净值</span>
                          <span className="text-xl font-medium text-green-600">¥{selectedDepreciationRecord.currentValue.toLocaleString()}</span>
                        </div>
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
                          <span className="text-sm text-muted-foreground">残值（5%）</span>
                          <span className="font-medium text-gray-600">
                            ¥{(selectedDepreciationRecord.purchasePrice * 0.05).toLocaleString()}
                          </span>
                        </div>
                      </div>
                    </div>
                  </Card>

                  {/* 折旧进度 */}
                  <Card className="p-4">
                    <h4 className="mb-4 flex items-center gap-2">
                      <TrendingUp className="w-4 h-4 text-blue-600" />
                      折旧进度分析
                    </h4>
                    <div className="space-y-4">
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-muted-foreground">使用年限进度</span>
                          <span className="font-medium">
                            {((selectedDepreciationRecord.usedMonths / (selectedDepreciationRecord.depreciationYears * 12)) * 100).toFixed(1)}%
                          </span>
                        </div>
                        <Progress 
                          value={(selectedDepreciationRecord.usedMonths / (selectedDepreciationRecord.depreciationYears * 12)) * 100} 
                          className="h-3"
                        />
                        <div className="flex items-center justify-between mt-1 text-xs text-muted-foreground">
                          <span>已使用 {selectedDepreciationRecord.usedMonths} 个月</span>
                          <span>总年限 {selectedDepreciationRecord.depreciationYears * 12} 个月</span>
                        </div>
                      </div>

                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-muted-foreground">折旧率</span>
                          <span className="font-medium text-orange-600">
                            {selectedDepreciationRecord.depreciationRate.toFixed(1)}%
                          </span>
                        </div>
                        <Progress 
                          value={selectedDepreciationRecord.depreciationRate} 
                          className="h-3"
                        />
                        <div className="flex items-center justify-between mt-1 text-xs text-muted-foreground">
                          <span>已折旧 ¥{selectedDepreciationRecord.accumulatedDepreciation.toLocaleString()}</span>
                          <span>原值 ¥{selectedDepreciationRecord.purchasePrice.toLocaleString()}</span>
                        </div>
                      </div>

                      {selectedDepreciationRecord.depreciationMethod === '工作量法' && selectedDepreciationRecord.totalWorkload && (
                        <div>
                          <div className="flex items-center justify-between mb-2">
                            <span className="text-sm text-muted-foreground">工作量完成度</span>
                            <span className="font-medium text-purple-600">
                              {((selectedDepreciationRecord.usageHours || 0) / selectedDepreciationRecord.totalWorkload * 100).toFixed(1)}%
                            </span>
                          </div>
                          <Progress 
                            value={(selectedDepreciationRecord.usageHours || 0) / selectedDepreciationRecord.totalWorkload * 100} 
                            className="h-3"
                          />
                          <div className="flex items-center justify-between mt-1 text-xs text-muted-foreground">
                            <span>已工作 {selectedDepreciationRecord.usageHours || 0} 小时</span>
                            <span>预计 {selectedDepreciationRecord.totalWorkload} 小时</span>
                          </div>
                        </div>
                      )}
                    </div>
                  </Card>

                  {/* 价值变化趋势 */}
                  <Card className="p-4">
                    <h4 className="mb-4 flex items-center gap-2">
                      <BarChart3 className="w-4 h-4 text-green-600" />
                      资产价值对比
                    </h4>
                    <ResponsiveContainer width="100%" height={200}>
                      <BarChart
                        data={[
                          {
                            name: '资产价值',
                            原值: selectedDepreciationRecord.purchasePrice,
                            累计折旧: selectedDepreciationRecord.accumulatedDepreciation,
                            当前净值: selectedDepreciationRecord.currentValue,
                            预计残值: selectedDepreciationRecord.purchasePrice * 0.05,
                          }
                        ]}
                        layout="vertical"
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis type="number" />
                        <YAxis type="category" dataKey="name" />
                        <RechartsTooltip />
                        <Legend />
                        <Bar dataKey="原值" fill="#3b82f6" name="购买原值" />
                        <Bar dataKey="累计折旧" fill="#ef4444" name="累计折旧" />
                        <Bar dataKey="当前净值" fill="#10b981" name="当前净值" />
                        <Bar dataKey="预计残值" fill="#6b7280" name="预计残值" />
                      </BarChart>
                    </ResponsiveContainer>
                  </Card>

                  {/* 预计报废信息 */}
                  <Card className="p-4 bg-gradient-to-r from-gray-50 to-slate-50 border-gray-200">
                    <h4 className="mb-4 flex items-center gap-2">
                      <Archive className="w-4 h-4 text-gray-600" />
                      预计报废信息
                    </h4>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                      <div className="p-3 bg-white rounded-lg border border-gray-200">
                        <div className="text-xs text-muted-foreground mb-2">剩余使用年限</div>
                        <div className="font-medium text-gray-900">
                          {Math.max(0, selectedDepreciationRecord.depreciationYears - Math.floor(selectedDepreciationRecord.usedMonths / 12))}年
                          {Math.max(0, 12 - (selectedDepreciationRecord.usedMonths % 12))}个月
                        </div>
                      </div>
                      <div className="p-3 bg-white rounded-lg border border-gray-200">
                        <div className="text-xs text-muted-foreground mb-2">预计报废日期</div>
                        <div className="font-medium text-gray-900">
                          {(() => {
                            const date = new Date(selectedDepreciationRecord.purchaseDate);
                            date.setFullYear(date.getFullYear() + selectedDepreciationRecord.depreciationYears);
                            return date.toLocaleDateString('zh-CN');
                          })()}
                        </div>
                      </div>
                      <div className="p-3 bg-white rounded-lg border border-gray-200">
                        <div className="text-xs text-muted-foreground mb-2">预计残值</div>
                        <div className="text-lg font-medium text-gray-600">
                          ¥{(selectedDepreciationRecord.purchasePrice * 0.05).toLocaleString()}
                        </div>
                      </div>
                    </div>
                  </Card>

                  {/* 折旧计算公式说明 */}
                  <Card className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
                    <h4 className="mb-3 flex items-center gap-2">
                      <Cpu className="w-4 h-4 text-blue-600" />
                      折旧计算公式
                    </h4>
                    {selectedDepreciationRecord.depreciationMethod === '直线法' ? (
                      <div className="space-y-2 text-sm">
                        <div className="p-3 bg-white rounded-lg border border-blue-100">
                          <div className="font-medium text-blue-900 mb-2">直线法（平均年限法）</div>
                          <div className="text-blue-700 space-y-1">
                            <div>年折旧额 = 原值 ÷ 预计使用年限</div>
                            <div className="text-xs text-muted-foreground mt-2">
                              = ¥{selectedDepreciationRecord.purchasePrice.toLocaleString()} ÷ {selectedDepreciationRecord.depreciationYears}年
                              = ¥{selectedDepreciationRecord.annualDepreciation.toLocaleString()}/年
                            </div>
                          </div>
                        </div>
                        <div className="p-3 bg-white rounded-lg border border-blue-100">
                          <div className="font-medium text-blue-900 mb-2">月折旧额</div>
                          <div className="text-blue-700">
                            月折旧额 = 年折旧额 ÷ 12 = ¥{(selectedDepreciationRecord.annualDepreciation / 12).toLocaleString()}/月
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="space-y-2 text-sm">
                        <div className="p-3 bg-white rounded-lg border border-blue-100">
                          <div className="font-medium text-blue-900 mb-2">工作量法</div>
                          <div className="text-blue-700 space-y-1">
                            <div>单位折旧额 = 原值 ÷ 预计总工作量</div>
                            <div className="text-xs text-muted-foreground mt-2">
                              = ¥{selectedDepreciationRecord.purchasePrice.toLocaleString()} ÷ {selectedDepreciationRecord.totalWorkload || 0}小时
                              = ¥{selectedDepreciationRecord.totalWorkload 
                                ? (selectedDepreciationRecord.purchasePrice / selectedDepreciationRecord.totalWorkload).toFixed(2)
                                : '0'}/小时
                            </div>
                          </div>
                        </div>
                        <div className="p-3 bg-white rounded-lg border border-blue-100">
                          <div className="font-medium text-blue-900 mb-2">累计折旧额</div>
                          <div className="text-blue-700">
                            累计折旧 = 单位折旧额 × 累计工作量 = ¥{selectedDepreciationRecord.accumulatedDepreciation.toLocaleString()}
                          </div>
                        </div>
                      </div>
                    )}
                  </Card>
                </div>
              )}

              <DialogFooter>
                <Button variant="outline" onClick={() => setShowDepreciationViewDialog(false)}>
                  关闭
                </Button>
                <Button 
                  className="bg-blue-600 hover:bg-blue-700"
                  onClick={() => {
                    setShowDepreciationViewDialog(false);
                    setShowDepreciationDetailDialog(true);
                  }}
                >
                  <FileText className="w-4 h-4 mr-2" />
                  查看折旧明细
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </TabsContent>

        {/* 报废处理 */}
        <TabsContent value="disposal" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-red-50 to-orange-50 border-red-200">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0">
                <Trash2 className="w-5 h-5 text-white" />
              </div>
              <div className="flex-1">
                <h4 className="font-medium text-red-900 mb-2">💡 报废处理全流程管理</h4>
                <div className="text-sm text-red-900 space-y-1">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
                    <div className="flex items-start gap-1">
                      <div className="w-5 h-5 rounded bg-red-100 text-red-600 flex items-center justify-center flex-shrink-0 mt-0.5">1</div>
                      <div>
                        <strong>报废申请</strong>: 申请人填写报废申请，详细说明理由，上传设备照片
                      </div>
                    </div>
                    <div className="flex items-start gap-1">
                      <div className="w-5 h-5 rounded bg-orange-100 text-orange-600 flex items-center justify-center flex-shrink-0 mt-0.5">2</div>
                      <div>
                        <strong>审批流程</strong>: 审批人员审核报废申请，可批准或驳回
                      </div>
                    </div>
                    <div className="flex items-start gap-1">
                      <div className="w-5 h-5 rounded bg-green-100 text-green-600 flex items-center justify-center flex-shrink-0 mt-0.5">3</div>
                      <div>
                        <strong>状态更新</strong>: 审批通过后，资产状态自动更新为"报废"
                      </div>
                    </div>
                    <div className="flex items-start gap-1">
                      <div className="w-5 h-5 rounded bg-gray-100 text-gray-600 flex items-center justify-center flex-shrink-0 mt-0.5">4</div>
                      <div>
                        <strong>档案管理</strong>: 从在用资产列表移除，保留完整历史记录
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* 统计卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 bg-gradient-to-br from-yellow-50 to-yellow-100 border-yellow-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-yellow-700">待审批</p>
                  <p className="mt-2 text-2xl font-medium text-yellow-600">{pendingDisposal}</p>
                  <p className="text-xs text-yellow-600 mt-1">申请中</p>
                </div>
                <Clock className="w-10 h-10 text-yellow-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 border-green-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-green-700">已批准</p>
                  <p className="mt-2 text-2xl font-medium text-green-600">{approvedDisposal}</p>
                  <p className="text-xs text-green-600 mt-1">通过审批</p>
                </div>
                <CheckCircle className="w-10 h-10 text-green-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100 border-red-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-red-700">已驳回</p>
                  <p className="mt-2 text-2xl font-medium text-red-600">{rejectedDisposal}</p>
                  <p className="text-xs text-red-600 mt-1">审批驳回</p>
                </div>
                <XCircle className="w-10 h-10 text-red-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 border-gray-200">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-gray-700">已报废</p>
                  <p className="mt-2 text-2xl font-medium text-gray-600">{completedDisposal}</p>
                  <p className="text-xs text-gray-600 mt-1">已完成</p>
                </div>
                <Archive className="w-10 h-10 text-gray-600 opacity-50" />
              </div>
            </Card>
          </div>

          <div className="flex items-center gap-3">
            <Button className="bg-red-600 hover:bg-red-700" onClick={() => setShowDisposalDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新建报废申请
            </Button>
            
            <Select defaultValue="all-status">
              <SelectTrigger className="w-40">
                <SelectValue placeholder="筛选状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all-status">全部状态</SelectItem>
                <SelectItem value="pending">待审批</SelectItem>
                <SelectItem value="approved">已批准</SelectItem>
                <SelectItem value="rejected">已驳回</SelectItem>
                <SelectItem value="disposed">已报废</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 报废申请列表 */}
          <Card>
            <div className="p-4 border-b bg-gray-50">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-red-600" />
                  报废申请记录
                  <Badge variant="outline" className="ml-2">{disposalRequests.length}条</Badge>
                </h3>
                <div className="flex items-center gap-2">
                  <Input placeholder="搜索申请单号、设备名称..." className="w-64" />
                  <Button variant="outline" size="sm">
                    <Search className="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-36">申请单号</TableHead>
                    <TableHead className="w-40">设备信息</TableHead>
                    <TableHead className="w-28">申请人</TableHead>
                    <TableHead className="w-32">申请日期</TableHead>
                    <TableHead className="w-64">报废理由</TableHead>
                    <TableHead className="w-36">资产价值</TableHead>
                    <TableHead className="w-24">使用年限</TableHead>
                    <TableHead className="w-24">照片附件</TableHead>
                    <TableHead className="w-36">审批信息</TableHead>
                    <TableHead className="w-24">状态</TableHead>
                    <TableHead className="w-40">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {disposalRequests.map((request) => (
                    <TableRow key={request.id} className="hover:bg-gray-50">
                      <TableCell>
                        <div className="font-medium text-red-600 text-sm">{request.requestNo}</div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div className="font-medium">{request.equipmentName}</div>
                          <div className="text-xs text-muted-foreground">{request.equipmentCode}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1 text-sm">
                          <User className="w-3 h-3 text-muted-foreground" />
                          {request.applicant}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1 text-sm">
                          <Calendar className="w-3 h-3 text-muted-foreground" />
                          {request.applyDate}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm max-w-xs">
                          <div className="line-clamp-2 text-muted-foreground">{request.reason}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm space-y-1">
                          <div className="flex items-center gap-1 text-muted-foreground">
                            <span className="text-xs">原值:</span>
                            <span className="font-medium">¥{request.purchasePrice.toLocaleString()}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <span className="text-xs text-muted-foreground">现值:</span>
                            <span className="font-medium text-red-600">¥{request.currentValue.toLocaleString()}</span>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-xs">
                          {request.usageYears}年
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-xs border-blue-300 text-blue-600 hover:bg-blue-50"
                        >
                          <Upload className="w-3 h-3 mr-1" />
                          {request.photos.length}张
                        </Button>
                      </TableCell>
                      <TableCell>
                        {request.approver ? (
                          <div className="text-sm space-y-1">
                            <div className="flex items-center gap-1">
                              <User className="w-3 h-3 text-green-600" />
                              <span className="font-medium">{request.approver}</span>
                            </div>
                            <div className="flex items-center gap-1 text-xs text-muted-foreground">
                              <Clock className="w-3 h-3" />
                              {request.approveDate}
                            </div>
                            {request.approvalComments && (
                              <div className="text-xs text-muted-foreground line-clamp-1">
                                {request.approvalComments}
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-sm text-yellow-600 flex items-center gap-1">
                            <AlertCircle className="w-3 h-3" />
                            待审批
                          </span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge className={getDisposalStatusColor(request.status)}>
                          {request.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            title="查看详情"
                            onClick={() => handleViewDisposal(request)}
                          >
                            <Eye className="w-3 h-3" />
                          </Button>
                          {request.status === '待审批' && (
                            <Button
                              size="sm"
                              className="bg-green-600 hover:bg-green-700"
                              title="审批"
                              onClick={() => handleStartApproval(request)}
                            >
                              <Send className="w-3 h-3" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>

          {/* 报废流程图 */}
          <Card className="p-6 bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200">
            <h4 className="flex items-center gap-2 mb-4">
              <Activity className="w-5 h-5 text-blue-600" />
              报废处理流程
            </h4>
            <div className="flex items-center justify-between">
              <div className="flex-1">
                <div className="flex items-center">
                  <div className="flex flex-col items-center">
                    <div className="w-12 h-12 rounded-full bg-red-100 border-2 border-red-300 flex items-center justify-center">
                      <FileText className="w-6 h-6 text-red-600" />
                    </div>
                    <p className="mt-2 text-sm font-medium text-red-900">提交申请</p>
                    <p className="text-xs text-muted-foreground mt-1">填写理由和照片</p>
                  </div>
                  
                  <div className="flex-1 h-0.5 bg-gradient-to-r from-red-300 to-yellow-300 mx-4"></div>
                  
                  <div className="flex flex-col items-center">
                    <div className="w-12 h-12 rounded-full bg-yellow-100 border-2 border-yellow-300 flex items-center justify-center">
                      <Clock className="w-6 h-6 text-yellow-600" />
                    </div>
                    <p className="mt-2 text-sm font-medium text-yellow-900">等待审批</p>
                    <p className="text-xs text-muted-foreground mt-1">审批人员处理</p>
                  </div>
                  
                  <div className="flex-1 h-0.5 bg-gradient-to-r from-yellow-300 to-green-300 mx-4"></div>
                  
                  <div className="flex flex-col items-center">
                    <div className="w-12 h-12 rounded-full bg-green-100 border-2 border-green-300 flex items-center justify-center">
                      <CheckCircle className="w-6 h-6 text-green-600" />
                    </div>
                    <p className="mt-2 text-sm font-medium text-green-900">审批通过</p>
                    <p className="text-xs text-muted-foreground mt-1">批准报废申请</p>
                  </div>
                  
                  <div className="flex-1 h-0.5 bg-gradient-to-r from-green-300 to-gray-300 mx-4"></div>
                  
                  <div className="flex flex-col items-center">
                    <div className="w-12 h-12 rounded-full bg-gray-100 border-2 border-gray-300 flex items-center justify-center">
                      <Archive className="w-6 h-6 text-gray-600" />
                    </div>
                    <p className="mt-2 text-sm font-medium text-gray-900">资产报废</p>
                    <p className="text-xs text-muted-foreground mt-1">更新状态归档</p>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 设备详情对话框（只读） */}
      <Dialog open={showEquipmentDialog} onOpenChange={setShowEquipmentDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-green-600" />
              物资档案详情
            </DialogTitle>
            <DialogDescription>
              查看设备的完整信息。如需编辑，请前往"基础信息管理 → 农具档案管理"
            </DialogDescription>
          </DialogHeader>
          
          {selectedEquipment && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="flex items-center gap-2 mb-4">
                  <FileText className="w-4 h-4 text-green-600" />
                  基本信息
                </h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="text-sm font-medium text-blue-600 mt-1">{selectedEquipment.code}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="text-sm font-medium mt-1">{selectedEquipment.name}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备分类</Label>
                    <Badge variant="outline" className="mt-1 bg-purple-50 text-purple-700 border-purple-200">
                      {selectedEquipment.category}
                    </Badge>
                  </div>
                  <div>
                    <Label className="text-xs">型号规格</Label>
                    <p className="text-sm mt-1">{selectedEquipment.model}</p>
                  </div>
                  <div>
                    <Label className="text-xs">生产厂家</Label>
                    <p className="text-sm mt-1">{selectedEquipment.manufacturer}</p>
                  </div>
                  <div>
                    <Label className="text-xs">序列号</Label>
                    <p className="text-sm text-muted-foreground mt-1">{selectedEquipment.serialNumber || '-'}</p>
                  </div>
                </div>
              </Card>

              {/* 购买与价值信息 */}
              <Card className="p-4 bg-blue-50">
                <h4 className="flex items-center gap-2 mb-4">
                  <DollarSign className="w-4 h-4 text-blue-600" />
                  购买与价值信息
                </h4>
                <div className="grid grid-cols-4 gap-4">
                  <div>
                    <Label className="text-xs">购买日期</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <Calendar className="w-3 h-3 text-muted-foreground" />
                      <p className="text-sm">{selectedEquipment.purchaseDate}</p>
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">购买价格</Label>
                    <p className="text-sm font-medium text-blue-600 mt-1">
                      ¥{selectedEquipment.purchasePrice.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">当前价值</Label>
                    <p className="text-sm font-medium text-green-600 mt-1">
                      ¥{selectedEquipment.currentValue.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">累计折旧</Label>
                    <p className="text-sm font-medium text-orange-600 mt-1">
                      ¥{(selectedEquipment.purchasePrice - selectedEquipment.currentValue).toLocaleString()}
                    </p>
                  </div>
                </div>
              </Card>

              {/* 折旧信息 */}
              <Card className="p-4 bg-orange-50">
                <h4 className="flex items-center gap-2 mb-4">
                  <TrendingDown className="w-4 h-4 text-orange-600" />
                  折旧信息
                </h4>
                <div className="grid grid-cols-4 gap-4">
                  <div>
                    <Label className="text-xs">折旧年限</Label>
                    <p className="text-sm font-medium mt-1">{selectedEquipment.depreciationYears}年</p>
                  </div>
                  <div>
                    <Label className="text-xs">已使用时长</Label>
                    <p className="text-sm mt-1">{calculateDepreciation(selectedEquipment).monthsUsed}个月</p>
                  </div>
                  <div>
                    <Label className="text-xs">年折旧额</Label>
                    <p className="text-sm mt-1">
                      ¥{calculateDepreciation(selectedEquipment).annualDepreciation.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">折旧率</Label>
                    <div className="flex items-center gap-2 mt-1">
                      <Progress value={calculateDepreciation(selectedEquipment).depreciationRate} className="flex-1" />
                      <span className="text-sm font-medium">
                        {calculateDepreciation(selectedEquipment).depreciationRate.toFixed(1)}%
                      </span>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 使用状态 */}
              <Card className="p-4 bg-green-50">
                <h4 className="flex items-center gap-2 mb-4">
                  <Activity className="w-4 h-4 text-green-600" />
                  使用状态
                </h4>
                <div className="grid grid-cols-4 gap-4">
                  <div>
                    <Label className="text-xs">当前状态</Label>
                    <Badge className={`${getStatusColor(selectedEquipment.status)} mt-1`}>
                      {selectedEquipment.status}
                    </Badge>
                  </div>
                  <div>
                    <Label className="text-xs">累计使用次数</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <Timer className="w-3 h-3 text-muted-foreground" />
                      <p className="text-sm font-medium">{selectedEquipment.usageHours}次</p>
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">存放位置</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <MapPin className="w-3 h-3 text-muted-foreground" />
                      <p className="text-sm">{selectedEquipment.location || '-'}</p>
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">责任人</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <User className="w-3 h-3 text-muted-foreground" />
                      <p className="text-sm">{selectedEquipment.assignedTo || '未分配'}</p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 维护记录 */}
              {(selectedEquipment.lastMaintenanceDate || selectedEquipment.nextMaintenanceDate) && (
                <Card className="p-4 bg-yellow-50">
                  <h4 className="flex items-center gap-2 mb-4">
                    <Wrench className="w-4 h-4 text-yellow-600" />
                    维护信息
                  </h4>
                  <div className="grid grid-cols-2 gap-4">
                    {selectedEquipment.lastMaintenanceDate && (
                      <div>
                        <Label className="text-xs">上次维护日期</Label>
                        <div className="flex items-center gap-1 mt-1">
                          <Clock className="w-3 h-3 text-muted-foreground" />
                          <p className="text-sm">{selectedEquipment.lastMaintenanceDate}</p>
                        </div>
                      </div>
                    )}
                    {selectedEquipment.nextMaintenanceDate && (
                      <div>
                        <Label className="text-xs">下次维护日期</Label>
                        <div className="flex items-center gap-1 mt-1">
                          <Calendar className="w-3 h-3 text-muted-foreground" />
                          <p className="text-sm">{selectedEquipment.nextMaintenanceDate}</p>
                        </div>
                      </div>
                    )}
                  </div>
                </Card>
              )}

              {/* 技术规格 */}
              {selectedEquipment.specifications && (
                <Card className="p-4">
                  <h4 className="flex items-center gap-2 mb-3">
                    <Settings className="w-4 h-4 text-gray-600" />
                    技术规格说明
                  </h4>
                  <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                    {selectedEquipment.specifications}
                  </p>
                </Card>
              )}

              {/* 数据来源提示 */}
              <Card className="p-3 bg-blue-50 border-blue-200">
                <div className="flex items-center gap-2 text-sm text-blue-900">
                  <AlertCircle className="w-4 h-4 text-blue-600" />
                  <p>
                    此信息为只读模式。如需修改，请前往
                    <strong className="mx-1">基础信息管理 → 农资档案管理/农具档案管理</strong>
                    进行编辑。
                  </p>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setShowEquipmentDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 维修工单对话框 */}
      <Dialog open={showMaintenanceDialog} onOpenChange={setShowMaintenanceDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>创建维修工单</DialogTitle>
            <DialogDescription>
              记录设备维修保养信息
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>工单号</Label>
                <Input placeholder="自动生成" disabled />
              </div>
              <div>
                <Label>维修类型</Label>
                <Select>
                  <SelectTrigger>
                    <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>设备选择</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择设备" />
                  </SelectTrigger>
                  <SelectContent>
                    {equipmentList.map(eq => (
                      <SelectItem key={eq.id} value={eq.id}>
                        {eq.name} ({eq.code})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>维修人员</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="选择维修人员" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="李维修">李维修</SelectItem>
                    <SelectItem value="王师傅">王师傅</SelectItem>
                    <SelectItem value="维修组">维修组</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>故障描述/保养内容</Label>
              <Textarea placeholder="详细描述故障现象或保养内容..." rows={3} />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>开始时间</Label>
                <Input type="datetime-local" />
              </div>
              <div>
                <Label>结束时间</Label>
                <Input type="datetime-local" />
              </div>
            </div>

            <div>
              <Label>更换配件/耗材</Label>
              <div className="space-y-3">
                {/* 配件选择区 */}
                <div className="grid grid-cols-12 gap-2">
                  <div className="col-span-6">
                    <Select
                      value={selectedMaterialId}
                      onValueChange={(value) => {
                        setSelectedMaterialId(value);
                        const material = materialList.find(m => m.id === value);
                        if (material) {
                          setNewPart({ 
                            name: material.name, 
                            quantity: 0, 
                            cost: material.purchasePrice 
                          });
                        }
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="从农资库选择配件" />
                      </SelectTrigger>
                      <SelectContent>
                        {materialList.map((material) => (
                          <SelectItem key={material.id} value={material.id}>
                            <div className="flex items-center justify-between w-full gap-3">
                              <div className="flex items-center gap-2">
                                <span className="font-medium">{material.name}</span>
                                <span className="text-xs text-muted-foreground">({material.spec})</span>
                              </div>
                              <div className="flex items-center gap-2 text-xs">
                                <Badge variant="outline" className="bg-blue-50">
                                  ¥{material.purchasePrice}/{material.unit}
                                </Badge>
                                <Badge variant={material.currentStock > 20 ? 'outline' : 'destructive'} className={material.currentStock > 20 ? 'bg-green-50 text-green-700' : ''}>
                                  库存:{material.currentStock}
                                </Badge>
                              </div>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <Input 
                    type="number" 
                    placeholder="数量" 
                    className="col-span-2"
                    value={newPart.quantity || ''}
                    onChange={(e) => setNewPart({ ...newPart, quantity: Number(e.target.value) })}
                  />
                  <div className="col-span-2 flex items-center justify-center bg-gray-50 border rounded-md px-3 text-sm text-muted-foreground">
                    {selectedMaterialId ? (
                      <>¥{materialList.find(m => m.id === selectedMaterialId)?.purchasePrice || 0}</>
                    ) : (
                      '单价'
                    )}
                  </div>
                  <Button 
                    size="sm" 
                    className="col-span-2 bg-blue-600 hover:bg-blue-700"
                    onClick={handleAddPart}
                  >
                    <Plus className="w-3 h-3 mr-1" />
                    添加
                  </Button>
                </div>

                {/* 显示选中物料的详细信息 */}
                {selectedMaterialId && (() => {
                  const material = materialList.find(m => m.id === selectedMaterialId);
                  return material ? (
                    <Card className="p-3 bg-blue-50 border-blue-200">
                      <div className="flex items-center justify-between text-sm">
                        <div className="flex items-center gap-4">
                          <div>
                            <span className="text-xs text-muted-foreground">物料编码：</span>
                            <span className="font-medium">{material.code}</span>
                          </div>
                          <div>
                            <span className="text-xs text-muted-foreground">规格：</span>
                            <span className="font-medium">{material.spec}</span>
                          </div>
                          <div>
                            <span className="text-xs text-muted-foreground">单位：</span>
                            <span className="font-medium">{material.unit}</span>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <Badge variant={material.currentStock > 20 ? 'outline' : 'destructive'} 
                                 className={material.currentStock > 20 ? 'bg-green-100 text-green-700' : ''}>
                            当前库存: {material.currentStock}{material.unit}
                          </Badge>
                          {material.currentStock <= 20 && (
                            <span className="text-xs text-orange-600 flex items-center gap-1">
                              <AlertTriangle className="w-3 h-3" />
                              库存偏低
                            </span>
                          )}
                        </div>
                      </div>
                    </Card>
                  ) : null;
                })()}

                {/* 已添加的配件列表 */}
                {maintenanceParts.length > 0 && (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-50 px-3 py-2 border-b">
                      <p className="text-sm font-medium">已添加配件清单 ({maintenanceParts.length}项)</p>
                    </div>
                    <div className="divide-y max-h-48 overflow-y-auto">
                      {maintenanceParts.map((part, index) => (
                        <div key={index} className="flex items-center justify-between px-3 py-2 hover:bg-gray-50">
                          <div className="flex-1 grid grid-cols-12 gap-2 text-sm">
                            <div className="col-span-5">
                              <span className="font-medium">{part.name}</span>
                            </div>
                            <div className="col-span-2 text-muted-foreground">
                              x{part.quantity}
                            </div>
                            <div className="col-span-3 text-muted-foreground">
                              ¥{part.cost.toLocaleString()}/个
                            </div>
                            <div className="col-span-2 text-right font-medium text-blue-600">
                              ¥{(part.quantity * part.cost).toLocaleString()}
                            </div>
                          </div>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="ml-2 text-red-600 hover:text-red-700 hover:bg-red-50"
                            onClick={() => handleRemovePart(index)}
                          >
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                    <div className="bg-gray-50 px-3 py-2 border-t">
                      <div className="flex justify-between text-sm">
                        <span className="font-medium">配件费用小计：</span>
                        <span className="font-medium text-blue-600">
                          ¥{maintenanceParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toLocaleString()}
                        </span>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            <div>
              <Label>人工费用（元）</Label>
              <Input 
                type="number" 
                placeholder="0" 
                value={laborCost || ''}
                onChange={(e) => setLaborCost(Number(e.target.value))}
              />
            </div>

            {/* 费用汇总 */}
            {(maintenanceParts.length > 0 || laborCost > 0) && (
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">配件费用：</span>
                    <span className="font-medium">
                      ¥{maintenanceParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toLocaleString()}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">人工费用：</span>
                    <span className="font-medium">¥{laborCost.toLocaleString()}</span>
                  </div>
                  <div className="flex justify-between pt-2 border-t border-blue-300">
                    <span className="font-medium text-blue-900">总计费用：</span>
                    <span className="text-lg font-medium text-blue-600">
                      ¥{calculateTotalCost().toLocaleString()}
                    </span>
                  </div>
                </div>
              </Card>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowMaintenanceDialog(false)}>
              取消
            </Button>
            <Button className="bg-orange-600 hover:bg-orange-700" onClick={handleSaveMaintenance}>
              <Send className="w-4 h-4 mr-2" />
              创建工单
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 报废申请对话框 */}
      <Dialog open={showDisposalDialog} onOpenChange={setShowDisposalDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Trash2 className="w-5 h-5 text-red-600" />
              报废申请
            </DialogTitle>
            <DialogDescription>
              填写资产报废申请信息，提交后进入审批流程
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>申请单号</Label>
                <Input placeholder="系统自动生成" disabled className="bg-gray-50" />
              </div>
              <div>
                <Label>申请人</Label>
                <Input defaultValue="当前用户" disabled className="bg-gray-50" />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>申请日期</Label>
                <Input type="date" defaultValue={new Date().toISOString().split('T')[0]} disabled className="bg-gray-50" />
              </div>
              <div>
                <Label>申请部门</Label>
                <Input defaultValue="资产管理部" disabled className="bg-gray-50" />
              </div>
            </div>

            <div>
              <Label>设备选择 <span className="text-red-500">*</span></Label>
              <Select
                value={disposalFormData.equipmentId}
                onValueChange={(value) => setDisposalFormData({ ...disposalFormData, equipmentId: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择要报废的设备" />
                </SelectTrigger>
                <SelectContent>
                  {equipmentList.map(eq => (
                    <SelectItem key={eq.id} value={eq.id}>
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{eq.name}</span>
                        <span className="text-xs text-muted-foreground">({eq.code})</span>
                        <Badge variant="outline" className="ml-2">{eq.status}</Badge>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {disposalFormData.equipmentId && (() => {
              const selected = equipmentList.find(e => e.id === disposalFormData.equipmentId);
              return selected ? (
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <h4 className="text-sm font-medium text-blue-900 mb-3">设备详细信息</h4>
                  <div className="grid grid-cols-3 gap-3 text-sm">
                    <div>
                      <span className="text-xs text-muted-foreground">设备分类：</span>
                      <p className="font-medium">{selected.category}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">型号规格：</span>
                      <p className="font-medium">{selected.model}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">生产厂家：</span>
                      <p className="font-medium">{selected.manufacturer}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">购买日期：</span>
                      <p className="font-medium">{selected.purchaseDate}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">购买价格：</span>
                      <p className="font-medium text-blue-600">¥{selected.purchasePrice.toLocaleString()}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">当前价值：</span>
                      <p className="font-medium text-green-600">¥{selected.currentValue.toLocaleString()}</p>
                    </div>
                  </div>
                </Card>
              ) : null;
            })()}

            <div>
              <Label>报废理由 <span className="text-red-500">*</span></Label>
              <Textarea
                placeholder="请详细说明报废理由，如：&#10;1. 设备老化、技术落后、已超过使用年限&#10;2. 维修成本过高、无维修价值&#10;3. 设备严重损坏、无法正常使用&#10;4. 其他原因（请详细说明）"
                rows={5}
                value={disposalFormData.reason}
                onChange={(e) => setDisposalFormData({ ...disposalFormData, reason: e.target.value })}
              />
              <p className="text-xs text-muted-foreground mt-1">
                已输入 {disposalFormData.reason.length} 字，建议至少50字以上
              </p>
            </div>

            <div>
              <Label>照片附件 <span className="text-xs text-muted-foreground">(建议上传)</span></Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 transition-colors cursor-pointer">
                <Upload className="w-10 h-10 mx-auto text-muted-foreground mb-3" />
                <p className="text-sm text-muted-foreground mb-1">
                  点击上传或拖拽设备照片到此区域
                </p>
                <p className="text-xs text-muted-foreground mb-3">
                  支持 JPG、PNG 格式，单个文件不超过5MB，最多上传10张
                </p>
                <Button size="sm" variant="outline" type="button">
                  <Upload className="w-3 h-3 mr-1" />
                  选择文件
                </Button>
              </div>
              {disposalFormData.photos.length > 0 && (
                <div className="mt-2 flex flex-wrap gap-2">
                  {disposalFormData.photos.map((photo, idx) => (
                    <div key={idx} className="relative group">
                      <div className="w-20 h-20 rounded border bg-gray-100 flex items-center justify-center">
                        <Upload className="w-8 h-8 text-gray-400" />
                      </div>
                      <Button
                        size="sm"
                        variant="destructive"
                        className="absolute -top-2 -right-2 w-6 h-6 p-0 rounded-full opacity-0 group-hover:opacity-100"
                      >
                        ×
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <Card className="p-3 bg-yellow-50 border-yellow-200">
              <div className="flex items-start gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div className="text-xs text-yellow-900">
                  <p className="font-medium mb-1">📋 温馨提示：</p>
                  <ul className="space-y-0.5">
                    <li>• 报废申请需要经过审批流程，请确保填写信息准确完整</li>
                    <li>• 请上传清晰的设备当前状态照片作为报废依据</li>
                    <li>• 审批通过后，资产状态将自动更新为"报废"</li>
                    <li>• 报废资产将从在用资产列表中移除，但保留完整历史记录</li>
                  </ul>
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowDisposalDialog(false);
              setDisposalFormData({ equipmentId: '', reason: '', photos: [] });
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-red-600 hover:bg-red-700" onClick={handleSubmitDisposal}>
              <Send className="w-4 h-4 mr-2" />
              提交申请
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 报废详情对话框 */}
      <Dialog open={showDisposalDetailDialog} onOpenChange={setShowDisposalDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-blue-600" />
              报废申请详情
            </DialogTitle>
            <DialogDescription>
              查看报废申请的完整信息
            </DialogDescription>
          </DialogHeader>

          {selectedDisposal && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="flex items-center gap-2 mb-3">
                  <FileText className="w-4 h-4 text-gray-600" />
                  申请基本信息
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">申请单号</Label>
                    <p className="font-medium text-red-600 mt-1">{selectedDisposal.requestNo}</p>
                  </div>
                  <div>
                    <Label className="text-xs">申请人</Label>
                    <p className="mt-1">{selectedDisposal.applicant}</p>
                  </div>
                  <div>
                    <Label className="text-xs">申请日期</Label>
                    <p className="mt-1">{selectedDisposal.applyDate}</p>
                  </div>
                </div>
              </Card>

              {/* 设备信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="flex items-center gap-2 mb-3">
                  <Box className="w-4 h-4 text-blue-600" />
                  报废设备信息
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedDisposal.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedDisposal.equipmentCode}</p>
                  </div>
                  <div>
                    <Label className="text-xs">使用年限</Label>
                    <p className="mt-1">{selectedDisposal.usageYears}年</p>
                  </div>
                  <div>
                    <Label className="text-xs">购买价格</Label>
                    <p className="font-medium text-blue-600 mt-1">
                      ¥{selectedDisposal.purchasePrice.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">当前价值</Label>
                    <p className="font-medium text-green-600 mt-1">
                      ¥{selectedDisposal.currentValue.toLocaleString()}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">累计折旧</Label>
                    <p className="font-medium text-orange-600 mt-1">
                      ¥{(selectedDisposal.purchasePrice - selectedDisposal.currentValue).toLocaleString()}
                    </p>
                  </div>
                </div>
              </Card>

              {/* 报废理由 */}
              <Card className="p-4 bg-red-50 border-red-200">
                <h4 className="flex items-center gap-2 mb-3">
                  <AlertCircle className="w-4 h-4 text-red-600" />
                  报废理由说明
                </h4>
                <p className="text-sm text-gray-700 whitespace-pre-wrap">{selectedDisposal.reason}</p>
              </Card>

              {/* 照片附件 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-3">
                  <Upload className="w-4 h-4 text-gray-600" />
                  照片附件
                  <Badge variant="outline">{selectedDisposal.photos.length}张</Badge>
                </h4>
                <div className="grid grid-cols-4 gap-3">
                  {selectedDisposal.photos.map((photo, idx) => (
                    <div key={idx} className="relative group">
                      <div className="aspect-square rounded-lg border bg-gray-100 flex items-center justify-center overflow-hidden">
                        <Upload className="w-12 h-12 text-gray-400" />
                      </div>
                      <p className="text-xs text-center text-muted-foreground mt-1">{photo}</p>
                    </div>
                  ))}
                </div>
              </Card>

              {/* 审批信息 */}
              {selectedDisposal.approver && (
                <Card className="p-4 bg-green-50 border-green-200">
                  <h4 className="flex items-center gap-2 mb-3">
                    <CheckCircle className="w-4 h-4 text-green-600" />
                    审批信息
                  </h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <Label className="text-xs">审批人</Label>
                      <p className="font-medium mt-1">{selectedDisposal.approver}</p>
                    </div>
                    <div>
                      <Label className="text-xs">审批日期</Label>
                      <p className="mt-1">{selectedDisposal.approveDate}</p>
                    </div>
                    <div>
                      <Label className="text-xs">审批状态</Label>
                      <Badge className={`${getDisposalStatusColor(selectedDisposal.status)} mt-1`}>
                        {selectedDisposal.status}
                      </Badge>
                    </div>
                  </div>
                  {selectedDisposal.approvalComments && (
                    <div className="mt-3">
                      <Label className="text-xs">审批意见</Label>
                      <p className="text-sm text-gray-700 mt-1 p-3 bg-white rounded border">
                        {selectedDisposal.approvalComments}
                      </p>
                    </div>
                  )}
                </Card>
              )}

              {/* 状态标识 */}
              <div className="flex items-center justify-center p-4 bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg border">
                <div className="text-center">
                  <p className="text-xs text-muted-foreground mb-1">当前状态</p>
                  <Badge className={`${getDisposalStatusColor(selectedDisposal.status)} text-base px-4 py-1`}>
                    {selectedDisposal.status}
                  </Badge>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowDisposalDetailDialog(false);
              setSelectedDisposal(null);
            }}>
              关闭
            </Button>
            {selectedDisposal?.status === '待审批' && (
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={() => {
                  setShowDisposalDetailDialog(false);
                  handleStartApproval(selectedDisposal);
                }}
              >
                <Send className="w-4 h-4 mr-2" />
                开始审批
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 审批对话框 */}
      <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Send className="w-5 h-5 text-green-600" />
              报废申请审批
            </DialogTitle>
            <DialogDescription>
              审核报废申请，批准后资产状态将更新为"报废"
            </DialogDescription>
          </DialogHeader>

          {selectedDisposal && (
            <div className="space-y-4">
              <Card className="p-4 bg-gray-50">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">申请单号</Label>
                    <p className="font-medium text-red-600 mt-1">{selectedDisposal.requestNo}</p>
                  </div>
                  <div>
                    <Label className="text-xs">申请人</Label>
                    <p className="mt-1">{selectedDisposal.applicant}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedDisposal.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedDisposal.equipmentCode}</p>
                  </div>
                </div>
              </Card>

              <div>
                <Label className="text-xs">报废理由</Label>
                <div className="mt-2 p-3 bg-gray-50 rounded border text-sm text-gray-700 whitespace-pre-wrap max-h-32 overflow-y-auto">
                  {selectedDisposal.reason}
                </div>
              </div>

              <div>
                <Label>审批意见 <span className="text-red-500">*</span></Label>
                <Textarea
                  placeholder="请填写审批意见..."
                  rows={4}
                />
              </div>

              <Card className="p-3 bg-blue-50 border-blue-200">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div className="text-xs text-blue-900">
                    <p className="font-medium mb-1">审批说明：</p>
                    <ul className="space-y-0.5">
                      <li>• <strong>批准</strong>：资产状态将更新为"报废"，从在用资产列表中移除</li>
                      <li>• <strong>驳回</strong>：申请将被驳回，资产状态保持不变</li>
                      <li>• 审批操作不可撤销，请谨慎操作</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowApprovalDialog(false);
              setSelectedDisposal(null);
            }}>
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={handleRejectDisposal}
            >
              <XCircle className="w-4 h-4 mr-2" />
              驳回申请
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700"
              onClick={handleApproveDisposal}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              批准报废
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 新建保养计划对话框 */}
      <Dialog open={showPlanDialog} onOpenChange={setShowPlanDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Calendar className="w-5 h-5 text-blue-600" />
              新建保养计划
            </DialogTitle>
            <DialogDescription>
              为设备创建定期保养计划，系统将自动提醒保养时间
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 设备选择 */}
            <div>
              <Label>选择设备 <span className="text-red-500">*</span></Label>
              <Select
                value={planFormData.equipmentId}
                onValueChange={(value) => setPlanFormData({ ...planFormData, equipmentId: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择需要制定保养计划的设备" />
                </SelectTrigger>
                <SelectContent>
                  {equipmentList.map(eq => (
                    <SelectItem key={eq.id} value={eq.id}>
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{eq.name}</span>
                        <span className="text-xs text-muted-foreground">({eq.code})</span>
                        <Badge variant="outline" className={getStatusColor(eq.status)}>
                          {eq.status}
                        </Badge>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 显示选中设备的信息 */}
            {planFormData.equipmentId && (() => {
              const selectedEq = equipmentList.find(e => e.id === planFormData.equipmentId);
              return selectedEq ? (
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <h4 className="text-sm font-medium text-blue-900 mb-3">设备信息</h4>
                  <div className="grid grid-cols-3 gap-3 text-sm">
                    <div>
                      <span className="text-xs text-muted-foreground">设备分类：</span>
                      <p className="font-medium">{selectedEq.category}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">型号规格：</span>
                      <p className="font-medium">{selectedEq.model}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">使用时长：</span>
                      <p className="font-medium text-blue-600">{selectedEq.usageHours}小时</p>
                    </div>
                  </div>
                </Card>
              ) : null;
            })()}

            {/* 计划类型和保养间隔 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>计划类型 <span className="text-red-500">*</span></Label>
                <Select
                  value={planFormData.planType}
                  onValueChange={(value: '按时间' | '按工作量') => 
                    setPlanFormData({ 
                      ...planFormData, 
                      planType: value,
                      intervalUnit: value === '按时间' ? '天' : '小时'
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="按时间">
                      <div className="flex items-center gap-2">
                        <Clock className="w-4 h-4 text-blue-600" />
                        <span>按时间（日历天数）</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="按工作量">
                      <div className="flex items-center gap-2">
                        <Timer className="w-4 h-4 text-purple-600" />
                        <span>按工作量（使用小时）</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>保养间隔 <span className="text-red-500">*</span></Label>
                <div className="flex gap-2">
                  <Input
                    type="number"
                    placeholder={planFormData.planType === '按时间' ? '例如：90' : '例如：500'}
                    value={planFormData.interval || ''}
                    onChange={(e) => setPlanFormData({ ...planFormData, interval: Number(e.target.value) })}
                    className="flex-1"
                  />
                  <div className="w-20">
                    <Select
                      value={planFormData.intervalUnit}
                      onValueChange={(value: '天' | '小时') => 
                        setPlanFormData({ ...planFormData, intervalUnit: value })
                      }
                      disabled={planFormData.planType === '按工作量'}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="天">天</SelectItem>
                        <SelectItem value="小时">小时</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {planFormData.planType === '按时间' 
                    ? '系统将根据日历时间自动计算保养日期' 
                    : '系统将根据设备使用时长自动计算保养时间'}
                </p>
              </div>
            </div>

            {/* 自动提醒 */}
            <div className="flex items-center justify-between p-4 border rounded-lg bg-gray-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                  <AlertCircle className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="font-medium">自动提醒功能</p>
                  <p className="text-sm text-muted-foreground">
                    到期前7天自动发送提醒通知
                  </p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  className="sr-only peer"
                  checked={planFormData.autoRemind}
                  onChange={(e) => setPlanFormData({ ...planFormData, autoRemind: e.target.checked })}
                />
                <div className="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>

            {/* 保养内容 */}
            <div>
              <Label>保养项目内容 <span className="text-red-500">*</span></Label>
              <div className="space-y-3">
                {/* 添加保养项目 */}
                <div className="flex gap-2">
                  <Input
                    placeholder="输入保养项目，例如：更换机油、检查刹车系统"
                    value={planFormData.newItem}
                    onChange={(e) => setPlanFormData({ ...planFormData, newItem: e.target.value })}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        handleAddMaintenanceItem();
                      }
                    }}
                    className="flex-1"
                  />
                  <Button
                    type="button"
                    className="bg-blue-600 hover:bg-blue-700"
                    onClick={handleAddMaintenanceItem}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    添加
                  </Button>
                </div>

                {/* 已添加的保养项目列表 */}
                {planFormData.maintenanceItems.length > 0 && (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-50 px-3 py-2 border-b">
                      <p className="text-sm font-medium">
                        保养项目清单 ({planFormData.maintenanceItems.length}项)
                      </p>
                    </div>
                    <div className="divide-y max-h-48 overflow-y-auto">
                      {planFormData.maintenanceItems.map((item, index) => (
                        <div key={index} className="flex items-center justify-between px-3 py-2.5 hover:bg-gray-50">
                          <div className="flex items-center gap-2">
                            <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-medium">
                              {index + 1}
                            </div>
                            <span className="text-sm">{item}</span>
                          </div>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                            onClick={() => handleRemoveMaintenanceItem(index)}
                          >
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 常用保养项目快捷添加 */}
                <Card className="p-3 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
                  <p className="text-xs font-medium text-blue-900 mb-2">💡 常用保养项目快捷添加：</p>
                  <div className="flex flex-wrap gap-2">
                    {['更换机油', '检查刹车系统', '清洁空滤', '润滑传动部件', '检查液压系统', '更换滤网', '清洗喷头', '检查电气系统'].map((item) => (
                      <Button
                        key={item}
                        size="sm"
                        variant="outline"
                        className="text-xs border-blue-300 text-blue-600 hover:bg-blue-100"
                        onClick={() => {
                          if (!planFormData.maintenanceItems.includes(item)) {
                            setPlanFormData({
                              ...planFormData,
                              maintenanceItems: [...planFormData.maintenanceItems, item],
                            });
                            toast.success(`已添加：${item}`);
                          } else {
                            toast.info('该项目已存在');
                          }
                        }}
                      >
                        <Plus className="w-3 h-3 mr-1" />
                        {item}
                      </Button>
                    ))}
                  </div>
                </Card>
              </div>
            </div>

            {/* 提示信息 */}
            <Card className="p-3 bg-yellow-50 border-yellow-200">
              <div className="flex items-start gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div className="text-xs text-yellow-900">
                  <p className="font-medium mb-1">📋 温馨提示：</p>
                  <ul className="space-y-0.5">
                    <li>• 保养计划创建后，系统将自动跟踪保养周期</li>
                    <li>• 开启自动提醒后，到期前7天会发送通知</li>
                    <li>• 可根据设备实际情况选择按时间或按工作量保养</li>
                    <li>• 保养项目可随时编辑修改，建议详细列出所有保养内容</li>
                  </ul>
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowPlanDialog(false);
              setPlanFormData({
                equipmentId: '',
                planType: '按时间',
                interval: 0,
                intervalUnit: '天',
                autoRemind: true,
                maintenanceItems: [],
                newItem: '',
              });
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleSavePlan}>
              <CheckCircle className="w-4 h-4 mr-2" />
              创建计划
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看保养计划详情对话框 */}
      <Dialog open={showPlanDetailDialog} onOpenChange={setShowPlanDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-blue-600" />
              保养计划详情
            </DialogTitle>
            <DialogDescription>
              查看设备保养计划的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedPlan && (() => {
            const equipment = equipmentList.find(e => e.code === selectedPlan.equipmentCode);
            const daysLeft = Math.ceil((new Date(selectedPlan.nextMaintenanceDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
            
            return (
              <div className="space-y-4">
                {/* 设备信息 */}
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <h4 className="flex items-center gap-2 mb-4">
                    <Box className="w-4 h-4 text-blue-600" />
                    设备信息
                  </h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <Label className="text-xs">设备编号</Label>
                      <p className="font-medium text-blue-600 mt-1">{selectedPlan.equipmentCode}</p>
                    </div>
                    <div>
                      <Label className="text-xs">设备名称</Label>
                      <p className="font-medium mt-1">{selectedPlan.equipmentName}</p>
                    </div>
                    {equipment && (
                      <>
                        <div>
                          <Label className="text-xs">设备分类</Label>
                          <p className="font-medium mt-1">{equipment.category}</p>
                        </div>
                        <div>
                          <Label className="text-xs">型号规格</Label>
                          <p className="mt-1">{equipment.model}</p>
                        </div>
                        <div>
                          <Label className="text-xs">使用时长</Label>
                          <p className="font-medium text-purple-600 mt-1">{equipment.usageHours}小时</p>
                        </div>
                        <div>
                          <Label className="text-xs">设备状态</Label>
                          <Badge className={`mt-1 ${
                            equipment.status === '空闲' ? 'bg-green-100 text-green-700' :
                            equipment.status === '使用中' ? 'bg-blue-100 text-blue-700' :
                            equipment.status === '维修中' ? 'bg-red-100 text-red-700' :
                            'bg-gray-100 text-gray-700'
                          }`}>
                            {equipment.status}
                          </Badge>
                        </div>
                      </>
                    )}
                  </div>
                </Card>

                {/* 保养计划信息 */}
                <Card className="p-4">
                  <h4 className="flex items-center gap-2 mb-4">
                    <Calendar className="w-4 h-4 text-green-600" />
                    保养计划信息
                  </h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <Label className="text-xs">计划类型</Label>
                      <Badge variant="outline" className={`mt-1 ${
                        selectedPlan.planType === '按时间' ? 'border-blue-300 text-blue-600' :
                        'border-purple-300 text-purple-600'
                      }`}>
                        {selectedPlan.planType}
                      </Badge>
                    </div>
                    <div>
                      <Label className="text-xs">保养间隔</Label>
                      <p className="font-medium mt-1">
                        每 {selectedPlan.interval}{selectedPlan.intervalUnit}
                      </p>
                    </div>
                    <div>
                      <Label className="text-xs">上次保养</Label>
                      {selectedPlan.lastMaintenanceDate ? (
                        <div className="mt-1">
                          <p>{selectedPlan.lastMaintenanceDate}</p>
                          <p className="text-xs text-muted-foreground">
                            {Math.ceil((new Date().getTime() - new Date(selectedPlan.lastMaintenanceDate).getTime()) / (1000 * 60 * 60 * 24))}天前
                          </p>
                        </div>
                      ) : (
                        <p className="text-muted-foreground mt-1">未保养</p>
                      )}
                    </div>
                    <div>
                      <Label className="text-xs">下次保养</Label>
                      <div className="mt-1">
                        <p className="font-medium">{selectedPlan.nextMaintenanceDate}</p>
                        {daysLeft > 0 && daysLeft <= 7 && (
                          <p className="text-xs text-yellow-600 flex items-center gap-1">
                            <AlertTriangle className="w-3 h-3" />
                            即将到期
                          </p>
                        )}
                      </div>
                    </div>
                    <div>
                      <Label className="text-xs">剩余天数</Label>
                      <p className={`font-medium mt-1 ${
                        daysLeft < 0 ? 'text-red-600' :
                        daysLeft <= 7 ? 'text-yellow-600' :
                        'text-green-600'
                      }`}>
                        {daysLeft < 0 ? `逾期${Math.abs(daysLeft)}天` :
                         daysLeft === 0 ? '今天' :
                         `还有${daysLeft}天`}
                      </p>
                    </div>
                    <div>
                      <Label className="text-xs">计划状态</Label>
                      <Badge className={`mt-1 ${
                        selectedPlan.status === '正常' ? 'bg-green-100 text-green-700' :
                        selectedPlan.status === '即将到期' ? 'bg-yellow-100 text-yellow-700' :
                        'bg-red-100 text-red-700'
                      }`}>
                        {selectedPlan.status}
                      </Badge>
                    </div>
                    <div>
                      <Label className="text-xs">自动提醒</Label>
                      <div className="flex items-center gap-2 mt-1">
                        {selectedPlan.autoRemind ? (
                          <>
                            <CheckCircle className="w-4 h-4 text-green-600" />
                            <span className="text-green-600">已启用</span>
                          </>
                        ) : (
                          <>
                            <XCircle className="w-4 h-4 text-gray-400" />
                            <span className="text-muted-foreground">未启用</span>
                          </>
                        )}
                      </div>
                    </div>
                    {selectedPlan.planType === '按工作量' && selectedPlan.currentUsage && (
                      <div>
                        <Label className="text-xs">当前工作量</Label>
                        <p className="font-medium text-purple-600 mt-1">
                          {selectedPlan.currentUsage}小时 / {selectedPlan.interval}小时
                        </p>
                        <Progress 
                          value={(selectedPlan.currentUsage / selectedPlan.interval) * 100} 
                          className="mt-2"
                        />
                      </div>
                    )}
                  </div>
                </Card>

                {/* 保养项目清单 */}
                <Card className="p-4">
                  <h4 className="flex items-center gap-2 mb-4">
                    <FileText className="w-4 h-4 text-orange-600" />
                    保养项目清单
                  </h4>
                  {selectedPlan.maintenanceItems && selectedPlan.maintenanceItems.length > 0 ? (
                    <div className="border rounded-lg overflow-hidden">
                      <div className="bg-gray-50 px-4 py-2 border-b">
                        <p className="text-sm font-medium">
                          共 {selectedPlan.maintenanceItems.length} 项保养内容
                        </p>
                      </div>
                      <div className="divide-y">
                        {selectedPlan.maintenanceItems.map((item, index) => (
                          <div key={index} className="flex items-center gap-3 px-4 py-3">
                            <div className="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center flex-shrink-0">
                              <span className="font-medium">{index + 1}</span>
                            </div>
                            <span className="text-sm">{item}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground text-center py-8">暂无保养项目</p>
                  )}
                </Card>

                {/* 历史保养记录 */}
                {selectedPlan.maintenanceHistory && selectedPlan.maintenanceHistory.length > 0 && (
                  <Card className="p-4">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="flex items-center gap-2">
                        <RefreshCcw className="w-4 h-4 text-purple-600" />
                        历史保养记录
                      </h4>
                      <Badge variant="outline" className="border-purple-300 text-purple-600">
                        共 {selectedPlan.maintenanceHistory.length} 次
                      </Badge>
                    </div>
                    
                    <div className="space-y-4">
                      {selectedPlan.maintenanceHistory.map((history, index) => (
                        <Card key={history.id} className="p-4 border-2 hover:border-purple-200 transition-colors">
                          {/* 保养头部信息 */}
                          <div className="flex items-start justify-between mb-3 pb-3 border-b">
                            <div className="flex items-start gap-3">
                              <div className="w-10 h-10 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center flex-shrink-0">
                                <span className="font-medium">#{index + 1}</span>
                              </div>
                              <div>
                                <div className="flex items-center gap-2">
                                  <span className="font-medium">{history.maintenanceDate}</span>
                                  {history.qualityRating && (
                                    <Badge className={
                                      history.qualityRating === '优秀' ? 'bg-green-100 text-green-700' :
                                      history.qualityRating === '良好' ? 'bg-blue-100 text-blue-700' :
                                      'bg-gray-100 text-gray-700'
                                    }>
                                      {history.qualityRating}
                                    </Badge>
                                  )}
                                </div>
                                <div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
                                  <div className="flex items-center gap-1">
                                    <User className="w-3 h-3" />
                                    {history.technician}
                                  </div>
                                  {history.technicianPhone && (
                                    <span>{history.technicianPhone}</span>
                                  )}
                                  <div className="flex items-center gap-1">
                                    <Timer className="w-3 h-3" />
                                    {history.duration}小时
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div className="text-right">
                              <div className="font-medium text-green-600 text-lg">
                                ¥{history.totalCost.toLocaleString()}
                              </div>
                              <div className="text-xs text-muted-foreground mt-1">
                                总费用
                              </div>
                            </div>
                          </div>

                          {/* 保养明细 */}
                          <div className="grid grid-cols-2 gap-4">
                            {/* 完成项目 */}
                            <div>
                              <Label className="text-xs mb-2 block">完成项目</Label>
                              <div className="bg-gray-50 rounded-lg p-3 space-y-1">
                                {history.completedItems.map((item, idx) => (
                                  <div key={idx} className="flex items-center gap-2 text-sm">
                                    <CheckCircle className="w-3 h-3 text-green-600 flex-shrink-0" />
                                    <span>{item}</span>
                                  </div>
                                ))}
                              </div>
                            </div>

                            {/* 使用配件 */}
                            <div>
                              <Label className="text-xs mb-2 block">使用配件</Label>
                              {history.usedParts.length > 0 ? (
                                <div className="bg-gray-50 rounded-lg p-3 space-y-2">
                                  {history.usedParts.map((part, idx) => (
                                    <div key={idx} className="flex items-center justify-between text-sm">
                                      <span className="flex-1">{part.name}</span>
                                      <span className="text-muted-foreground">
                                        x{part.quantity} · ¥{(part.quantity * part.cost).toFixed(2)}
                                      </span>
                                    </div>
                                  ))}
                                  <div className="pt-2 border-t flex justify-between text-xs">
                                    <span className="text-muted-foreground">配件费用：</span>
                                    <span className="font-medium">
                                      ¥{history.usedParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                                    </span>
                                  </div>
                                </div>
                              ) : (
                                <div className="bg-gray-50 rounded-lg p-3 text-sm text-muted-foreground text-center">
                                  未使用配件
                                </div>
                              )}
                            </div>
                          </div>

                          {/* 费用明细 */}
                          <div className="mt-3 pt-3 border-t">
                            <div className="grid grid-cols-3 gap-4 text-sm">
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">配件费用：</span>
                                <span className="font-medium">
                                  ¥{history.usedParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">人工费用：</span>
                                <span className="font-medium">¥{history.laborCost.toFixed(2)}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">总费用：</span>
                                <span className="font-medium text-green-600">¥{history.totalCost.toLocaleString()}</span>
                              </div>
                            </div>
                          </div>

                          {/* 备注说明 */}
                          {history.notes && (
                            <div className="mt-3 pt-3 border-t">
                              <Label className="text-xs mb-1 block">保养备注</Label>
                              <div className="bg-blue-50 rounded-lg p-3 text-sm text-muted-foreground">
                                {history.notes}
                              </div>
                            </div>
                          )}
                        </Card>
                      ))}
                    </div>

                    {/* 历史记录统计 */}
                    <Card className="mt-4 p-4 bg-gradient-to-r from-purple-50 to-blue-50 border-purple-200">
                      <div className="grid grid-cols-4 gap-4 text-center">
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">保养次数</div>
                          <div className="font-medium text-purple-600">
                            {selectedPlan.maintenanceHistory.length}次
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">累计耗时</div>
                          <div className="font-medium text-blue-600">
                            {selectedPlan.maintenanceHistory.reduce((sum, h) => sum + h.duration, 0)}小时
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">累计费用</div>
                          <div className="font-medium text-green-600">
                            ¥{selectedPlan.maintenanceHistory.reduce((sum, h) => sum + h.totalCost, 0).toLocaleString()}
                          </div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground mb-1">平均费用</div>
                          <div className="font-medium text-orange-600">
                            ¥{(selectedPlan.maintenanceHistory.reduce((sum, h) => sum + h.totalCost, 0) / selectedPlan.maintenanceHistory.length).toFixed(2)}
                          </div>
                        </div>
                      </div>
                    </Card>
                  </Card>
                )}
              </div>
            );
          })()}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowPlanDetailDialog(false);
              setSelectedPlan(null);
            }}>
              关闭
            </Button>
            {selectedPlan && (
              <>
                <Button variant="outline" onClick={() => {
                  setShowPlanDetailDialog(false);
                  handleEditPlan(selectedPlan);
                }}>
                  <Edit className="w-4 h-4 mr-2" />
                  编辑计划
                </Button>
                {(() => {
                  const daysLeft = Math.ceil((new Date(selectedPlan.nextMaintenanceDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
                  return daysLeft <= 7 && (
                    <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
                      setShowPlanDetailDialog(false);
                      handleExecuteMaintenance(selectedPlan);
                    }}>
                      <Play className="w-4 h-4 mr-2" />
                      执行保养
                    </Button>
                  );
                })()}
              </>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑保养计划对话框 */}
      <Dialog open={showPlanEditDialog} onOpenChange={setShowPlanEditDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5 text-blue-600" />
              编辑保养计划
            </DialogTitle>
            <DialogDescription>
              修改设备的保养计划配置
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 设备信息显示 */}
            {selectedPlan && (() => {
              const equipment = equipmentList.find(e => e.code === selectedPlan.equipmentCode);
              return equipment ? (
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <h4 className="text-sm font-medium text-blue-900 mb-3">设备信息</h4>
                  <div className="grid grid-cols-3 gap-3 text-sm">
                    <div>
                      <span className="text-xs text-muted-foreground">设备名称：</span>
                      <p className="font-medium">{equipment.name}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">设备编号：</span>
                      <p className="font-medium text-blue-600">{equipment.code}</p>
                    </div>
                    <div>
                      <span className="text-xs text-muted-foreground">使用时长：</span>
                      <p className="font-medium text-purple-600">{equipment.usageHours}小时</p>
                    </div>
                  </div>
                </Card>
              ) : null;
            })()}

            {/* 计划类型和保养间隔 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>计划类型 <span className="text-red-500">*</span></Label>
                <Select
                  value={editPlanFormData.planType}
                  onValueChange={(value: '按时间' | '按工作量') => 
                    setEditPlanFormData({ 
                      ...editPlanFormData, 
                      planType: value,
                      intervalUnit: value === '按时间' ? '天' : '小时'
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="按时间">
                      <div className="flex items-center gap-2">
                        <Clock className="w-4 h-4 text-blue-600" />
                        <span>按时间（日历天数）</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="按工作量">
                      <div className="flex items-center gap-2">
                        <Timer className="w-4 h-4 text-purple-600" />
                        <span>按工作量（使用小时）</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>保养间隔 <span className="text-red-500">*</span></Label>
                <div className="flex gap-2">
                  <Input
                    type="number"
                    placeholder={editPlanFormData.planType === '按时间' ? '例如：90' : '例如：500'}
                    value={editPlanFormData.interval || ''}
                    onChange={(e) => setEditPlanFormData({ ...editPlanFormData, interval: Number(e.target.value) })}
                    className="flex-1"
                  />
                  <div className="w-20">
                    <Select
                      value={editPlanFormData.intervalUnit}
                      onValueChange={(value: '天' | '小时') => 
                        setEditPlanFormData({ ...editPlanFormData, intervalUnit: value })
                      }
                      disabled={editPlanFormData.planType === '按工作量'}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="天">天</SelectItem>
                        <SelectItem value="小时">小时</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            </div>

            {/* 自动提醒 */}
            <div className="flex items-center justify-between p-4 border rounded-lg bg-gray-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                  <AlertCircle className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="font-medium">自动提醒功能</p>
                  <p className="text-sm text-muted-foreground">
                    到期前7天自动发送提醒通知
                  </p>
                </div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  className="sr-only peer"
                  checked={editPlanFormData.autoRemind}
                  onChange={(e) => setEditPlanFormData({ ...editPlanFormData, autoRemind: e.target.checked })}
                />
                <div className="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>

            {/* 保养内容 */}
            <div>
              <Label>保养项目内容 <span className="text-red-500">*</span></Label>
              <div className="space-y-3">
                {/* 添加保养项目 */}
                <div className="flex gap-2">
                  <Input
                    placeholder="输入保养项目"
                    value={editPlanFormData.newItem}
                    onChange={(e) => setEditPlanFormData({ ...editPlanFormData, newItem: e.target.value })}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        if (editPlanFormData.newItem.trim()) {
                          setEditPlanFormData({
                            ...editPlanFormData,
                            maintenanceItems: [...editPlanFormData.maintenanceItems, editPlanFormData.newItem.trim()],
                            newItem: '',
                          });
                          toast.success('保养项目已添加');
                        }
                      }
                    }}
                    className="flex-1"
                  />
                  <Button
                    type="button"
                    className="bg-blue-600 hover:bg-blue-700"
                    onClick={() => {
                      if (editPlanFormData.newItem.trim()) {
                        setEditPlanFormData({
                          ...editPlanFormData,
                          maintenanceItems: [...editPlanFormData.maintenanceItems, editPlanFormData.newItem.trim()],
                          newItem: '',
                        });
                        toast.success('保养项目已添加');
                      }
                    }}
                  >
                    <Plus className="w-4 h-4 mr-1" />
                    添加
                  </Button>
                </div>

                {/* 已添加的保养项目列表 */}
                {editPlanFormData.maintenanceItems.length > 0 && (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-50 px-3 py-2 border-b">
                      <p className="text-sm font-medium">
                        保养项目清单 ({editPlanFormData.maintenanceItems.length}项)
                      </p>
                    </div>
                    <div className="divide-y max-h-48 overflow-y-auto">
                      {editPlanFormData.maintenanceItems.map((item, index) => (
                        <div key={index} className="flex items-center justify-between px-3 py-2.5 hover:bg-gray-50">
                          <div className="flex items-center gap-2">
                            <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-medium">
                              {index + 1}
                            </div>
                            <span className="text-sm">{item}</span>
                          </div>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                            onClick={() => {
                              setEditPlanFormData({
                                ...editPlanFormData,
                                maintenanceItems: editPlanFormData.maintenanceItems.filter((_, i) => i !== index),
                              });
                              toast.success('保养项目已移除');
                            }}
                          >
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowPlanEditDialog(false);
              setSelectedPlan(null);
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleSaveEditPlan}>
              <CheckCircle className="w-4 h-4 mr-2" />
              保存修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 执行保养对话框 */}
      <Dialog open={showExecuteMaintenanceDialog} onOpenChange={setShowExecuteMaintenanceDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Play className="w-5 h-5 text-green-600" />
              执行保养任务
            </DialogTitle>
            <DialogDescription>
              记录保养任务的执行情况，完成后将自动生成维修工单记录
            </DialogDescription>
          </DialogHeader>

          {selectedPlan && (
            <div className="space-y-4">
              {/* 设备和计划信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedPlan.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedPlan.equipmentCode}</p>
                  </div>
                  <div>
                    <Label className="text-xs">保养类型</Label>
                    <Badge className="mt-1 bg-blue-100 text-blue-700">定期保养</Badge>
                  </div>
                  <div>
                    <Label className="text-xs">计划日期</Label>
                    <p className="mt-1">{selectedPlan.nextMaintenanceDate}</p>
                  </div>
                </div>
              </Card>

              {/* 维护人员信息 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>维护人员 <span className="text-red-500">*</span></Label>
                  <Input
                    placeholder="请输入维护人员姓名"
                    value={executeFormData.technician}
                    onChange={(e) => setExecuteFormData({ ...executeFormData, technician: e.target.value })}
                  />
                </div>
                <div>
                  <Label>联系电话</Label>
                  <Input
                    placeholder="请输入联系电话"
                    value={executeFormData.technicianPhone}
                    onChange={(e) => setExecuteFormData({ ...executeFormData, technicianPhone: e.target.value })}
                  />
                </div>
              </div>

              {/* 保养时间 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>开始时间 <span className="text-red-500">*</span></Label>
                  <Input
                    type="datetime-local"
                    value={executeFormData.actualStartTime}
                    onChange={(e) => setExecuteFormData({ ...executeFormData, actualStartTime: e.target.value })}
                  />
                </div>
                <div>
                  <Label>结束时间 <span className="text-red-500">*</span></Label>
                  <Input
                    type="datetime-local"
                    value={executeFormData.actualEndTime}
                    onChange={(e) => setExecuteFormData({ ...executeFormData, actualEndTime: e.target.value })}
                  />
                </div>
              </div>

              {/* 保养项目完成情况 */}
              <div>
                <Label>完成的保养项目 <span className="text-red-500">*</span></Label>
                <Card className="p-4 bg-gray-50 mt-2">
                  <p className="text-xs text-muted-foreground mb-3">请勾选已完成的保养项目</p>
                  <div className="space-y-2">
                    {selectedPlan.maintenanceItems?.map((item, index) => (
                      <div key={index} className="flex items-center gap-3 p-2 rounded hover:bg-white">
                        <input
                          type="checkbox"
                          id={`item-${index}`}
                          checked={executeFormData.completedItems.includes(item)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setExecuteFormData({
                                ...executeFormData,
                                completedItems: [...executeFormData.completedItems, item],
                              });
                            } else {
                              setExecuteFormData({
                                ...executeFormData,
                                completedItems: executeFormData.completedItems.filter(i => i !== item),
                              });
                            }
                          }}
                          className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                        />
                        <label htmlFor={`item-${index}`} className="flex-1 cursor-pointer">
                          <span className="text-sm">{item}</span>
                        </label>
                      </div>
                    ))}
                  </div>
                  <div className="mt-3 pt-3 border-t">
                    <p className="text-sm">
                      已完成：
                      <span className="font-medium text-green-600 ml-1">
                        {executeFormData.completedItems.length}
                      </span>
                      {' / '}
                      <span className="font-medium">
                        {selectedPlan.maintenanceItems?.length || 0}
                      </span>
                      {' '}项
                    </p>
                  </div>
                </Card>
              </div>

              {/* 使用配件（可选） */}
              <div>
                <Label>使用的配件/耗材（可选）</Label>
                <div className="space-y-3 mt-2">
                  {/* 配件添加区 - 复用维修工单的配件选择逻辑 */}
                  <div className="grid grid-cols-12 gap-2">
                    <div className="col-span-6">
                      <Select
                        value={selectedMaterialId}
                        onValueChange={(value) => {
                          setSelectedMaterialId(value);
                          const material = materialList.find(m => m.id === value);
                          if (material) {
                            setNewPart({ 
                              name: material.name, 
                              quantity: 0, 
                              cost: material.purchasePrice 
                            });
                          }
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="从农资库选择配件" />
                        </SelectTrigger>
                        <SelectContent>
                          {materialList.map((material) => (
                            <SelectItem key={material.id} value={material.id}>
                              <div className="flex items-center justify-between w-full gap-3">
                                <span className="font-medium">{material.name} ({material.spec})</span>
                                <span className="text-xs text-muted-foreground">
                                  ¥{material.purchasePrice}/{material.unit}
                                </span>
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <Input 
                      type="number" 
                      placeholder="数量" 
                      className="col-span-2"
                      value={newPart.quantity || ''}
                      onChange={(e) => setNewPart({ ...newPart, quantity: Number(e.target.value) })}
                    />
                    <div className="col-span-2 flex items-center justify-center bg-gray-50 border rounded-md px-3 text-sm text-muted-foreground">
                      {selectedMaterialId ? (
                        <>¥{materialList.find(m => m.id === selectedMaterialId)?.purchasePrice || 0}</>
                      ) : (
                        '单价'
                      )}
                    </div>
                    <Button 
                      size="sm" 
                      className="col-span-2 bg-blue-600 hover:bg-blue-700"
                      onClick={() => {
                        if (!selectedMaterialId || !newPart.quantity) {
                          toast.error('请选择配件并输入数量');
                          return;
                        }
                        const material = materialList.find(m => m.id === selectedMaterialId);
                        if (material) {
                          setExecuteFormData({
                            ...executeFormData,
                            usedParts: [...executeFormData.usedParts, {
                              name: `${material.name} (${material.spec})`,
                              quantity: newPart.quantity,
                              cost: material.purchasePrice,
                            }],
                          });
                          setNewPart({ name: '', quantity: 0, cost: 0 });
                          setSelectedMaterialId('');
                          toast.success('配件添加成功');
                        }
                      }}
                    >
                      <Plus className="w-3 h-3 mr-1" />
                      添加
                    </Button>
                  </div>

                  {/* 已添加配件列表 */}
                  {executeFormData.usedParts.length > 0 && (
                    <div className="border rounded-lg overflow-hidden">
                      <div className="bg-gray-50 px-3 py-2 border-b flex items-center justify-between">
                        <span className="text-sm font-medium">已添加配件</span>
                        <span className="text-sm text-muted-foreground">
                          共 {executeFormData.usedParts.length} 项
                        </span>
                      </div>
                      <div className="divide-y">
                        {executeFormData.usedParts.map((part, index) => (
                          <div key={index} className="flex items-center justify-between px-3 py-2">
                            <div className="flex-1">
                              <span className="text-sm font-medium">{part.name}</span>
                              <span className="text-xs text-muted-foreground ml-2">
                                x{part.quantity} · ¥{part.cost}/个
                              </span>
                            </div>
                            <div className="flex items-center gap-3">
                              <span className="text-sm font-medium text-green-600">
                                ¥{(part.quantity * part.cost).toFixed(2)}
                              </span>
                              <Button
                                size="sm"
                                variant="ghost"
                                className="text-red-600 hover:text-red-700"
                                onClick={() => {
                                  setExecuteFormData({
                                    ...executeFormData,
                                    usedParts: executeFormData.usedParts.filter((_, i) => i !== index),
                                  });
                                }}
                              >
                                <Trash2 className="w-3 h-3" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                      <div className="bg-blue-50 px-3 py-2 border-t">
                        <div className="flex justify-between items-center text-sm">
                          <span className="text-muted-foreground">配件费用小计：</span>
                          <span className="font-medium text-blue-600">
                            ¥{executeFormData.usedParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                          </span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 人工费用 */}
              <div>
                <Label>人工费用（元）</Label>
                <Input
                  type="number"
                  placeholder="请输入人工费用"
                  value={executeFormData.laborCost || ''}
                  onChange={(e) => setExecuteFormData({ ...executeFormData, laborCost: Number(e.target.value) })}
                />
              </div>

              {/* 备注说明 */}
              <div>
                <Label>备注说明</Label>
                <Textarea
                  placeholder="请输入保养过程中的备注信息..."
                  rows={4}
                  value={executeFormData.notes}
                  onChange={(e) => setExecuteFormData({ ...executeFormData, notes: e.target.value })}
                />
              </div>

              {/* 费用汇总 */}
              <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
                <h4 className="flex items-center gap-2 mb-3">
                  <DollarSign className="w-4 h-4 text-green-600" />
                  费用汇总
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">配件费用：</span>
                    <span className="font-medium">
                      ¥{executeFormData.usedParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">人工费用：</span>
                    <span className="font-medium">¥{executeFormData.laborCost.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between pt-2 border-t">
                    <span className="font-medium">总费用：</span>
                    <span className="font-medium text-green-600">
                      ¥{(executeFormData.usedParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0) + executeFormData.laborCost).toFixed(2)}
                    </span>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowExecuteMaintenanceDialog(false);
              setSelectedPlan(null);
              setExecuteFormData({
                technician: '',
                technicianPhone: '',
                actualStartTime: '',
                actualEndTime: '',
                completedItems: [],
                usedParts: [],
                laborCost: 0,
                notes: '',
              });
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveExecuteMaintenance}>
              <CheckCircle className="w-4 h-4 mr-2" />
              完成保养
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 维修工单详情对话框 */}
      <Dialog open={showWorkOrderDetailDialog} onOpenChange={setShowWorkOrderDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-orange-600" />
              维修工单详情
            </DialogTitle>
            <DialogDescription>
              查看维修工单的完整信息
            </DialogDescription>
          </DialogHeader>

          {selectedWorkOrder && (
            <div className="space-y-4">
              {/* 工单基本信息 */}
              <Card className="p-4 bg-gradient-to-r from-orange-50 to-red-50 border-orange-200">
                <h4 className="flex items-center gap-2 mb-4">
                  <FileText className="w-4 h-4 text-orange-600" />
                  工单基本信息
                </h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">工单号</Label>
                    <p className="font-medium text-orange-600 mt-1">{selectedWorkOrder.workOrderNo}</p>
                  </div>
                  <div>
                    <Label className="text-xs">维修类型</Label>
                    <Badge variant="outline" className={`mt-1 ${
                      selectedWorkOrder.maintenanceType === '紧急维修' ? 'border-red-300 text-red-600' :
                      selectedWorkOrder.maintenanceType === '定期保养' ? 'border-blue-300 text-blue-600' :
                      'border-yellow-300 text-yellow-600'
                    }`}>
                      {selectedWorkOrder.maintenanceType}
                    </Badge>
                  </div>
                  <div>
                    <Label className="text-xs">工单状态</Label>
                    <Badge className={`mt-1 ${
                      selectedWorkOrder.status === '已完成' ? 'bg-green-100 text-green-700' :
                      selectedWorkOrder.status === '进行中' ? 'bg-blue-100 text-blue-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {selectedWorkOrder.status}
                    </Badge>
                  </div>
                  <div>
                    <Label className="text-xs">结算状态</Label>
                    <Badge className={`mt-1 ${
                      selectedWorkOrder.paymentStatus === '已结算' ? 'bg-green-100 text-green-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {selectedWorkOrder.paymentStatus || '未结算'}
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 设备信息 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <Box className="w-4 h-4 text-blue-600" />
                  设备信息
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedWorkOrder.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedWorkOrder.equipmentCode}</p>
                  </div>
                  {selectedWorkOrder.faultLevel && (
                    <div>
                      <Label className="text-xs">故障等级</Label>
                      <Badge variant="outline" className={`mt-1 ${
                        selectedWorkOrder.faultLevel === '严重' ? 'border-red-300 text-red-600' :
                        selectedWorkOrder.faultLevel === '一般' ? 'border-yellow-300 text-yellow-600' :
                        'border-gray-300 text-gray-600'
                      }`}>
                        {selectedWorkOrder.faultLevel}
                      </Badge>
                    </div>
                  )}
                </div>
              </Card>

              {/* 故障描述 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <AlertCircle className="w-4 h-4 text-red-600" />
                  故障描述
                </h4>
                <div className="bg-gray-50 p-4 rounded-lg">
                  <p className="text-sm leading-relaxed">{selectedWorkOrder.description}</p>
                </div>
              </Card>

              {/* 维修人员信息 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <User className="w-4 h-4 text-purple-600" />
                  维修人员信息
                </h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">维修人员</Label>
                    <p className="font-medium mt-1">{selectedWorkOrder.technician}</p>
                  </div>
                  {selectedWorkOrder.technicianPhone && (
                    <div>
                      <Label className="text-xs">联系电话</Label>
                      <p className="mt-1">{selectedWorkOrder.technicianPhone}</p>
                    </div>
                  )}
                </div>
              </Card>

              {/* 维修时间 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <Clock className="w-4 h-4 text-green-600" />
                  维修时间
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">开始时间</Label>
                    <p className="font-medium mt-1">{selectedWorkOrder.startTime}</p>
                  </div>
                  <div>
                    <Label className="text-xs">结束时间</Label>
                    <p className="font-medium mt-1">
                      {selectedWorkOrder.endTime || <span className="text-yellow-600">进行中...</span>}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">维修耗时</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedWorkOrder.duration}小时</p>
                  </div>
                </div>
              </Card>

              {/* 配件清单 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <Package className="w-4 h-4 text-indigo-600" />
                  使用配件清单
                </h4>
                {selectedWorkOrder.parts.length > 0 ? (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-50 px-4 py-2 border-b">
                      <div className="grid grid-cols-12 gap-4 text-xs font-medium text-muted-foreground">
                        <div className="col-span-5">配件名称</div>
                        <div className="col-span-2 text-center">数量</div>
                        <div className="col-span-2 text-center">单价</div>
                        <div className="col-span-3 text-right">小计</div>
                      </div>
                    </div>
                    <div className="divide-y">
                      {selectedWorkOrder.parts.map((part, index) => (
                        <div key={index} className="grid grid-cols-12 gap-4 px-4 py-3 text-sm">
                          <div className="col-span-5">{part.name}</div>
                          <div className="col-span-2 text-center">{part.quantity}</div>
                          <div className="col-span-2 text-center">¥{part.cost.toFixed(2)}</div>
                          <div className="col-span-3 text-right font-medium text-green-600">
                            ¥{(part.quantity * part.cost).toFixed(2)}
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="bg-blue-50 px-4 py-3 border-t">
                      <div className="flex justify-between items-center text-sm">
                        <span className="text-muted-foreground">配件费用合计：</span>
                        <span className="font-medium text-blue-600">
                          ¥{selectedWorkOrder.parts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                        </span>
                      </div>
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground text-center py-8">未使用配件</p>
                )}
              </Card>

              {/* 费用汇总 */}
              <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
                <h4 className="flex items-center gap-2 mb-4">
                  <DollarSign className="w-4 h-4 text-green-600" />
                  费用汇总
                </h4>
                <div className="space-y-3 text-sm">
                  <div className="flex justify-between items-center">
                    <span className="text-muted-foreground">配件费用：</span>
                    <span className="font-medium">
                      ¥{selectedWorkOrder.parts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-foreground">人工费用：</span>
                    <span className="font-medium">¥{selectedWorkOrder.laborCost.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between items-center pt-3 border-t-2 border-green-300">
                    <span className="font-medium">总费用：</span>
                    <span className="font-medium text-green-600 text-lg">
                      ¥{selectedWorkOrder.totalCost.toLocaleString()}
                    </span>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowWorkOrderDetailDialog(false);
              setSelectedWorkOrder(null);
            }}>
              关闭
            </Button>
            {selectedWorkOrder && selectedWorkOrder.status === '待处理' && (
              <Button 
                className="bg-blue-600 hover:bg-blue-700" 
                onClick={() => {
                  setShowWorkOrderDetailDialog(false);
                  handleProcessWorkOrder(selectedWorkOrder);
                }}
              >
                <Play className="w-4 h-4 mr-2" />
                开始处理
              </Button>
            )}
            {selectedWorkOrder && selectedWorkOrder.status === '进行中' && (
              <Button 
                className="bg-green-600 hover:bg-green-700" 
                onClick={() => {
                  setShowWorkOrderDetailDialog(false);
                  handleCompleteWorkOrder(selectedWorkOrder);
                }}
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                完成工单
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 开始处理维修工单对话框 */}
      <Dialog open={showProcessWorkOrderDialog} onOpenChange={setShowProcessWorkOrderDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Play className="w-5 h-5 text-blue-600" />
              开始处理维修工单
            </DialogTitle>
            <DialogDescription>
              确认开始处理工单，工单状态将更新为"进行中"
            </DialogDescription>
          </DialogHeader>

          {selectedWorkOrder && (
            <div className="space-y-4">
              {/* 工单信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">工单号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedWorkOrder.workOrderNo}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedWorkOrder.equipmentName}</p>
                  </div>
                  <div className="col-span-2">
                    <Label className="text-xs">故障描述</Label>
                    <p className="mt-1 text-muted-foreground">{selectedWorkOrder.description}</p>
                  </div>
                </div>
              </Card>

              {/* 开始时间 */}
              <div>
                <Label>实际开始时间 <span className="text-red-500">*</span></Label>
                <Input
                  type="datetime-local"
                  value={processFormData.actualStartTime}
                  onChange={(e) => setProcessFormData({ ...processFormData, actualStartTime: e.target.value })}
                />
              </div>

              {/* 预计耗时 */}
              <div>
                <Label>预计维修耗时（小时） <span className="text-red-500">*</span></Label>
                <Input
                  type="number"
                  placeholder="请输入预计维修耗时"
                  value={processFormData.estimatedDuration || ''}
                  onChange={(e) => setProcessFormData({ ...processFormData, estimatedDuration: Number(e.target.value) })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  预计完成时间：{processFormData.actualStartTime && processFormData.estimatedDuration ? 
                    new Date(new Date(processFormData.actualStartTime).getTime() + processFormData.estimatedDuration * 60 * 60 * 1000).toLocaleString('zh-CN') : 
                    '-'}
                </p>
              </div>

              {/* 备注说明 */}
              <div>
                <Label>处理说明</Label>
                <Textarea
                  placeholder="请输入开始处理的说明信息..."
                  rows={4}
                  value={processFormData.processNotes}
                  onChange={(e) => setProcessFormData({ ...processFormData, processNotes: e.target.value })}
                />
              </div>

              {/* 提示信息 */}
              <Card className="p-4 bg-yellow-50 border-yellow-200">
                <div className="flex items-start gap-3">
                  <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm">
                    <p className="font-medium text-yellow-900 mb-1">操作提示</p>
                    <ul className="space-y-1 text-yellow-700">
                      <li>• 确认开始处理后，工单状态将变为"进行中"</li>
                      <li>• 请确保已经准备好所需的配件和工具</li>
                      <li>• 维修过程中可随时记录使用的配件和实际情况</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowProcessWorkOrderDialog(false);
              setSelectedWorkOrder(null);
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleSaveProcessWorkOrder}>
              <Play className="w-4 h-4 mr-2" />
              开始处理
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 完成维修工单对话框 */}
      <Dialog open={showCompleteWorkOrderDialog} onOpenChange={setShowCompleteWorkOrderDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-green-600" />
              完成维修工单
            </DialogTitle>
            <DialogDescription>
              填写维修完成信息，确认工单完成
            </DialogDescription>
          </DialogHeader>

          {selectedWorkOrder && (
            <div className="space-y-4">
              {/* 工单信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">工单号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedWorkOrder.workOrderNo}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedWorkOrder.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">维修类型</Label>
                    <Badge className="mt-1 bg-blue-100 text-blue-700">{selectedWorkOrder.maintenanceType}</Badge>
                  </div>
                </div>
              </Card>

              {/* 完成时间 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>实际完成时间 <span className="text-red-500">*</span></Label>
                  <Input
                    type="datetime-local"
                    value={completeFormData.actualEndTime}
                    onChange={(e) => setCompleteFormData({ ...completeFormData, actualEndTime: e.target.value })}
                  />
                </div>
                <div>
                  <Label>实际维修耗时（小时） <span className="text-red-500">*</span></Label>
                  <Input
                    type="number"
                    placeholder="请输入实际耗时"
                    value={completeFormData.actualDuration || ''}
                    onChange={(e) => setCompleteFormData({ ...completeFormData, actualDuration: Number(e.target.value) })}
                  />
                </div>
              </div>

              {/* 已使用配件 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="text-sm font-medium mb-3">已使用配件清单</h4>
                {selectedWorkOrder.parts.length > 0 ? (
                  <div className="border rounded-lg overflow-hidden bg-white">
                    <div className="divide-y">
                      {selectedWorkOrder.parts.map((part, index) => (
                        <div key={index} className="flex items-center justify-between px-3 py-2 text-sm">
                          <span>{part.name}</span>
                          <span className="text-muted-foreground">
                            x{part.quantity} · ¥{part.cost} = ¥{(part.quantity * part.cost).toFixed(2)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">未使用配件</p>
                )}
              </Card>

              {/* 额外配件（可选） */}
              <div>
                <Label>额外使用配件（可选）</Label>
                <div className="space-y-3 mt-2">
                  <div className="grid grid-cols-12 gap-2">
                    <div className="col-span-6">
                      <Select
                        value={selectedMaterialId}
                        onValueChange={(value) => {
                          setSelectedMaterialId(value);
                          const material = materialList.find(m => m.id === value);
                          if (material) {
                            setNewPart({ 
                              name: material.name, 
                              quantity: 0, 
                              cost: material.purchasePrice 
                            });
                          }
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择额外配件" />
                        </SelectTrigger>
                        <SelectContent>
                          {materialList.map((material) => (
                            <SelectItem key={material.id} value={material.id}>
                              {material.name} ({material.spec}) - ¥{material.purchasePrice}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <Input 
                      type="number" 
                      placeholder="数量" 
                      className="col-span-2"
                      value={newPart.quantity || ''}
                      onChange={(e) => setNewPart({ ...newPart, quantity: Number(e.target.value) })}
                    />
                    <div className="col-span-2 flex items-center justify-center bg-gray-50 border rounded-md px-3 text-sm text-muted-foreground">
                      {selectedMaterialId ? (
                        <>¥{materialList.find(m => m.id === selectedMaterialId)?.purchasePrice || 0}</>
                      ) : (
                        '单价'
                      )}
                    </div>
                    <Button 
                      size="sm" 
                      className="col-span-2 bg-blue-600 hover:bg-blue-700"
                      onClick={() => {
                        if (!selectedMaterialId || !newPart.quantity) {
                          toast.error('请选择配件并输入数量');
                          return;
                        }
                        const material = materialList.find(m => m.id === selectedMaterialId);
                        if (material) {
                          setCompleteFormData({
                            ...completeFormData,
                            additionalParts: [...completeFormData.additionalParts, {
                              name: `${material.name} (${material.spec})`,
                              quantity: newPart.quantity,
                              cost: material.purchasePrice,
                            }],
                          });
                          setNewPart({ name: '', quantity: 0, cost: 0 });
                          setSelectedMaterialId('');
                          toast.success('配件添加成功');
                        }
                      }}
                    >
                      <Plus className="w-3 h-3 mr-1" />
                      添加
                    </Button>
                  </div>

                  {completeFormData.additionalParts.length > 0 && (
                    <div className="border rounded-lg overflow-hidden">
                      <div className="divide-y">
                        {completeFormData.additionalParts.map((part, index) => (
                          <div key={index} className="flex items-center justify-between px-3 py-2">
                            <span className="text-sm">{part.name} x{part.quantity}</span>
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-medium text-green-600">
                                ¥{(part.quantity * part.cost).toFixed(2)}
                              </span>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => {
                                  setCompleteFormData({
                                    ...completeFormData,
                                    additionalParts: completeFormData.additionalParts.filter((_, i) => i !== index),
                                  });
                                }}
                              >
                                <Trash2 className="w-3 h-3 text-red-600" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 额外人工费用 */}
              <div>
                <Label>额外人工费用（元）</Label>
                <Input
                  type="number"
                  placeholder="如有额外人工费用请填写"
                  value={completeFormData.additionalLaborCost || ''}
                  onChange={(e) => setCompleteFormData({ ...completeFormData, additionalLaborCost: Number(e.target.value) })}
                />
              </div>

              {/* 解决方案说明 */}
              <div>
                <Label>解决方案说明 <span className="text-red-500">*</span></Label>
                <Textarea
                  placeholder="请详细描述故障原因、维修过程和解决方案..."
                  rows={5}
                  value={completeFormData.solutionNotes}
                  onChange={(e) => setCompleteFormData({ ...completeFormData, solutionNotes: e.target.value })}
                />
              </div>

              {/* 质量检查 */}
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-start gap-3">
                  <input
                    type="checkbox"
                    id="qualityCheck"
                    checked={completeFormData.qualityCheck}
                    onChange={(e) => setCompleteFormData({ ...completeFormData, qualityCheck: e.target.checked })}
                    className="w-5 h-5 text-green-600 border-gray-300 rounded focus:ring-green-500 mt-1"
                  />
                  <label htmlFor="qualityCheck" className="flex-1 cursor-pointer">
                    <p className="font-medium text-green-900">质量检查确认 <span className="text-red-500">*</span></p>
                    <ul className="text-sm text-green-700 mt-2 space-y-1">
                      <li>✓ 已完成维修工作，故障已排除</li>
                      <li>✓ 设备功能测试正常，可以正常使用</li>
                      <li>✓ 已清理维修现场，工具配件已归位</li>
                      <li>✓ 已向使用人员说明注意事项</li>
                    </ul>
                  </label>
                </div>
              </Card>

              {/* 费用汇总 */}
              <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
                <h4 className="flex items-center gap-2 mb-3">
                  <DollarSign className="w-4 h-4 text-green-600" />
                  最终费用汇总
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">原配件费用：</span>
                    <span className="font-medium">
                      ¥{selectedWorkOrder.parts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">额外配件费用：</span>
                    <span className="font-medium">
                      ¥{completeFormData.additionalParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">原人工费用：</span>
                    <span className="font-medium">¥{selectedWorkOrder.laborCost.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">额外人工费用：</span>
                    <span className="font-medium">¥{completeFormData.additionalLaborCost.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between pt-2 border-t-2 border-green-300">
                    <span className="font-medium">最终总费用：</span>
                    <span className="font-medium text-green-600 text-lg">
                      ¥{(
                        selectedWorkOrder.totalCost + 
                        completeFormData.additionalParts.reduce((sum, part) => sum + (part.quantity * part.cost), 0) +
                        completeFormData.additionalLaborCost
                      ).toFixed(2)}
                    </span>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowCompleteWorkOrderDialog(false);
              setSelectedWorkOrder(null);
              setCompleteFormData({
                actualEndTime: '',
                actualDuration: 0,
                additionalParts: [],
                additionalLaborCost: 0,
                solutionNotes: '',
                qualityCheck: false,
              });
            }}>
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveCompleteWorkOrder}>
              <CheckCircle className="w-4 h-4 mr-2" />
              确认完成
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 调度详情查看弹窗 */}
      <Dialog open={showDispatchDetailDialog} onOpenChange={setShowDispatchDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-blue-600" />
              设备调度详情
            </DialogTitle>
            <DialogDescription>
              查看设备调度的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedDispatchRecord && (
            <div className="space-y-4">
              {/* 设备基本信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="flex items-center gap-2 mb-4">
                  <Box className="w-4 h-4 text-blue-600" />
                  设备基本信息
                </h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">设备编号</Label>
                    <p className="font-medium text-blue-600 mt-1">{selectedDispatchRecord.equipmentCode}</p>
                  </div>
                  <div>
                    <Label className="text-xs">设备名称</Label>
                    <p className="font-medium mt-1">{selectedDispatchRecord.equipmentName}</p>
                  </div>
                  <div>
                    <Label className="text-xs">当前状态</Label>
                    <Badge className={`${getStatusColor(selectedDispatchRecord.status)} mt-1`}>
                      {selectedDispatchRecord.status}
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 位置与任务信息 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <MapPin className="w-4 h-4 text-green-600" />
                  位置与任务信息
                </h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-xs">当前位置</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <MapPin className="w-3 h-3 text-muted-foreground" />
                      <p>{selectedDispatchRecord.currentLocation}</p>
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">关联任务</Label>
                    <p className="font-medium text-blue-600 mt-1">
                      {selectedDispatchRecord.assignedTask || '无任务'}
                    </p>
                  </div>
                  <div>
                    <Label className="text-xs">责任人</Label>
                    <div className="flex items-center gap-1 mt-1">
                      <User className="w-3 h-3 text-muted-foreground" />
                      <p>{selectedDispatchRecord.assignedTo || '未分配'}</p>
                    </div>
                  </div>
                  {selectedDispatchRecord.actualUsageHours && (
                    <div>
                      <Label className="text-xs">使用时长</Label>
                      <div className="flex items-center gap-1 mt-1">
                        <Timer className="w-3 h-3 text-blue-600" />
                        <p className="font-medium">{selectedDispatchRecord.actualUsageHours}小时</p>
                      </div>
                    </div>
                  )}
                </div>
              </Card>

              {/* 时间信息 */}
              <Card className="p-4">
                <h4 className="flex items-center gap-2 mb-4">
                  <Clock className="w-4 h-4 text-purple-600" />
                  时间信息
                </h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  {selectedDispatchRecord.startTime && (
                    <div>
                      <Label className="text-xs">开始时间</Label>
                      <div className="flex items-center gap-1 mt-1">
                        <Clock className="w-3 h-3 text-green-600" />
                        <p>{selectedDispatchRecord.startTime}</p>
                      </div>
                    </div>
                  )}
                  {selectedDispatchRecord.estimatedEndTime && (
                    <div>
                      <Label className="text-xs">预计结束时间</Label>
                      <div className="flex items-center gap-1 mt-1">
                        <Calendar className="w-3 h-3 text-muted-foreground" />
                        <p>{selectedDispatchRecord.estimatedEndTime}</p>
                      </div>
                    </div>
                  )}
                </div>
              </Card>

              {/* 备注信息 */}
              {selectedDispatchRecord.notes && (
                <Card className="p-4">
                  <h4 className="flex items-center gap-2 mb-3">
                    <FileText className="w-4 h-4 text-gray-600" />
                    备注说明
                  </h4>
                  <p className="text-sm text-gray-700 p-3 bg-gray-50 rounded border">
                    {selectedDispatchRecord.notes}
                  </p>
                </Card>
              )}

              {/* 状态标识 */}
              <div className="flex items-center justify-center p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border">
                <div className="text-center">
                  <p className="text-xs text-muted-foreground mb-1">当前状态</p>
                  <Badge className={`${getStatusColor(selectedDispatchRecord.status)} text-base px-4 py-1`}>
                    {selectedDispatchRecord.status}
                  </Badge>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => {
              setShowDispatchDetailDialog(false);
              setSelectedDispatchRecord(null);
            }}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
