import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Modal, message, Button } from 'antd';
import { Clock } from 'lucide-react';
import { slotApi, LockCabinetSlotVO, SlotPageParam } from '../../api/lockCabinet/slots';
import { lockCabinetApi, LockCabinetVO } from '../../api/lockCabinet';
import { dateFormatter } from '../../utils/formatTime';
import keyImg from '../../assets/key.png';
import lockImg from '../../assets/lock.png';
import './LockCabinet3D.css';

interface MapDataProps {
  cabinetId: string;
}

export default function MapData({ cabinetId }: MapDataProps) {
  const wrapperRef = useRef<HTMLDivElement>(null);
  const sceneHostRef = useRef<HTMLDivElement>(null);
  const [cabinetInfo, setCabinetInfo] = useState<LockCabinetVO | null>(null);
  const [slotData, setSlotData] = useState<LockCabinetSlotVO[]>([]);
  const [updateTime, setUpdateTime] = useState<string | null>(null);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [errorInfo, setErrorInfo] = useState('');

  // 仓位详情弹框：钥匙仓/锁仓点击展示
  const [slotDetailVisible, setSlotDetailVisible] = useState(false);
  const [slotDetailType, setSlotDetailType] = useState<'key' | 'lock'>('key');
  const [slotDetailNo, setSlotDetailNo] = useState(1);
  
  // 3D 控制状态
  const [isDragging, setIsDragging] = useState(false);
  const previousMousePosition = useRef({ x: 0, y: 0 });
  const rotation = useRef({ x: 0, y: 0 });
  // 用户缩放（在自适应 fitScale 的基础上）
  const userScale = useRef(1);
  const [fitScale, setFitScale] = useState(1);

  // 统计数据
  const stats = React.useMemo(() => {
    const total = slotData.length;
    const occupied = slotData.filter(s => s.isOccupied === '1').length;
    const free = total - occupied;
    const abnormal = slotData.filter(s => s.status === '1').length;
    return { total, occupied, free, abnormal };
  }, [slotData]);

  // 右侧两块：随机展示（每次刷新/重新进入会变化）
  const randomRightStats = React.useMemo(() => {
    const total = stats.total > 0 ? stats.total : 50;
    const occupied = Math.floor(Math.random() * (total + 1));
    const abnormal = Math.floor(Math.random() * (occupied + 1));
    return { occupied, abnormal };
  }, [stats.total]);

  // 获取机柜详情
  const getCabinetInfo = async () => {
    if (!cabinetId) return;
    try {
      const info = await lockCabinetApi.selectIsLockCabinetById(Number(cabinetId));
      setCabinetInfo(info);
    } catch (error: any) {
      console.error('获取机柜信息失败:', error);
      message.error(error.message || '获取机柜信息失败');
    }
  };

  // 获取槽位数据
  const getData = async () => {
    if (!cabinetId) return;

    const params: SlotPageParam = {
      pageNo: 1,
      pageSize: -1,
      cabinetId: Number(cabinetId),
    };

    try {
      const response = await slotApi.getIsLockCabinetSlotsPage(params);
      const slots = response.list || [];
      setSlotData(slots);
      if (slots.length > 0 && slots[0].createTime) {
        setUpdateTime(dateFormatter(slots[0].createTime));
      }
    } catch (error: any) {
      console.error('获取数据失败:', error);
      message.error(error.message || '获取数据失败');
    }
  };

  // 3D 拖拽处理
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    setIsDragging(true);
    previousMousePosition.current = { x: e.clientX, y: e.clientY };
  }, []);

  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (!isDragging) return;
    
    const deltaX = e.clientX - previousMousePosition.current.x;
    const deltaY = e.clientY - previousMousePosition.current.y;
    
    rotation.current.y += deltaX * 0.5;
    rotation.current.x -= deltaY * 0.5;
    rotation.current.x = Math.max(-45, Math.min(45, rotation.current.x));
    
    const effectiveScale = fitScale * userScale.current;
    if (wrapperRef.current) {
      wrapperRef.current.style.transform = `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${effectiveScale})`;
    }
    
    previousMousePosition.current = { x: e.clientX, y: e.clientY };
  }, [isDragging, fitScale]);

  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 滚轮缩放
  const handleWheel = useCallback((e: React.WheelEvent) => {
    e.preventDefault();
    // 为确保“柜子高度不超过一屏”，这里限制最大只能缩放到 fitScale（即 userScale <= 1）
    userScale.current += e.deltaY * -0.001;
    userScale.current = Math.max(0.3, Math.min(1, userScale.current));
    const effectiveScale = fitScale * userScale.current;
    if (wrapperRef.current) {
      wrapperRef.current.style.transform = `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${effectiveScale})`;
    }
  }, [fitScale]);

  // 触摸支持
  const touchStartDistance = useRef(0);
  const initialScale = useRef(1);

  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    if (e.touches.length === 1) {
      setIsDragging(true);
      previousMousePosition.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
    } else if (e.touches.length === 2) {
      touchStartDistance.current = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      initialScale.current = userScale.current;
    }
  }, []);

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    e.preventDefault();
    if (e.touches.length === 1 && isDragging) {
      const deltaX = e.touches[0].clientX - previousMousePosition.current.x;
      const deltaY = e.touches[0].clientY - previousMousePosition.current.y;
      
      rotation.current.y += deltaX * 0.5;
      rotation.current.x -= deltaY * 0.5;
      rotation.current.x = Math.max(-45, Math.min(45, rotation.current.x));
      
      if (wrapperRef.current) {
        const effectiveScale = fitScale * userScale.current;
        wrapperRef.current.style.transform = `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${effectiveScale})`;
      }
      previousMousePosition.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
    } else if (e.touches.length === 2) {
      const currentDistance = Math.hypot(
        e.touches[0].clientX - e.touches[1].clientX,
        e.touches[0].clientY - e.touches[1].clientY
      );
      userScale.current = initialScale.current * (currentDistance / touchStartDistance.current);
      // 同样限制最大只能到 1（不超过 fitScale）
      userScale.current = Math.max(0.3, Math.min(1, userScale.current));
      if (wrapperRef.current) {
        const effectiveScale = fitScale * userScale.current;
        wrapperRef.current.style.transform = `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${effectiveScale})`;
      }
    }
  }, [isDragging, fitScale]);

  const handleTouchEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 获取槽位状态
  const getSlotStatus = (slot: LockCabinetSlotVO) => {
    if (slot.status === '1') return '异常';
    if (slot.isOccupied === '1') return '已占用';
    return '空闲';
  };

  // 获取槽位类型名称
  const getSlotTypeName = (slot: LockCabinetSlotVO) => {
    return slot.slotType === '0' ? '钥匙' : '挂锁';
  };

  useEffect(() => {
    if (cabinetId) {
      getCabinetInfo();
      getData();
    }
  }, [cabinetId]);

  // 自适应缩放：保证柜子整体高度不超过可视区域（左侧容器）
  useEffect(() => {
    if (!sceneHostRef.current) return;
    const host = sceneHostRef.current;

    const BASE_W = 800;
    const BASE_H = 1100;

    const update = () => {
      const rect = host.getBoundingClientRect();
      if (!rect.width || !rect.height) return;
      const nextFit = Math.min(rect.width / BASE_W, rect.height / BASE_H);
      // 允许放大（容器更大时），但在常见 1 屏高度下基本都会 <= 1
      const clamped = Math.max(0.2, Math.min(2, nextFit));
      setFitScale(clamped);

      // 立即同步当前 transform（避免等待下一次交互）
      const effectiveScale = clamped * userScale.current;
      if (wrapperRef.current) {
        wrapperRef.current.style.transform = `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${effectiveScale})`;
      }
    };

    update();
    const ro = new ResizeObserver(() => update());
    ro.observe(host);

    return () => ro.disconnect();
  }, []);

  // 按行分组槽位数据（用于 3D 显示）
  const groupedSlots = React.useMemo(() => {
    const grouped: Record<number, LockCabinetSlotVO[]> = {};
    slotData.forEach(slot => {
      const row = slot.row || 0;
      if (!grouped[row]) grouped[row] = [];
      grouped[row].push(slot);
    });
    return grouped;
  }, [slotData]);

  // 获取钥匙槽位（前4个）
  const keySlots = React.useMemo(() => {
    return slotData.filter(s => s.slotType === '0').slice(0, 4);
  }, [slotData]);

  // 获取挂锁槽位（按行分组，最多5行，每行10个）
  const lockSlots = React.useMemo(() => {
    const locks = slotData.filter(s => s.slotType === '1');
    const rows: LockCabinetSlotVO[][] = [];
    for (let i = 0; i < 5; i++) {
      rows.push(locks.slice(i * 10, (i + 1) * 10));
    }
    return rows;
  }, [slotData]);

  const openSlotDetail = (type: 'key' | 'lock', slotNo: number) => {
    setSlotDetailType(type);
    setSlotDetailNo(slotNo);
    setSlotDetailVisible(true);
  };

  // 从机柜详情 remark 解析钥匙/锁仓状态（keys/locks，slotNo，status: online/offline），用于 3D 仓位渲染
  const remarkSlots = React.useMemo(() => {
    const keyOnline: Record<number, boolean> = {};
    const lockOnline: Record<number, boolean> = {};
    try {
      const raw = cabinetInfo?.remark?.trim() || '';
      if (!raw) return { keyOnline, lockOnline };
      const data = JSON.parse(raw);
      const keys = data.keys || data.钥匙仓 || [];
      const locks = data.locks || data.锁仓 || [];
      keys.forEach((item: any) => {
        const no = item.slotNo ?? item.编号 ?? 0;
        const status = (item.status ?? item.状态 ?? '').toLowerCase();
        keyOnline[no] = status === 'online' || status === '在线';
      });
      locks.forEach((item: any) => {
        const no = item.slotNo ?? item.编号 ?? 0;
        const status = (item.status ?? item.状态 ?? '').toLowerCase();
        lockOnline[no] = status === 'online' || status === '在线';
      });
    } catch {
      /* ignore parse error */
    }
    return { keyOnline, lockOnline };
  }, [cabinetInfo?.remark]);

  return (
    <div className="flex gap-6 h-full min-h-0">
      {/* 左侧：3D 机柜 */}
      <div className="flex-1 min-h-0 bg-white rounded-lg shadow-sm p-4 overflow-hidden relative">
        <div
          ref={sceneHostRef}
          className="w-full h-full flex items-center justify-center select-none touch-none"
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
          onWheel={handleWheel}
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        >
          <div className="lc3dRoot">
            <div className="lc3dScene">
              <div
                ref={wrapperRef}
                className="lc3dCabinetWrapper"
                style={{
                  transform: `rotateX(${rotation.current.x}deg) rotateY(${rotation.current.y}deg) scale(${fitScale * userScale.current})`,
                }}
              >
                {/* 地面阴影 */}
                <div className="lc3dGroundShadow" />

                {/* 3D 盒子 */}
                <div className="lc3dCabinet3d">
                  {/* 背面 */}
                  <div className="lc3dCabinetBack" />
                  {/* 左侧面 */}
                  <div className="lc3dCabinetLeft" />
                  {/* 右侧面 */}
                  <div className="lc3dCabinetRight" />
                  {/* 顶部 */}
                  <div className="lc3dCabinetTop" />
                  {/* 底部 */}
                  <div className="lc3dCabinetBottom" />

                  {/* 正面（包含所有内容） */}
                  <div className="lc3dCabinetFront">
                    {/* 顶部挂钩 */}
                    <div className="lc3dHook lc3dHookLeft" />
                    <div className="lc3dHook lc3dHookRight" />

                    {/* 左侧螺丝 */}
                    <div className="lc3dScrewsLeft">
                      {Array.from({ length: 14 }).map((_, i) => (
                        <div key={i} className="lc3dScrew" />
                      ))}
                    </div>

                    {/* 右侧螺丝 */}
                    <div className="lc3dScrewsRight">
                      {Array.from({ length: 14 }).map((_, i) => (
                        <div key={i} className="lc3dScrew" />
                      ))}
                    </div>

                    {/* 头部 */}
                    <div className="lc3dHeader">
                      <div className="lc3dLogo">
                        <div className="lc3dLogoIcon">
                          <svg viewBox="0 0 50 40">
                            <path
                              d="M5 20 Q5 8 20 8 L35 8 Q45 8 45 18 Q45 28 35 28 L25 28 Q20 28 20 33 Q20 38 25 38"
                              stroke="#c41e3a"
                              strokeWidth="4"
                              fill="none"
                              strokeLinecap="round"
                            />
                            <circle cx="25" cy="38" r="3" fill="#c41e3a" />
                          </svg>
                        </div>
                        <span className="lc3dLogoText">BOZZYS</span>
                      </div>
                      <div className="lc3dTitle">LOTO锁控系统</div>
                    </div>

                    {/* 主面板 */}
                    <div className="lc3dMainPanel">
                      {/* 屏幕区域 */}
                      <div className="lc3dScreenSection">
                        <div className="lc3dMonitorFrame">
                          <div className="lc3dScreen">
                            <div className="lc3dScreenContent">
                              <div className="lc3dScreenHeader">
                                <span>设备状态监控</span>
                                <span>{new Date().toLocaleString('zh-CN')}</span>
                              </div>
                              <div className="lc3dScreenTable">
                                <div className="lc3dScreenRow">
                                  <span>编号</span>
                                  <span>状态</span>
                                  <span>用户</span>
                                  <span>时间</span>
                                </div>
                                {slotData.slice(0, 4).map((slot, idx) => (
                                  <div key={idx} className="lc3dScreenRow">
                                    <span>{slot.slotName || slot.slotCode || String(idx + 1).padStart(3, '0')}</span>
                                    <span style={{ color: slot.status === '1' ? '#ff4444' : slot.isOccupied === '1' ? '#44ff44' : '#ffff44' }}>
                                      {slot.status === '1' ? '异常' : slot.isOccupied === '1' ? '借出' : '待归'}
                                    </span>
                                    <span>{slot.hardwareId ? String(slot.hardwareId) : '-'}</span>
                                    <span>{slot.updateTime ? new Date(slot.updateTime).toLocaleTimeString('zh-CN') : '-'}</span>
                                  </div>
                                ))}
                              </div>
                              <div className="lc3dScreenButtons">
                                <button className={`lc3dScreenBtn lc3dScreenBtnRed`} type="button">
                                  紧急解锁
                                </button>
                                <button className={`lc3dScreenBtn lc3dScreenBtnGreen`} type="button">
                                  系统设置
                                </button>
                              </div>
                            </div>
                          </div>
                          {/* 底部区域：刷卡和指纹 */}
                          <div className="lc3dMonitorBottomArea">
                            <div className="lc3dCardReader">
                              <div className="lc3dCardReaderIcon" />
                            </div>
                            <div className="lc3dFingerprintReader">
                              <div className="lc3dFingerprintIcon" />
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 抽屉 */}
                      <div className="lc3dDrawer">
                        <div className="lc3dDrawerHandle" />
                      </div>

                      {/* 钥匙仓区域：根据 remark 在线/离线渲染状态灯，红灯=有东西，绿灯=没有东西 */}
                      <div className="lc3dKeySection">
                        <div className="lc3dKeySectionTitle">钥匙仓</div>
                        <div className="lc3dKeyRow">
                          {Array.from({ length: 4 }).map((_, idx) => {
                            const slotNo = idx + 1;
                            const slot = keySlots[idx];
                            const isOnlineFromRemark = remarkSlots.keyOnline[slotNo];
                            const useRemark = cabinetInfo?.remark?.trim();
                            const indicatorClass = useRemark
                              ? (isOnlineFromRemark ? 'lc3dKeyIndicatorRed' : 'lc3dKeyIndicatorGreen')
                              : (slot?.status === '1' || slot?.isOccupied === '1' ? 'lc3dKeyIndicatorRed' : 'lc3dKeyIndicatorGreen');

                            return (
                              <div
                                key={idx}
                                className="lc3dKeySlot lc3dSlotClickable"
                                role="button"
                                tabIndex={0}
                                onMouseDown={(e) => e.stopPropagation()}
                                onClick={() => openSlotDetail('key', slotNo)}
                              >
                                <span className="lc3dKeyNumber">{slotNo}</span>
                                {isOnlineFromRemark && (
                                  <img src={keyImg} alt="钥匙" className="lc3dSlotHardwareImg" style={{ width: 30, height: 30 }} title="在线" />
                                )}
                                <div className={`lc3dKeyIndicator ${indicatorClass}`} />
                              </div>
                            );
                          })}
                        </div>
                      </div>

                      {/* 锁仓区域：根据 remark 在线/离线渲染状态灯，红灯=有东西，绿灯=没有东西 */}
                      <div className="lc3dLockSection">
                        <div className="lc3dLockSectionTitle">锁仓</div>
                        {lockSlots.map((row, rowIdx) => (
                          <div key={rowIdx} className="lc3dLockRow">
                            {Array.from({ length: 10 }).map((_, slotIdx) => {
                              const slot = row[slotIdx];
                              const num = rowIdx * 10 + slotIdx + 1;
                              const isOnlineFromRemark = remarkSlots.lockOnline[num];
                              const useRemark = cabinetInfo?.remark?.trim();
                              const lockIndicatorClass = useRemark
                                ? (isOnlineFromRemark ? 'lc3dLockIndicatorRed' : 'lc3dLockIndicatorGreen')
                                : (slot?.status === '1' || slot?.isOccupied === '1' ? 'lc3dLockIndicatorRed' : 'lc3dLockIndicatorOff');
                              return (
                                <div
                                  key={slotIdx}
                                  className="lc3dLockSlot lc3dSlotClickable"
                                  role="button"
                                  tabIndex={0}
                                  onMouseDown={(e) => e.stopPropagation()}
                                  onClick={() => openSlotDetail('lock', num)}
                                >
                                  <span className="lc3dLockNumber">{num}</span>
                                  {isOnlineFromRemark && (
                                    <img src={lockImg} alt="锁" className="lc3dSlotHardwareLockImg" style={{ width: 30, height: 20 }} title="在线" />
                                  )}
                                  <div className={`lc3dLockIndicator ${lockIndicatorClass}`} />
                                  <div className="lc3dLockHole" />
                                </div>
                              );
                            })}
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="lc3dControlsHint">拖拽鼠标旋转 3D 视角 | 滚轮缩放</div>
            </div>
          </div>
        </div>
      </div>

      {/* 右侧：详情信息 */}
      <div className="w-[620px] h-full min-h-0 bg-white rounded-lg shadow-sm p-5 overflow-hidden flex flex-col" style={{width: '400px'}}>
        {/* 顶部信息（固定不滚动） */}
        <div className="shrink-0">
          {/* 标题 */}
          <div className="mb-4">
            <h2 className="text-lg font-bold text-gray-900 mb-2">锁控柜信息</h2>
            <div className="h-1 bg-blue-500 rounded" />
          </div>

          {/* 基本信息 */}
          <div className="mb-4 space-y-2">
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">名称</span>
            <span className="text-gray-900 font-medium">{cabinetInfo?.cabinetName || '-'}</span>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">硬件ID</span>
            <span className="text-gray-900 font-medium">{cabinetInfo?.hardwareId || '-'}</span>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">序列号</span>
            <span className="text-gray-900 font-medium">{cabinetInfo?.serialNumber || '-'}</span>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">岗位</span>
            <span className="text-gray-900 font-medium">{cabinetInfo?.workstationName || '-'}</span>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">在线状态</span>
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${
              cabinetInfo?.isOnline === '1' 
                ? 'bg-green-100 text-green-700' 
                : 'bg-gray-100 text-gray-700'
            }`}>
              {cabinetInfo?.isOnline === '1' ? '在线' : '离线'}
            </span>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-200">
            <span className="text-gray-600">运行状态</span>
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${
              cabinetInfo?.status === '0' 
                ? 'bg-blue-100 text-blue-700' 
                : cabinetInfo?.status === '1'
                ? 'bg-red-100 text-red-700'
                : 'bg-gray-100 text-gray-700'
            }`}>
              {cabinetInfo?.status === '0' ? '正常' : cabinetInfo?.status === '1' ? '异常' : '未知'}
            </span>
          </div>
          </div>

          {/* 统计卡片：左侧（总槽位/空闲），右侧两个盒子（上：已占用，下：异常，随机数） */}
          <div className="grid grid-cols-2 gap-3 mb-3">
            {/* 左列 */}
            <div className="flex flex-col gap-3">
              <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-3 text-white shadow-lg">
                <div className="text-2xl font-bold leading-none mb-1">{stats.total}</div>
                <div className="text-xs opacity-90">总槽位</div>
              </div>
              <div className="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl p-3 text-white shadow-lg">
                <div className="text-2xl font-bold leading-none mb-1">{stats.free}</div>
                <div className="text-xs opacity-90">空闲</div>
              </div>
            </div>

            {/* 右列（随机数） */}
            <div className="flex flex-col gap-3">
              <div
                className="rounded-xl p-3 text-white shadow-lg"
                style={{ background: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)' }}
              >
                <div className="text-2xl font-bold leading-none mb-1">{randomRightStats.occupied}</div>
                <div className="text-xs opacity-90">已占用</div>
              </div>
              <div
                className="rounded-xl p-3 text-white shadow-lg"
                style={{ background: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)' }}
              >
                <div className="text-2xl font-bold leading-none mb-1">{randomRightStats.abnormal}</div>
                <div className="text-xs opacity-90">异常</div>
              </div>
            </div>
          </div>
        </div>

        {/* 列表区域（超出才滚动） */}
        <div className="flex-1 min-h-0 overflow-y-auto pr-1">
          {/* 设备列表 */}
          <div>
            <h3 className="text-base font-bold text-gray-900 mb-3">设备列表</h3>
            <div className="space-y-3">
              {slotData.slice(0, 10).map((slot, idx) => (
                <div
                  key={idx}
                  className="bg-gray-50 rounded-lg p-3 border border-gray-200 hover:shadow-md transition-shadow"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-medium text-gray-900">
                      {getSlotTypeName(slot)}-{slot.slotName || slot.slotCode || idx + 1}
                    </span>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      slot.status === '1'
                        ? 'bg-red-100 text-red-700'
                        : slot.isOccupied === '1'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-700'
                    }`}>
                      {getSlotStatus(slot)}
                    </span>
                  </div>
                  <div className="text-sm text-gray-600">
                    {getSlotTypeName(slot)} · 槽位 {slot.slotName || slot.slotCode || idx + 1} ·
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 更新时间 */}
          {updateTime && (
            <div className="mt-4 inline-flex items-center gap-3 px-4 py-2 bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg">
              <Clock className="w-4 h-4 text-blue-500" />
              <div>
                <div className="text-xs text-gray-500">最后更新</div>
                <div className="text-sm font-bold text-gray-800">{updateTime}</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 仓位详情弹框：钥匙仓/锁仓点击展示，参考挂锁详情样式 */}
      <Modal
        title={slotDetailType === 'key' ? `钥匙-${slotDetailNo} - 详情` : `挂锁-${slotDetailNo} - 详情`}
        open={slotDetailVisible}
        onCancel={() => setSlotDetailVisible(false)}
        footer={[
          <Button key="edit" type="primary" onClick={() => { message.info('编辑功能待接入'); }}>
            编辑
          </Button>,
          <Button key="delete" danger onClick={() => { message.info('删除功能待接入'); }}>
            删除
          </Button>,
        ]}
        width={480}
        destroyOnClose
      >
        <div className="pt-2">
          <div className="text-base font-semibold text-gray-900 mb-4">基本信息</div>
          <div className="space-y-0 border-t border-gray-100">
            <div className="flex justify-between items-center py-3 border-b border-gray-100">
              <span className="text-gray-600">设备名称</span>
              <span className="text-gray-900 font-medium">
                {slotDetailType === 'key' ? `钥匙-${slotDetailNo}` : `挂锁-${slotDetailNo}`}
              </span>
            </div>
            <div className="flex justify-between items-center py-3 border-b border-gray-100">
              <span className="text-gray-600">NFC编号</span>
              <span className="text-gray-900 font-medium">
                {slotDetailType === 'key' ? `KEY${String(slotDetailNo).padStart(3, '0')}` : `LOCK${String(slotDetailNo).padStart(3, '0')}`}
              </span>
            </div>
            <div className="flex justify-between items-center py-3 border-b border-gray-100">
              <span className="text-gray-600">设备类型</span>
              <span className="text-gray-900 font-medium">{slotDetailType === 'key' ? '钥匙' : '锁具'}</span>
            </div>
            <div className="flex justify-between items-center py-3 border-b border-gray-100">
              <span className="text-gray-600">状态</span>
              <span className="inline-flex px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-700 border border-green-200">启用</span>
            </div>
            <div className="flex justify-between items-center py-3 border-b border-gray-100">
              <span className="text-gray-600">在线状态</span>
              <span className={`inline-flex px-3 py-1 rounded-full text-sm font-medium border ${
                (slotDetailType === 'key' ? remarkSlots.keyOnline[slotDetailNo] : remarkSlots.lockOnline[slotDetailNo])
                  ? 'bg-green-100 text-green-700 border-green-200'
                  : 'bg-gray-100 text-gray-600 border-gray-200'
              }`}>
                {(slotDetailType === 'key' ? remarkSlots.keyOnline[slotDetailNo] : remarkSlots.lockOnline[slotDetailNo]) ? '在线' : '离线'}
              </span>
            </div>
          </div>
        </div>
      </Modal>

      {/* 异常信息对话框 */}
      <Modal
        title="异常信息"
        open={dialogVisible}
        onCancel={() => setDialogVisible(false)}
        footer={[
          <button
            key="close"
            onClick={() => setDialogVisible(false)}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            关闭
          </button>
        ]}
      >
        <div className="text-center font-bold">{errorInfo}</div>
      </Modal>
    </div>
  );
}
