import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Slider } from '../ui/slider';
import { Switch } from '../ui/switch';
import { Progress } from '../ui/progress';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import {
  Droplets,
  Power,
  PlayCircle,
  PauseCircle,
  StopCircle,
  TrendingUp,
  TrendingDown,
  Activity,
  Timer,
  Gauge,
  Settings,
  Eye,
  Calendar,
  Download,
  RefreshCw,
  AlertTriangle,
  CheckCircle,
  Beaker,
  TestTube,
  ArrowUp,
  ArrowDown,
  Waves,
  BarChart3,
  Zap,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface FertilizerFormulaProps {
  activePath?: string;
}

type TankStatus = '运行中' | '待机' | '加水中' | '搅拌中' | '故障';
type WaterControlStatus = '开启' | '关闭';

// 水肥机设备接口
interface WaterFertilizerDevice {
  id: string;
  deviceNo: string;
  deviceName: string;
  fieldName: string;
  status: '在线' | '离线';
}

interface FertilizerTank {
  id: string;
  deviceId: string; // 所属水肥机ID
  tankNo: string;
  tankName: string;
  fertilizer: string;
  capacity: number;
  currentLevel: number;
  levelPercent: number;
  minLevel: number;
  maxLevel: number;
  waterControlStatus: WaterControlStatus;
  stirringStatus: '运行' | '停止';
  stirringDuration: number;
  targetStirringTime: number;
  status: TankStatus;
  temperature: number;
  lastUpdate: string;
}

interface HistoryData {
  date: string;
  tankALevel: number;
  tankBLevel: number;
  tankCLevel: number;
  tankAStirring: number;
  tankBStirring: number;
  tankCStirring: number;
}

export function FertilizerFormula({ activePath }: FertilizerFormulaProps) {
  const [activeTab, setActiveTab] = useState('water-control');
  const [selectedDeviceId, setSelectedDeviceId] = useState('dev-001');
  const [selectedTankId, setSelectedTankId] = useState('tank-1-1');
  const [historyDateRange, setHistoryDateRange] = useState('7');
  
  // 目标时长调整弹窗状态
  const [stirringTimeDialogOpen, setStirringTimeDialogOpen] = useState(false);
  const [selectedTankForEdit, setSelectedTankForEdit] = useState<FertilizerTank | null>(null);
  const [newStirringTime, setNewStirringTime] = useState<number>(0);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/water-control')) {
        setActiveTab('water-control');
      } else if (activePath.includes('/level-setting')) {
        setActiveTab('level-setting');
      } else if (activePath.includes('/stirring-control')) {
        setActiveTab('stirring-control');
      } else if (activePath.includes('/history-data')) {
        setActiveTab('history-data');
      }
    }
  }, [activePath]);

  // 水肥机设备数据
  const [devices] = useState<WaterFertilizerDevice[]>([
    {
      id: 'dev-001',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      fieldName: '1号温室大棚',
      status: '在线',
    },
    {
      id: 'dev-002',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      fieldName: '2号露天田块',
      status: '在线',
    },
    {
      id: 'dev-003',
      deviceNo: 'WF-2024-003',
      deviceName: '3号田块水肥设备',
      fieldName: '3号田块',
      status: '在线',
    },
    {
      id: 'dev-004',
      deviceNo: 'WF-2024-004',
      deviceName: '4号温室水肥系统',
      fieldName: '4号智能温室',
      status: '在线',
    },
  ]);

  // 肥料桶数据（每个水肥机3个桶）
  const [allTanks, setAllTanks] = useState<FertilizerTank[]>([
    // 设备1的肥料桶
    {
      id: 'tank-1-1',
      deviceId: 'dev-001',
      tankNo: 'TANK-A',
      tankName: 'A肥料桶',
      fertilizer: '氮肥溶液',
      capacity: 500,
      currentLevel: 320,
      levelPercent: 64,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 22.5,
      lastUpdate: '2024-10-24 18:30:00',
    },
    {
      id: 'tank-1-2',
      deviceId: 'dev-001',
      tankNo: 'TANK-B',
      tankName: 'B肥料桶',
      fertilizer: '磷肥溶液',
      capacity: 500,
      currentLevel: 180,
      levelPercent: 36,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '开启',
      stirringStatus: '运行',
      stirringDuration: 8,
      targetStirringTime: 15,
      status: '加水中',
      temperature: 23.2,
      lastUpdate: '2024-10-24 18:31:00',
    },
    {
      id: 'tank-1-3',
      deviceId: 'dev-001',
      tankNo: 'TANK-C',
      tankName: 'C肥料桶',
      fertilizer: '钾肥溶液',
      capacity: 500,
      currentLevel: 425,
      levelPercent: 85,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '运行',
      stirringDuration: 12,
      targetStirringTime: 15,
      status: '搅拌中',
      temperature: 22.8,
      lastUpdate: '2024-10-24 18:29:00',
    },
    // 设备2的肥料桶
    {
      id: 'tank-2-1',
      deviceId: 'dev-002',
      tankNo: 'TANK-A',
      tankName: 'A肥料桶',
      fertilizer: '氮肥溶液',
      capacity: 500,
      currentLevel: 280,
      levelPercent: 56,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 21.8,
      lastUpdate: '2024-10-24 18:25:00',
    },
    {
      id: 'tank-2-2',
      deviceId: 'dev-002',
      tankNo: 'TANK-B',
      tankName: 'B肥料桶',
      fertilizer: '磷肥溶液',
      capacity: 500,
      currentLevel: 350,
      levelPercent: 70,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 22.1,
      lastUpdate: '2024-10-24 18:28:00',
    },
    {
      id: 'tank-2-3',
      deviceId: 'dev-002',
      tankNo: 'TANK-C',
      tankName: 'C肥料桶',
      fertilizer: '钾肥溶液',
      capacity: 500,
      currentLevel: 390,
      levelPercent: 78,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '运行',
      stirringDuration: 5,
      targetStirringTime: 15,
      status: '搅拌中',
      temperature: 22.5,
      lastUpdate: '2024-10-24 18:26:00',
    },
    // 设备3的肥料桶
    {
      id: 'tank-3-1',
      deviceId: 'dev-003',
      tankNo: 'TANK-A',
      tankName: 'A肥料桶',
      fertilizer: '氮肥溶液',
      capacity: 500,
      currentLevel: 410,
      levelPercent: 82,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 23.5,
      lastUpdate: '2024-10-24 18:20:00',
    },
    {
      id: 'tank-3-2',
      deviceId: 'dev-003',
      tankNo: 'TANK-B',
      tankName: 'B肥料桶',
      fertilizer: '磷肥溶液',
      capacity: 500,
      currentLevel: 150,
      levelPercent: 30,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '开启',
      stirringStatus: '运行',
      stirringDuration: 10,
      targetStirringTime: 15,
      status: '加水中',
      temperature: 23.0,
      lastUpdate: '2024-10-24 18:22:00',
    },
    {
      id: 'tank-3-3',
      deviceId: 'dev-003',
      tankNo: 'TANK-C',
      tankName: 'C肥料桶',
      fertilizer: '钾肥溶液',
      capacity: 500,
      currentLevel: 440,
      levelPercent: 88,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 22.3,
      lastUpdate: '2024-10-24 18:24:00',
    },
    // 设备4的肥料桶
    {
      id: 'tank-4-1',
      deviceId: 'dev-004',
      tankNo: 'TANK-A',
      tankName: 'A肥料桶',
      fertilizer: '氮肥溶液',
      capacity: 500,
      currentLevel: 365,
      levelPercent: 73,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '运行',
      stirringDuration: 7,
      targetStirringTime: 15,
      status: '搅拌中',
      temperature: 22.7,
      lastUpdate: '2024-10-24 18:18:00',
    },
    {
      id: 'tank-4-2',
      deviceId: 'dev-004',
      tankNo: 'TANK-B',
      tankName: 'B肥料桶',
      fertilizer: '磷肥溶液',
      capacity: 500,
      currentLevel: 220,
      levelPercent: 44,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 21.9,
      lastUpdate: '2024-10-24 18:19:00',
    },
    {
      id: 'tank-4-3',
      deviceId: 'dev-004',
      tankNo: 'TANK-C',
      tankName: 'C肥料桶',
      fertilizer: '钾肥溶液',
      capacity: 500,
      currentLevel: 405,
      levelPercent: 81,
      minLevel: 100,
      maxLevel: 450,
      waterControlStatus: '关闭',
      stirringStatus: '停止',
      stirringDuration: 0,
      targetStirringTime: 15,
      status: '待机',
      temperature: 22.4,
      lastUpdate: '2024-10-24 18:21:00',
    },
  ]);

  // 根据选中的水肥机筛选肥料桶
  const tanks = allTanks.filter(tank => tank.deviceId === selectedDeviceId);
  const selectedDevice = devices.find(d => d.id === selectedDeviceId) || devices[0];

  // 历史数据（最近7天）
  const [historyData] = useState<HistoryData[]>([
    { date: '10-09', tankALevel: 310, tankBLevel: 280, tankCLevel: 390, tankAStirring: 45, tankBStirring: 50, tankCStirring: 48 },
    { date: '10-10', tankALevel: 285, tankBLevel: 245, tankCLevel: 410, tankAStirring: 40, tankBStirring: 45, tankCStirring: 52 },
    { date: '10-11', tankALevel: 340, tankBLevel: 290, tankCLevel: 385, tankAStirring: 50, tankBStirring: 48, tankCStirring: 45 },
    { date: '10-12', tankALevel: 295, tankBLevel: 210, tankCLevel: 425, tankAStirring: 42, tankBStirring: 55, tankCStirring: 50 },
    { date: '10-13', tankALevel: 350, tankBLevel: 265, tankCLevel: 395, tankAStirring: 48, tankBStirring: 52, tankCStirring: 47 },
    { date: '10-14', tankALevel: 315, tankBLevel: 195, tankCLevel: 415, tankAStirring: 45, tankBStirring: 58, tankCStirring: 53 },
    { date: '10-15', tankALevel: 320, tankBLevel: 180, tankCLevel: 425, tankAStirring: 46, tankBStirring: 60, tankCStirring: 55 },
  ]);

  const selectedTank = tanks.find(t => t.id === selectedTankId) || tanks[0];

  const getStatusColor = (status: TankStatus) => {
    switch (status) {
      case '运行中': return 'bg-success-muted text-success-muted-foreground';
      case '待机': return 'bg-muted text-muted-foreground';
      case '加水中': return 'bg-info-muted text-info-muted-foreground';
      case '搅拌中': return 'bg-muted text-muted-foreground';
      case '故障': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getLevelStatus = (tank: FertilizerTank) => {
    if (tank.currentLevel < tank.minLevel) {
      return { status: '低液位', color: 'text-error', icon: ArrowDown };
    } else if (tank.currentLevel > tank.maxLevel) {
      return { status: '高液位', color: 'text-warning', icon: ArrowUp };
    } else {
      return { status: '正常', color: 'text-success', icon: CheckCircle };
    }
  };

  const handleWaterControl = (tankId: string, action: 'start' | 'stop') => {
    const tank = allTanks.find(t => t.id === tankId);
    if (!tank) return;

    if (action === 'start') {
      setAllTanks(allTanks.map(t => 
        t.id === tankId 
          ? { ...t, waterControlStatus: '开启', status: '加水中' }
          : t
      ));
      toast.success(`${tank.tankName} 加水已启动`);
    } else {
      setAllTanks(allTanks.map(t => 
        t.id === tankId 
          ? { ...t, waterControlStatus: '关闭', status: '待机' }
          : t
      ));
      toast.success(`${tank.tankName} 加水已停止`);
    }
  };

  const handleLevelUpdate = (tankId: string, field: 'currentLevel' | 'minLevel' | 'maxLevel', value: number) => {
    setAllTanks(allTanks.map(t => {
      if (t.id === tankId) {
        const updated = { ...t, [field]: value };
        if (field === 'currentLevel') {
          updated.levelPercent = Math.round((value / t.capacity) * 100);
        }
        return updated;
      }
      return t;
    }));
  };

  const handleStirringControl = (tankId: string, action: 'start' | 'stop') => {
    const tank = allTanks.find(t => t.id === tankId);
    if (!tank) return;

    if (action === 'start') {
      setAllTanks(allTanks.map(t => 
        t.id === tankId 
          ? { ...t, stirringStatus: '运行', status: '搅拌中', stirringDuration: 0 }
          : t
      ));
      toast.success(`${tank.tankName} 搅拌已启动`);
    } else {
      setAllTanks(allTanks.map(t => 
        t.id === tankId 
          ? { ...t, stirringStatus: '停止', status: '待机' }
          : t
      ));
      toast.success(`${tank.tankName} 搅拌已停止`);
    }
  };

  const handleStirringTimeUpdate = (tankId: string, minutes: number) => {
    setAllTanks(allTanks.map(t => 
      t.id === tankId 
        ? { ...t, targetStirringTime: minutes }
        : t
    ));
    toast.success('搅拌时长已更新');
  };

  // 打开目标时长调整弹窗
  const openStirringTimeDialog = (tank: FertilizerTank) => {
    setSelectedTankForEdit(tank);
    setNewStirringTime(tank.targetStirringTime);
    setStirringTimeDialogOpen(true);
  };

  // 确认目标时长调整
  const confirmStirringTimeUpdate = () => {
    if (selectedTankForEdit && newStirringTime > 0) {
      handleStirringTimeUpdate(selectedTankForEdit.id, newStirringTime);
      setStirringTimeDialogOpen(false);
      setSelectedTankForEdit(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>施肥配方管理</h2>
          <p className="text-sm text-muted-foreground mt-1">
            加水控制、液位管理、搅拌控制、数据监测
          </p>
        </div>
      </div>

      {/* 水肥机选择 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <Label>选择水肥机设备</Label>
          <Select value={selectedDeviceId} onValueChange={setSelectedDeviceId}>
            <SelectTrigger className="w-96">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {devices.map((device) => (
                <SelectItem key={device.id} value={device.id}>
                  {device.deviceName} ({device.deviceNo}) - {device.fieldName}
                  <Badge className="ml-2 bg-success-muted text-success-muted-foreground" variant="outline">
                    {device.status}
                  </Badge>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <div className="text-sm text-muted-foreground">
            当前设备：<span className="text-foreground">{selectedDevice.deviceName}</span>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">当前设备肥料桶</p>
              <p className="mt-2 text-3xl text-info">{tanks.length}</p>
              <p className="text-xs text-info mt-1">个肥料桶</p>
            </div>
            <Beaker className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">加水运行中</p>
              <p className="mt-2 text-3xl text-success">
                {tanks.filter(t => t.waterControlStatus === '开启').length}
              </p>
              <p className="text-xs text-success mt-1">个正在加水</p>
            </div>
            <Droplets className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">搅拌运行中</p>
              <p className="mt-2 text-3xl text-foreground">
                {tanks.filter(t => t.stirringStatus === '运行').length}
              </p>
              <p className="text-xs text-foreground mt-1">个正在搅拌</p>
            </div>
            <Activity className="w-12 h-12 text-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">平均液位</p>
              <p className="mt-2 text-3xl text-warning">
                {Math.round(tanks.reduce((sum, t) => sum + t.levelPercent, 0) / tanks.length)}%
              </p>
              <p className="text-xs text-warning mt-1">容量占比</p>
            </div>
            <Gauge className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="water-control">加水控制</TabsTrigger>
          <TabsTrigger value="level-setting">液位设定</TabsTrigger>
          <TabsTrigger value="stirring-control">搅拌控制</TabsTrigger>
          <TabsTrigger value="history-data">历史监测</TabsTrigger>
        </TabsList>

        {/* 加水控制 */}
        <TabsContent value="water-control" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Droplets className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">加水控制功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>实时展示</strong>: 各肥料桶液位高度和加水开关状态</li>
                  <li>• <strong>远程控制</strong>: 支持远程启动和停止加水操作</li>
                  <li>• <strong>液位监测</strong>: 实时监控液位变化趋势</li>
                  <li>• <strong>安全保障</strong>: 确保肥料溶液处于合理液位范围</li>
                  <li>• <strong>连续性保障</strong>: 保障施肥作业连续性与稳定性</li>
                  <li>• <strong>状态跟踪</strong>: 加水状态、液位百分比实时更新</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 肥料桶列表 */}
          <div className="grid grid-cols-1 gap-4">
            {tanks.map((tank) => {
              const levelStatus = getLevelStatus(tank);
              const LevelIcon = levelStatus.icon;
              
              return (
                <Card key={tank.id} className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{tank.tankName}</h4>
                        <Badge variant="outline">{tank.tankNo}</Badge>
                        <Badge className={getStatusColor(tank.status)}>
                          {tank.status}
                        </Badge>
                        <Badge variant="outline">{tank.fertilizer}</Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        容量: {tank.capacity}L | 更新时间: {tank.lastUpdate}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      {tank.waterControlStatus === '关闭' ? (
                        <Button 
                          className="bg-blue-600 hover:bg-blue-700"
                          onClick={() => handleWaterControl(tank.id, 'start')}
                        >
                          <PlayCircle className="w-4 h-4 mr-2" />
                          启动加水
                        </Button>
                      ) : (
                        <Button 
                          variant="outline"
                          onClick={() => handleWaterControl(tank.id, 'stop')}
                        >
                          <StopCircle className="w-4 h-4 mr-2" />
                          停止加水
                        </Button>
                      )}
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <Card className="p-4 bg-blue-50">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs text-muted-foreground">当前液位</p>
                        <Badge className={levelStatus.color.replace('text-', 'bg-').replace('-600', '-100') + ' ' + levelStatus.color}>
                          <LevelIcon className="w-3 h-3 mr-1" />
                          {levelStatus.status}
                        </Badge>
                      </div>
                      <div className="flex items-baseline gap-2">
                        <p className="text-2xl">{tank.currentLevel}</p>
                        <p className="text-sm text-muted-foreground">L</p>
                      </div>
                      <Progress value={tank.levelPercent} className="h-2 mt-2" />
                      <p className="text-xs text-muted-foreground mt-1">{tank.levelPercent}% 容量</p>
                    </Card>

                    <Card className="p-4 bg-green-50">
                      <p className="text-xs text-muted-foreground mb-2">加水状态</p>
                      <div className="flex items-center gap-2 mb-2">
                        <Power className={`w-5 h-5 ${tank.waterControlStatus === '开启' ? 'text-green-600' : 'text-gray-400'}`} />
                        <p className="text-lg">{tank.waterControlStatus}</p>
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {tank.waterControlStatus === '开启' ? '加水进行中...' : '等待启动'}
                      </p>
                    </Card>

                    <Card className="p-4 bg-purple-50">
                      <p className="text-xs text-muted-foreground mb-2">液位范围</p>
                      <div className="space-y-1 text-sm">
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">最低:</span>
                          <span>{tank.minLevel} L</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">最高:</span>
                          <span>{tank.maxLevel} L</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">温度:</span>
                          <span>{tank.temperature}°C</span>
                        </div>
                      </div>
                    </Card>
                  </div>

                  {/* 液位可视化 */}
                  <div className="relative h-40 bg-gradient-to-b from-gray-50 to-gray-100 rounded-lg overflow-hidden shadow-inner">
                    {/* 水位容器 */}
                    <div 
                      className="absolute bottom-0 left-0 right-0 transition-all duration-500"
                      style={{ height: `${tank.levelPercent}%` }}
                    >
                      {/* 水体基础层 */}
                      <div className="absolute inset-0 bg-gradient-to-t from-blue-600 via-blue-500 to-blue-400">
                        {/* 水波动效层1 - 主波浪 */}
                        <div className="absolute inset-0 water-wave opacity-80" />
                        
                        {/* 水波动效层2 - 次波浪 */}
                        <div 
                          className="absolute inset-0 water-wave opacity-60"
                          style={{ animationDelay: '0.8s', animationDuration: '2.3s' }}
                        />
                        
                        {/* 水波动效层3 - 微波浪 */}
                        <div 
                          className="absolute inset-0 water-wave opacity-40"
                          style={{ animationDelay: '1.2s', animationDuration: '1.8s' }}
                        />
                        
                        {/* 光泽效果 */}
                        <div className="absolute inset-0 water-shimmer" />
                        
                        {/* 气泡效果（加水时显示） - 增强版 */}
                        {tank.waterControlStatus === '开启' && (
                          <>
                            {/* 第一批气泡 - 大气泡 */}
                            <div 
                              className="absolute w-3 h-3 bg-white/50 rounded-full animate-bounce"
                              style={{ 
                                left: '15%', 
                                bottom: '5%',
                                animationDuration: '1.8s',
                                animationDelay: '0s',
                                boxShadow: '0 0 8px rgba(255,255,255,0.6)'
                              }}
                            />
                            <div 
                              className="absolute w-2.5 h-2.5 bg-white/45 rounded-full animate-bounce"
                              style={{ 
                                left: '28%', 
                                bottom: '8%',
                                animationDuration: '2.1s',
                                animationDelay: '0.3s',
                                boxShadow: '0 0 6px rgba(255,255,255,0.5)'
                              }}
                            />
                            <div 
                              className="absolute w-2 h-2 bg-white/40 rounded-full animate-bounce"
                              style={{ 
                                left: '42%', 
                                bottom: '3%',
                                animationDuration: '1.9s',
                                animationDelay: '0.6s',
                                boxShadow: '0 0 5px rgba(255,255,255,0.4)'
                              }}
                            />
                            
                            {/* 第二批气泡 - 中气泡 */}
                            <div 
                              className="absolute w-2.5 h-2.5 bg-white/38 rounded-full animate-bounce"
                              style={{ 
                                left: '55%', 
                                bottom: '10%',
                                animationDuration: '2.3s',
                                animationDelay: '0.2s',
                                boxShadow: '0 0 5px rgba(255,255,255,0.4)'
                              }}
                            />
                            <div 
                              className="absolute w-2 h-2 bg-white/35 rounded-full animate-bounce"
                              style={{ 
                                left: '68%', 
                                bottom: '6%',
                                animationDuration: '2s',
                                animationDelay: '0.5s',
                                boxShadow: '0 0 4px rgba(255,255,255,0.3)'
                              }}
                            />
                            <div 
                              className="absolute w-1.5 h-1.5 bg-white/32 rounded-full animate-bounce"
                              style={{ 
                                left: '78%', 
                                bottom: '12%',
                                animationDuration: '2.4s',
                                animationDelay: '0.8s'
                              }}
                            />
                            
                            {/* 第三批气泡 - 小气泡 */}
                            <div 
                              className="absolute w-1.5 h-1.5 bg-white/30 rounded-full animate-bounce"
                              style={{ 
                                left: '35%', 
                                bottom: '15%',
                                animationDuration: '1.7s',
                                animationDelay: '0.4s'
                              }}
                            />
                            <div 
                              className="absolute w-1 h-1 bg-white/28 rounded-full animate-bounce"
                              style={{ 
                                left: '62%', 
                                bottom: '4%',
                                animationDuration: '2.2s',
                                animationDelay: '0.7s'
                              }}
                            />
                            <div 
                              className="absolute w-1 h-1 bg-white/25 rounded-full animate-bounce"
                              style={{ 
                                left: '88%', 
                                bottom: '8%',
                                animationDuration: '1.6s',
                                animationDelay: '1s'
                              }}
                            />
                          </>
                        )}
                      </div>
                      
                      {/* 水面波纹效果 - 增强晃动 */}
                      <div 
                        className="absolute top-0 left-0 right-0 h-4 bg-gradient-to-b from-white/20 to-transparent"
                        style={{
                          boxShadow: '0 -2px 8px rgba(255, 255, 255, 0.3) inset'
                        }}
                      >
                        {/* 主波浪层 */}
                        <svg 
                          className="absolute top-0 left-0 w-full h-full" 
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 1200 40"
                          preserveAspectRatio="none"
                        >
                          <path
                            d="M0,20 Q200,5 400,20 T800,20 T1200,20 L1200,40 L0,40 Z"
                            fill="rgba(59, 130, 246, 0.6)"
                          >
                            <animate
                              attributeName="d"
                              dur="2s"
                              repeatCount="indefinite"
                              values="
                                M0,20 Q200,5 400,20 T800,20 T1200,20 L1200,40 L0,40 Z;
                                M0,20 Q200,35 400,20 T800,20 T1200,20 L1200,40 L0,40 Z;
                                M0,20 Q200,10 400,20 T800,20 T1200,20 L1200,40 L0,40 Z;
                                M0,20 Q200,30 400,20 T800,20 T1200,20 L1200,40 L0,40 Z;
                                M0,20 Q200,5 400,20 T800,20 T1200,20 L1200,40 L0,40 Z
                              "
                            />
                          </path>
                        </svg>
                        
                        {/* 副波浪层 */}
                        <svg 
                          className="absolute top-0 left-0 w-full h-full opacity-60" 
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 1200 40"
                          preserveAspectRatio="none"
                        >
                          <path
                            d="M0,25 Q300,15 600,25 T1200,25 L1200,40 L0,40 Z"
                            fill="rgba(96, 165, 250, 0.5)"
                          >
                            <animate
                              attributeName="d"
                              dur="2.3s"
                              repeatCount="indefinite"
                              values="
                                M0,25 Q300,15 600,25 T1200,25 L1200,40 L0,40 Z;
                                M0,25 Q300,32 600,25 T1200,25 L1200,40 L0,40 Z;
                                M0,25 Q300,18 600,25 T1200,25 L1200,40 L0,40 Z;
                                M0,25 Q300,28 600,25 T1200,25 L1200,40 L0,40 Z;
                                M0,25 Q300,15 600,25 T1200,25 L1200,40 L0,40 Z
                              "
                            />
                          </path>
                        </svg>
                      </div>
                      
                      {/* 液位标签 */}
                      <div className="absolute top-3 left-0 right-0 flex justify-center z-10">
                        <Badge className="bg-white/95 text-blue-700 shadow-lg backdrop-blur-sm">
                          <Waves className="w-3 h-3 mr-1" />
                          {tank.currentLevel} L ({tank.levelPercent}%)
                        </Badge>
                      </div>
                    </div>
                    
                    {/* 最高液位线 */}
                    <div 
                      className="absolute left-0 right-0 border-t-2 border-dashed border-orange-500 z-10"
                      style={{ bottom: `${(tank.maxLevel / tank.capacity) * 100}%` }}
                    >
                      <span className="absolute right-2 -top-3 text-xs text-orange-600 bg-white/80 px-1 rounded">最高</span>
                    </div>
                    
                    {/* 最低液位线 */}
                    <div 
                      className="absolute left-0 right-0 border-t-2 border-dashed border-red-500 z-10"
                      style={{ bottom: `${(tank.minLevel / tank.capacity) * 100}%` }}
                    >
                      <span className="absolute right-2 -top-3 text-xs text-red-600 bg-white/80 px-1 rounded">最低</span>
                    </div>
                    
                    {/* 容量刻度 */}
                    <div className="absolute left-2 top-0 bottom-0 flex flex-col justify-between text-xs text-gray-500 py-2">
                      <span className="bg-white/70 px-1 rounded">{tank.capacity}L</span>
                      <span className="bg-white/70 px-1 rounded">{Math.floor(tank.capacity * 0.5)}L</span>
                      <span className="bg-white/70 px-1 rounded">0L</span>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </TabsContent>

        {/* 液位设定 */}
        <TabsContent value="level-setting" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-green-50 to-teal-50 border-green-200">
            <div className="flex items-start gap-2">
              <Gauge className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-green-900">
                <p className="mb-2">液位设定功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>传感器监测</strong>: 实时传感器自动监测当前液位，数据自动更新</li>
                  <li>• <strong>可视化展示</strong>: 通过图表直观展示肥料桶液位状态</li>
                  <li>• <strong>阈值设置</strong>: 配置液位上下限阈值，智能预警</li>
                  <li>• <strong>自动触发</strong>: 根据设定阈值自动触发加水或停止操作</li>
                  <li>• <strong>精确控制</strong>: 实现液位的精确控制和管理</li>
                  <li>• <strong>智能管理</strong>: 传感器数据驱动的自适应液位管理系统</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 选择肥料桶 */}
          <Card className="p-4">
            <Label>选择肥料桶</Label>
            <Select value={selectedTankId} onValueChange={setSelectedTankId}>
              <SelectTrigger className="mt-2">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {tanks.map((tank) => (
                  <SelectItem key={tank.id} value={tank.id}>
                    {tank.tankName} ({tank.tankNo}) - {tank.fertilizer}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </Card>

          {/* 液位设定 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Settings className="w-5 h-5 text-green-600" />
              {selectedTank.tankName} 液位参数设置
            </h4>

            <div className="space-y-6">
              {/* 当前液位 - 传感器实时监测 */}
              <div className="p-4 bg-blue-50 rounded-lg border-2 border-blue-200">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Activity className="w-5 h-5 text-blue-600" />
                    <Label className="text-base">当前液位（传感器实时监测）</Label>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-lg px-3 py-1">{selectedTank.currentLevel} L</Badge>
                    <Badge className="bg-blue-600 text-white text-lg px-3 py-1">{selectedTank.levelPercent}%</Badge>
                  </div>
                </div>
                
                {/* 只读进度条 */}
                <div className="relative h-8 bg-gray-200 rounded-full overflow-hidden">
                  <div 
                    className="absolute top-0 left-0 h-full bg-gradient-to-r from-blue-500 to-blue-600 transition-all duration-500"
                    style={{ width: `${selectedTank.levelPercent}%` }}
                  >
                    <div className="absolute inset-0 flex items-center justify-center text-white text-xs">
                      {selectedTank.levelPercent >= 20 && `${selectedTank.currentLevel} L`}
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center gap-2 mt-2">
                  <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                  <p className="text-xs text-muted-foreground">
                    传感器实时数据 · 更新时间: {selectedTank.lastUpdate}
                  </p>
                </div>
                <p className="text-xs text-blue-600 mt-1">
                  💡 当前液位由传感器自动监测，无法手动修改
                </p>
              </div>

              {/* 最低液位 */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>最低液位阈值</Label>
                  <Badge variant="outline" className="text-red-600">{selectedTank.minLevel} L</Badge>
                </div>
                <Slider
                  value={[selectedTank.minLevel]}
                  onValueChange={(v) => handleLevelUpdate(selectedTank.id, 'minLevel', v[0])}
                  min={0}
                  max={selectedTank.capacity / 2}
                  step={10}
                  className="mt-2"
                />
                <p className="text-xs text-muted-foreground mt-2">
                  低于此值将自动触发加水（建议设置为容量的20%）
                </p>
              </div>

              {/* 最高液位 */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <Label>最高液位阈值</Label>
                  <Badge variant="outline" className="text-orange-600">{selectedTank.maxLevel} L</Badge>
                </div>
                <Slider
                  value={[selectedTank.maxLevel]}
                  onValueChange={(v) => handleLevelUpdate(selectedTank.id, 'maxLevel', v[0])}
                  min={selectedTank.capacity / 2}
                  max={selectedTank.capacity}
                  step={10}
                  className="mt-2"
                />
                <p className="text-xs text-muted-foreground mt-2">
                  高于此值将自动停止加水（建议设置为容量的90%）
                </p>
              </div>

              {/* 自动控制开关 */}
              <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                <div className="flex items-center gap-2">
                  <Zap className="w-5 h-5 text-blue-600" />
                  <div>
                    <p className="font-medium">自动加水控制</p>
                    <p className="text-xs text-muted-foreground">根据液位阈值自动触发加水操作</p>
                  </div>
                </div>
                <Switch defaultChecked />
              </div>

              {/* 液位可视化图表 */}
              <div>
                <div className="flex items-center gap-2 mb-4">
                  <Label className="block">液位可视化</Label>
                  <Badge variant="outline" className="text-xs">
                    <Activity className="w-3 h-3 mr-1" />
                    传感器实时数据
                  </Badge>
                </div>
                <div className="relative h-64 bg-gray-100 rounded-lg overflow-hidden border-2 border-gray-200">
                  {/* 当前液位 */}
                  <div 
                    className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-blue-600 to-blue-400 transition-all duration-300"
                    style={{ height: `${selectedTank.levelPercent}%` }}
                  >
                    <div className="absolute top-4 left-0 right-0 flex justify-center">
                      <div className="bg-white/95 px-4 py-2 rounded-lg shadow-lg border-2 border-blue-200">
                        <div className="flex items-center gap-2 mb-1">
                          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                          <p className="text-xs text-muted-foreground">传感器监测</p>
                        </div>
                        <p className="text-2xl text-blue-600">{selectedTank.currentLevel} L</p>
                        <p className="text-xs text-muted-foreground">{selectedTank.levelPercent}% 容量</p>
                      </div>
                    </div>
                  </div>
                  
                  {/* 最高液位线 */}
                  <div 
                    className="absolute left-0 right-0 border-t-4 border-orange-500 z-10"
                    style={{ bottom: `${(selectedTank.maxLevel / selectedTank.capacity) * 100}%` }}
                  >
                    <div className="absolute left-4 -top-8 bg-orange-500 text-white px-3 py-1 rounded text-xs">
                      最高: {selectedTank.maxLevel}L
                    </div>
                  </div>
                  
                  {/* 最低液位线 */}
                  <div 
                    className="absolute left-0 right-0 border-t-4 border-red-500 z-10"
                    style={{ bottom: `${(selectedTank.minLevel / selectedTank.capacity) * 100}%` }}
                  >
                    <div className="absolute left-4 -top-8 bg-red-500 text-white px-3 py-1 rounded text-xs">
                      最低: {selectedTank.minLevel}L
                    </div>
                  </div>

                  {/* 容量刻度 */}
                  <div className="absolute right-4 top-0 bottom-0 flex flex-col justify-between text-xs text-gray-600 py-2">
                    <span>{selectedTank.capacity}L</span>
                    <span>{Math.floor(selectedTank.capacity * 0.75)}L</span>
                    <span>{Math.floor(selectedTank.capacity * 0.5)}L</span>
                    <span>{Math.floor(selectedTank.capacity * 0.25)}L</span>
                    <span>0L</span>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 搅拌控制 */}
        <TabsContent value="stirring-control" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Activity className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">搅拌控制功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>实时显示</strong>: 各肥料桶搅拌时长状态</li>
                  <li>• <strong>时长设置</strong>: 用户可自定义设置搅拌时长</li>
                  <li>• <strong>手动控制</strong>: 支持手动启停搅拌操作</li>
                  <li>• <strong>充分溶解</strong>: 确保肥料充分溶解与混合</li>
                  <li>• <strong>防止沉淀</strong>: 持续搅拌防止肥料沉淀</li>
                  <li>• <strong>浓度均匀</strong>: 维持肥液浓度均匀稳定</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 搅拌控制列表 */}
          <div className="grid grid-cols-1 gap-4">
            {tanks.map((tank) => (
              <Card key={tank.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h4>{tank.tankName}</h4>
                      <Badge variant="outline">{tank.tankNo}</Badge>
                      <Badge className={tank.stirringStatus === '运行' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-700'}>
                        搅拌{tank.stirringStatus}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">{tank.fertilizer}</p>
                  </div>
                  <div className="flex gap-2">
                    {tank.stirringStatus === '停止' ? (
                      <Button 
                        className="bg-purple-600 hover:bg-purple-700"
                        onClick={() => handleStirringControl(tank.id, 'start')}
                      >
                        <PlayCircle className="w-4 h-4 mr-2" />
                        启动搅拌
                      </Button>
                    ) : (
                      <Button 
                        variant="outline"
                        onClick={() => handleStirringControl(tank.id, 'stop')}
                      >
                        <StopCircle className="w-4 h-4 mr-2" />
                        停止搅拌
                      </Button>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <Card className="p-4 bg-purple-50">
                    <p className="text-xs text-muted-foreground mb-2">搅拌状态</p>
                    <div className="flex items-center gap-2 mb-2">
                      <Activity className={`w-5 h-5 ${tank.stirringStatus === '运行' ? 'text-purple-600 animate-pulse' : 'text-gray-400'}`} />
                      <p className="text-lg">{tank.stirringStatus}</p>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {tank.stirringStatus === '运行' ? '搅拌进行中...' : '等待启动'}
                    </p>
                  </Card>

                  <Card className="p-4 bg-blue-50">
                    <p className="text-xs text-muted-foreground mb-2">已运行时长</p>
                    <div className="flex items-baseline gap-2">
                      <p className="text-2xl">{tank.stirringDuration}</p>
                      <p className="text-sm text-muted-foreground">分钟</p>
                    </div>
                    {tank.stirringStatus === '运行' && (
                      <Progress 
                        value={(tank.stirringDuration / tank.targetStirringTime) * 100} 
                        className="h-2 mt-2" 
                      />
                    )}
                  </Card>

                  <Card className="p-4 bg-green-50">
                    <p className="text-xs text-muted-foreground mb-2">目标时长</p>
                    <div className="flex items-baseline gap-2 mb-2">
                      <p className="text-2xl">{tank.targetStirringTime}</p>
                      <p className="text-sm text-muted-foreground">分钟</p>
                    </div>
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => openStirringTimeDialog(tank)}
                    >
                      <Settings className="w-3 h-3 mr-1" />
                      调整
                    </Button>
                  </Card>
                </div>

                {tank.stirringStatus === '运行' && (
                  <div className="mt-4">
                    <div className="flex items-center justify-between text-sm mb-2">
                      <span className="flex items-center gap-2">
                        <Timer className="w-4 h-4" />
                        搅拌进度
                      </span>
                      <span>
                        {tank.stirringDuration} / {tank.targetStirringTime} 分钟
                      </span>
                    </div>
                    <Progress 
                      value={(tank.stirringDuration / tank.targetStirringTime) * 100} 
                      className="h-3" 
                    />
                    <p className="text-xs text-muted-foreground mt-2">
                      预计剩余: {tank.targetStirringTime - tank.stirringDuration} 分钟
                    </p>
                  </div>
                )}
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 历史监测数据 */}
        <TabsContent value="history-data" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-orange-50 to-amber-50 border-orange-200">
            <div className="flex items-start gap-2">
              <BarChart3 className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-orange-900">
                <p className="mb-2">历史监测数据：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>默认展示</strong>: 近7天内实时液位与搅拌时长历史趋势</li>
                  <li>• <strong>图表形式</strong>: 折线图、面积图直观展示变化</li>
                  <li>• <strong>自定义查询</strong>: 支持选择最长30天时段查询</li>
                  <li>• <strong>多维分析</strong>: 液位变化、搅拌时长分开展示</li>
                  <li>• <strong>数据支持</strong>: 为施肥策略优化提供数据依据</li>
                  <li>• <strong>趋势分析</strong>: 发现规律，优化管理策略</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 时间范围选择 */}
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <Label>查询时段</Label>
              <Select value={historyDateRange} onValueChange={setHistoryDateRange}>
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">最近1天</SelectItem>
                  <SelectItem value="3">最近3天</SelectItem>
                  <SelectItem value="7">最近7天</SelectItem>
                  <SelectItem value="15">最近15天</SelectItem>
                  <SelectItem value="30">最近30天</SelectItem>
                </SelectContent>
              </Select>
              <div className="ml-auto text-sm text-muted-foreground">
                {selectedDevice.deviceName} - 历史监测数据
              </div>
            </div>
          </Card>

          {/* 液位统计卡片 */}
          <div>
            <div className="flex items-center gap-2 mb-3">
              <Gauge className="w-5 h-5 text-blue-600" />
              <h4>液位统计</h4>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Card className="p-4">
                <p className="text-xs text-muted-foreground mb-2">A桶平均液位</p>
                <p className="text-2xl text-blue-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankALevel, 0) / historyData.length)} L
                </p>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <CheckCircle className="w-3 h-3" />
                  稳定运行
                </p>
              </Card>

              <Card className="p-4">
                <p className="text-xs text-muted-foreground mb-2">B桶平均液位</p>
                <p className="text-2xl text-purple-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankBLevel, 0) / historyData.length)} L
                </p>
                <p className="text-xs text-orange-600 mt-1 flex items-center gap-1">
                  <AlertTriangle className="w-3 h-3" />
                  偏低
                </p>
              </Card>

              <Card className="p-4">
                <p className="text-xs text-muted-foreground mb-2">C桶平均液位</p>
                <p className="text-2xl text-green-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankCLevel, 0) / historyData.length)} L
                </p>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <CheckCircle className="w-3 h-3" />
                  稳定运行
                </p>
              </Card>
            </div>
          </div>

          {/* 搅拌时长统计卡片 */}
          <div>
            <div className="flex items-center gap-2 mb-3">
              <Timer className="w-5 h-5 text-purple-600" />
              <h4>搅拌时长统计</h4>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-xs text-blue-700">A桶日均搅拌时长</p>
                  <Beaker className="w-4 h-4 text-blue-600" />
                </div>
                <p className="text-2xl text-blue-700">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankAStirring, 0) / historyData.length)} 
                  <span className="text-sm ml-1">分钟</span>
                </p>
                <div className="mt-2 flex items-center justify-between text-xs">
                  <span className="text-blue-600">
                    总计: {historyData.reduce((sum, d) => sum + d.tankAStirring, 0)} 分钟
                  </span>
                  <Badge variant="outline" className="text-blue-700 border-blue-300">
                    {historyDateRange}天
                  </Badge>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-xs text-purple-700">B桶日均搅拌时长</p>
                  <TestTube className="w-4 h-4 text-purple-600" />
                </div>
                <p className="text-2xl text-purple-700">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankBStirring, 0) / historyData.length)}
                  <span className="text-sm ml-1">分钟</span>
                </p>
                <div className="mt-2 flex items-center justify-between text-xs">
                  <span className="text-purple-600">
                    总计: {historyData.reduce((sum, d) => sum + d.tankBStirring, 0)} 分钟
                  </span>
                  <Badge variant="outline" className="text-purple-700 border-purple-300">
                    {historyDateRange}天
                  </Badge>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 border-green-200">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-xs text-green-700">C桶日均搅拌时长</p>
                  <Beaker className="w-4 h-4 text-green-600" />
                </div>
                <p className="text-2xl text-green-700">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankCStirring, 0) / historyData.length)}
                  <span className="text-sm ml-1">分钟</span>
                </p>
                <div className="mt-2 flex items-center justify-between text-xs">
                  <span className="text-green-600">
                    总计: {historyData.reduce((sum, d) => sum + d.tankCStirring, 0)} 分钟
                  </span>
                  <Badge variant="outline" className="text-green-700 border-green-300">
                    {historyDateRange}天
                  </Badge>
                </div>
              </Card>
            </div>
          </div>

          {/* 液位历史趋势 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Gauge className="w-5 h-5 text-blue-600" />
              液位历史趋势（最近{historyDateRange}天）
            </h4>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={historyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis label={{ value: '液位 (L)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line type="monotone" dataKey="tankALevel" stroke="#3b82f6" strokeWidth={2} name="A桶液位" />
                <Line type="monotone" dataKey="tankBLevel" stroke="#a855f7" strokeWidth={2} name="B桶液位" />
                <Line type="monotone" dataKey="tankCLevel" stroke="#10b981" strokeWidth={2} name="C桶液位" />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* 搅拌时长历史趋势 - 柱状图 */}
          <Card className="p-6 bg-gradient-to-br from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-center justify-between mb-4">
              <h4 className="flex items-center gap-2">
                <Timer className="w-5 h-5 text-purple-600" />
                搅拌时长历史趋势（最近{historyDateRange}天）
              </h4>
              <div className="flex gap-2">
                <Badge variant="outline" className="text-blue-600 border-blue-300">
                  <Beaker className="w-3 h-3 mr-1" />
                  A桶：氮肥
                </Badge>
                <Badge variant="outline" className="text-purple-600 border-purple-300">
                  <TestTube className="w-3 h-3 mr-1" />
                  B桶：磷肥
                </Badge>
                <Badge variant="outline" className="text-green-600 border-green-300">
                  <Beaker className="w-3 h-3 mr-1" />
                  C桶：钾肥
                </Badge>
              </div>
            </div>
            <ResponsiveContainer width="100%" height={320}>
              <BarChart data={historyData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis 
                  dataKey="date" 
                  tick={{ fill: '#6b7280' }}
                  axisLine={{ stroke: '#9ca3af' }}
                />
                <YAxis 
                  label={{ 
                    value: '搅拌时长 (分钟)', 
                    angle: -90, 
                    position: 'insideLeft',
                    style: { fill: '#6b7280' }
                  }}
                  tick={{ fill: '#6b7280' }}
                  axisLine={{ stroke: '#9ca3af' }}
                />
                <RechartsTooltip 
                  contentStyle={{ 
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
                  }}
                  labelStyle={{ fontWeight: 600, color: '#374151' }}
                />
                <Legend 
                  wrapperStyle={{ paddingTop: '20px' }}
                  iconType="rect"
                />
                <Bar 
                  dataKey="tankAStirring" 
                  fill="#3b82f6" 
                  name="A桶搅拌时长"
                  radius={[8, 8, 0, 0]}
                  maxBarSize={60}
                />
                <Bar 
                  dataKey="tankBStirring" 
                  fill="#a855f7" 
                  name="B桶搅拌时长"
                  radius={[8, 8, 0, 0]}
                  maxBarSize={60}
                />
                <Bar 
                  dataKey="tankCStirring" 
                  fill="#10b981" 
                  name="C桶搅拌时长"
                  radius={[8, 8, 0, 0]}
                  maxBarSize={60}
                />
              </BarChart>
            </ResponsiveContainer>
            <div className="mt-4 grid grid-cols-3 gap-4 pt-4 border-t border-purple-200">
              <div className="text-center">
                <p className="text-xs text-muted-foreground mb-1">A桶平均</p>
                <p className="text-lg text-blue-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankAStirring, 0) / historyData.length)} 分钟/天
                </p>
              </div>
              <div className="text-center">
                <p className="text-xs text-muted-foreground mb-1">B桶平均</p>
                <p className="text-lg text-purple-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankBStirring, 0) / historyData.length)} 分钟/天
                </p>
              </div>
              <div className="text-center">
                <p className="text-xs text-muted-foreground mb-1">C桶平均</p>
                <p className="text-lg text-green-600">
                  {Math.round(historyData.reduce((sum, d) => sum + d.tankCStirring, 0) / historyData.length)} 分钟/天
                </p>
              </div>
            </div>
          </Card>

          {/* 搅拌时长趋势线图 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h4 className="flex items-center gap-2">
                <Activity className="w-5 h-5 text-purple-600" />
                搅拌时长变化趋势
              </h4>
              <Badge variant="outline" className="text-purple-600">
                <TrendingUp className="w-3 h-3 mr-1" />
                趋势分析
              </Badge>
            </div>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={historyData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis 
                  dataKey="date" 
                  tick={{ fill: '#6b7280' }}
                  axisLine={{ stroke: '#9ca3af' }}
                />
                <YAxis 
                  label={{ 
                    value: '搅拌时长 (分钟)', 
                    angle: -90, 
                    position: 'insideLeft',
                    style: { fill: '#6b7280' }
                  }}
                  tick={{ fill: '#6b7280' }}
                  axisLine={{ stroke: '#9ca3af' }}
                />
                <RechartsTooltip 
                  contentStyle={{ 
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
                  }}
                  labelStyle={{ fontWeight: 600, color: '#374151' }}
                />
                <Legend wrapperStyle={{ paddingTop: '20px' }} />
                <Line 
                  type="monotone" 
                  dataKey="tankAStirring" 
                  stroke="#3b82f6" 
                  strokeWidth={3}
                  name="A桶搅拌时长"
                  dot={{ fill: '#3b82f6', r: 5 }}
                  activeDot={{ r: 7 }}
                />
                <Line 
                  type="monotone" 
                  dataKey="tankBStirring" 
                  stroke="#a855f7" 
                  strokeWidth={3}
                  name="B桶搅拌时长"
                  dot={{ fill: '#a855f7', r: 5 }}
                  activeDot={{ r: 7 }}
                />
                <Line 
                  type="monotone" 
                  dataKey="tankCStirring" 
                  stroke="#10b981" 
                  strokeWidth={3}
                  name="C桶搅拌时长"
                  dot={{ fill: '#10b981', r: 5 }}
                  activeDot={{ r: 7 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 目标时长调整弹窗 */}
      <Dialog open={stirringTimeDialogOpen} onOpenChange={setStirringTimeDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5 text-purple-600" />
              调整目标搅拌时长
            </DialogTitle>
            <DialogDescription>
              设置肥料桶的目标搅拌时长，确保肥料充分溶解和混合
            </DialogDescription>
          </DialogHeader>

          {selectedTankForEdit && (
            <div className="space-y-4 py-4">
              {/* 肥料桶信息 */}
              <div className="flex items-center gap-2 p-3 bg-purple-50 rounded-lg">
                <Beaker className="w-5 h-5 text-purple-600" />
                <div className="flex-1">
                  <p className="font-medium">{selectedTankForEdit.tankName}</p>
                  <p className="text-sm text-muted-foreground">{selectedTankForEdit.fertilizer}</p>
                </div>
                <Badge variant="outline">{selectedTankForEdit.tankNo}</Badge>
              </div>

              {/* 当前目标时长 */}
              <div className="p-3 bg-gray-50 rounded-lg">
                <p className="text-xs text-muted-foreground mb-1">当前目标时长</p>
                <p className="text-2xl text-gray-900">{selectedTankForEdit.targetStirringTime} <span className="text-sm text-muted-foreground">分钟</span></p>
              </div>

              {/* 新目标时长输入 */}
              <div className="space-y-2">
                <Label htmlFor="stirring-time">新目标时长（分钟）</Label>
                <div className="flex items-center gap-3">
                  <Input
                    id="stirring-time"
                    type="number"
                    min="1"
                    max="120"
                    value={newStirringTime}
                    onChange={(e) => setNewStirringTime(parseInt(e.target.value) || 0)}
                    className="flex-1"
                    placeholder="请输入1-120分钟"
                  />
                  <span className="text-sm text-muted-foreground whitespace-nowrap">分钟</span>
                </div>
                <p className="text-xs text-muted-foreground">
                  💡 建议设置范围：5-30分钟，根据肥料类型调整
                </p>
              </div>

              {/* 快捷时长选择 */}
              <div className="space-y-2">
                <Label>快捷选择</Label>
                <div className="grid grid-cols-4 gap-2">
                  {[10, 15, 20, 30].map((time) => (
                    <Button
                      key={time}
                      size="sm"
                      variant={newStirringTime === time ? "default" : "outline"}
                      onClick={() => setNewStirringTime(time)}
                      className={newStirringTime === time ? "bg-purple-600 hover:bg-purple-700" : ""}
                    >
                      {time}分钟
                    </Button>
                  ))}
                </div>
              </div>

              {/* 预览效果 */}
              {newStirringTime !== selectedTankForEdit.targetStirringTime && newStirringTime > 0 && (
                <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <Timer className="w-4 h-4 text-blue-600" />
                    <p className="text-sm font-medium text-blue-900">调整预览</p>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <span className="text-gray-600">{selectedTankForEdit.targetStirringTime} 分钟</span>
                    <ArrowDown className="w-4 h-4 text-blue-600" />
                    <span className="text-blue-600 font-medium">{newStirringTime} 分钟</span>
                    <Badge variant="outline" className="ml-auto">
                      {newStirringTime > selectedTankForEdit.targetStirringTime ? '延长' : '缩短'}
                      {Math.abs(newStirringTime - selectedTankForEdit.targetStirringTime)}分钟
                    </Badge>
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setStirringTimeDialogOpen(false)}
            >
              取消
            </Button>
            <Button
              onClick={confirmStirringTimeUpdate}
              disabled={!newStirringTime || newStirringTime < 1 || newStirringTime > 120}
              className="bg-purple-600 hover:bg-purple-700"
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              确认调整
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
