import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import {
  RotateCcw,
  Plus,
  Search,
  Filter,
  Download,
  CheckCircle,
  XCircle,
  Clock,
  User,
  Package,
  Calendar,
  AlertTriangle,
  Tag,
  Eye,
  Edit,
  Send,
  Scan,
  CheckSquare,
  History,
  FileCheck,
  BarChart3,
  TrendingUp,
  Activity,
  Wrench,
  AlertCircle,
  Link2,
  FileText,
  MapPin,
  Archive,
  Zap,
  ShoppingCart,
  Trash2,
  Info,
  DollarSign,
  Lightbulb,
  TrendingDown,
} 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,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface AssetReturnProps {
  activePath?: string;
}

type ReturnStatus = '待归还' | '已登记' | '待验收' | '已验收' | '已核销';
type MaterialCondition = '正常' | '损坏' | '遗失' | '需要保养';
type ToolStatus = '在用' | '闲置' | '维修中' | '已报废';

interface ReturnItem {
  id: string;
  materialId: string;
  materialName: string;
  materialType: string;
  borrowedQuantity: number;
  returnedQuantity: number;
  unit: string;
  condition: MaterialCondition;
  conditionNotes?: string;
  batchNo?: string;
}

interface ReturnRecord {
  id: string;
  code: string;
  requisitionCode: string;
  requisitionId: string;
  returner: string;
  returnerId: string;
  department: string;
  registerDate: string;
  items: ReturnItem[];
  status: ReturnStatus;
  notes?: string;
  processor?: string;
  processDate?: string;
  processNotes?: string;
  actualCondition?: {
    normal: number;
    damaged: number;
    lost: number;
    needMaintenance: number;
  };
}

interface RequisitionRecord {
  id: string;
  code: string;
  applicant: string;
  applyDate: string;
  items: {
    materialId: string;
    materialName: string;
    quantity: number;
    unit: string;
    returned: number;
    pending: number;
  }[];
  relatedField?: string;
  relatedTask?: string;
  checkoutDate: string;
  status: '未归还' | '部分归还' | '已归还';
}

interface SettlementRecord {
  id: string;
  requisitionCode: string;
  returnCode: string;
  materialName: string;
  borrowedQty: number;
  returnedQty: number;
  condition: MaterialCondition;
  settlementDate: string;
  processor: string;
  status: '已核销' | '待核销';
  // 全流程时间节点
  applyTime?: string;
  approvalTime?: string;
  checkoutTime?: string;
  returnRegisterTime?: string;
  verificationTime?: string;
  // 物资明细
  items?: {
    materialName: string;
    materialType: string;
    borrowedQty: number;
    returnedQty: number;
    unit: string;
    normalQty: number;
    damagedQty: number;
    lostQty: number;
    maintenanceQty: number;
  }[];
}

interface AssetUsageHistory {
  id: string;
  assetCode: string;
  assetName: string;
  assetType: string;
  totalBorrows: number;
  currentStatus: ToolStatus;
  borrowFrequency: number;
  avgBorrowDuration: number;
  damageCount: number;
  maintenanceCount: number;
  lastBorrowDate: string;
  lastReturnDate: string;
  utilizationRate: number;
  conditionScore: number;
  estimatedValue: number;
  depreciationRate: number;
}

export function AssetReturn({ activePath }: AssetReturnProps) {
  const [activeTab, setActiveTab] = useState('register');
  const [showRegisterDialog, setShowRegisterDialog] = useState(false);
  const [showProcessDialog, setShowProcessDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showSettlementDialog, setShowSettlementDialog] = useState(false);
  const [showSettlementDetailDialog, setShowSettlementDetailDialog] = useState(false);
  const [showAssetDetailDialog, setShowAssetDetailDialog] = useState(false);
  const [selectedReturn, setSelectedReturn] = useState<ReturnRecord | null>(null);
  const [selectedRequisition, setSelectedRequisition] = useState<RequisitionRecord | null>(null);
  const [selectedItems, setSelectedItems] = useState<ReturnItem[]>([]);
  const [selectedSettlement, setSelectedSettlement] = useState<SettlementRecord | null>(null);
  const [selectedAsset, setSelectedAsset] = useState<AssetHistoryRecord | null>(null);
  const [returnNotes, setReturnNotes] = useState('');
  const [dateRange, setDateRange] = useState<'year' | 'month'>('month');
  
  // 验收处理状态
  const [verificationItems, setVerificationItems] = useState<{
    itemId: string;
    actualQuantity: number;
    normalQty: number;
    damagedQty: number;
    lostQty: number;
    maintenanceQty: number;
    verificationNotes: string;
  }[]>([]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/return/register')) {
        setActiveTab('register');
      } else if (activePath.includes('/return/process')) {
        setActiveTab('process');
      } else if (activePath.includes('/return/settlement')) {
        setActiveTab('settlement');
      } else if (activePath.includes('/return/history')) {
        setActiveTab('history');
      }
    }
  }, [activePath]);

  // 模拟数据
  const [returnRecords, setReturnRecords] = useState<ReturnRecord[]>([
    {
      id: 'ret-1',
      code: 'GH202410150001',
      requisitionCode: 'LY202410140003',
      requisitionId: 'req-3',
      returner: '赵六',
      returnerId: 'emp-003',
      department: '种植三队',
      registerDate: '2024-10-15 16:30',
      items: [
        {
          id: 'item-1',
          materialId: 'mat-4',
          materialName: '滴灌管',
          materialType: '农具',
          borrowedQuantity: 200,
          returnedQuantity: 200,
          unit: '米',
          condition: '正常',
          batchNo: 'BATCH-20241001-001',
        },
      ],
      status: '已验收',
      processor: '仓库-张',
      processDate: '2024-10-15 17:00',
      processNotes: '物资完好，已入库',
      actualCondition: {
        normal: 200,
        damaged: 0,
        lost: 0,
        needMaintenance: 0,
      },
    },
    {
      id: 'ret-2',
      code: 'GH202410150002',
      requisitionCode: 'LY202410150001',
      requisitionId: 'req-1',
      returner: '张三',
      returnerId: 'emp-001',
      department: '种植一队',
      registerDate: '2024-10-15 18:00',
      items: [
        {
          id: 'item-2',
          materialId: 'mat-5',
          materialName: '喷雾器',
          materialType: '农具',
          borrowedQuantity: 5,
          returnedQuantity: 4,
          unit: '台',
          condition: '损坏',
          conditionNotes: '1台机器喷头损坏，1台遗失',
        },
      ],
      status: '待验收',
      notes: '施肥作业完成，1台喷雾器损坏需要维修',
    },
    {
      id: 'ret-3',
      code: 'GH202410140001',
      requisitionCode: 'LY202410120001',
      requisitionId: 'req-4',
      returner: '李四',
      returnerId: 'emp-004',
      department: '种植二队',
      registerDate: '2024-10-14 09:30',
      items: [
        {
          id: 'item-3',
          materialId: 'mat-6',
          materialName: '手推车',
          materialType: '农具',
          borrowedQuantity: 3,
          returnedQuantity: 3,
          unit: '辆',
          condition: '需要保养',
          conditionNotes: '轮胎磨损，需要润滑保养',
        },
      ],
      status: '已核销',
      processor: '仓库-李',
      processDate: '2024-10-14 10:00',
      processNotes: '已验收，转维修保养',
      actualCondition: {
        normal: 0,
        damaged: 0,
        lost: 0,
        needMaintenance: 3,
      },
    },
  ]);

  const [requisitionRecords, setRequisitionRecords] = useState<RequisitionRecord[]>([
    {
      id: 'req-3',
      code: 'LY202410140003',
      applicant: '赵六',
      applyDate: '2024-10-14 15:20',
      items: [
        {
          materialId: 'mat-4',
          materialName: '滴灌管',
          quantity: 200,
          unit: '米',
          returned: 200,
          pending: 0,
        },
      ],
      relatedField: '3号大棚',
      checkoutDate: '2024-10-15 08:00',
      status: '已归还',
    },
    {
      id: 'req-5',
      code: 'LY202410100001',
      applicant: '王五',
      applyDate: '2024-10-10 09:00',
      items: [
        {
          materialId: 'mat-7',
          materialName: '割草机',
          quantity: 2,
          unit: '台',
          returned: 0,
          pending: 2,
        },
        {
          materialId: 'mat-8',
          materialName: '除草机',
          quantity: 3,
          unit: '台',
          returned: 0,
          pending: 3,
        },
      ],
      relatedTask: '任务-2024005',
      checkoutDate: '2024-10-10 10:30',
      status: '未归还',
    },
    {
      id: 'req-6',
      code: 'LY202410080002',
      applicant: '孙七',
      applyDate: '2024-10-08 14:00',
      items: [
        {
          materialId: 'mat-9',
          materialName: '水泵',
          quantity: 1,
          unit: '台',
          returned: 1,
          pending: 0,
        },
        {
          materialId: 'mat-10',
          materialName: '水管',
          quantity: 100,
          unit: '米',
          returned: 80,
          pending: 20,
        },
      ],
      relatedField: '5号田块',
      checkoutDate: '2024-10-08 15:00',
      status: '部分归还',
    },
  ]);

  const [settlementRecords] = useState<SettlementRecord[]>([
    {
      id: 'settle-1',
      requisitionCode: 'LY202410140003',
      returnCode: 'GH202410150001',
      materialName: '滴灌管',
      borrowedQty: 200,
      returnedQty: 200,
      condition: '正常',
      settlementDate: '2024-10-15 17:30',
      processor: '仓库-张',
      status: '已核销',
      applyTime: '2024-10-14 09:00',
      approvalTime: '2024-10-14 10:30',
      checkoutTime: '2024-10-14 14:00',
      returnRegisterTime: '2024-10-15 16:30',
      verificationTime: '2024-10-15 17:00',
      items: [
        {
          materialName: '滴灌管',
          materialType: '灌溉设备',
          borrowedQty: 200,
          returnedQty: 200,
          unit: '米',
          normalQty: 200,
          damagedQty: 0,
          lostQty: 0,
          maintenanceQty: 0,
        },
      ],
    },
    {
      id: 'settle-2',
      requisitionCode: 'LY202410120001',
      returnCode: 'GH202410140001',
      materialName: '手推车',
      borrowedQty: 3,
      returnedQty: 3,
      condition: '需要保养',
      settlementDate: '2024-10-14 10:30',
      processor: '仓库-李',
      status: '已核销',
      applyTime: '2024-10-12 08:30',
      approvalTime: '2024-10-12 09:00',
      checkoutTime: '2024-10-12 10:00',
      returnRegisterTime: '2024-10-14 09:00',
      verificationTime: '2024-10-14 10:00',
      items: [
        {
          materialName: '手推车',
          materialType: '运输工具',
          borrowedQty: 3,
          returnedQty: 3,
          unit: '台',
          normalQty: 1,
          damagedQty: 0,
          lostQty: 0,
          maintenanceQty: 2,
        },
      ],
    },
    {
      id: 'settle-3',
      requisitionCode: 'LY202410150001',
      returnCode: 'GH202410150002',
      materialName: '喷雾器',
      borrowedQty: 5,
      returnedQty: 4,
      condition: '损坏',
      settlementDate: '2024-10-15 18:30',
      processor: '仓库-王',
      status: '待核销',
      applyTime: '2024-10-15 08:00',
      approvalTime: '2024-10-15 08:20',
      checkoutTime: '2024-10-15 09:00',
      returnRegisterTime: '2024-10-15 17:00',
      verificationTime: '2024-10-15 17:30',
      items: [
        {
          materialName: '喷雾器',
          materialType: '农具',
          borrowedQty: 5,
          returnedQty: 4,
          unit: '台',
          normalQty: 3,
          damagedQty: 1,
          lostQty: 1,
          maintenanceQty: 0,
        },
        {
          materialName: '药剂桶',
          materialType: '容器',
          borrowedQty: 2,
          returnedQty: 2,
          unit: '个',
          normalQty: 2,
          damagedQty: 0,
          lostQty: 0,
          maintenanceQty: 0,
        },
      ],
    },
  ]);

  const [assetHistory] = useState<AssetUsageHistory[]>([
    {
      id: 'asset-1',
      assetCode: 'TOOL-001',
      assetName: '割草机',
      assetType: '动力工具',
      totalBorrows: 45,
      currentStatus: '在用',
      borrowFrequency: 8.5,
      avgBorrowDuration: 5.2,
      damageCount: 2,
      maintenanceCount: 8,
      lastBorrowDate: '2024-10-10',
      lastReturnDate: '2024-10-15',
      utilizationRate: 78,
      conditionScore: 85,
      estimatedValue: 3500,
      depreciationRate: 15,
    },
    {
      id: 'asset-2',
      assetCode: 'TOOL-002',
      assetName: '喷雾器',
      assetType: '手动工具',
      totalBorrows: 62,
      currentStatus: '维修中',
      borrowFrequency: 10.3,
      avgBorrowDuration: 3.5,
      damageCount: 5,
      maintenanceCount: 12,
      lastBorrowDate: '2024-10-15',
      lastReturnDate: '2024-10-15',
      utilizationRate: 92,
      conditionScore: 65,
      estimatedValue: 800,
      depreciationRate: 25,
    },
    {
      id: 'asset-3',
      assetCode: 'TOOL-003',
      assetName: '手推车',
      assetType: '运输工具',
      totalBorrows: 89,
      currentStatus: '闲置',
      borrowFrequency: 12.5,
      avgBorrowDuration: 4.8,
      damageCount: 8,
      maintenanceCount: 15,
      lastBorrowDate: '2024-10-14',
      lastReturnDate: '2024-10-14',
      utilizationRate: 65,
      conditionScore: 70,
      estimatedValue: 1200,
      depreciationRate: 20,
    },
    {
      id: 'asset-4',
      assetCode: 'TOOL-004',
      assetName: '水泵',
      assetType: '动力工具',
      totalBorrows: 35,
      currentStatus: '在用',
      borrowFrequency: 5.8,
      avgBorrowDuration: 8.5,
      damageCount: 1,
      maintenanceCount: 5,
      lastBorrowDate: '2024-10-08',
      lastReturnDate: '2024-10-14',
      utilizationRate: 55,
      conditionScore: 90,
      estimatedValue: 4500,
      depreciationRate: 10,
    },
  ]);

  // 统计数据
  const totalReturns = returnRecords.length;
  const pendingProcess = returnRecords.filter(r => r.status === '待验收').length;
  const processed = returnRecords.filter(r => r.status === '已验收').length;
  const settled = returnRecords.filter(r => r.status === '已核销').length;
  const pendingReturns = requisitionRecords.filter(r => r.status === '未归还').length;
  const pendingSettlement = settlementRecords.filter(s => s.status === '待核销').length;
  const settledCount = settlementRecords.filter(s => s.status === '已核销').length;

  // 图表数据
  const conditionChartData = [
    { name: '正常', value: 15, color: '#10b981' },
    { name: '损坏', value: 3, color: '#ef4444' },
    { name: '遗失', value: 1, color: '#f59e0b' },
    { name: '需要保养', value: 5, color: '#3b82f6' },
  ];

  // 根据日期范围生成趋势数据
  const returnTrendData = dateRange === 'year' 
    ? [
        { period: '2020', count: 285, damage: 18, maintenance: 42 },
        { period: '2021', count: 342, damage: 25, maintenance: 51 },
        { period: '2022', count: 398, damage: 21, maintenance: 58 },
        { period: '2023', count: 456, damage: 29, maintenance: 67 },
        { period: '2024', count: 412, damage: 23, maintenance: 62 },
      ]
    : [
        { period: '6月', count: 28, damage: 2, maintenance: 5 },
        { period: '7月', count: 35, damage: 3, maintenance: 6 },
        { period: '8月', count: 32, damage: 1, maintenance: 4 },
        { period: '9月', count: 40, damage: 4, maintenance: 7 },
        { period: '10月', count: 38, damage: 2, maintenance: 6 },
      ];

  const utilizationData = assetHistory.slice(0, 5).map(asset => ({
    asset: asset.assetName,
    utilizationRate: asset.utilizationRate,
    conditionScore: asset.conditionScore,
  }));

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

  const getStatusColor = (status: ReturnStatus) => {
    switch (status) {
      case '待归还': return 'bg-yellow-100 text-yellow-700';
      case '已登记': return 'bg-blue-100 text-blue-700';
      case '待验收': return 'bg-orange-100 text-orange-700';
      case '已验收': return 'bg-green-100 text-green-700';
      case '已核销': return 'bg-purple-100 text-purple-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getConditionColor = (condition: MaterialCondition) => {
    switch (condition) {
      case '正常': return 'bg-green-100 text-green-700';
      case '损坏': return 'bg-red-100 text-red-700';
      case '遗失': return 'bg-orange-100 text-orange-700';
      case '需要保养': return 'bg-blue-100 text-blue-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getToolStatusColor = (status: ToolStatus) => {
    switch (status) {
      case '在用': return 'bg-green-100 text-green-700';
      case '闲置': return 'bg-gray-100 text-gray-700';
      case '维修中': return 'bg-orange-100 text-orange-700';
      case '已报废': return 'bg-red-100 text-red-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const handleRegisterReturn = () => {
    // 验证是否选择了领用单
    if (!selectedRequisition && selectedItems.length === 0) {
      toast.error('请先选择领用单');
      return;
    }

    // 验证归还数量
    const hasInvalidQuantity = selectedItems.some(item => 
      item.returnedQuantity <= 0 || item.returnedQuantity > item.borrowedQuantity
    );
    
    if (hasInvalidQuantity) {
      toast.error('归还数量不能为0或超过借出数量');
      return;
    }

    // 生成归还单号
    const returnCode = `GH${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(returnRecords.length + 1).padStart(4, '0')}`;
    
    // 创建新的归还记录
    const newReturnRecord: ReturnRecord = {
      id: `ret-${Date.now()}`,
      code: returnCode,
      requisitionCode: selectedRequisition?.code || '',
      requisitionId: selectedRequisition?.id || '',
      returner: selectedRequisition?.applicant || '当前用户',
      returnerId: 'emp-current',
      department: '种植一队',
      registerDate: new Date().toLocaleString('zh-CN'),
      items: selectedItems.map(item => ({
        ...item,
        batchNo: item.batchNo || `BATCH-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-001`,
      })),
      status: '待验收',
      notes: returnNotes,
    };
    
    // 添加到归还记录列表
    setReturnRecords([newReturnRecord, ...returnRecords]);
    
    // 更新领用单状态
    if (selectedRequisition) {
      setRequisitionRecords(requisitionRecords.map(req => {
        if (req.id === selectedRequisition.id) {
          // 计算已归还数量
          const updatedItems = req.items.map(reqItem => {
            const returnItem = selectedItems.find(si => si.materialId === reqItem.materialId);
            if (returnItem) {
              const newReturned = reqItem.returned + returnItem.returnedQuantity;
              return {
                ...reqItem,
                returned: newReturned,
                pending: reqItem.quantity - newReturned,
              };
            }
            return reqItem;
          });
          
          // 判断整体归还状态
          const allReturned = updatedItems.every(item => item.pending === 0);
          const someReturned = updatedItems.some(item => item.returned > 0);
          const newStatus = allReturned ? '已归还' : (someReturned ? '部分归还' : '未归还');
          
          return {
            ...req,
            items: updatedItems,
            status: newStatus as '未归还' | '部分归还' | '已归还',
          };
        }
        return req;
      }));
    }
    
    toast.success(`归还登记成功！归还单号: ${returnCode}`, {
      description: '等待仓库管理员验收，验收通过后将自动更新库存'
    });
    
    setShowRegisterDialog(false);
    setSelectedItems([]);
    setSelectedRequisition(null);
    setReturnNotes('');
  };

  const handleProcessReturn = () => {
    if (!selectedReturn) return;
    
    // 验证所有物资是否已验收
    const allVerified = verificationItems.length === selectedReturn.items.length;
    if (!allVerified) {
      toast.error('请完成所有物资的验收');
      return;
    }
    
    // 验证数量匹配
    const hasQuantityMismatch = verificationItems.some(item => {
      const totalVerified = item.normalQty + item.damagedQty + item.lostQty + item.maintenanceQty;
      return totalVerified !== item.actualQuantity;
    });
    
    if (hasQuantityMismatch) {
      toast.error('验收数量分配错误，请检查各状态数量总和是否等于实际验收数量');
      return;
    }
    
    // 统计验收结果
    let totalNormal = 0;
    let totalDamaged = 0;
    let totalLost = 0;
    let totalMaintenance = 0;
    
    verificationItems.forEach(item => {
      totalNormal += item.normalQty;
      totalDamaged += item.damagedQty;
      totalLost += item.lostQty;
      totalMaintenance += item.maintenanceQty;
    });
    
    // 更新归还记录状态为"已验收"
    setReturnRecords(returnRecords.map(record => {
      if (record.id === selectedReturn.id) {
        return {
          ...record,
          status: '已验收',
          processor: '仓库-张',
          processDate: new Date().toLocaleString('zh-CN'),
          processNotes: `验收完成：正常${totalNormal}件，损坏${totalDamaged}件，遗失${totalLost}件，需保养${totalMaintenance}件`,
          actualCondition: {
            normal: totalNormal,
            damaged: totalDamaged,
            lost: totalLost,
            needMaintenance: totalMaintenance,
          },
        };
      }
      return record;
    }));
    
    // 显示验收结果摘要
    const messages = [];
    if (totalNormal > 0) messages.push(`正常物资 ${totalNormal} 件已入库`);
    if (totalDamaged > 0) messages.push(`损坏物资 ${totalDamaged} 件已转维修`);
    if (totalLost > 0) messages.push(`遗失物资 ${totalLost} 件已记录损失`);
    if (totalMaintenance > 0) messages.push(`需保养物资 ${totalMaintenance} 件已安排保养`);
    
    toast.success('归还验收完成，系统已更新库存和状态', {
      description: messages.join('；')
    });
    
    setShowProcessDialog(false);
    setVerificationItems([]);
    setSelectedReturn(null);
  };
  
  const handleSettlement = () => {
    if (!selectedReturn) return;
    
    toast.success('核销完成', {
      description: '领用记录已关联核销，借-还闭环已完成'
    });
    
    setShowSettlementDialog(false);
  };

  const handleAddItem = () => {
    const newItem: ReturnItem = {
      id: `item-${Date.now()}`,
      materialId: '',
      materialName: '',
      materialType: '',
      borrowedQuantity: 0,
      returnedQuantity: 0,
      unit: '',
      condition: '正常',
    };
    setSelectedItems([...selectedItems, newItem]);
  };

  const handleRemoveItem = (itemId: string) => {
    setSelectedItems(selectedItems.filter(item => item.id !== itemId));
  };

  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>
        <Button className="bg-green-600 hover:bg-green-700" onClick={() => {
          setSelectedItems([]);
          setSelectedRequisition(null);
          setReturnNotes('');
          setShowRegisterDialog(true);
        }}>
          <Plus className="w-4 h-4 mr-2" />
          新建归还登记
        </Button>
      </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-green-600">{totalReturns}</p>
              <p className="text-xs text-green-600 mt-1">本月新增 {totalReturns} 项</p>
            </div>
            <RotateCcw className="w-12 h-12 text-green-600 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-orange-600">{pendingProcess}</p>
              <p className="text-xs text-orange-600 mt-1">需及时处理</p>
            </div>
            <Clock className="w-12 h-12 text-orange-600 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-blue-600">{processed}</p>
              <p className="text-xs text-blue-600 mt-1">待核销处理</p>
            </div>
            <CheckCircle className="w-12 h-12 text-blue-600 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-purple-600">{settled}</p>
              <p className="text-xs text-green-600 mt-1">完成率 100%</p>
            </div>
            <FileCheck className="w-12 h-12 text-purple-600 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-yellow-600">{pendingReturns}</p>
              <p className="text-xs text-red-600 mt-1">超期 2 项</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-yellow-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="register">归还登记</TabsTrigger>
          <TabsTrigger value="process">归还处理</TabsTrigger>
          <TabsTrigger value="settlement">领用记录关联核销</TabsTrigger>
          <TabsTrigger value="history">归还历史与资产台账</TabsTrigger>
        </TabsList>

        {/* 归还登记 */}
        <TabsContent value="register" className="space-y-4">
          <Card className="p-4 bg-green-50 border-green-200">
            <div className="flex items-start gap-2">
              <RotateCcw className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">归还登记功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>移动端发起</strong>: 归还人可通过移动端发起归还申请</li>
                  <li>• <strong>关联原单</strong>: 选择原领用单，自动带出物资信息</li>
                  <li>• <strong>登记数量</strong>: 登记本次归还的物资、数量</li>
                  <li>• <strong>状态备注</strong>: 可备注说明物资当前状态（正常、损坏、需要保养）</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 待归还领用单 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Package className="w-5 h-5 text-yellow-600" />
                待归还领用单 ({pendingReturns})
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>领用单号</TableHead>
                  <TableHead>领用人</TableHead>
                  <TableHead>领用时间</TableHead>
                  <TableHead>出库时间</TableHead>
                  <TableHead>物品清单</TableHead>
                  <TableHead>关联信息</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {requisitionRecords.filter(r => r.status !== '已归还').map((req) => (
                  <TableRow key={req.id}>
                    <TableCell className="font-medium">{req.code}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-muted-foreground" />
                        {req.applicant}
                      </div>
                    </TableCell>
                    <TableCell>{req.applyDate}</TableCell>
                    <TableCell>{req.checkoutDate}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {req.items.map((item, idx) => (
                          <div key={idx} className="text-xs">
                            {item.materialName} × {item.quantity}{item.unit}
                            {item.pending > 0 && (
                              <span className="text-orange-600 ml-1">
                                (待还: {item.pending}{item.unit})
                              </span>
                            )}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs">
                        {req.relatedField && (
                          <div className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            {req.relatedField}
                          </div>
                        )}
                        {req.relatedTask && (
                          <div className="flex items-center gap-1">
                            <FileText className="w-3 h-3" />
                            {req.relatedTask}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={
                        req.status === '未归还' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'
                      }>
                        {req.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        className="bg-green-600 hover:bg-green-700"
                        onClick={() => {
                          setSelectedRequisition(req);
                          setSelectedItems(req.items.map(item => ({
                            id: `item-${item.materialId}`,
                            materialId: item.materialId,
                            materialName: item.materialName,
                            materialType: '农具',
                            borrowedQuantity: item.quantity,
                            returnedQuantity: item.pending,
                            unit: item.unit,
                            condition: '正常',
                          })));
                          setShowRegisterDialog(true);
                        }}
                      >
                        <Send className="w-3 h-3 mr-1" />
                        登记归还
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 归还登记记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <History className="w-5 h-5 text-gray-600" />
                归还登记记录
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>归还单号</TableHead>
                  <TableHead>关联领用单</TableHead>
                  <TableHead>归还人</TableHead>
                  <TableHead>登记时间</TableHead>
                  <TableHead>归还物品</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {returnRecords.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.code}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1 text-xs">
                        <Link2 className="w-3 h-3" />
                        {record.requisitionCode}
                      </div>
                    </TableCell>
                    <TableCell>{record.returner}</TableCell>
                    <TableCell>{record.registerDate}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {record.items.map(item => (
                          <div key={item.id} className="text-xs">
                            {item.materialName} × {item.returnedQuantity}{item.unit}
                            <Badge className={`ml-2 ${getConditionColor(item.condition)}`} variant="outline">
                              {item.condition}
                            </Badge>
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(record.status)}>{record.status}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setSelectedReturn(record);
                            setShowDetailDialog(true);
                          }}
                        >
                          <Eye className="w-3 h-3" />
                        </Button>
                        {record.status === '已登记' && (
                          <Button size="sm" variant="outline">
                            <Edit className="w-3 h-3" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 归还处理 */}
        <TabsContent value="process" className="space-y-4">
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <CheckSquare className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">归还处理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>现场接收</strong>: 仓库管理员根据归还申请单现场接收物资</li>
                  <li>• <strong>查验清点</strong>: 查验清点实物，确认归还数量与完好程度</li>
                  <li>• <strong>状态记录</strong>: 记录验收结果（正常、损坏、遗失）</li>
                  <li>• <strong>智能更新</strong>: 验收完成后系统根据结果智能更新库存</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 待验收列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Clock className="w-5 h-5 text-orange-600" />
                待验收归还 ({pendingProcess})
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>归还单号</TableHead>
                  <TableHead>关联领用单</TableHead>
                  <TableHead>归还人</TableHead>
                  <TableHead>登记时间</TableHead>
                  <TableHead>归还物品</TableHead>
                  <TableHead>申报状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {returnRecords.filter(r => r.status === '待验收').map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.code}</TableCell>
                    <TableCell>{record.requisitionCode}</TableCell>
                    <TableCell>{record.returner}</TableCell>
                    <TableCell>{record.registerDate}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {record.items.map(item => (
                          <div key={item.id} className="text-xs">
                            {item.materialName} × {item.returnedQuantity}{item.unit}
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        {record.items.map(item => (
                          <Badge key={item.id} className={getConditionColor(item.condition)} variant="outline">
                            {item.condition}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        className="bg-blue-600 hover:bg-blue-700"
                        onClick={() => {
                          setSelectedReturn(record);
                          // 初始化验收数据
                          setVerificationItems(record.items.map(item => ({
                            itemId: item.id,
                            actualQuantity: item.returnedQuantity,
                            normalQty: item.condition === '正常' ? item.returnedQuantity : 0,
                            damagedQty: item.condition === '损坏' ? item.returnedQuantity : 0,
                            lostQty: item.condition === '遗失' ? item.returnedQuantity : 0,
                            maintenanceQty: item.condition === '需要保养' ? item.returnedQuantity : 0,
                            verificationNotes: item.conditionNotes || '',
                          })));
                          setShowProcessDialog(true);
                        }}
                      >
                        <Scan className="w-3 h-3 mr-1" />
                        开始验收
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 验收记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <FileCheck className="w-5 h-5 text-green-600" />
                验收记录
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>归还单号</TableHead>
                  <TableHead>验收人</TableHead>
                  <TableHead>验收时间</TableHead>
                  <TableHead>验收结果</TableHead>
                  <TableHead>实际状况</TableHead>
                  <TableHead>验收备注</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {returnRecords.filter(r => r.status === '已验收' || r.status === '已核销').map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.code}</TableCell>
                    <TableCell>{record.processor}</TableCell>
                    <TableCell>{record.processDate}</TableCell>
                    <TableCell>
                      <Badge className="bg-green-100 text-green-700">验收通过</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1 text-xs">
                        {record.actualCondition && (
                          <>
                            {record.actualCondition.normal > 0 && (
                              <div className="flex items-center gap-1">
                                <CheckCircle className="w-3 h-3 text-green-600" />
                                正常: {record.actualCondition.normal}
                              </div>
                            )}
                            {record.actualCondition.damaged > 0 && (
                              <div className="flex items-center gap-1">
                                <AlertCircle className="w-3 h-3 text-red-600" />
                                损坏: {record.actualCondition.damaged}
                              </div>
                            )}
                            {record.actualCondition.lost > 0 && (
                              <div className="flex items-center gap-1">
                                <XCircle className="w-3 h-3 text-orange-600" />
                                遗失: {record.actualCondition.lost}
                              </div>
                            )}
                            {record.actualCondition.needMaintenance > 0 && (
                              <div className="flex items-center gap-1">
                                <Wrench className="w-3 h-3 text-blue-600" />
                                需保养: {record.actualCondition.needMaintenance}
                              </div>
                            )}
                          </>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>{record.processNotes}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 领用记录关联核销 */}
        <TabsContent value="settlement" className="space-y-4">
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Link2 className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">领用记录关联核销功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动关联</strong>: 系统自动将归还记录与原始领用出库记录关联</li>
                  <li>• <strong>借还闭环</strong>: 形成完整的"借-还"闭环管理</li>
                  <li>• <strong>有据可查</strong>: 确保每笔领用都有据可查���有踪可循</li>
                  <li>• <strong>差异处理</strong>: 自动识别数量差异、状态差异并提醒处理</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 核销流程图 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5" />
              借还闭环流程
            </h4>
            <div className="flex items-center justify-around py-8">
              <div className="flex flex-col items-center">
                <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-2">
                  <FileText className="w-8 h-8 text-green-600" />
                </div>
                <p className="text-sm">领用申请</p>
                <p className="text-xs text-muted-foreground mt-1">发起领用</p>
              </div>
              <div className="flex-1 h-0.5 bg-gray-300 mx-2"></div>
              <div className="flex flex-col items-center">
                <div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center mb-2">
                  <Package className="w-8 h-8 text-blue-600" />
                </div>
                <p className="text-sm">物资出库</p>
                <p className="text-xs text-muted-foreground mt-1">领取物资</p>
              </div>
              <div className="flex-1 h-0.5 bg-gray-300 mx-2"></div>
              <div className="flex flex-col items-center">
                <div className="w-16 h-16 rounded-full bg-orange-100 flex items-center justify-center mb-2">
                  <RotateCcw className="w-8 h-8 text-orange-600" />
                </div>
                <p className="text-sm">归还登记</p>
                <p className="text-xs text-muted-foreground mt-1">登记归还</p>
              </div>
              <div className="flex-1 h-0.5 bg-gray-300 mx-2"></div>
              <div className="flex flex-col items-center">
                <div className="w-16 h-16 rounded-full bg-purple-100 flex items-center justify-center mb-2">
                  <CheckSquare className="w-8 h-8 text-purple-600" />
                </div>
                <p className="text-sm">验收核销</p>
                <p className="text-xs text-muted-foreground mt-1">完成闭环</p>
              </div>
            </div>
          </Card>

          {/* 核销统计卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">待核销</p>
                  <p className="mt-2 text-2xl text-orange-600">{pendingSettlement}</p>
                  <p className="text-xs text-orange-600 mt-1">需及时处理</p>
                </div>
                <AlertTriangle className="w-10 h-10 text-orange-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">已核销</p>
                  <p className="mt-2 text-2xl text-green-600">{settledCount}</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">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">核销完成率</p>
                  <p className="mt-2 text-2xl text-blue-600">
                    {settlementRecords.length > 0 
                      ? Math.round((settledCount / settlementRecords.length) * 100)
                      : 0}%
                  </p>
                  <p className="text-xs text-blue-600 mt-1">本月数据</p>
                </div>
                <TrendingUp className="w-10 h-10 text-blue-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">异常差异</p>
                  <p className="mt-2 text-2xl text-red-600">
                    {settlementRecords.filter(s => s.borrowedQty !== s.returnedQty).length}
                  </p>
                  <p className="text-xs text-red-600 mt-1">需要处理</p>
                </div>
                <AlertCircle className="w-10 h-10 text-red-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 核销记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <FileCheck className="w-5 h-5 text-purple-600" />
                核销记录查询
              </h3>
            </div>

            <div className="p-4 border-b">
              <div className="flex gap-4">
                <div className="flex-1">
                  <Input placeholder="搜索领用单号、归还单号..." prefix={<Search className="w-4 h-4" />} />
                </div>
                <Select defaultValue="all">
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="核销状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="settled">已核销</SelectItem>
                    <SelectItem value="pending">待核销</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>领用单号</TableHead>
                  <TableHead>归还单号</TableHead>
                  <TableHead>物资名称</TableHead>
                  <TableHead>领用数量</TableHead>
                  <TableHead>归还数量</TableHead>
                  <TableHead>物资状态</TableHead>
                  <TableHead>核销时间</TableHead>
                  <TableHead>核销人</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {settlementRecords.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-medium">{record.requisitionCode}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1 text-xs">
                        <Link2 className="w-3 h-3" />
                        {record.returnCode}
                      </div>
                    </TableCell>
                    <TableCell>{record.materialName}</TableCell>
                    <TableCell>{record.borrowedQty}</TableCell>
                    <TableCell>
                      {record.returnedQty}
                      {record.borrowedQty !== record.returnedQty && (
                        <Badge className="ml-2 bg-orange-100 text-orange-700" variant="outline">
                          差异: {record.borrowedQty - record.returnedQty}
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge className={getConditionColor(record.condition as MaterialCondition)} variant="outline">
                        {record.condition}
                      </Badge>
                    </TableCell>
                    <TableCell>{record.settlementDate}</TableCell>
                    <TableCell>{record.processor}</TableCell>
                    <TableCell>
                      <Badge className={
                        record.status === '已核销' 
                          ? 'bg-green-100 text-green-700' 
                          : 'bg-yellow-100 text-yellow-700'
                      }>
                        {record.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          setSelectedSettlement(record);
                          setShowSettlementDetailDialog(true);
                        }}
                      >
                        <Eye className="w-3 h-3 mr-1" />
                        详情
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 归还历史与资产台账 */}
        <TabsContent value="history" className="space-y-4">
          {/* 日期范围选择器 */}
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Calendar className="w-5 h-5 text-blue-600" />
                <h3 className="font-medium">数据统计报表</h3>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">时间范围：</span>
                <div className="flex bg-gray-100 rounded-lg p-1">
                  <button
                    onClick={() => setDateRange('month')}
                    className={`px-4 py-1.5 rounded-md text-sm transition-all ${
                      dateRange === 'month'
                        ? 'bg-white text-green-700 shadow-sm font-medium'
                        : 'text-gray-600 hover:text-gray-900'
                    }`}
                  >
                    按月
                  </button>
                  <button
                    onClick={() => setDateRange('year')}
                    className={`px-4 py-1.5 rounded-md text-sm transition-all ${
                      dateRange === 'year'
                        ? 'bg-white text-green-700 shadow-sm font-medium'
                        : 'text-gray-600 hover:text-gray-900'
                    }`}
                  >
                    按年
                  </button>
                </div>
              </div>
            </div>
          </Card>

          <Card className="p-4 bg-orange-50 border-orange-200">
            <div className="flex items-start gap-2">
              <Archive className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-orange-900">
                <p className="mb-2">归还历史与资产台账功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>使用频率统计</strong>: 提供所有资产（特别是工具类）的借用频率分析</li>
                  <li>• <strong>归还历史查询</strong>: 完整记录每次借还的状态变化历史</li>
                  <li>• <strong>使用率分析</strong>: 深度分析资产使用率、损耗情况、闲置率</li>
                  <li>• <strong>损耗趋势预测</strong>: 基于历史数据预测资产损耗和维修需求</li>
                  <li>• <strong>决策支持</strong>: 为采购、维修、报废决策提供数据依据</li>
                  <li>• <strong>成本核算</strong>: 统计资产使用成本、维护成本、损失成本</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 资产使用概览统计 */}
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">总资产数</p>
                  <p className="mt-2 text-2xl text-blue-600">{assetHistory.length}</p>
                  <p className="text-xs text-blue-600 mt-1">在管资产</p>
                </div>
                <Package className="w-10 h-10 text-blue-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">平均利用率</p>
                  <p className="mt-2 text-2xl text-green-600">
                    {assetHistory.length > 0 
                      ? Math.round(assetHistory.reduce((sum, a) => sum + a.utilizationRate, 0) / assetHistory.length)
                      : 0}%
                  </p>
                  <p className="text-xs text-green-600 mt-1">综合评估</p>
                </div>
                <TrendingUp className="w-10 h-10 text-green-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">高频使用</p>
                  <p className="mt-2 text-2xl text-purple-600">
                    {assetHistory.filter(a => a.utilizationRate >= 80).length}
                  </p>
                  <p className="text-xs text-purple-600 mt-1">利用率≥80%</p>
                </div>
                <Zap className="w-10 h-10 text-purple-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">闲置资产</p>
                  <p className="mt-2 text-2xl text-orange-600">
                    {assetHistory.filter(a => a.utilizationRate < 30).length}
                  </p>
                  <p className="text-xs text-orange-600 mt-1">利用率＜30%</p>
                </div>
                <AlertTriangle className="w-10 h-10 text-orange-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">需维修</p>
                  <p className="mt-2 text-2xl text-red-600">
                    {assetHistory.filter(a => a.currentStatus === '待维修' || a.damageCount > 3).length}
                  </p>
                  <p className="text-xs text-red-600 mt-1">状况不良</p>
                </div>
                <Wrench className="w-10 h-10 text-red-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 决策建议卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Card className="p-4 bg-green-50 border-green-200">
              <div className="flex items-start gap-2">
                <ShoppingCart className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h4 className="font-medium text-green-900 mb-2">采购建议</h4>
                  <div className="space-y-2 text-xs text-green-800">
                    <div className="flex items-center gap-2">
                      <CheckCircle className="w-3 h-3" />
                      <span>高频工具（利用率≥80%）建议增购</span>
                    </div>
                    <div className="border-t border-green-200 pt-2 mt-2">
                      <p className="font-medium mb-1">推荐增购清单：</p>
                      {assetHistory.filter(a => a.utilizationRate >= 80).slice(0, 3).map(a => (
                        <div key={a.id} className="flex items-center justify-between py-1">
                          <span>{a.assetName}</span>
                          <Badge className="bg-green-200 text-green-800" variant="outline">
                            利用率{a.utilizationRate}%
                          </Badge>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            <Card className="p-4 bg-blue-50 border-blue-200">
              <div className="flex items-start gap-2">
                <Wrench className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h4 className="font-medium text-blue-900 mb-2">维修建议</h4>
                  <div className="space-y-2 text-xs text-blue-800">
                    <div className="flex items-center gap-2">
                      <AlertCircle className="w-3 h-3" />
                      <span>损坏次数≥3次的资产需重点关注</span>
                    </div>
                    <div className="border-t border-blue-200 pt-2 mt-2">
                      <p className="font-medium mb-1">优先维修清单：</p>
                      {assetHistory.filter(a => a.damageCount >= 3 || a.conditionScore < 60).slice(0, 3).map(a => (
                        <div key={a.id} className="flex items-center justify-between py-1">
                          <span>{a.assetName}</span>
                          <Badge className="bg-blue-200 text-blue-800" variant="outline">
                            损坏{a.damageCount}次
                          </Badge>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            <Card className="p-4 bg-red-50 border-red-200">
              <div className="flex items-start gap-2">
                <Trash2 className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
                <div>
                  <h4 className="font-medium text-red-900 mb-2">报废建议</h4>
                  <div className="space-y-2 text-xs text-red-800">
                    <div className="flex items-center gap-2">
                      <XCircle className="w-3 h-3" />
                      <span>状况评分＜40分且闲置建议报废</span>
                    </div>
                    <div className="border-t border-red-200 pt-2 mt-2">
                      <p className="font-medium mb-1">建议报废清单：</p>
                      {assetHistory.filter(a => a.conditionScore < 40 || (a.utilizationRate < 10 && a.damageCount > 0)).slice(0, 3).map(a => (
                        <div key={a.id} className="flex items-center justify-between py-1">
                          <span>{a.assetName}</span>
                          <Badge className="bg-red-200 text-red-800" variant="outline">
                            评分{a.conditionScore}
                          </Badge>
                        </div>
                      ))}
                      {assetHistory.filter(a => a.conditionScore < 40 || (a.utilizationRate < 10 && a.damageCount > 0)).length === 0 && (
                        <p className="text-muted-foreground">暂无需报废资产</p>
                      )}
                    </div>
                  </div>
                </div>
              </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">
                <PieChart className="w-4 h-4" />
                归还物资状态分布
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={conditionChartData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, value }) => `${name}: ${value}`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {conditionChartData.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">
                <TrendingUp className="w-4 h-4" />
                归还趋势与损坏率
                <Badge variant="outline" className="ml-2 text-xs">
                  {dateRange === 'year' ? '按年统计' : '按月统计'}
                </Badge>
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={returnTrendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="period" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line type="monotone" dataKey="count" stroke="#10b981" name="归还次数" strokeWidth={2} />
                  <Line type="monotone" dataKey="damage" stroke="#ef4444" name="损坏次数" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4 col-span-2">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4" />
                资产利用率分析
              </h4>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={utilizationData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="asset" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Bar dataKey="utilizationRate" fill="#3b82f6" name="利用率(%)" />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            {/* 借用频率排行 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-purple-600" />
                借用频率TOP10
              </h4>
              <div className="space-y-2">
                {assetHistory
                  .sort((a, b) => b.totalBorrows - a.totalBorrows)
                  .slice(0, 10)
                  .map((asset, index) => (
                    <div key={asset.id} className="flex items-center gap-2">
                      <div className={`w-6 h-6 rounded flex items-center justify-center text-xs ${
                        index === 0 ? 'bg-yellow-100 text-yellow-700' :
                        index === 1 ? 'bg-gray-100 text-gray-700' :
                        index === 2 ? 'bg-orange-100 text-orange-700' :
                        'bg-blue-50 text-blue-600'
                      }`}>
                        {index + 1}
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-sm">{asset.assetName}</span>
                          <span className="text-xs text-muted-foreground">
                            {asset.totalBorrows}次 ({asset.borrowFrequency}次/月)
                          </span>
                        </div>
                        <div className="h-1.5 bg-gray-200 rounded-full overflow-hidden">
                          <div 
                            className="h-full bg-purple-500"
                            style={{ width: `${(asset.totalBorrows / assetHistory[0]?.totalBorrows * 100) || 0}%` }}
                          />
                        </div>
                      </div>
                    </div>
                  ))}
              </div>
            </Card>

            {/* 资产类型分布 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Package className="w-4 h-4 text-blue-600" />
                资产类型分布与使用情况
              </h4>
              <div className="space-y-3">
                {Array.from(new Set(assetHistory.map(a => a.assetType))).map(type => {
                  const typeAssets = assetHistory.filter(a => a.assetType === type);
                  const avgUtilization = Math.round(
                    typeAssets.reduce((sum, a) => sum + a.utilizationRate, 0) / typeAssets.length
                  );
                  return (
                    <div key={type} className="border-l-4 border-blue-500 pl-3">
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium text-sm">{type}</span>
                        <div className="flex items-center gap-2 text-xs">
                          <Badge variant="outline">{typeAssets.length}件</Badge>
                          <Badge className="bg-blue-100 text-blue-700">{avgUtilization}%平均利用率</Badge>
                        </div>
                      </div>
                      <div className="grid grid-cols-3 gap-2 text-xs text-muted-foreground">
                        <div>借用: {typeAssets.reduce((sum, a) => sum + a.totalBorrows, 0)}次</div>
                        <div>损坏: {typeAssets.reduce((sum, a) => sum + a.damageCount, 0)}次</div>
                        <div>保养: {typeAssets.reduce((sum, a) => sum + a.maintenanceCount, 0)}次</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </Card>

          </div>

          {/* 资产台账 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Wrench className="w-5 h-5 text-green-600" />
                资产使用台账
              </h3>
            </div>

            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>资产编号</TableHead>
                    <TableHead>资产名称</TableHead>
                    <TableHead>资产类型</TableHead>
                    <TableHead>借用次数</TableHead>
                    <TableHead>借用频率</TableHead>
                    <TableHead>平均借用天数</TableHead>
                    <TableHead>损坏次数</TableHead>
                    <TableHead>保养次数</TableHead>
                    <TableHead>利用率</TableHead>
                    <TableHead>当前状态</TableHead>
                    <TableHead>预估价值</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {assetHistory.map((asset) => (
                    <TableRow key={asset.id}>
                      <TableCell className="font-medium">{asset.assetCode}</TableCell>
                      <TableCell>{asset.assetName}</TableCell>
                      <TableCell>{asset.assetType}</TableCell>
                      <TableCell>{asset.totalBorrows}次</TableCell>
                      <TableCell>{asset.borrowFrequency}次/月</TableCell>
                      <TableCell>{asset.avgBorrowDuration}天</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          {asset.damageCount > 0 && (
                            <AlertCircle className="w-3 h-3 text-red-600" />
                          )}
                          {asset.damageCount}次
                        </div>
                      </TableCell>
                      <TableCell>{asset.maintenanceCount}次</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                            <div
                              className={`h-full ${
                                asset.utilizationRate >= 80 ? 'bg-green-500' :
                                asset.utilizationRate >= 50 ? 'bg-yellow-500' : 'bg-red-500'
                              }`}
                              style={{ width: `${asset.utilizationRate}%` }}
                            />
                          </div>
                          <span className="text-xs">{asset.utilizationRate}%</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={getToolStatusColor(asset.currentStatus)}>
                          {asset.currentStatus}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div>
                          <div>¥{asset.estimatedValue.toLocaleString()}</div>
                          <div className="text-xs text-muted-foreground">
                            折旧率: {asset.depreciationRate}%
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Button 
                          size="sm" 
                          variant="outline"
                          onClick={() => {
                            setSelectedAsset(asset);
                            setShowAssetDetailDialog(true);
                          }}
                        >
                          <Eye className="w-3 h-3 mr-1" />
                          详情
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 归还登记对话框 - 增强版 */}
      <Dialog open={showRegisterDialog} onOpenChange={setShowRegisterDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <RotateCcw className="w-5 h-5 text-green-600" />
              物资归还登记
            </DialogTitle>
            <DialogDescription>
              选择原领用单，登记归还物资信息，请如实填写物资当前状态
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-5">
            {/* 关联领用单信息 */}
            {selectedRequisition ? (
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="flex items-center gap-2 text-sm font-medium">
                    <Link2 className="w-4 h-4 text-blue-600" />
                    关联领用单信息
                  </h4>
                  <Button 
                    size="sm" 
                    variant="ghost"
                    onClick={() => {
                      setSelectedRequisition(null);
                      setSelectedItems([]);
                    }}
                  >
                    <XCircle className="w-3 h-3 mr-1" />
                    重新选择
                  </Button>
                </div>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">领用单号</p>
                    <p className="font-medium">{selectedRequisition.code}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">领用人</p>
                    <p className="font-medium">{selectedRequisition.applicant}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">出库时间</p>
                    <p>{selectedRequisition.checkoutDate}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">关联信息</p>
                    <div className="flex items-center gap-1 text-xs">
                      {selectedRequisition.relatedField && (
                        <Badge variant="outline" className="bg-white">
                          <MapPin className="w-3 h-3 mr-1" />
                          {selectedRequisition.relatedField}
                        </Badge>
                      )}
                      {selectedRequisition.relatedTask && (
                        <Badge variant="outline" className="bg-white">
                          <FileText className="w-3 h-3 mr-1" />
                          {selectedRequisition.relatedTask}
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              </Card>
            ) : (
              <div>
                <Label>选择原领用单 <span className="text-red-500">*</span></Label>
                <Select onValueChange={(value) => {
                  const req = requisitionRecords.find(r => r.id === value);
                  if (req) {
                    setSelectedRequisition(req);
                    setSelectedItems(req.items.map(item => ({
                      id: `item-${item.materialId}`,
                      materialId: item.materialId,
                      materialName: item.materialName,
                      materialType: '农具',
                      borrowedQuantity: item.quantity,
                      returnedQuantity: item.pending,
                      unit: item.unit,
                      condition: '正常',
                    })));
                  }
                }}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择需要归还的领用单" />
                  </SelectTrigger>
                  <SelectContent>
                    {requisitionRecords.filter(r => r.status !== '已归还').map(req => (
                      <SelectItem key={req.id} value={req.id}>
                        <div className="flex items-center gap-2 py-1">
                          <span className="font-medium">{req.code}</span>
                          <span className="text-muted-foreground">-</span>
                          <span>{req.applicant}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {requisitionRecords.filter(r => r.status !== '已归还').length === 0 && (
                  <p className="text-xs text-muted-foreground mt-2">
                    当前没有待归还的领用单
                  </p>
                )}
              </div>
            )}

            {/* 归还人信息 */}
            <div className="grid grid-cols-3 gap-4">
              <div>
                <Label className="text-sm">归还人</Label>
                <div className="flex items-center gap-2 mt-2 px-3 py-2 bg-gray-50 rounded-md border">
                  <User className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm">{selectedRequisition?.applicant || '当前用户'}</span>
                </div>
              </div>
              <div>
                <Label className="text-sm">归还登记时间</Label>
                <div className="flex items-center gap-2 mt-2 px-3 py-2 bg-gray-50 rounded-md border">
                  <Calendar className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm">{new Date().toLocaleString('zh-CN')}</span>
                </div>
              </div>
              <div>
                <Label className="text-sm">所属部门</Label>
                <div className="flex items-center gap-2 mt-2 px-3 py-2 bg-gray-50 rounded-md border">
                  <Tag className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm">{selectedRequisition ? '种植一队' : '-'}</span>
                </div>
              </div>
            </div>

            {/* 归还物品清单 */}
            <div>
              <Label>归还物品清单</Label>
              <div className="space-y-2 mt-2">
                {selectedItems.map((item) => (
                  <Card key={item.id} className="p-3">
                    <div className="grid grid-cols-6 gap-2 items-end">
                      <div className="col-span-2">
                        <Label className="text-xs">物资名称</Label>
                        <Input value={item.materialName} disabled />
                      </div>
                      <div>
                        <Label className="text-xs">借出数量</Label>
                        <Input value={item.borrowedQuantity} disabled />
                      </div>
                      <div>
                        <Label className="text-xs">归还数量</Label>
                        <Input 
                          type="number" 
                          value={item.returnedQuantity} 
                          max={item.borrowedQuantity}
                          onChange={(e) => {
                            const newQty = Number(e.target.value);
                            setSelectedItems(selectedItems.map(i => 
                              i.id === item.id ? { ...i, returnedQuantity: newQty } : i
                            ));
                          }}
                        />
                      </div>
                      <div>
                        <Label className="text-xs">物资状态</Label>
                        <Select 
                          value={item.condition}
                          onValueChange={(value: MaterialCondition) => {
                            setSelectedItems(selectedItems.map(i => 
                              i.id === item.id ? { ...i, condition: value } : i
                            ));
                          }}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="正常">正常</SelectItem>
                            <SelectItem value="损坏">损坏</SelectItem>
                            <SelectItem value="遗失">遗失</SelectItem>
                            <SelectItem value="需要保养">需要保养</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label className="text-xs">备注</Label>
                        <Input 
                          placeholder="状态说明"
                          value={item.conditionNotes || ''}
                          onChange={(e) => {
                            setSelectedItems(selectedItems.map(i => 
                              i.id === item.id ? { ...i, conditionNotes: e.target.value } : i
                            ));
                          }}
                        />
                      </div>
                    </div>
                  </Card>
                ))}
                {selectedItems.length === 0 && (
                  <div className="text-center py-8 text-muted-foreground">
                    请先选择领用单
                  </div>
                )}
              </div>
            </div>

            <div>
              <Label>归还备注</Label>
              <Textarea 
                placeholder="填写归还说明、物资使用情况等..." 
                rows={3}
                value={returnNotes}
                onChange={(e) => setReturnNotes(e.target.value)}
              />
            </div>

            <Card className="p-3 bg-yellow-50 border-yellow-200">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-4 h-4 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div className="text-xs text-yellow-900">
                  <p>温馨提示：</p>
                  <ul className="mt-1 space-y-0.5">
                    <li>• 请如实填写物资状态，便于仓库管理员验收</li>
                    <li>• 损坏或遗失的物资将进入后续处理流程</li>
                    <li>• 需要保养的物资将安排维护保养</li>
                  </ul>
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter className="gap-2">
            <Button 
              variant="outline" 
              onClick={() => {
                setShowRegisterDialog(false);
                setSelectedItems([]);
                setSelectedRequisition(null);
                setReturnNotes('');
              }}
            >
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={handleRegisterReturn}
              disabled={selectedItems.length === 0}
            >
              <Send className="w-4 h-4 mr-2" />
              提交归还登记
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 归还处理对话框 - 增强版 */}
      <Dialog open={showProcessDialog} onOpenChange={(open) => {
        setShowProcessDialog(open);
        if (!open) {
          setVerificationItems([]);
          setSelectedReturn(null);
        }
      }}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckSquare className="w-5 h-5 text-blue-600" />
              归还验收处理
            </DialogTitle>
            <DialogDescription>
              仓库管理员现场验收：查验清点实物，确认归还数量与物资完好程度，系统将根据验收结果智能更新库存
            </DialogDescription>
          </DialogHeader>

          {selectedReturn && (
            <div className="space-y-5">
              {/* 归还单基本信息 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">归还单号</p>
                    <p className="font-medium text-blue-900">{selectedReturn.code}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">关联领用单</p>
                    <p className="text-blue-900">{selectedReturn.requisitionCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">归还人/部门</p>
                    <p className="text-blue-900">{selectedReturn.returner} / {selectedReturn.department}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">登记时间</p>
                    <p className="text-blue-900">{selectedReturn.registerDate}</p>
                  </div>
                </div>
              </Card>



              {/* 验收说明 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                    <CheckSquare className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="flex-1">
                    <h4 className="font-medium text-blue-900 mb-2">验收操作指南</h4>
                    <div className="grid grid-cols-2 gap-3 text-xs text-blue-800">
                      <div className="flex items-start gap-2">
                        <span className="text-blue-600 font-medium">1.</span>
                        <span>清单已自动带出申请单的所有物品</span>
                      </div>
                      <div className="flex items-start gap-2">
                        <span className="text-blue-600 font-medium">2.</span>
                        <span>确认实际验收数量（默认=申报数量）</span>
                      </div>
                      <div className="flex items-start gap-2">
                        <span className="text-blue-600 font-medium">3.</span>
                        <span>按实际状况分配数量到各状态</span>
                      </div>
                      <div className="flex items-start gap-2">
                        <span className="text-blue-600 font-medium">4.</span>
                        <span>确保各状态数量总和=实际验收数量</span>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 验收清单 */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <Label className="text-base">验收清单（逐项查验）</Label>
                  <div className="text-xs text-muted-foreground">
                    共 {selectedReturn.items.length} 项物品待验收
                  </div>
                </div>
                
                <div className="space-y-4">
                  {selectedReturn.items.map((item, index) => {
                    const verificationItem = verificationItems.find(v => v.itemId === item.id);
                    if (!verificationItem) return null;
                    
                    const totalVerified = verificationItem.normalQty + verificationItem.damagedQty + 
                                        verificationItem.lostQty + verificationItem.maintenanceQty;
                    const quantityMatch = totalVerified === verificationItem.actualQuantity;
                    
                    return (
                      <Card key={item.id} className="p-4 border-2 hover:border-blue-200 transition-colors">
                        <div className="space-y-4">
                          {/* 物资基本信息 */}
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-3">
                              <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0">
                                <span className="font-medium text-blue-600">#{index + 1}</span>
                              </div>
                              <div>
                                <p className="font-medium">{item.materialName}</p>
                                <div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
                                  <span>类型：{item.materialType}</span>
                                  <span>•</span>
                                  <span>借出数量：{item.borrowedQuantity}{item.unit}</span>
                                  <span>•</span>
                                  <span>申报归还：{item.returnedQuantity}{item.unit}</span>
                                  <span>•</span>
                                  <span>
                                    申报状态：
                                    <Badge className={`ml-1 ${getConditionColor(item.condition)}`} variant="outline">
                                      {item.condition}
                                    </Badge>
                                  </span>
                                </div>
                                {item.batchNo && (
                                  <div className="text-xs text-muted-foreground mt-1">
                                    批次号：{item.batchNo}
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>

                          {/* 验收录入区域 */}
                          <div className="grid grid-cols-2 gap-4">
                            {/* 左侧：实际验收数量 */}
                            <div className="space-y-3">
                              <div>
                                <Label className="text-sm">实际验收数量 <span className="text-red-500">*</span></Label>
                                <Input
                                  type="number"
                                  value={verificationItem.actualQuantity}
                                  onChange={(e) => {
                                    const newQty = parseInt(e.target.value) || 0;
                                    setVerificationItems(prev => prev.map(v => 
                                      v.itemId === item.id ? { ...v, actualQuantity: newQty } : v
                                    ));
                                  }}
                                  className="mt-1"
                                  min={0}
                                  max={item.borrowedQuantity}
                                />
                                <p className="text-xs text-muted-foreground mt-1">
                                  现场清点后的实际数量（不超过借出数量）
                                </p>
                              </div>

                              <div>
                                <Label className="text-sm">验收备注</Label>
                                <Textarea
                                  value={verificationItem.verificationNotes}
                                  onChange={(e) => {
                                    setVerificationItems(prev => prev.map(v => 
                                      v.itemId === item.id ? { ...v, verificationNotes: e.target.value } : v
                                    ));
                                  }}
                                  placeholder="记录验收情况、发现的问题等..."
                                  rows={3}
                                  className="mt-1"
                                />
                              </div>
                            </div>

                            {/* 右侧：按状态分配数量 */}
                            <div className="space-y-2">
                              <Label className="text-sm">
                                物资状态分配 
                                <span className="text-red-500 ml-1">*</span>
                                <span className="text-xs text-muted-foreground ml-2">
                                  （总计：{totalVerified}/{verificationItem.actualQuantity}{item.unit}）
                                </span>
                              </Label>
                              
                              <div className="grid grid-cols-2 gap-2">
                                {/* 正常 */}
                                <div className="border rounded-lg p-3 bg-green-50">
                                  <div className="flex items-center gap-2 mb-2">
                                    <CheckCircle className="w-4 h-4 text-green-600" />
                                    <span className="text-sm font-medium text-green-900">正常</span>
                                  </div>
                                  <Input
                                    type="number"
                                    value={verificationItem.normalQty}
                                    onChange={(e) => {
                                      const qty = parseInt(e.target.value) || 0;
                                      setVerificationItems(prev => prev.map(v => 
                                        v.itemId === item.id ? { ...v, normalQty: qty } : v
                                      ));
                                    }}
                                    min={0}
                                    max={verificationItem.actualQuantity}
                                    className="bg-white"
                                  />
                                  <p className="text-xs text-green-700 mt-1">可直接入库</p>
                                </div>

                                {/* 损坏 */}
                                <div className="border rounded-lg p-3 bg-red-50">
                                  <div className="flex items-center gap-2 mb-2">
                                    <AlertCircle className="w-4 h-4 text-red-600" />
                                    <span className="text-sm font-medium text-red-900">损坏</span>
                                  </div>
                                  <Input
                                    type="number"
                                    value={verificationItem.damagedQty}
                                    onChange={(e) => {
                                      const qty = parseInt(e.target.value) || 0;
                                      setVerificationItems(prev => prev.map(v => 
                                        v.itemId === item.id ? { ...v, damagedQty: qty } : v
                                      ));
                                    }}
                                    min={0}
                                    max={verificationItem.actualQuantity}
                                    className="bg-white"
                                  />
                                  <p className="text-xs text-red-700 mt-1">转维修流程</p>
                                </div>

                                {/* 遗失 */}
                                <div className="border rounded-lg p-3 bg-orange-50">
                                  <div className="flex items-center gap-2 mb-2">
                                    <XCircle className="w-4 h-4 text-orange-600" />
                                    <span className="text-sm font-medium text-orange-900">遗失</span>
                                  </div>
                                  <Input
                                    type="number"
                                    value={verificationItem.lostQty}
                                    onChange={(e) => {
                                      const qty = parseInt(e.target.value) || 0;
                                      setVerificationItems(prev => prev.map(v => 
                                        v.itemId === item.id ? { ...v, lostQty: qty } : v
                                      ));
                                    }}
                                    min={0}
                                    max={verificationItem.actualQuantity}
                                    className="bg-white"
                                  />
                                  <p className="text-xs text-orange-700 mt-1">记录损失</p>
                                </div>

                                {/* 需要保养 */}
                                <div className="border rounded-lg p-3 bg-blue-50">
                                  <div className="flex items-center gap-2 mb-2">
                                    <Wrench className="w-4 h-4 text-blue-600" />
                                    <span className="text-sm font-medium text-blue-900">需保养</span>
                                  </div>
                                  <Input
                                    type="number"
                                    value={verificationItem.maintenanceQty}
                                    onChange={(e) => {
                                      const qty = parseInt(e.target.value) || 0;
                                      setVerificationItems(prev => prev.map(v => 
                                        v.itemId === item.id ? { ...v, maintenanceQty: qty } : v
                                      ));
                                    }}
                                    min={0}
                                    max={verificationItem.actualQuantity}
                                    className="bg-white"
                                  />
                                  <p className="text-xs text-blue-700 mt-1">安排保养</p>
                                </div>
                              </div>

                              {/* 数量校验提示 */}
                              {!quantityMatch && (
                                <div className="flex items-center gap-2 p-2 bg-red-50 border border-red-200 rounded-md">
                                  <AlertTriangle className="w-4 h-4 text-red-600 flex-shrink-0" />
                                  <p className="text-xs text-red-700">
                                    状态数量总和（{totalVerified}）需等于实际验收数量（{verificationItem.actualQuantity}）
                                  </p>
                                </div>
                              )}
                              
                              {quantityMatch && totalVerified > 0 && (
                                <div className="flex items-center gap-2 p-2 bg-green-50 border border-green-200 rounded-md">
                                  <CheckCircle className="w-4 h-4 text-green-600 flex-shrink-0" />
                                  <p className="text-xs text-green-700">
                                    数量分配正确
                                  </p>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      </Card>
                    );
                  })}
                </div>
              </div>

              {/* 验收汇总 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="mb-3 flex items-center gap-2">
                  <BarChart3 className="w-4 h-4" />
                  验收汇总
                </h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div className="text-center p-3 bg-white rounded-lg border">
                    <div className="flex items-center justify-center gap-2 mb-1">
                      <CheckCircle className="w-4 h-4 text-green-600" />
                      <span className="text-muted-foreground">正常</span>
                    </div>
                    <p className="text-2xl font-medium text-green-600">
                      {verificationItems.reduce((sum, item) => sum + item.normalQty, 0)}
                    </p>
                  </div>
                  <div className="text-center p-3 bg-white rounded-lg border">
                    <div className="flex items-center justify-center gap-2 mb-1">
                      <AlertCircle className="w-4 h-4 text-red-600" />
                      <span className="text-muted-foreground">损坏</span>
                    </div>
                    <p className="text-2xl font-medium text-red-600">
                      {verificationItems.reduce((sum, item) => sum + item.damagedQty, 0)}
                    </p>
                  </div>
                  <div className="text-center p-3 bg-white rounded-lg border">
                    <div className="flex items-center justify-center gap-2 mb-1">
                      <XCircle className="w-4 h-4 text-orange-600" />
                      <span className="text-muted-foreground">遗失</span>
                    </div>
                    <p className="text-2xl font-medium text-orange-600">
                      {verificationItems.reduce((sum, item) => sum + item.lostQty, 0)}
                    </p>
                  </div>
                  <div className="text-center p-3 bg-white rounded-lg border">
                    <div className="flex items-center justify-center gap-2 mb-1">
                      <Wrench className="w-4 h-4 text-blue-600" />
                      <span className="text-muted-foreground">需保养</span>
                    </div>
                    <p className="text-2xl font-medium text-blue-600">
                      {verificationItems.reduce((sum, item) => sum + item.maintenanceQty, 0)}
                    </p>
                  </div>
                </div>
              </Card>

              {/* 库存更新说明 */}
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-start gap-2">
                  <Activity className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-green-900">
                    <p className="font-medium mb-2">验收完成后系统将智能更新库存：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>正常物资</strong>：直接入库，增加可用库存，更新库存台账</li>
                      <li>• <strong>损坏物资</strong>：标记状态为"待维修"，生成维修工单，不计入可用库存</li>
                      <li>• <strong>遗失物资</strong>：记录资产损失，生成损失报告，通知相关责任人</li>
                      <li>• <strong>需保养物资</strong>：标记状态为"待保养"，生成保养任务，暂不计入可用库存</li>
                      <li>• <strong>溯源记录</strong>：完整记录借-还-验收全流程，支持质量安全溯源</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter className="gap-2">
            <Button 
              variant="outline" 
              onClick={() => {
                setShowProcessDialog(false);
                setVerificationItems([]);
              }}
            >
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={handleProcessReturn}
            >
              <CheckSquare className="w-4 h-4 mr-2" />
              确认验收并更新库存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>归还详情</DialogTitle>
          </DialogHeader>

          {selectedReturn && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4">
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">归还单号</p>
                    <p className="font-medium">{selectedReturn.code}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">关联领用单</p>
                    <p>{selectedReturn.requisitionCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">归还人</p>
                    <p>{selectedReturn.returner}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">所属部门</p>
                    <p>{selectedReturn.department}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">登记时间</p>
                    <p>{selectedReturn.registerDate}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">当前状态</p>
                    <Badge className={getStatusColor(selectedReturn.status)}>
                      {selectedReturn.status}
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 归还物品 */}
              <Card className="p-4">
                <h4 className="mb-3">归还物品</h4>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>物资名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>借出数量</TableHead>
                      <TableHead>归还数量</TableHead>
                      <TableHead>物资状态</TableHead>
                      <TableHead>备注</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedReturn.items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>{item.materialName}</TableCell>
                        <TableCell>{item.materialType}</TableCell>
                        <TableCell>{item.borrowedQuantity}{item.unit}</TableCell>
                        <TableCell>{item.returnedQuantity}{item.unit}</TableCell>
                        <TableCell>
                          <Badge className={getConditionColor(item.condition)} variant="outline">
                            {item.condition}
                          </Badge>
                        </TableCell>
                        <TableCell>{item.conditionNotes || '-'}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </Card>

              {/* 验收信息 */}
              {selectedReturn.processor && (
                <Card className="p-4">
                  <h4 className="mb-3">验收信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <p className="text-muted-foreground mb-1">验收人</p>
                      <p>{selectedReturn.processor}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">验收时间</p>
                      <p>{selectedReturn.processDate}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground mb-1">验收结果</p>
                      <Badge className="bg-green-100 text-green-700">验收通过</Badge>
                    </div>
                    {selectedReturn.processNotes && (
                      <div className="col-span-3">
                        <p className="text-muted-foreground mb-1">验收意见</p>
                        <p>{selectedReturn.processNotes}</p>
                      </div>
                    )}
                  </div>
                </Card>
              )}
            </div>
          )}

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

      {/* 核销处理对话框 */}
      <Dialog open={showSettlementDialog} onOpenChange={setShowSettlementDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Link2 className="w-5 h-5 text-purple-600" />
              领用记录关联核销
            </DialogTitle>
            <DialogDescription>
              将归还记录与原始领用记录关联核销，完成借-还闭环管理
            </DialogDescription>
          </DialogHeader>

          {selectedReturn && (
            <div className="space-y-5">
              {/* 核销说明 */}
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-start gap-2">
                  <Activity className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-purple-900">
                    <p className="font-medium mb-2">核销流程说明：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 系统将本次归还记录与原始领用出库记录自动关联</li>
                      <li>• 形成完整的"借-还"闭环，确保每笔领用有据可查、有踪可循</li>
                      <li>• 自动分析数量差异、状态差异，生成差异报告</li>
                      <li>• 核销后自动更新领用单状态，记录溯源信息</li>
                    </ul>
                  </div>
                </div>
              </Card>

              {/* 归还单信息 */}
              <div className="grid grid-cols-2 gap-4">
                <Card className="p-4 bg-blue-50">
                  <h4 className="mb-3 flex items-center gap-2">
                    <RotateCcw className="w-4 h-4 text-blue-600" />
                    归还单信息
                  </h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">归还单号：</span>
                      <span className="font-medium">{selectedReturn.code}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">归还人：</span>
                      <span>{selectedReturn.returner}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">验收人：</span>
                      <span>{selectedReturn.processor}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">验收时间：</span>
                      <span>{selectedReturn.processDate}</span>
                    </div>
                  </div>
                </Card>

                <Card className="p-4 bg-green-50">
                  <h4 className="mb-3 flex items-center gap-2">
                    <FileText 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">{selectedReturn.requisitionCode}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">领用人：</span>
                      <span>{selectedReturn.returner}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">出库时间：</span>
                      <span>2024-10-15 08:00</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">关联地块：</span>
                      <span>3号大棚</span>
                    </div>
                  </div>
                </Card>
              </div>

              {/* 借还对比清单 */}
              <Card>
                <div className="p-4 border-b bg-gray-50">
                  <h4 className="flex items-center gap-2">
                    <BarChart3 className="w-4 h-4" />
                    借还对比清单（差异分析）
                  </h4>
                </div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>物资名称</TableHead>
                      <TableHead>领用数量</TableHead>
                      <TableHead>归还数量</TableHead>
                      <TableHead>数量差异</TableHead>
                      <TableHead>物资状态</TableHead>
                      <TableHead>验收备注</TableHead>
                      <TableHead>核销结果</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedReturn.items.map((item) => {
                      const quantityDiff = item.borrowedQuantity - item.returnedQuantity;
                      const hasQuantityDiff = quantityDiff !== 0;
                      
                      return (
                        <TableRow key={item.id}>
                          <TableCell className="font-medium">{item.materialName}</TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <span>{item.borrowedQuantity}{item.unit}</span>
                              <Badge variant="outline" className="bg-green-50 text-green-700">
                                借出
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <span>{item.returnedQuantity}{item.unit}</span>
                              <Badge variant="outline" className="bg-blue-50 text-blue-700">
                                归还
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            {hasQuantityDiff ? (
                              <div className="flex items-center gap-1">
                                <AlertTriangle className="w-4 h-4 text-orange-600" />
                                <Badge className="bg-orange-100 text-orange-700">
                                  差{Math.abs(quantityDiff)}{item.unit}
                                </Badge>
                              </div>
                            ) : (
                              <div className="flex items-center gap-1">
                                <CheckCircle className="w-4 h-4 text-green-600" />
                                <Badge className="bg-green-100 text-green-700">
                                  一致
                                </Badge>
                              </div>
                            )}
                          </TableCell>
                          <TableCell>
                            <Badge className={getConditionColor(item.condition)} variant="outline">
                              {item.condition}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <span className="text-xs text-muted-foreground">
                              {item.conditionNotes || '-'}
                            </span>
                          </TableCell>
                          <TableCell>
                            {hasQuantityDiff ? (
                              <Badge className="bg-orange-100 text-orange-700" variant="outline">
                                部分核销
                              </Badge>
                            ) : (
                              <Badge className="bg-green-100 text-green-700" variant="outline">
                                完全核销
                              </Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </Card>

              {/* 差异汇总 */}
              {selectedReturn.actualCondition && (
                <Card className="p-4 bg-gray-50">
                  <h4 className="mb-3 flex items-center gap-2">
                    <TrendingUp className="w-4 h-4" />
                    验收结果汇总
                  </h4>
                  <div className="grid grid-cols-4 gap-4">
                    <div className="text-center p-3 bg-white rounded-lg border">
                      <div className="flex items-center justify-center gap-2 mb-1">
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="text-sm text-muted-foreground">正常</span>
                      </div>
                      <p className="text-2xl font-medium text-green-600">
                        {selectedReturn.actualCondition.normal}
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">已入库</p>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border">
                      <div className="flex items-center justify-center gap-2 mb-1">
                        <AlertCircle className="w-4 h-4 text-red-600" />
                        <span className="text-sm text-muted-foreground">损坏</span>
                      </div>
                      <p className="text-2xl font-medium text-red-600">
                        {selectedReturn.actualCondition.damaged}
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">待维修</p>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border">
                      <div className="flex items-center justify-center gap-2 mb-1">
                        <XCircle className="w-4 h-4 text-orange-600" />
                        <span className="text-sm text-muted-foreground">遗失</span>
                      </div>
                      <p className="text-2xl font-medium text-orange-600">
                        {selectedReturn.actualCondition.lost}
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">已记损</p>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border">
                      <div className="flex items-center justify-center gap-2 mb-1">
                        <Wrench className="w-4 h-4 text-blue-600" />
                        <span className="text-sm text-muted-foreground">需保养</span>
                      </div>
                      <p className="text-2xl font-medium text-blue-600">
                        {selectedReturn.actualCondition.needMaintenance}
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">待保养</p>
                    </div>
                  </div>
                </Card>
              )}

              {/* 核销确认 */}
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-start gap-2">
                  <CheckCircle className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-green-900">
                    <p className="font-medium mb-2">核销后系统将自动执行：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 将本次归还记录与原始领用记录建立关联关系</li>
                      <li>• 更新领用单状态为"已归还"或"部分归还"</li>
                      <li>• 生成完整的借-还溯源记录，支持质量安全追溯</li>
                      <li>• 差异物资自动生成处理工单（损坏→维修工单，遗失→损失报告）</li>
                      <li>• 更新资产台账，记录资产使用历史和状态变更</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter className="gap-2">
            <Button 
              variant="outline" 
              onClick={() => setShowSettlementDialog(false)}
            >
              <XCircle className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button 
              className="bg-purple-600 hover:bg-purple-700" 
              onClick={handleSettlement}
            >
              <CheckSquare className="w-4 h-4 mr-2" />
              确认核销
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 核销详情对话框 */}
      <Dialog open={showSettlementDetailDialog} onOpenChange={setShowSettlementDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileCheck className="w-5 h-5 text-purple-600" />
              核销记录详情
            </DialogTitle>
            <DialogDescription>
              查看完整的借-还闭环记录和全流程时间节点
            </DialogDescription>
          </DialogHeader>

          {selectedSettlement && (
            <div className="space-y-5">
              {/* 基本信息 */}
              <Card className="p-4 bg-gray-50">
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">领用单号</p>
                    <p className="font-medium">{selectedSettlement.requisitionCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">归还单号</p>
                    <p className="font-medium">{selectedSettlement.returnCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">核销人</p>
                    <p>{selectedSettlement.processor}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">核销状态</p>
                    <Badge className={
                      selectedSettlement.status === '已核销' 
                        ? 'bg-green-100 text-green-700' 
                        : 'bg-yellow-100 text-yellow-700'
                    }>
                      {selectedSettlement.status}
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 全流程时间轴 */}
              <Card className="p-5">
                <h4 className="mb-4 flex items-center gap-2">
                  <Activity className="w-5 h-5 text-blue-600" />
                  全流程时间节点
                </h4>
                <div className="relative">
                  {/* 时间轴线 */}
                  <div className="absolute left-0 right-0 top-8 h-0.5 bg-gradient-to-r from-blue-200 via-green-200 to-purple-200"></div>
                  
                  <div className="grid grid-cols-5 gap-2 relative">
                    {/* 1. 申请时间 */}
                    <div className="flex flex-col items-center">
                      <div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center mb-3 relative z-10 border-4 border-white shadow-sm">
                        <FileText className="w-7 h-7 text-blue-600" />
                      </div>
                      <p className="text-xs font-medium text-center mb-1">申请时间</p>
                      <p className="text-xs text-muted-foreground text-center">
                        {selectedSettlement.applyTime || '-'}
                      </p>
                      <Badge className="mt-2 bg-blue-100 text-blue-700 text-xs" variant="outline">
                        发起申请
                      </Badge>
                    </div>

                    {/* 2. 审批时间 */}
                    <div className="flex flex-col items-center">
                      <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-3 relative z-10 border-4 border-white shadow-sm">
                        <CheckCircle className="w-7 h-7 text-green-600" />
                      </div>
                      <p className="text-xs font-medium text-center mb-1">审批时间</p>
                      <p className="text-xs text-muted-foreground text-center">
                        {selectedSettlement.approvalTime || '-'}
                      </p>
                      <Badge className="mt-2 bg-green-100 text-green-700 text-xs" variant="outline">
                        审批通过
                      </Badge>
                    </div>

                    {/* 3. 领用时间 */}
                    <div className="flex flex-col items-center">
                      <div className="w-16 h-16 rounded-full bg-yellow-100 flex items-center justify-center mb-3 relative z-10 border-4 border-white shadow-sm">
                        <Package className="w-7 h-7 text-yellow-600" />
                      </div>
                      <p className="text-xs font-medium text-center mb-1">领用时间</p>
                      <p className="text-xs text-muted-foreground text-center">
                        {selectedSettlement.checkoutTime || '-'}
                      </p>
                      <Badge className="mt-2 bg-yellow-100 text-yellow-700 text-xs" variant="outline">
                        物资出库
                      </Badge>
                    </div>

                    {/* 4. 归还登记 */}
                    <div className="flex flex-col items-center">
                      <div className="w-16 h-16 rounded-full bg-orange-100 flex items-center justify-center mb-3 relative z-10 border-4 border-white shadow-sm">
                        <RotateCcw className="w-7 h-7 text-orange-600" />
                      </div>
                      <p className="text-xs font-medium text-center mb-1">归还登记</p>
                      <p className="text-xs text-muted-foreground text-center">
                        {selectedSettlement.returnRegisterTime || '-'}
                      </p>
                      <Badge className="mt-2 bg-orange-100 text-orange-700 text-xs" variant="outline">
                        登记归还
                      </Badge>
                    </div>

                    {/* 5. 验收核销 */}
                    <div className="flex flex-col items-center">
                      <div className="w-16 h-16 rounded-full bg-purple-100 flex items-center justify-center mb-3 relative z-10 border-4 border-white shadow-sm">
                        <CheckSquare className="w-7 h-7 text-purple-600" />
                      </div>
                      <p className="text-xs font-medium text-center mb-1">验收核销</p>
                      <p className="text-xs text-muted-foreground text-center">
                        {selectedSettlement.verificationTime || '-'}
                      </p>
                      <Badge className="mt-2 bg-purple-100 text-purple-700 text-xs" variant="outline">
                        完成闭环
                      </Badge>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 物资明细清单 */}
              {selectedSettlement.items && selectedSettlement.items.length > 0 && (
                <Card>
                  <div className="p-4 border-b bg-blue-50">
                    <h4 className="flex items-center gap-2">
                      <Package className="w-5 h-5 text-blue-600" />
                      物资明细清单
                    </h4>
                  </div>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>物资名称</TableHead>
                        <TableHead>物资类型</TableHead>
                        <TableHead>领用数量</TableHead>
                        <TableHead>归还数量</TableHead>
                        <TableHead>完好情况</TableHead>
                        <TableHead>差异</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {selectedSettlement.items.map((item, index) => {
                        const diff = item.borrowedQty - item.returnedQty;
                        const hasDiff = diff !== 0;
                        
                        return (
                          <TableRow key={index}>
                            <TableCell className="font-medium">{item.materialName}</TableCell>
                            <TableCell>
                              <Badge variant="outline" className="bg-gray-50">
                                {item.materialType}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <span className="font-medium">{item.borrowedQty}</span>
                              <span className="text-muted-foreground ml-1">{item.unit}</span>
                            </TableCell>
                            <TableCell>
                              <span className="font-medium">{item.returnedQty}</span>
                              <span className="text-muted-foreground ml-1">{item.unit}</span>
                            </TableCell>
                            <TableCell>
                              <div className="flex flex-wrap gap-1">
                                {item.normalQty > 0 && (
                                  <Badge className="bg-green-100 text-green-700 text-xs" variant="outline">
                                    正常 {item.normalQty}
                                  </Badge>
                                )}
                                {item.damagedQty > 0 && (
                                  <Badge className="bg-red-100 text-red-700 text-xs" variant="outline">
                                    损坏 {item.damagedQty}
                                  </Badge>
                                )}
                                {item.lostQty > 0 && (
                                  <Badge className="bg-orange-100 text-orange-700 text-xs" variant="outline">
                                    遗失 {item.lostQty}
                                  </Badge>
                                )}
                                {item.maintenanceQty > 0 && (
                                  <Badge className="bg-blue-100 text-blue-700 text-xs" variant="outline">
                                    需保养 {item.maintenanceQty}
                                  </Badge>
                                )}
                              </div>
                            </TableCell>
                            <TableCell>
                              {hasDiff ? (
                                <div className="flex items-center gap-1">
                                  <AlertTriangle className="w-4 h-4 text-orange-600" />
                                  <Badge className="bg-orange-100 text-orange-700">
                                    差 {Math.abs(diff)}{item.unit}
                                  </Badge>
                                </div>
                              ) : (
                                <div className="flex items-center gap-1">
                                  <CheckCircle className="w-4 h-4 text-green-600" />
                                  <Badge className="bg-green-100 text-green-700">
                                    一致
                                  </Badge>
                                </div>
                              )}
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </Card>
              )}

              {/* 完好情况汇总 */}
              {selectedSettlement.items && selectedSettlement.items.length > 0 && (
                <Card className="p-4">
                  <h4 className="mb-4 flex items-center gap-2">
                    <BarChart3 className="w-5 h-5 text-purple-600" />
                    完好情况汇总
                  </h4>
                  <div className="grid grid-cols-4 gap-4">
                    <div className="text-center p-4 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center justify-center gap-2 mb-2">
                        <CheckCircle className="w-5 h-5 text-green-600" />
                        <span className="text-sm text-muted-foreground">正常</span>
                      </div>
                      <p className="text-3xl font-medium text-green-600">
                        {selectedSettlement.items.reduce((sum, item) => sum + item.normalQty, 0)}
                      </p>
                    </div>
                    <div className="text-center p-4 bg-red-50 rounded-lg border border-red-200">
                      <div className="flex items-center justify-center gap-2 mb-2">
                        <AlertCircle className="w-5 h-5 text-red-600" />
                        <span className="text-sm text-muted-foreground">损坏</span>
                      </div>
                      <p className="text-3xl font-medium text-red-600">
                        {selectedSettlement.items.reduce((sum, item) => sum + item.damagedQty, 0)}
                      </p>
                    </div>
                    <div className="text-center p-4 bg-orange-50 rounded-lg border border-orange-200">
                      <div className="flex items-center justify-center gap-2 mb-2">
                        <XCircle className="w-5 h-5 text-orange-600" />
                        <span className="text-sm text-muted-foreground">遗失</span>
                      </div>
                      <p className="text-3xl font-medium text-orange-600">
                        {selectedSettlement.items.reduce((sum, item) => sum + item.lostQty, 0)}
                      </p>
                    </div>
                    <div className="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
                      <div className="flex items-center justify-center gap-2 mb-2">
                        <Wrench className="w-5 h-5 text-blue-600" />
                        <span className="text-sm text-muted-foreground">需保养</span>
                      </div>
                      <p className="text-3xl font-medium text-blue-600">
                        {selectedSettlement.items.reduce((sum, item) => sum + item.maintenanceQty, 0)}
                      </p>
                    </div>
                  </div>
                </Card>
              )}
            </div>
          )}

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

      {/* 资产详情与历史记录对话框 */}
      <Dialog open={showAssetDetailDialog} onOpenChange={setShowAssetDetailDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Package className="w-5 h-5 text-blue-600" />
              资产详情与使用历史
            </DialogTitle>
            <DialogDescription>
              完整的资产使用记录、损耗分析和决策建议
            </DialogDescription>
          </DialogHeader>

          {selectedAsset && (
            <div className="space-y-5">
              {/* 资产基本信息 */}
              <Card className="p-4 bg-gray-50">
                <h4 className="mb-3 flex items-center gap-2">
                  <Info className="w-4 h-4" />
                  资产基本信息
                </h4>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground mb-1">资产编号</p>
                    <p className="font-medium">{selectedAsset.assetCode}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">资产名称</p>
                    <p className="font-medium">{selectedAsset.assetName}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">资产类型</p>
                    <p>{selectedAsset.assetType}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground mb-1">当前状态</p>
                    <Badge className={getToolStatusColor(selectedAsset.currentStatus)}>
                      {selectedAsset.currentStatus}
                    </Badge>
                  </div>
                </div>
              </Card>

              {/* 使用统计概览 */}
              <div className="grid grid-cols-4 gap-4">
                <Card className="p-4 text-center">
                  <RotateCcw className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                  <p className="text-xs text-muted-foreground mb-1">总借用次数</p>
                  <p className="text-2xl font-medium text-blue-600">{selectedAsset.totalBorrows}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {selectedAsset.borrowFrequency}次/月
                  </p>
                </Card>

                <Card className="p-4 text-center">
                  <Clock className="w-8 h-8 text-green-600 mx-auto mb-2" />
                  <p className="text-xs text-muted-foreground mb-1">平均借用天数</p>
                  <p className="text-2xl font-medium text-green-600">{selectedAsset.avgBorrowDuration}</p>
                  <p className="text-xs text-muted-foreground mt-1">天/次</p>
                </Card>

                <Card className="p-4 text-center">
                  <AlertCircle className="w-8 h-8 text-red-600 mx-auto mb-2" />
                  <p className="text-xs text-muted-foreground mb-1">损坏次数</p>
                  <p className="text-2xl font-medium text-red-600">{selectedAsset.damageCount}</p>
                  <p className="text-xs text-muted-foreground mt-1">需关注</p>
                </Card>

                <Card className="p-4 text-center">
                  <Wrench className="w-8 h-8 text-orange-600 mx-auto mb-2" />
                  <p className="text-xs text-muted-foreground mb-1">保养次数</p>
                  <p className="text-2xl font-medium text-orange-600">{selectedAsset.maintenanceCount}</p>
                  <p className="text-xs text-muted-foreground mt-1">定期保养</p>
                </Card>
              </div>

              {/* 性能指标 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <TrendingUp className="w-4 h-4" />
                  性能指标评估
                </h4>
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm">利用率</span>
                    <span className="text-sm font-medium">{selectedAsset.utilizationRate}%</span>
                  </div>
                  <div className="h-3 bg-gray-200 rounded-full overflow-hidden">
                    <div
                      className={`h-full ${
                        selectedAsset.utilizationRate >= 80 ? 'bg-green-500' :
                        selectedAsset.utilizationRate >= 50 ? 'bg-yellow-500' : 'bg-red-500'
                      }`}
                      style={{ width: `${selectedAsset.utilizationRate}%` }}
                    />
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    {selectedAsset.utilizationRate >= 80 ? '✓ 高效使用' :
                     selectedAsset.utilizationRate >= 50 ? '⚠ 中等利用' : '✗ 利用不足'}
                  </p>
                </div>
              </Card>

              {/* 价值与成本 */}
              <Card className="p-4 bg-blue-50">
                <h4 className="mb-3 flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-blue-600" />
                  价值与成本分析
                </h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="text-center p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">预估价值</p>
                    <p className="text-xl font-medium text-blue-600">
                      ¥{selectedAsset.estimatedValue.toLocaleString()}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      折旧率: {selectedAsset.depreciationRate}%
                    </p>
                  </div>
                  <div className="text-center p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">维修成本</p>
                    <p className="text-xl font-medium text-orange-600">
                      ¥{(selectedAsset.damageCount * 150).toLocaleString()}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      {selectedAsset.damageCount}次 × ¥150
                    </p>
                  </div>
                  <div className="text-center p-3 bg-white rounded-lg">
                    <p className="text-xs text-muted-foreground mb-1">单次使用成本</p>
                    <p className="text-xl font-medium text-green-600">
                      ¥{selectedAsset.totalBorrows > 0 
                        ? Math.round((selectedAsset.estimatedValue + selectedAsset.damageCount * 150) / selectedAsset.totalBorrows)
                        : 0}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      (价值+维修)/借用次数
                    </p>
                  </div>
                </div>
              </Card>

              {/* 借还历史记录 */}
              <Card>
                <div className="p-4 border-b bg-gray-50">
                  <h4 className="flex items-center gap-2">
                    <History className="w-4 h-4" />
                    借还历史记录
                  </h4>
                </div>
                <div className="p-4">
                  <div className="space-y-3 max-h-64 overflow-y-auto">
                    {/* 模拟历史记录 */}
                    {Array.from({ length: selectedAsset.totalBorrows }, (_, i) => {
                      const isProblem = Math.random() > 0.8;
                      return (
                        <div key={i} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                          <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                            isProblem ? 'bg-red-100' : 'bg-green-100'
                          }`}>
                            {isProblem ? (
                              <AlertCircle className="w-4 h-4 text-red-600" />
                            ) : (
                              <CheckCircle className="w-4 h-4 text-green-600" />
                            )}
                          </div>
                          <div className="flex-1">
                            <div className="flex items-center justify-between mb-1">
                              <span className="text-sm font-medium">
                                第{selectedAsset.totalBorrows - i}次借用
                              </span>
                              <span className="text-xs text-muted-foreground">
                                2024-{String(10 - Math.floor(i / 3)).padStart(2, '0')}-{String(15 + (i % 3) * 10).padStart(2, '0')}
                              </span>
                            </div>
                            <div className="text-xs text-muted-foreground">
                              <p>领用人: {['张三', '李四', '王五', '赵六'][i % 4]}</p>
                              <p>借用天数: {3 + Math.floor(Math.random() * 7)}天</p>
                              <p>归还状态: {isProblem ? (
                                <Badge className="bg-red-100 text-red-700 ml-1" variant="outline">
                                  {['损坏', '需保养'][Math.floor(Math.random() * 2)]}
                                </Badge>
                              ) : (
                                <Badge className="bg-green-100 text-green-700 ml-1" variant="outline">
                                  正常
                                </Badge>
                              )}</p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </Card>

              {/* 决策建议 */}
              <Card className={`p-4 ${
                selectedAsset.utilizationRate >= 80 && selectedAsset.damageCount <= 2 ? 'bg-green-50 border-green-200' :
                selectedAsset.damageCount >= 5 || selectedAsset.utilizationRate < 10 ? 'bg-red-50 border-red-200' :
                'bg-yellow-50 border-yellow-200'
              }`}>
                <h4 className="mb-3 flex items-center gap-2">
                  <Lightbulb className="w-4 h-4" />
                  智能决策建议
                </h4>
                <div className="space-y-2 text-sm">
                  {selectedAsset.utilizationRate >= 80 && selectedAsset.damageCount <= 2 && (
                    <>
                      <p className="flex items-center gap-2 text-green-800">
                        <CheckCircle className="w-4 h-4" />
                        <strong>优质资产</strong>：使用率高且损坏少，建议继续保持
                      </p>
                      <p className="text-green-700 pl-6">
                        • 可考虑增购同类资产以满足更多需求<br />
                        • 建议作为标准配置纳入常规采购计划
                      </p>
                    </>
                  )}
                  {selectedAsset.utilizationRate >= 80 && selectedAsset.damageCount > 2 && (
                    <>
                      <p className="flex items-center gap-2 text-yellow-800">
                        <AlertTriangle className="w-4 h-4" />
                        <strong>高频使用·需维护</strong>：使用频繁且损坏较多
                      </p>
                      <p className="text-yellow-700 pl-6">
                        • 立即安排专业维修保养，延长使用寿命<br />
                        • 增加保养频率，建议每{Math.ceil(30 / selectedAsset.borrowFrequency)}次使用后保养<br />
                        • 考虑增购替换件，避免影响生产
                      </p>
                    </>
                  )}
                  {selectedAsset.utilizationRate < 30 && selectedAsset.damageCount <= 2 && (
                    <>
                      <p className="flex items-center gap-2 text-orange-800">
                        <Info className="w-4 h-4" />
                        <strong>闲置资产</strong>：使用率低
                      </p>
                      <p className="text-orange-700 pl-6">
                        • 分析闲置原因：是否需求减少或有替代品<br />
                        • 考虑调配到其他部门或项目使用<br />
                        • 如长期闲置，建议纳入处置计划
                      </p>
                    </>
                  )}
                  {selectedAsset.damageCount >= 5 && (
                    <>
                      <p className="flex items-center gap-2 text-red-800">
                        <XCircle className="w-4 h-4" />
                        <strong>建议报废</strong>：损坏次数过多
                      </p>
                      <p className="text-red-700 pl-6">
                        • 维修成本: ¥{(selectedAsset.damageCount * 150).toLocaleString()}，占残值{selectedAsset.estimatedValue > 0 ? Math.round(selectedAsset.damageCount * 150 / selectedAsset.estimatedValue * 100) : 0}%<br />
                        • 建议启动报废流程，采购新资产替换<br />
                        • 可回收残值约¥{Math.round(selectedAsset.estimatedValue * 0.1).toLocaleString()}
                      </p>
                    </>
                  )}
                  {selectedAsset.damageCount >= 3 && selectedAsset.damageCount < 5 && (
                    <>
                      <p className="flex items-center gap-2 text-blue-800">
                        <Wrench className="w-4 h-4" />
                        <strong>维修建议</strong>：损坏次数较多
                      </p>
                      <p className="text-blue-700 pl-6">
                        • 累计维修成本: ¥{(selectedAsset.damageCount * 150).toLocaleString()}<br />
                        • 建议进行全面检查，找出频繁损坏的根本原因<br />
                        • 加强使用培训，规范操作流程
                      </p>
                    </>
                  )}
                </div>
              </Card>
            </div>
          )}

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