import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import {
  MapPin,
  Plus,
  Edit,
  Trash2,
  Download,
  FileText,
  BarChart3,
  Layers,
  Droplets,
  Leaf,
  Zap,
  TrendingUp,
  AlertCircle,
  CheckCircle2,
  Search,
  Save,
  X,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { BaseMap } from '../shared/BaseMap';
import { SimpleMapPointPicker } from './SimpleMapPointPicker';

interface SamplePoint {
  id: string;
  code: string;
  fieldName: string;
  latitude: number;
  longitude: number;
  sampleDate: string;
  sampler: string;
  deviceId?: string; // IoT设备ID
  layers: SoilLayer[];
}

interface SoilLayer {
  depth: string; // 如 "0-20cm"
  deviceId?: string; // IoT设备ID，用于读取该层数据
  // 以下字段从设备读取，仅用于展示
  pH?: number;
  organicMatter?: number; // 有机质 g/kg
  nitrogen?: number; // 全氮 g/kg
  phosphorus?: number; // 有效磷 mg/kg
  potassium?: number; // 速效钾 mg/kg
  moisture?: number; // 含水量 %
}

// IoT设备接口
interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: string;
  status: 'online' | 'offline';
  // 实时监测数据
  data: {
    pH: number;
    organicMatter: number;
    nitrogen: number;
    phosphorus: number;
    potassium: number;
    moisture: number;
    lastUpdate: string;
  };
}

export function SoilBaseData() {
  const [activeTab, setActiveTab] = useState('list');
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showLayerDialog, setShowLayerDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedPoint, setSelectedPoint] = useState<SamplePoint | null>(null);
  const [pointToDelete, setPointToDelete] = useState<string | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  
  // 模拟IoT设备列表
  const [iotDevices] = useState<IoTDevice[]>([
    {
      id: 'dev-1',
      code: 'IOT-SOIL-001',
      name: '土壤传感器001',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 6.8,
        organicMatter: 28.5,
        nitrogen: 1.2,
        phosphorus: 25.3,
        potassium: 180,
        moisture: 22.5,
        lastUpdate: '2024-10-18 14:30:00',
      },
    },
    {
      id: 'dev-2',
      code: 'IOT-SOIL-002',
      name: '土壤传感器002',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 7.2,
        organicMatter: 32.1,
        nitrogen: 1.5,
        phosphorus: 28.6,
        potassium: 195,
        moisture: 20.3,
        lastUpdate: '2024-10-18 14:28:00',
      },
    },
    {
      id: 'dev-3',
      code: 'IOT-SOIL-003',
      name: '土壤传感器003',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 5.8,
        organicMatter: 22.3,
        nitrogen: 0.9,
        phosphorus: 18.5,
        potassium: 152,
        moisture: 24.6,
        lastUpdate: '2024-10-18 14:25:00',
      },
    },
    {
      id: 'dev-4',
      code: 'IOT-SOIL-004',
      name: '土壤传感器004',
      type: '多参数土壤传感器',
      status: 'offline',
      data: {
        pH: 6.5,
        organicMatter: 18.2,
        nitrogen: 0.8,
        phosphorus: 18.5,
        potassium: 145,
        moisture: 25.8,
        lastUpdate: '2024-10-17 18:30:00',
      },
    },
  ]);
  
  // 新增采样点表单
  const [newPoint, setNewPoint] = useState({
    code: '',
    fieldName: '',
    latitude: 0,
    longitude: 0,
    sampleDate: '',
    sampler: '',
    deviceId: '',
    layers: [
      { depth: '0-20cm', deviceId: '' },
      { depth: '20-40cm', deviceId: '' },
      { depth: '40-60cm', deviceId: '' },
    ] as SoilLayer[],
  });

  // 模拟采样点数据
  const [samplePoints, setSamplePoints] = useState<SamplePoint[]>([
    {
      id: 'sp-1',
      code: 'SP001',
      fieldName: '东区1号地',
      latitude: 39.9042,
      longitude: 116.4074,
      sampleDate: '2024-10-15',
      sampler: '张三',
      deviceId: 'dev-1',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-1', pH: 6.8, organicMatter: 28.5, nitrogen: 1.2, phosphorus: 25.3, potassium: 180, moisture: 22.5 },
        { depth: '20-40cm', deviceId: 'dev-1', pH: 6.5, organicMatter: 18.2, nitrogen: 0.8, phosphorus: 18.5, potassium: 145, moisture: 25.8 },
        { depth: '40-60cm', deviceId: 'dev-1', pH: 6.3, organicMatter: 12.5, nitrogen: 0.5, phosphorus: 12.3, potassium: 98, moisture: 28.2 },
      ],
    },
    {
      id: 'sp-2',
      code: 'SP002',
      fieldName: '东区1号地',
      latitude: 39.9052,
      longitude: 116.4084,
      sampleDate: '2024-10-15',
      sampler: '张三',
      deviceId: 'dev-2',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-2', pH: 7.2, organicMatter: 32.1, nitrogen: 1.5, phosphorus: 28.6, potassium: 195, moisture: 20.3 },
        { depth: '20-40cm', deviceId: 'dev-2', pH: 6.8, organicMatter: 22.3, nitrogen: 1.0, phosphorus: 21.2, potassium: 158, moisture: 23.5 },
      ],
    },
    {
      id: 'sp-3',
      code: 'SP003',
      fieldName: '西区2号地',
      latitude: 39.9032,
      longitude: 116.4064,
      sampleDate: '2024-10-14',
      sampler: '李四',
      deviceId: 'dev-3',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-3', pH: 5.8, organicMatter: 22.3, nitrogen: 0.9, phosphorus: 18.5, potassium: 152, moisture: 24.6 },
        { depth: '20-40cm', deviceId: 'dev-3', pH: 5.5, organicMatter: 15.8, nitrogen: 0.6, phosphorus: 14.2, potassium: 125, moisture: 26.8 },
        { depth: '40-60cm', deviceId: 'dev-3', pH: 5.3, organicMatter: 10.2, nitrogen: 0.4, phosphorus: 9.8, potassium: 88, moisture: 29.1 },
      ],
    },
  ]);

  const handleViewLayers = (point: SamplePoint) => {
    setSelectedPoint(point);
    setShowLayerDialog(true);
  };

  const handleMapPointSelect = (lat: number, lng: number) => {
    setNewPoint({ ...newPoint, latitude: lat, longitude: lng });
    toast.success(`已选择坐标: ${lat.toFixed(6)}, ${lng.toFixed(6)}`);
  };

  const handleEditPoint = (point: SamplePoint) => {
    setSelectedPoint(point);
    setNewPoint({
      code: point.code,
      fieldName: point.fieldName,
      latitude: point.latitude,
      longitude: point.longitude,
      sampleDate: point.sampleDate,
      sampler: point.sampler,
      deviceId: point.deviceId || '',
      layers: JSON.parse(JSON.stringify(point.layers)), // 深拷贝
    });
    setShowEditDialog(true);
  };

  const handleUpdateSamplePoint = () => {
    if (!newPoint.code || !newPoint.fieldName || !newPoint.sampleDate || !newPoint.sampler) {
      toast.error('请填写完整的采样点基本信息');
      return;
    }
    if (newPoint.latitude === 0 || newPoint.longitude === 0) {
      toast.error('请在地图上选择采样点位置');
      return;
    }

    if (!selectedPoint) return;

    // 从设备读取数据并填充到分层信息
    const layersWithData = newPoint.layers.map(layer => {
      if (layer.deviceId) {
        const device = iotDevices.find(d => d.id === layer.deviceId);
        if (device) {
          return {
            ...layer,
            pH: device.data.pH,
            organicMatter: device.data.organicMatter,
            nitrogen: device.data.nitrogen,
            phosphorus: device.data.phosphorus,
            potassium: device.data.potassium,
            moisture: device.data.moisture,
          };
        }
      }
      return layer;
    });

    const updatedPoints = samplePoints.map(point =>
      point.id === selectedPoint.id
        ? { ...point, ...newPoint, layers: layersWithData }
        : point
    );

    setSamplePoints(updatedPoints);
    setShowEditDialog(false);
    setSelectedPoint(null);
    setNewPoint({
      code: '',
      fieldName: '',
      latitude: 0,
      longitude: 0,
      sampleDate: '',
      sampler: '',
      deviceId: '',
      layers: [
        { depth: '0-20cm', deviceId: '' },
        { depth: '20-40cm', deviceId: '' },
        { depth: '40-60cm', deviceId: '' },
      ],
    });
    toast.success('采样点更新成功！');
  };

  const handleAddSamplePoint = () => {
    if (!newPoint.code || !newPoint.fieldName || !newPoint.sampleDate || !newPoint.sampler) {
      toast.error('请填写完整的采样点基本信息');
      return;
    }
    if (newPoint.latitude === 0 || newPoint.longitude === 0) {
      toast.error('请在地图上选择采样点位置');
      return;
    }

    // 从设备读取数据并填充到分层信息
    const layersWithData = newPoint.layers.map(layer => {
      if (layer.deviceId) {
        const device = iotDevices.find(d => d.id === layer.deviceId);
        if (device) {
          return {
            ...layer,
            pH: device.data.pH,
            organicMatter: device.data.organicMatter,
            nitrogen: device.data.nitrogen,
            phosphorus: device.data.phosphorus,
            potassium: device.data.potassium,
            moisture: device.data.moisture,
          };
        }
      }
      return layer;
    });

    const newSamplePoint: SamplePoint = {
      id: `sp-${Date.now()}`,
      ...newPoint,
      layers: layersWithData,
    };

    setSamplePoints([...samplePoints, newSamplePoint]);
    setShowAddDialog(false);
    setNewPoint({
      code: '',
      fieldName: '',
      latitude: 0,
      longitude: 0,
      sampleDate: '',
      sampler: '',
      deviceId: '',
      layers: [
        { depth: '0-20cm', deviceId: '' },
        { depth: '20-40cm', deviceId: '' },
        { depth: '40-60cm', deviceId: '' },
      ],
    });
    toast.success('采样点添加成功！');
  };

  const handleAddLayer = () => {
    const newLayer: SoilLayer = {
      depth: `${newPoint.layers.length * 20}-${(newPoint.layers.length + 1) * 20}cm`,
      deviceId: '',
    };
    setNewPoint({ ...newPoint, layers: [...newPoint.layers, newLayer] });
  };

  const handleUpdateLayerDevice = (layerIndex: number, deviceId: string) => {
    const updatedLayers = [...newPoint.layers];
    updatedLayers[layerIndex] = { ...updatedLayers[layerIndex], deviceId };
    setNewPoint({ ...newPoint, layers: updatedLayers });
  };

  const handleRemoveLayer = (index: number) => {
    if (newPoint.layers.length > 1) {
      const updatedLayers = newPoint.layers.filter((_, i) => i !== index);
      setNewPoint({ ...newPoint, layers: updatedLayers });
    }
  };

  const handleExportData = () => {
    // 生成CSV数据
    const headers = ['采样点编号', '地块', '纬度', '经度', '采样日期', '采样人', '深度', 'pH值', '有机质(g/kg)', '全氮(g/kg)', '有效磷(mg/kg)', '速效钾(mg/kg)', '含水量(%)'];
    const rows = samplePoints.flatMap(point =>
      point.layers.map(layer => [
        point.code,
        point.fieldName,
        point.latitude,
        point.longitude,
        point.sampleDate,
        point.sampler,
        layer.depth,
        layer.pH,
        layer.organicMatter,
        layer.nitrogen,
        layer.phosphorus,
        layer.potassium,
        layer.moisture,
      ])
    );

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(',')),
    ].join('\n');

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `土壤基础数据_${new Date().toLocaleDateString()}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    toast.success('土壤数据已导出为CSV格式');
  };

  const handleGenerateReport = () => {
    toast.success('正在生成土壤检测报告...');
    setTimeout(() => {
      // 生成报告HTML内容
      const reportHTML = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>土壤��测报告</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #2d5016; border-bottom: 3px solid #4ade80; padding-bottom: 10px; }
    h2 { color: #16a34a; margin-top: 30px; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
    th { background-color: #f0fdf4; color: #166534; }
    tr:nth-child(even) { background-color: #f9fafb; }
    .summary { background: #f0fdf4; padding: 20px; border-radius: 8px; margin: 20px 0; }
    .footer { margin-top: 40px; text-align: center; color: #666; font-size: 12px; }
  </style>
</head>
<body>
  <h1>土壤基础数据检测报告</h1>
  <div class="summary">
    <h3>报告概要</h3>
    <p><strong>生成日期：</strong>${new Date().toLocaleDateString()}</p>
    <p><strong>采样点总数：</strong>${samplePoints.length} 个</p>
    <p><strong>覆盖地块：</strong>3 个</p>
    <p><strong>分层样本：</strong>8 层</p>
  </div>
  
  <h2>采样点详细数据</h2>
  ${samplePoints.map(point => `
    <h3>${point.code} - ${point.fieldName}</h3>
    <p><strong>坐标：</strong>${point.latitude.toFixed(6)}, ${point.longitude.toFixed(6)}</p>
    <p><strong>采样日期：</strong>${point.sampleDate} | <strong>采样人：</strong>${point.sampler}</p>
    <table>
      <thead>
        <tr>
          <th>深度</th>
          <th>pH值</th>
          <th>有机质(g/kg)</th>
          <th>全氮(g/kg)</th>
          <th>有效磷(mg/kg)</th>
          <th>速效钾(mg/kg)</th>
          <th>含水量(%)</th>
        </tr>
      </thead>
      <tbody>
        ${point.layers.map(layer => `
          <tr>
            <td>${layer.depth}</td>
            <td>${layer.pH}</td>
            <td>${layer.organicMatter}</td>
            <td>${layer.nitrogen}</td>
            <td>${layer.phosphorus}</td>
            <td>${layer.potassium}</td>
            <td>${layer.moisture}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  `).join('')}
  
  <h2>统计分析</h2>
  <div class="summary">
    <p><strong>平均pH值：</strong>6.5 (中性)</p>
    <p><strong>平均有机质：</strong>27.6 g/kg (较高)</p>
    <p><strong>平均全氮：</strong>1.2 g/kg (中等)</p>
    <p><strong>土壤综合评价：</strong>土壤理化性状良好，养分含量较为丰富，适宜大多数作物生长</p>
  </div>
  
  <div class="footer">
    <p>本报告由智慧农业生产管理系统自动生成</p>
    <p>报告生成时间：${new Date().toLocaleString()}</p>
  </div>
</body>
</html>
      `;

      // 创建下载链接
      const blob = new Blob([reportHTML], { type: 'text/html;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `土壤检测报告_${new Date().toLocaleDateString()}.html`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      toast.success('土壤检测报告已生成！');
    }, 1000);
  };

  const handleDeleteClick = (pointId: string) => {
    setPointToDelete(pointId);
    setShowDeleteDialog(true);
  };

  const handleConfirmDelete = () => {
    if (pointToDelete) {
      setSamplePoints(samplePoints.filter(p => p.id !== pointToDelete));
      toast.success('采样点已删除');
      setPointToDelete(null);
      setShowDeleteDialog(false);
    }
  };

  const getpHLevel = (pH: number) => {
    if (pH < 5.5) return { label: '强酸性', color: 'bg-red-500' };
    if (pH < 6.5) return { label: '酸性', color: 'bg-orange-500' };
    if (pH < 7.5) return { label: '中性', color: 'bg-green-500' };
    if (pH < 8.5) return { label: '碱性', color: 'bg-blue-500' };
    return { label: '强碱性', color: 'bg-purple-500' };
  };

  const getOrganicMatterLevel = (om: number) => {
    if (om < 10) return { label: '极低', color: 'text-red-600' };
    if (om < 20) return { label: '低', color: 'text-orange-600' };
    if (om < 30) return { label: '中等', color: 'text-yellow-600' };
    if (om < 40) return { label: '较高', color: 'text-green-600' };
    return { label: '高', color: 'text-blue-600' };
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">土壤基础数据</h2>
          <p className="text-muted-foreground">
            土壤采样点管理、分层数据记录与统计分析
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExportData}>
            <Download className="w-4 h-4 mr-2" />
            导出数据
          </Button>
          <Button variant="outline" onClick={handleGenerateReport}>
            <FileText className="w-4 h-4 mr-2" />
            生成报告
          </Button>
          <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowAddDialog(true)}>
            <Plus className="w-4 h-4 mr-2" />
            新增采样点
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">采样点总数</p>
              <p className="mt-2 text-2xl text-green-600">{samplePoints.length}</p>
            </div>
            <MapPin className="w-10 h-10 text-green-600 opacity-50" />
          </div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">覆盖地块</p>
              <p className="mt-2 text-2xl text-blue-600">3 个</p>
            </div>
            <Layers className="w-10 h-10 text-blue-600 opacity-50" />
          </div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">分层样本</p>
              <p className="mt-2 text-2xl text-purple-600">8 层</p>
            </div>
            <BarChart3 className="w-10 h-10 text-purple-600 opacity-50" />
          </div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-orange-50 to-orange-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">平均pH值</p>
              <p className="mt-2 text-2xl text-orange-600">6.5</p>
            </div>
            <Droplets className="w-10 h-10 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="list">采样点列表</TabsTrigger>
          <TabsTrigger value="distribution">空间分布</TabsTrigger>
          <TabsTrigger value="profile">剖面信息</TabsTrigger>
          <TabsTrigger value="statistics">统计分析</TabsTrigger>
        </TabsList>

        {/* 采样点列表 */}
        <TabsContent value="list" className="space-y-4">
          <Card className="p-4">
            <div className="flex gap-4 mb-4">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索采样点编号、地块名称..."
                    value={searchKeyword}
                    onChange={(e) => setSearchKeyword(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <Select defaultValue="all">
                <SelectTrigger className="w-[200px]">
                  <SelectValue placeholder="选择地块" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部地块</SelectItem>
                  <SelectItem value="field-1">东区1号地</SelectItem>
                  <SelectItem value="field-2">西区2号地</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          <div className="space-y-3">
            {samplePoints.map((point) => (
              <Card key={point.id} className="p-4">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-3">
                      <MapPin className="w-5 h-5 text-green-600" />
                      <div>
                        <div className="flex items-center gap-2">
                          <h4>{point.code}</h4>
                          <Badge variant="outline">{point.fieldName}</Badge>
                        </div>
                        <p className="text-sm text-muted-foreground mt-1">
                          坐标: {point.latitude.toFixed(6)}, {point.longitude.toFixed(6)}
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-4 gap-4 pl-8">
                      <div>
                        <span className="text-xs text-muted-foreground">采样日期</span>
                        <p className="text-sm mt-1">{point.sampleDate}</p>
                      </div>
                      <div>
                        <span className="text-xs text-muted-foreground">采样人</span>
                        <p className="text-sm mt-1">{point.sampler}</p>
                      </div>
                      <div>
                        <span className="text-xs text-muted-foreground">分层数</span>
                        <p className="text-sm mt-1">{point.layers.length} 层</p>
                      </div>
                      <div>
                        <span className="text-xs text-muted-foreground">表层pH值</span>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-sm">{point.layers[0].pH}</span>
                          <div className={`w-2 h-2 rounded-full ${getpHLevel(point.layers[0].pH).color}`} />
                        </div>
                      </div>
                    </div>

                    {/* 表层指标快览 */}
                    <div className="mt-3 p-3 bg-gray-50 rounded-lg">
                      <div className="text-xs text-muted-foreground mb-2">表层指标（0-20cm）</div>
                      <div className="grid grid-cols-5 gap-3 text-sm">
                        <div className="flex items-center gap-2">
                          <Leaf className="w-4 h-4 text-green-600" />
                          <span>有机质: <strong>{point.layers[0].organicMatter}</strong> g/kg</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Zap className="w-4 h-4 text-blue-600" />
                          <span>全氮: <strong>{point.layers[0].nitrogen}</strong> g/kg</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <TrendingUp className="w-4 h-4 text-orange-600" />
                          <span>有效磷: <strong>{point.layers[0].phosphorus}</strong> mg/kg</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <TrendingUp className="w-4 h-4 text-purple-600" />
                          <span>速效钾: <strong>{point.layers[0].potassium}</strong> mg/kg</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Droplets className="w-4 h-4 text-cyan-600" />
                          <span>含水量: <strong>{point.layers[0].moisture}</strong>%</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => handleViewLayers(point)}>
                      <Layers className="w-4 h-4 mr-1" />
                      查看剖面
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => handleEditPoint(point)}>
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => handleDeleteClick(point.id)}>
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 空间分布 */}
        <TabsContent value="distribution" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">采样点空间分布图</h3>
            <div className="relative h-[500px] rounded-lg border overflow-hidden">
              <BaseMap
                center={samplePoints.length > 0 ? [samplePoints[0].longitude, samplePoints[0].latitude] : [116.4074, 39.9042]}
                zoom={13}
                markers={samplePoints.map(point => ({
                  position: [point.longitude, point.latitude] as [number, number],
                  popup: `
                    <div style="padding: 8px;">
                      <div style="font-weight: 600; margin-bottom: 4px;">${point.code}</div>
                      <div style="font-size: 12px; color: #666;">${point.fieldName}</div>
                      <div style="font-size: 12px; color: #666;">采样日期: ${point.sampleDate}</div>
                      <div style="font-size: 12px; color: #666;">pH值: ${point.layers[0].pH}</div>
                      <div style="font-size: 12px; color: #666;">有机质: ${point.layers[0].organicMatter} g/kg</div>
                    </div>
                  `,
                  color: point.layers[0].pH < 6.5 ? '#f97316' : point.layers[0].pH < 7.5 ? '#22c55e' : '#3b82f6',
                }))}
              />
              {/* 图例 */}
              <div className="absolute bottom-4 right-4 bg-white p-4 rounded-lg shadow-lg border z-[1000]">
                <h4 className="text-sm mb-2">图例</h4>
                <div className="space-y-2 text-xs">
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-orange-500" />
                    <span>酸性土壤 (pH &lt; 6.5)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-green-500" />
                    <span>中性土壤 (6.5-7.5)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-blue-500" />
                    <span>碱性土壤 (pH &gt; 7.5)</span>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* 空间分布统计 */}
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-4">
              <h4 className="mb-3">采样密度统计</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">东区1号地:</span>
                  <span>2 个点 (13.3点/百亩)</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">西区2号地:</span>
                  <span>1 个点 (5.0点/百亩)</span>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <h4 className="mb-3">覆盖范围</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总面积:</span>
                  <span>350 亩</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">已采样:</span>
                  <span>350 亩 (100%)</span>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <h4 className="mb-3">采样建议</h4>
              <div className="text-sm text-muted-foreground">
                建议在南区3号地增加采样点，提高数据代表性
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 剖面信息 */}
        <TabsContent value="profile" className="space-y-4">
          <Card className="p-4">
            <div className="flex gap-4 mb-4">
              <Select defaultValue="sp-1">
                <SelectTrigger className="w-[300px]">
                  <SelectValue placeholder="选择采样点" />
                </SelectTrigger>
                <SelectContent>
                  {samplePoints.map((point) => (
                    <SelectItem key={point.id} value={point.id}>
                      {point.code} - {point.fieldName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 剖面可视化 */}
          <Card className="p-6">
            <h3 className="mb-4">土壤剖面可视化</h3>
            <div className="flex gap-6">
              {/* 左侧剖面图 */}
              <div className="w-1/3">
                <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
                  {samplePoints[0].layers.map((layer, index) => (
                    <div
                      key={index}
                      className="relative border-b last:border-b-0"
                      style={{
                        height: '120px',
                        background: `linear-gradient(to bottom, 
                          ${index === 0 ? '#8b7355' : index === 1 ? '#6b5344' : '#4a3829'},
                          ${index === 0 ? '#6b5344' : index === 1 ? '#4a3829' : '#2a1810'}
                        )`,
                      }}
                    >
                      <div className="absolute left-4 top-4 text-white">
                        <div className="text-sm font-medium">{layer.depth}</div>
                      </div>
                      <div className="absolute right-4 top-4 text-white text-xs bg-black/30 px-2 py-1 rounded">
                        pH: {layer.pH}
                      </div>
                    </div>
                  ))}
                </div>
                <div className="text-center text-sm text-muted-foreground mt-2">深度剖面图</div>
              </div>

              {/* 右侧数据表格 */}
              <div className="flex-1">
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-3 text-left text-sm">深度</th>
                        <th className="px-4 py-3 text-center text-sm">pH值</th>
                        <th className="px-4 py-3 text-center text-sm">有机质(g/kg)</th>
                        <th className="px-4 py-3 text-center text-sm">全氮(g/kg)</th>
                        <th className="px-4 py-3 text-center text-sm">有效磷(mg/kg)</th>
                        <th className="px-4 py-3 text-center text-sm">速效钾(mg/kg)</th>
                        <th className="px-4 py-3 text-center text-sm">含水量(%)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {samplePoints[0].layers.map((layer, index) => (
                        <tr key={index} className="border-t">
                          <td className="px-4 py-3 font-medium">{layer.depth}</td>
                          <td className="px-4 py-3 text-center">
                            <Badge className={getpHLevel(layer.pH).color}>{layer.pH}</Badge>
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span className={getOrganicMatterLevel(layer.organicMatter).color}>
                              {layer.organicMatter}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-center">{layer.nitrogen}</td>
                          <td className="px-4 py-3 text-center">{layer.phosphorus}</td>
                          <td className="px-4 py-3 text-center">{layer.potassium}</td>
                          <td className="px-4 py-3 text-center">{layer.moisture}%</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 趋势分析 */}
                <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <h4 className="mb-2 text-blue-900">剖面特征分析</h4>
                  <ul className="space-y-1 text-sm text-blue-800">
                    <li>• <strong>pH值</strong>: 随深度增加略有下降，表层为中性偏酸</li>
                    <li>• <strong>有机质</strong>: 表层含量高，向下递减，符合正常分布规律</li>
                    <li>• <strong>养分</strong>: 氮磷钾含量表层最高，20cm以下显著降低</li>
                    <li>• <strong>水分</strong>: 随深度增加含水量上升，底层保水性好</li>
                  </ul>
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 统计分析 */}
        <TabsContent value="statistics" className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4">pH值分布统计</h3>
              <div className="space-y-3">
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>强酸性 (&lt;5.5)</span>
                    <span>0 个 (0%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-red-500" style={{ width: '0%' }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>酸性 (5.5-6.5)</span>
                    <span>1 个 (33%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-orange-500" style={{ width: '33%' }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>中性 (6.5-7.5)</span>
                    <span>2 个 (67%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-green-500" style={{ width: '67%' }} />
                  </div>
                </div>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">有机质含量统计</h3>
              <div className="space-y-3">
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>极低 (&lt;10 g/kg)</span>
                    <span>0 个 (0%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-red-500" style={{ width: '0%' }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>低 (10-20 g/kg)</span>
                    <span>0 个 (0%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-orange-500" style={{ width: '0%' }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>中等 (20-30 g/kg)</span>
                    <span>2 个 (67%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-yellow-500" style={{ width: '67%' }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-1">
                    <span>较高 (30-40 g/kg)</span>
                    <span>1 个 (33%)</span>
                  </div>
                  <div className="w-full h-6 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full bg-green-500" style={{ width: '33%' }} />
                  </div>
                </div>
              </div>
            </Card>
          </div>

          {/* 综合统计 */}
          <Card className="p-6">
            <h3 className="mb-4">表层土壤指标统计（0-20cm）</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-sm">指标</th>
                    <th className="px-4 py-3 text-center text-sm">最小值</th>
                    <th className="px-4 py-3 text-center text-sm">最大值</th>
                    <th className="px-4 py-3 text-center text-sm">平均值</th>
                    <th className="px-4 py-3 text-center text-sm">标准差</th>
                    <th className="px-4 py-3 text-center text-sm">变异系数</th>
                    <th className="px-4 py-3 text-center text-sm">评价</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-4 py-3 font-medium">pH值</td>
                    <td className="px-4 py-3 text-center">5.8</td>
                    <td className="px-4 py-3 text-center">7.2</td>
                    <td className="px-4 py-3 text-center">6.6</td>
                    <td className="px-4 py-3 text-center">0.58</td>
                    <td className="px-4 py-3 text-center">8.8%</td>
                    <td className="px-4 py-3 text-center">
                      <Badge className="bg-green-500">适中</Badge>
                    </td>
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 font-medium">有机质 (g/kg)</td>
                    <td className="px-4 py-3 text-center">22.3</td>
                    <td className="px-4 py-3 text-center">32.1</td>
                    <td className="px-4 py-3 text-center">27.6</td>
                    <td className="px-4 py-3 text-center">4.1</td>
                    <td className="px-4 py-3 text-center">14.9%</td>
                    <td className="px-4 py-3 text-center">
                      <Badge className="bg-green-500">较高</Badge>
                    </td>
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 font-medium">全氮 (g/kg)</td>
                    <td className="px-4 py-3 text-center">0.9</td>
                    <td className="px-4 py-3 text-center">1.5</td>
                    <td className="px-4 py-3 text-center">1.2</td>
                    <td className="px-4 py-3 text-center">0.25</td>
                    <td className="px-4 py-3 text-center">20.8%</td>
                    <td className="px-4 py-3 text-center">
                      <Badge className="bg-yellow-500">中等</Badge>
                    </td>
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 font-medium">有效磷 (mg/kg)</td>
                    <td className="px-4 py-3 text-center">18.5</td>
                    <td className="px-4 py-3 text-center">28.6</td>
                    <td className="px-4 py-3 text-center">24.1</td>
                    <td className="px-4 py-3 text-center">4.2</td>
                    <td className="px-4 py-3 text-center">17.4%</td>
                    <td className="px-4 py-3 text-center">
                      <Badge className="bg-green-500">较高</Badge>
                    </td>
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 font-medium">速效钾 (mg/kg)</td>
                    <td className="px-4 py-3 text-center">152</td>
                    <td className="px-4 py-3 text-center">195</td>
                    <td className="px-4 py-3 text-center">176</td>
                    <td className="px-4 py-3 text-center">18.5</td>
                    <td className="px-4 py-3 text-center">10.5%</td>
                    <td className="px-4 py-3 text-center">
                      <Badge className="bg-green-500">高</Badge>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 新增采样点对话框 */}
      <Dialog open={showAddDialog} onOpenChange={(open) => {
        setShowAddDialog(open);
        if (!open) {
          setNewPoint({
            code: '',
            fieldName: '',
            latitude: 0,
            longitude: 0,
            sampleDate: '',
            sampler: '',
            deviceId: '',
            layers: [
              { depth: '0-20cm', deviceId: '' },
              { depth: '20-40cm', deviceId: '' },
              { depth: '40-60cm', deviceId: '' },
            ],
          });
        }
      }}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>新增采样点</DialogTitle>
            <DialogDescription className="sr-only">
              添加新的土壤采样点，包含GPS坐标定位和分层数据录入
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>采样点编号 *</Label>
                <Input
                  value={newPoint.code}
                  onChange={(e) => setNewPoint({ ...newPoint, code: e.target.value })}
                  placeholder="如: SP004"
                />
              </div>
              <div>
                <Label>所属地块 *</Label>
                <Input
                  value={newPoint.fieldName}
                  onChange={(e) => setNewPoint({ ...newPoint, fieldName: e.target.value })}
                  placeholder="如: 东区1号地"
                />
              </div>
              <div>
                <Label>采样日期 *</Label>
                <Input
                  type="date"
                  value={newPoint.sampleDate}
                  onChange={(e) => setNewPoint({ ...newPoint, sampleDate: e.target.value })}
                />
              </div>
              <div>
                <Label>采样人 *</Label>
                <Input
                  value={newPoint.sampler}
                  onChange={(e) => setNewPoint({ ...newPoint, sampler: e.target.value })}
                  placeholder="如: 张三"
                />
              </div>
              <div className="col-span-2">
                <Label>IoT设备（可选）</Label>
                <Select value={newPoint.deviceId || 'none'} onValueChange={(value) => setNewPoint({ ...newPoint, deviceId: value === 'none' ? '' : value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择物联网设备" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不绑定设备</SelectItem>
                    {iotDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        <div className="flex items-center gap-2">
                          <span>{device.code} - {device.name}</span>
                          <Badge variant={device.status === 'online' ? 'default' : 'secondary'} className="ml-2">
                            {device.status === 'online' ? '在线' : '离线'}
                          </Badge>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {newPoint.deviceId && (() => {
                  const device = iotDevices.find(d => d.id === newPoint.deviceId);
                  return device ? (
                    <div className="mt-2 p-3 bg-green-50 border border-green-200 rounded-lg">
                      <div className="text-xs text-green-800 mb-1">设备实时数据（最后更新：{device.data.lastUpdate}）</div>
                      <div className="grid grid-cols-6 gap-2 text-xs text-green-700">
                        <div>pH: {device.data.pH}</div>
                        <div>有机质: {device.data.organicMatter}</div>
                        <div>全氮: {device.data.nitrogen}</div>
                        <div>有效磷: {device.data.phosphorus}</div>
                        <div>速效钾: {device.data.potassium}</div>
                        <div>含水量: {device.data.moisture}%</div>
                      </div>
                    </div>
                  ) : null;
                })()}
              </div>
            </div>

            {/* GPS坐标定位 */}
            <div>
              <Label>GPS坐���定�� *</Label>
              <div className="grid grid-cols-2 gap-4 mb-2">
                <div>
                  <Input
                    type="number"
                    value={newPoint.latitude || ''}
                    onChange={(e) => setNewPoint({ ...newPoint, latitude: parseFloat(e.target.value) || 0 })}
                    placeholder="纬度"
                    step="0.000001"
                  />
                </div>
                <div>
                  <Input
                    type="number"
                    value={newPoint.longitude || ''}
                    onChange={(e) => setNewPoint({ ...newPoint, longitude: parseFloat(e.target.value) || 0 })}
                    placeholder="经度"
                    step="0.000001"
                  />
                </div>
              </div>
              <SimpleMapPointPicker
                onPointSelect={handleMapPointSelect}
                selectedPoint={newPoint.latitude && newPoint.longitude ? [newPoint.latitude, newPoint.longitude] : undefined}
              />
            </div>

            {/* 分层数据 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <Label>土壤分层数据</Label>
                <Button type="button" size="sm" variant="outline" onClick={handleAddLayer}>
                  <Plus className="w-4 h-4 mr-1" />
                  添加土层
                </Button>
              </div>
              <div className="space-y-4">
                {newPoint.layers.map((layer, layerIndex) => (
                  <Card key={layerIndex} className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <h4>第 {layerIndex + 1} 层 ({layer.depth})</h4>
                      {newPoint.layers.length > 1 && (
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          onClick={() => handleRemoveLayer(layerIndex)}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">深度 *</Label>
                        <Input
                          value={layer.depth}
                          onChange={(e) => {
                            const updatedLayers = [...newPoint.layers];
                            updatedLayers[layerIndex] = { ...updatedLayers[layerIndex], depth: e.target.value };
                            setNewPoint({ ...newPoint, layers: updatedLayers });
                          }}
                          placeholder="如: 0-20cm"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">IoT设备（可选）</Label>
                        <Select 
                          value={layer.deviceId || 'none'} 
                          onValueChange={(value) => handleUpdateLayerDevice(layerIndex, value === 'none' ? '' : value)}
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择设备读取数据" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="none">不绑定设备</SelectItem>
                            {iotDevices.map((device) => (
                              <SelectItem key={device.id} value={device.id}>
                                <span>{device.code} - {device.name}</span>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    {layer.deviceId && (() => {
                      const device = iotDevices.find(d => d.id === layer.deviceId);
                      return device ? (
                        <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                          <div className="text-xs text-blue-800 mb-2">从设备读取的数据（最后更新：{device.data.lastUpdate}）</div>
                          <div className="grid grid-cols-3 gap-3 text-sm">
                            <div className="flex items-center gap-2">
                              <Droplets className="w-4 h-4 text-blue-600" />
                              <span>pH: <strong>{device.data.pH}</strong></span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Leaf className="w-4 h-4 text-green-600" />
                              <span>有机质: <strong>{device.data.organicMatter}</strong> g/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Zap className="w-4 h-4 text-blue-600" />
                              <span>全氮: <strong>{device.data.nitrogen}</strong> g/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <TrendingUp className="w-4 h-4 text-orange-600" />
                              <span>有效磷: <strong>{device.data.phosphorus}</strong> mg/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <TrendingUp className="w-4 h-4 text-purple-600" />
                              <span>速效钾: <strong>{device.data.potassium}</strong> mg/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Droplets className="w-4 h-4 text-cyan-600" />
                              <span>含水量: <strong>{device.data.moisture}</strong>%</span>
                            </div>
                          </div>
                        </div>
                      ) : null;
                    })()}
                  </Card>
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button variant="outline" onClick={() => setShowAddDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleAddSamplePoint}>
                <Save className="w-4 h-4 mr-2" />
                保存采样点
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 编辑采样点对话框 */}
      <Dialog open={showEditDialog} onOpenChange={(open) => {
        setShowEditDialog(open);
        if (!open) {
          setSelectedPoint(null);
          setNewPoint({
            code: '',
            fieldName: '',
            latitude: 0,
            longitude: 0,
            sampleDate: '',
            sampler: '',
            deviceId: '',
            layers: [
              { depth: '0-20cm', deviceId: '' },
              { depth: '20-40cm', deviceId: '' },
              { depth: '40-60cm', deviceId: '' },
            ],
          });
        }
      }}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>编辑采样点</DialogTitle>
            <DialogDescription className="sr-only">
              编辑土壤采样点信息，包含GPS坐标定位和分层数据修改
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>采样点编号 *</Label>
                <Input
                  value={newPoint.code}
                  onChange={(e) => setNewPoint({ ...newPoint, code: e.target.value })}
                  placeholder="如: SP004"
                />
              </div>
              <div>
                <Label>所属地块 *</Label>
                <Input
                  value={newPoint.fieldName}
                  onChange={(e) => setNewPoint({ ...newPoint, fieldName: e.target.value })}
                  placeholder="如: 东区1号地"
                />
              </div>
              <div>
                <Label>采样日期 *</Label>
                <Input
                  type="date"
                  value={newPoint.sampleDate}
                  onChange={(e) => setNewPoint({ ...newPoint, sampleDate: e.target.value })}
                />
              </div>
              <div>
                <Label>采样人 *</Label>
                <Input
                  value={newPoint.sampler}
                  onChange={(e) => setNewPoint({ ...newPoint, sampler: e.target.value })}
                  placeholder="如: 张三"
                />
              </div>
              <div className="col-span-2">
                <Label>IoT设备（可选）</Label>
                <Select value={newPoint.deviceId || 'none'} onValueChange={(value) => setNewPoint({ ...newPoint, deviceId: value === 'none' ? '' : value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择物联网设备" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不绑定设备</SelectItem>
                    {iotDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        <div className="flex items-center gap-2">
                          <span>{device.code} - {device.name}</span>
                          <Badge variant={device.status === 'online' ? 'default' : 'secondary'} className="ml-2">
                            {device.status === 'online' ? '在线' : '离线'}
                          </Badge>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {newPoint.deviceId && (() => {
                  const device = iotDevices.find(d => d.id === newPoint.deviceId);
                  return device ? (
                    <div className="mt-2 p-3 bg-green-50 border border-green-200 rounded-lg">
                      <div className="text-xs text-green-800 mb-1">设备实时数据（最后更新：{device.data.lastUpdate}）</div>
                      <div className="grid grid-cols-6 gap-2 text-xs text-green-700">
                        <div>pH: {device.data.pH}</div>
                        <div>有机质: {device.data.organicMatter}</div>
                        <div>全氮: {device.data.nitrogen}</div>
                        <div>有效磷: {device.data.phosphorus}</div>
                        <div>速效钾: {device.data.potassium}</div>
                        <div>含水量: {device.data.moisture}%</div>
                      </div>
                    </div>
                  ) : null;
                })()}
              </div>
            </div>

            {/* GPS坐标定位 */}
            <div>
              <Label>GPS坐标定位 *</Label>
              <div className="grid grid-cols-2 gap-4 mb-2">
                <div>
                  <Input
                    type="number"
                    value={newPoint.latitude || ''}
                    onChange={(e) => setNewPoint({ ...newPoint, latitude: parseFloat(e.target.value) || 0 })}
                    placeholder="纬度"
                    step="0.000001"
                  />
                </div>
                <div>
                  <Input
                    type="number"
                    value={newPoint.longitude || ''}
                    onChange={(e) => setNewPoint({ ...newPoint, longitude: parseFloat(e.target.value) || 0 })}
                    placeholder="经度"
                    step="0.000001"
                  />
                </div>
              </div>
              <SimpleMapPointPicker
                onPointSelect={handleMapPointSelect}
                selectedPoint={newPoint.latitude && newPoint.longitude ? [newPoint.latitude, newPoint.longitude] : undefined}
              />
            </div>

            {/* 分层数据 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <Label>土壤分层数据</Label>
                <Button type="button" size="sm" variant="outline" onClick={handleAddLayer}>
                  <Plus className="w-4 h-4 mr-1" />
                  添加土层
                </Button>
              </div>
              <div className="space-y-4">
                {newPoint.layers.map((layer, layerIndex) => (
                  <Card key={layerIndex} className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <h4>第 {layerIndex + 1} 层 ({layer.depth})</h4>
                      {newPoint.layers.length > 1 && (
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          onClick={() => handleRemoveLayer(layerIndex)}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">深度 *</Label>
                        <Input
                          value={layer.depth}
                          onChange={(e) => {
                            const updatedLayers = [...newPoint.layers];
                            updatedLayers[layerIndex] = { ...updatedLayers[layerIndex], depth: e.target.value };
                            setNewPoint({ ...newPoint, layers: updatedLayers });
                          }}
                          placeholder="如: 0-20cm"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">IoT设备（可选）</Label>
                        <Select 
                          value={layer.deviceId || 'none'} 
                          onValueChange={(value) => handleUpdateLayerDevice(layerIndex, value === 'none' ? '' : value)}
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择设备读取数据" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="none">不绑定设备</SelectItem>
                            {iotDevices.map((device) => (
                              <SelectItem key={device.id} value={device.id}>
                                <span>{device.code} - {device.name}</span>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    {layer.deviceId && (() => {
                      const device = iotDevices.find(d => d.id === layer.deviceId);
                      return device ? (
                        <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                          <div className="text-xs text-blue-800 mb-2">从设备读取的数据（最后更新：{device.data.lastUpdate}）</div>
                          <div className="grid grid-cols-3 gap-3 text-sm">
                            <div className="flex items-center gap-2">
                              <Droplets className="w-4 h-4 text-blue-600" />
                              <span>pH: <strong>{device.data.pH}</strong></span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Leaf className="w-4 h-4 text-green-600" />
                              <span>有机质: <strong>{device.data.organicMatter}</strong> g/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Zap className="w-4 h-4 text-blue-600" />
                              <span>全氮: <strong>{device.data.nitrogen}</strong> g/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <TrendingUp className="w-4 h-4 text-orange-600" />
                              <span>有效磷: <strong>{device.data.phosphorus}</strong> mg/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <TrendingUp className="w-4 h-4 text-purple-600" />
                              <span>速效钾: <strong>{device.data.potassium}</strong> mg/kg</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <Droplets className="w-4 h-4 text-cyan-600" />
                              <span>含水量: <strong>{device.data.moisture}</strong>%</span>
                            </div>
                          </div>
                        </div>
                      ) : null;
                    })()}
                  </Card>
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button variant="outline" onClick={() => {
                setShowEditDialog(false);
                setSelectedPoint(null);
              }}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleUpdateSamplePoint}>
                <Save className="w-4 h-4 mr-2" />
                更新采样点
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 分层数据对话框 */}
      <Dialog open={showLayerDialog} onOpenChange={setShowLayerDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>土壤剖面分层数据 - {selectedPoint?.code}</DialogTitle>
            <DialogDescription className="sr-only">
              查看土壤剖面的分层详细数据
            </DialogDescription>
          </DialogHeader>
          {selectedPoint && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">采样点:</span> {selectedPoint.code}
                </div>
                <div>
                  <span className="text-muted-foreground">地块:</span> {selectedPoint.fieldName}
                </div>
                <div>
                  <span className="text-muted-foreground">采样日期:</span> {selectedPoint.sampleDate}
                </div>
                <div>
                  <span className="text-muted-foreground">采样人:</span> {selectedPoint.sampler}
                </div>
              </div>
              <div className="border rounded-lg overflow-hidden">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-sm">深度</th>
                      <th className="px-4 py-3 text-center text-sm">pH值</th>
                      <th className="px-4 py-3 text-center text-sm">有机质</th>
                      <th className="px-4 py-3 text-center text-sm">全氮</th>
                      <th className="px-4 py-3 text-center text-sm">有效磷</th>
                      <th className="px-4 py-3 text-center text-sm">速效钾</th>
                      <th className="px-4 py-3 text-center text-sm">含水量</th>
                    </tr>
                  </thead>
                  <tbody>
                    {selectedPoint.layers.map((layer, index) => (
                      <tr key={index} className="border-t">
                        <td className="px-4 py-3 font-medium">{layer.depth}</td>
                        <td className="px-4 py-3 text-center">{layer.pH}</td>
                        <td className="px-4 py-3 text-center">{layer.organicMatter} g/kg</td>
                        <td className="px-4 py-3 text-center">{layer.nitrogen} g/kg</td>
                        <td className="px-4 py-3 text-center">{layer.phosphorus} mg/kg</td>
                        <td className="px-4 py-3 text-center">{layer.potassium} mg/kg</td>
                        <td className="px-4 py-3 text-center">{layer.moisture}%</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除采样点</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除该采样点吗？此操作将删除该采样点的所有数据，包括分层信息和理化指标，且无法恢复。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setPointToDelete(null);
              setShowDeleteDialog(false);
            }}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-destructive hover:bg-destructive/90"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex gap-2">
          <AlertCircle className="w-5 h-5 text-blue-600 flex-shrink-0" />
          <div className="text-sm text-blue-800">
            <p className="mb-2">土壤基础数据管理说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>采样点管理</strong>: 记录GPS坐标、采样日期、负责人等基础信息</li>
              <li>• <strong>分层采样</strong>: 支持多层次土壤数据（0-20cm、20-40cm、40-60cm等）</li>
              <li>• <strong>理化指标</strong>: 记录pH值、有机质、氮磷钾、含水量等关键指标</li>
              <li>• <strong>空间可视化</strong>: 在地图上显示采样点分布，分析覆盖密度</li>
              <li>• <strong>剖面分析</strong>: 可视化展示土壤垂直分布特征</li>
              <li>• <strong>统计分析</strong>: 自动计算平均值、标准差、变异系数等统计指标</li>
              <li>• <strong>数据导出</strong>: 支持导出Excel格式，生成专业检测报告</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}
