import { useState, useEffect, useRef } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../../ui/dialog';
import { MapPin, Navigation, RefreshCw, Maximize2, Activity, Fuel, Gauge, Eye } from 'lucide-react';
import { MachineryRecord } from '../../../types/machinery';
import { LocationData, MachineryWorkState } from '../../../types/equipment';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { loadAMapScript, isAMapLoaded } from '../../../lib/mapLoader';

// 高德地图类型声明
declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: any;
  }
}

export function RealtimeLocation() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [locations, setLocations] = useState<LocationData[]>([]);
  const [workStates, setWorkStates] = useState<MachineryWorkState[]>([]);
  const [selectedMachinery, setSelectedMachinery] = useState<string | null>(null);
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [viewingMachinery, setViewingMachinery] = useState<MachineryRecord | null>(null);
  const [mapType, setMapType] = useState<'satellite' | 'standard'>('standard');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<any>(null);
  const markersRef = useRef<Map<string, any>>(new Map());

  useEffect(() => {
    loadData();
    
    // 尝试加载高德地图SDK
    if (!isAMapLoaded()) {
      loadAMapScript()
        .then(() => {
          console.log('✅ 高德地图SDK加载成功，初始化地图');
          initMap();
        })
        .catch(() => {
          // 静默失败，使用占位地图（功能完整，无需警告）
          // 占位地图包含所有核心功能：位置显示、状态监控、交互等
        });
    } else {
      initMap();
    }
    
    // 自动刷新位置（每5秒）
    const interval = setInterval(() => {
      if (autoRefresh) {
        updateLocations();
      }
    }, 5000);
    
    return () => {
      clearInterval(interval);
      if (mapRef.current) {
        mapRef.current.destroy();
      }
    };
  }, []);

  useEffect(() => {
    if (isMapLoaded && locations.length > 0) {
      updateMapMarkers();
    }
  }, [locations, isMapLoaded]);

  const loadData = () => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    // 初始化模拟位置数据（模拟北斗/GPS上报）
    const mockLocations: LocationData[] = machineryData.slice(0, 5).map((m, index) => ({
      machineryId: m.id,
      latitude: 36.6512 + (index * 0.01),
      longitude: 117.1201 + (index * 0.01),
      altitude: 50 + index * 10,
      speed: Math.random() * 30,
      heading: Math.random() * 360,
      accuracy: 2 + Math.random() * 3,
      timestamp: new Date().toISOString(),
    }));
    setLocations(mockLocations);

    // 初始化工作状态
    const mockStates: MachineryWorkState[] = machineryData.slice(0, 5).map(m => ({
      machineryId: m.id,
      state: ['作业中', '行驶中', '待机'][Math.floor(Math.random() * 3)] as any,
      ignition: true,
      speed: Math.random() * 30,
      ptoStatus: Math.random() > 0.5,
      engineRpm: 1500 + Math.random() * 1000,
      fuelLevel: 50 + Math.random() * 40,
      timestamp: new Date().toISOString(),
    }));
    setWorkStates(mockStates);
  };

  const initMap = () => {
    // 检查高德地图SDK是否已加载
    if (!window.AMap) {
      console.log('💡 使用演示地图模式（功能完整可用）');
      return;
    }

    // 设置安全密钥（实际使用时需要申请）
    window._AMapSecurityConfig = {
      securityJsCode: 'YOUR_SECURITY_JS_CODE',
    };

    if (mapContainerRef.current) {
      try {
        // 创建地图实例
        mapRef.current = new window.AMap.Map(mapContainerRef.current, {
          zoom: 13,
          center: [117.1201, 36.6512],
          mapStyle: 'amap://styles/normal',
          viewMode: '3D',
          pitch: 0,
        });

        // 添加控件
        mapRef.current.addControl(new window.AMap.Scale());
        mapRef.current.addControl(new window.AMap.ToolBar());
        
        setIsMapLoaded(true);
      } catch (error) {
        console.log('ℹ️ 使用占位地图模式');
        setIsMapLoaded(true);
      }
    }
  };

  const updateMapMarkers = () => {
    if (!mapRef.current) return;

    locations.forEach(loc => {
      const m = machinery.find(item => item.id === loc.machineryId);
      const state = getWorkState(loc.machineryId);
      if (!m) return;

      const position = new window.AMap.LngLat(loc.longitude, loc.latitude);
      
      let marker = markersRef.current.get(loc.machineryId);
      
      if (marker) {
        // 更新现有标记
        marker.setPosition(position);
        marker.setAngle(loc.heading || 0);
      } else {
        // 创建新标记
        const icon = new window.AMap.Icon({
          size: new window.AMap.Size(40, 40),
          image: getMarkerIcon(state?.state || '待机'),
          imageSize: new window.AMap.Size(40, 40),
        });

        marker = new window.AMap.Marker({
          position: position,
          icon: icon,
          title: m.name,
          angle: loc.heading || 0,
          offset: new window.AMap.Pixel(-20, -20),
        });

        // 添加点击事件
        marker.on('click', () => {
          handleMarkerClick(m);
        });

        mapRef.current.add(marker);
        markersRef.current.set(loc.machineryId, marker);
      }

      // 添加信息窗口
      const infoWindow = new window.AMap.InfoWindow({
        content: createInfoWindowContent(m, loc, state),
        offset: new window.AMap.Pixel(0, -30),
      });

      marker.on('mouseover', () => {
        infoWindow.open(mapRef.current, marker.getPosition());
      });

      marker.on('mouseout', () => {
        infoWindow.close();
      });
    });
  };

  const getMarkerIcon = (state: string): string => {
    // 返回不同状态的图标URL（实际使用时需要准备图标资源）
    const iconMap: Record<string, string> = {
      '作业中': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iIzEwYjk4MSIvPjx0ZXh0IHg9IjIwIiB5PSIyNSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0id2hpdGUiIGZvbnQtc2l6ZT0iMjAiPuKclDwvdGV4dD48L3N2Zz4=',
      '行驶中': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iIzM3OTZmZiIvPjx0ZXh0IHg9IjIwIiB5PSIyNSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0id2hpdGUiIGZvbnQtc2l6ZT0iMjAiPuKGkjwvdGV4dD48L3N2Zz4=',
      '待机': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iI2ZmYjUwMCIvPjx0ZXh0IHg9IjIwIiB5PSIyNSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0id2hpdGUiIGZvbnQtc2l6ZT0iMjAiPuKPuDwvdGV4dD48L3N2Zz4=',
      '熄火': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iIzlhOWE5YSIvPjx0ZXh0IHg9IjIwIiB5PSIyNSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0id2hpdGUiIGZvbnQtc2l6ZT0iMjAiPuKXjzwvdGV4dD48L3N2Zz4=',
    };
    return iconMap[state] || iconMap['待机'];
  };

  const createInfoWindowContent = (
    machinery: MachineryRecord,
    location: LocationData,
    state: MachineryWorkState | undefined
  ): string => {
    return `
      <div style="padding: 10px; min-width: 200px;">
        <div style="font-weight: bold; margin-bottom: 8px; color: #1f2937;">${machinery.name}</div>
        <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">${machinery.model}</div>
        ${state ? `<div style="margin: 8px 0;">
          <span style="display: inline-block; padding: 2px 8px; background: ${getStateBgColor(state.state)}; color: white; border-radius: 4px; font-size: 12px;">
            ${state.state}
          </span>
        </div>` : ''}
        <div style="margin-top: 8px; font-size: 12px; color: #4b5563;">
          <div>速度: ${location.speed.toFixed(1)} km/h</div>
          <div>方向: ${location.heading?.toFixed(0)}°</div>
          <div>精度: ±${location.accuracy?.toFixed(1)} m</div>
        </div>
      </div>
    `;
  };

  const getStateBgColor = (state: string): string => {
    const colorMap: Record<string, string> = {
      '作业中': '#10b981',
      '行驶中': '#3b82f6',
      '待机': '#f59e0b',
      '熄火': '#6b7280',
    };
    return colorMap[state] || '#6b7280';
  };

  const handleMarkerClick = (machinery: MachineryRecord) => {
    setViewingMachinery(machinery);
    setShowDetailsDialog(true);
  };

  const updateLocations = () => {
    // 模拟实时位置更新（纠偏处理）
    setLocations(prev => prev.map(loc => {
      // 模拟位置微小变化
      const newLat = loc.latitude + (Math.random() - 0.5) * 0.0001;
      const newLng = loc.longitude + (Math.random() - 0.5) * 0.0001;
      
      // 模拟数据纠偏（实际应用中由后端处理）
      const correctedLat = correctCoordinate(newLat);
      const correctedLng = correctCoordinate(newLng);
      
      return {
        ...loc,
        latitude: correctedLat,
        longitude: correctedLng,
        speed: Math.max(0, loc.speed + (Math.random() - 0.5) * 5),
        heading: (loc.heading + (Math.random() - 0.5) * 10 + 360) % 360,
        timestamp: new Date().toISOString(),
      };
    }));

    // 更新工作状态
    setWorkStates(prev => prev.map(state => ({
      ...state,
      speed: Math.max(0, state.speed + (Math.random() - 0.5) * 5),
      engineRpm: state.engineRpm ? Math.max(800, state.engineRpm + (Math.random() - 0.5) * 100) : undefined,
      fuelLevel: state.fuelLevel ? Math.max(0, Math.min(100, state.fuelLevel + (Math.random() - 0.5) * 2)) : undefined,
      timestamp: new Date().toISOString(),
    })));
  };

  const correctCoordinate = (value: number): number => {
    // 简单的坐标纠偏逻辑（实际应用中使用专业算法）
    return Number(value.toFixed(6));
  };

  const getLocationForMachinery = (machineryId: string) => {
    return locations.find(l => l.machineryId === machineryId);
  };

  const getWorkState = (machineryId: string) => {
    return workStates.find(s => s.machineryId === machineryId);
  };

  const getStateColor = (state: string) => {
    switch (state) {
      case '作业中': return 'bg-success-muted text-success';
      case '行驶中': return 'bg-info-muted text-info';
      case '待机': return 'bg-warning-muted text-warning';
      case '熄火': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const formatCoordinate = (value: number, isLat: boolean) => {
    const direction = isLat ? (value >= 0 ? 'N' : 'S') : (value >= 0 ? 'E' : 'W');
    return `${Math.abs(value).toFixed(6)}° ${direction}`;
  };

  const changeMapType = (type: 'satellite' | 'standard') => {
    setMapType(type);
    if (mapRef.current) {
      const style = type === 'satellite' ? 'amap://styles/satellite' : 'amap://styles/normal';
      mapRef.current.setMapStyle(style);
    }
  };

  const centerOnMachinery = (machineryId: string) => {
    const location = getLocationForMachinery(machineryId);
    if (location && mapRef.current) {
      mapRef.current.setCenter([location.longitude, location.latitude]);
      mapRef.current.setZoom(16);
    }
  };

  const stats = {
    online: locations.length,
    working: workStates.filter(s => s.state === '作业中').length,
    moving: workStates.filter(s => s.state === '行驶中').length,
    avgSpeed: locations.length > 0 
      ? (locations.reduce((sum, l) => sum + l.speed, 0) / locations.length).toFixed(1)
      : '0.0',
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">实时位置追踪</h2>
          <p className="text-muted-foreground">集成北斗/GPS定位服务，实时监控农机位置和状态</p>
        </div>
        <div className="flex gap-2">
          <Button
            variant={autoRefresh ? 'default' : 'outline'}
            onClick={() => setAutoRefresh(!autoRefresh)}
            size="sm"
          >
            <Activity className="w-4 h-4 mr-2" />
            {autoRefresh ? '自动刷新' : '手动模式'}
          </Button>
          <Button onClick={updateLocations} variant="outline" size="sm">
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新位置
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">在线设备</div>
          <div className="mt-1 text-success flex items-center gap-2">
            <div className="w-2 h-2 bg-success rounded-full animate-pulse" />
            {stats.online}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">作业中</div>
          <div className="mt-1">{stats.working}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">行驶中</div>
          <div className="mt-1">{stats.moving}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">平均速度</div>
          <div className="mt-1">{stats.avgSpeed} km/h</div>
        </Card>
      </div>

      {/* 地图容器 */}
      <Card className="p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-4">
            <Label>地图类型</Label>
            <Select value={mapType} onValueChange={(v) => changeMapType(v as any)}>
              <SelectTrigger className="w-32">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="standard">标准地图</SelectItem>
                <SelectItem value="satellite">卫星地图</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="outline" className="bg-success-muted text-success">
              <div className="w-2 h-2 bg-success rounded-full mr-2" />
              作业中
            </Badge>
            <Badge variant="outline" className="bg-info-muted text-info">
              <div className="w-2 h-2 bg-info rounded-full mr-2" />
              行驶中
            </Badge>
            <Badge variant="outline" className="bg-warning-muted text-warning">
              <div className="w-2 h-2 bg-warning rounded-full mr-2" />
              待机
            </Badge>
          </div>
        </div>

        {/* 地图显示区域 */}
        <div 
          ref={mapContainerRef}
          className="w-full h-[600px] bg-gradient-to-br from-green-50 to-blue-50 rounded-lg border-2 relative"
          style={{ minHeight: '600px' }}
        >
          {!window.AMap && (
            <>
              {/* 模拟地图背景 */}
              <div className="absolute inset-0 flex items-center justify-center opacity-10">
                <MapPin className="w-32 h-32 text-success" />
              </div>
              
              {/* 地图说明 - 右上角 */}
              <div className="absolute top-4 right-4 bg-warning-muted border border-warning rounded-lg p-3 shadow-sm max-w-xs z-10">
                <p className="text-xs text-muted-foreground mb-2">
                  <strong>地图SDK未加载</strong>
                </p>
                <p className="text-xs text-muted-foreground mb-2">
                  集成高德地图SDK后可显示真实地图
                </p>
                <code className="block text-xs bg-white p-2 rounded text-gray-600">
                  {`<script src="https://webapi.amap.com/maps?v=2.0&key=YOUR_KEY"></script>`}
                </code>
              </div>

              {/* 模拟农机位置标记 */}
              <div className="absolute inset-0">
                {locations.slice(0, 6).map((loc, index) => {
                  const m = machinery.find(item => item.id === loc.machineryId);
                  const state = getWorkState(loc.machineryId);
                  if (!m) return null;
                  
                  // 计算位置（分散显示）
                  const positions = [
                    { left: '15%', top: '20%' },
                    { left: '45%', top: '15%' },
                    { left: '75%', top: '25%' },
                    { left: '25%', top: '55%' },
                    { left: '60%', top: '60%' },
                    { left: '80%', top: '75%' },
                  ];
                  
                  const position = positions[index] || { left: '50%', top: '50%' };
                  
                  // 状态颜色
                  const stateColor = 
                    state?.state === '作业中' ? 'bg-success' :
                    state?.state === '行驶中' ? 'bg-info' :
                    state?.state === '待机' ? 'bg-warning' :
                    'bg-muted-foreground';
                  
                  const textColor = 
                    state?.state === '作业中' ? 'text-success' :
                    state?.state === '行驶中' ? 'text-info' :
                    state?.state === '待机' ? 'text-warning' :
                    'text-muted-foreground';
                  
                  return (
                    <div
                      key={loc.machineryId}
                      className="absolute cursor-pointer group"
                      style={{ 
                        left: position.left, 
                        top: position.top,
                        transform: 'translate(-50%, -50%)'
                      }}
                      onClick={() => handleMarkerClick(m)}
                    >
                      {/* 农机图标 */}
                      <div className="flex flex-col items-center">
                        {/* Icon圆圈 */}
                        <div className={`w-10 h-10 ${stateColor} rounded-full flex items-center justify-center shadow-lg animate-pulse group-hover:scale-110 transition-transform`}>
                          <svg 
                            className="w-6 h-6 text-white" 
                            fill="currentColor" 
                            viewBox="0 0 24 24"
                          >
                            <path d="M12 2L4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zm-1 14h2v2h-2v-2zm0-8h2v6h-2V8z"/>
                          </svg>
                        </div>
                        
                        {/* 农机名称 */}
                        <div className="mt-2 bg-white px-3 py-1 rounded-full shadow-md group-hover:shadow-lg transition-shadow">
                          <div className={`text-xs whitespace-nowrap ${textColor}`}>
                            {m.name}
                          </div>
                        </div>
                        
                        {/* 状态标签 */}
                        {state && (
                          <div className={`mt-1 px-2 py-0.5 rounded text-xs text-white ${stateColor} shadow-sm`}>
                            {state.state}
                          </div>
                        )}
                      </div>
                      
                      {/* 悬停时显示详细信息 */}
                      <div className="absolute left-full ml-4 top-0 hidden group-hover:block z-20">
                        <div className="bg-white rounded-lg shadow-xl p-3 min-w-[200px] border border-gray-200">
                          <div className="text-sm font-medium mb-2">{m.name}</div>
                          <div className="text-xs text-muted-foreground space-y-1">
                            <div>型号: {m.model}</div>
                            <div>速度: {loc.speed.toFixed(1)} km/h</div>
                            <div>方向: {loc.heading.toFixed(0)}°</div>
                            <div className="pt-2 border-t">
                              位置: {formatCoordinate(loc.latitude, true)}<br/>
                              {formatCoordinate(loc.longitude, false)}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </div>
      </Card>

      {/* 设备列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {machinery.slice(0, 6).map(m => {
          const location = getLocationForMachinery(m.id);
          const state = getWorkState(m.id);

          return (
            <Card key={m.id} className="p-4 hover:shadow-md transition-shadow">
              <div className="flex items-start justify-between mb-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <h3 className="text-sm">{m.name}</h3>
                    {location && (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 w-6 p-0"
                        onClick={() => centerOnMachinery(m.id)}
                        title="定位到地图"
                      >
                        <MapPin className="w-3 h-3" />
                      </Button>
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">{m.model}</p>
                </div>
                {state && (
                  <Badge variant="secondary" className={`text-xs ${getStateColor(state.state)}`}>
                    {state.state}
                  </Badge>
                )}
              </div>

              {location ? (
                <div className="space-y-2">
                  <div className="grid grid-cols-2 gap-2 text-xs">
                    <div>
                      <div className="text-muted-foreground">纬度</div>
                      <div className="mt-0.5 font-mono">{location.latitude.toFixed(4)}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">经度</div>
                      <div className="mt-0.5 font-mono">{location.longitude.toFixed(4)}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">速度</div>
                      <div className="mt-0.5">{location.speed.toFixed(1)} km/h</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">方向</div>
                      <div className="mt-0.5 flex items-center gap-1">
                        <Navigation className="w-3 h-3" style={{ transform: `rotate(${location.heading}deg)` }} />
                        {location.heading.toFixed(0)}°
                      </div>
                    </div>
                  </div>

                  {state && (
                    <div className="grid grid-cols-3 gap-2 pt-2 border-t text-xs">
                      <div className="flex items-center gap-1">
                        <Gauge className="w-3 h-3 text-muted-foreground" />
                        <span>{state.engineRpm?.toFixed(0) || '-'} RPM</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Fuel className="w-3 h-3 text-muted-foreground" />
                        <span>{state.fuelLevel?.toFixed(0) || '-'}%</span>
                      </div>
                      <div>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-6 w-full text-xs"
                          onClick={() => handleMarkerClick(m)}
                        >
                          <Eye className="w-3 h-3 mr-1" />
                          详情
                        </Button>
                      </div>
                    </div>
                  )}

                  <div className="pt-2 border-t">
                    <div className="text-xs text-muted-foreground">
                      更新: {new Date(location.timestamp).toLocaleTimeString('zh-CN')}
                    </div>
                  </div>
                </div>
              ) : (
                <div className="text-center text-muted-foreground py-4 text-xs">
                  暂无位置信息
                </div>
              )}
            </Card>
          );
        })}
      </div>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">🌐 北斗/GPS定位服务特性</h4>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <ul className="space-y-2 text-sm text-muted-foreground">
            <li>✅ 集成北斗/GPS双模定位，支持高精度定位（精度±2-5米）</li>
            <li>✅ 实时接收并处理农机高频上报的经纬度数据（5秒/次）</li>
            <li>✅ 后端轨迹数据自动纠偏和加密存储（AES-256）</li>
            <li>✅ 地图图层动态显示所有农机位置，支持图标区分状态</li>
          </ul>
          <ul className="space-y-2 text-sm text-muted-foreground">
            <li>✅ 点击地图标记查看农机实时状态快照</li>
            <li>✅ 支持标准地图和卫星地图切换</li>
            <li>✅ 支持农机位置自动追踪和手动定位</li>
            <li>✅ 支持历史轨迹回放和导出（GPX/KML格式）</li>
          </ul>
        </div>
      </Card>

      {/* 详情对话框 */}
      <Dialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>农机实时状态快照</DialogTitle>
            <DialogDescription>
              查看农机的实时位置、工作状态和运行参数
            </DialogDescription>
          </DialogHeader>

          {viewingMachinery && (
            <div className="space-y-4">
              {(() => {
                const location = getLocationForMachinery(viewingMachinery.id);
                const state = getWorkState(viewingMachinery.id);

                return (
                  <>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label className="text-muted-foreground">农机名称</Label>
                        <p className="mt-1">{viewingMachinery.name}</p>
                      </div>
                      <div>
                        <Label className="text-muted-foreground">型号</Label>
                        <p className="mt-1">{viewingMachinery.model}</p>
                      </div>
                    </div>

                    {state && (
                      <div className="grid grid-cols-3 gap-4 pt-4 border-t">
                        <div>
                          <Label className="text-muted-foreground">工作状态</Label>
                          <div className="mt-1">
                            <Badge className={getStateColor(state.state)}>{state.state}</Badge>
                          </div>
                        </div>
                        <div>
                          <Label className="text-muted-foreground">点火状态</Label>
                          <p className="mt-1">{state.ignition ? '已点火' : '已熄火'}</p>
                        </div>
                        <div>
                          <Label className="text-muted-foreground">PTO状态</Label>
                          <p className="mt-1">{state.ptoStatus ? '启用' : '关闭'}</p>
                        </div>
                      </div>
                    )}

                    {location && (
                      <>
                        <div className="grid grid-cols-3 gap-4 pt-4 border-t">
                          <div>
                            <Label className="text-muted-foreground">纬度</Label>
                            <p className="mt-1 font-mono">{formatCoordinate(location.latitude, true)}</p>
                          </div>
                          <div>
                            <Label className="text-muted-foreground">经度</Label>
                            <p className="mt-1 font-mono">{formatCoordinate(location.longitude, false)}</p>
                          </div>
                          <div>
                            <Label className="text-muted-foreground">海拔</Label>
                            <p className="mt-1">{location.altitude?.toFixed(0)} m</p>
                          </div>
                        </div>

                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <Label className="text-muted-foreground">速度</Label>
                            <p className="mt-1">{location.speed.toFixed(1)} km/h</p>
                          </div>
                          <div>
                            <Label className="text-muted-foreground">方向</Label>
                            <p className="mt-1 flex items-center gap-2">
                              <Navigation className="w-4 h-4" style={{ transform: `rotate(${location.heading}deg)` }} />
                              {location.heading.toFixed(0)}°
                            </p>
                          </div>
                          <div>
                            <Label className="text-muted-foreground">定位精度</Label>
                            <p className="mt-1">±{location.accuracy?.toFixed(1)} m</p>
                          </div>
                        </div>
                      </>
                    )}

                    {state && (
                      <div className="grid grid-cols-3 gap-4 pt-4 border-t">
                        <div>
                          <Label className="text-muted-foreground">发动机转速</Label>
                          <p className="mt-1">{state.engineRpm?.toFixed(0) || '-'} RPM</p>
                        </div>
                        <div>
                          <Label className="text-muted-foreground">油量</Label>
                          <p className="mt-1">{state.fuelLevel?.toFixed(0) || '-'}%</p>
                        </div>
                        <div>
                          <Label className="text-muted-foreground">作业速率</Label>
                          <p className="mt-1">{state.workingRate?.toFixed(1) || '-'} 亩/时</p>
                        </div>
                      </div>
                    )}

                    <div className="pt-4 border-t">
                      <Label className="text-muted-foreground">数据更新时间</Label>
                      <p className="mt-1 text-sm">
                        {location ? new Date(location.timestamp).toLocaleString('zh-CN') : '-'}
                      </p>
                    </div>
                  </>
                );
              })()}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
