'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import {
  Activity,
  AlertCircle,
  ArrowRight,
  BookOpen,
  Brain,
  CheckCircle,
  Clock,
  Edit,
  Eye,
  Gauge,
  Lightbulb,
  ListChecks,
  Merge,
  Play,
  Plus,
  Settings,
  Trash2,
  User,
  Zap,
  Power,
  PowerOff,
  Timer,
} from 'lucide-react';
import { toast } from 'sonner';

// 决策级别
type DecisionLevel = 'critical' | 'important' | 'normal' | 'suggestion';

// 决策来源
type DecisionSource = 'auto' | 'manual';

// 执行模式
type ExecutionMode = 'manual' | 'auto';

// 决策结果
interface DecisionResult {
  id: string;
  name: string;
  source: DecisionSource; // 决策来源：自动生成或手动添加
  executionMode: ExecutionMode; // 执行模式：手动执行或自动执行
  // 触发条件（手动和自动都需要）
  triggerCondition: {
    device: string; // 设备
    parameter: string; // 参数
    operator: string; // 等式（>、<、>=、<=、==）
    value: string; // 值
  };
  // 执行设置（手动和自动都需要）
  execution: {
    device: string; // 目标设备
    action: 'open' | 'close'; // 开关状态
    duration: number; // 持续时间（分钟）
  };
  level: DecisionLevel;
  confidence: number;
  recommendation: string;
  explanation: string;
  actionItems: string[];
  inputData: {
    models: Array<{ id: string; modelName: string }>;
    rules: Array<{ id: string; name: string }>;
    context: Array<{ id: string; name: string }>;
  };
  fusionProcess: {
    step: string;
    result: any;
    weight: number;
  }[];
  generatedAt: string;
  createdBy?: string; // 创建人（手动添加时）
}

export default function FusionPage() {
  const [showResultDialog, setShowResultDialog] = useState(false);
  const [showExecuteConfirmDialog, setShowExecuteConfirmDialog] = useState(false);
  const [showExecuteResultDialog, setShowExecuteResultDialog] = useState(false);
  const [showAddDecisionDialog, setShowAddDecisionDialog] = useState(false);
  const [showEditDecisionDialog, setShowEditDecisionDialog] = useState(false);
  const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
  const [selectedResult, setSelectedResult] = useState<DecisionResult | null>(null);
  const [executingResult, setExecutingResult] = useState<DecisionResult | null>(null);
  const [executeResult, setExecuteResult] = useState<any>(null);
  const [editingDecision, setEditingDecision] = useState<DecisionResult | null>(null);
  const [deletingDecisionId, setDeletingDecisionId] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('all');

  // 新增决策表单数据
  const [newDecision, setNewDecision] = useState({
    name: '',
    level: 'normal' as DecisionLevel,
    confidence: 80,
    executionMode: 'auto' as ExecutionMode,
    triggerDevice: '',
    triggerParameter: '',
    triggerOperator: '>',
    triggerValue: '',
    targetDevice: '',
    targetAction: 'open' as 'open' | 'close',
    duration: 30,
    recommendation: '',
    explanation: '',
    actionItems: '',
  });

  // 决策结果数据
  const [decisionResults, setDecisionResults] = useState<DecisionResult[]>([
    {
      id: 'decision_1',
      name: '3号大棚灌溉决策',
      source: 'auto' as DecisionSource,
      executionMode: 'auto' as ExecutionMode,
      triggerCondition: {
        device: '土壤传感器-03',
        parameter: '土壤湿度',
        operator: '<',
        value: '30',
      },
      execution: {
        device: '水肥机-01',
        action: 'open',
        duration: 45,
      },
      level: 'important',
      confidence: 0.89,
      recommendation: '当土壤湿度低于30%时，自动打开水肥机进行灌溉45分钟',
      explanation: '综合分析：\n1. 模型预测土壤湿度为35%，低于开花期最佳湿度(60-70%)\n2. 天气预报未来3天无降雨，蒸发量较大(8.5mm/day)\n3. 当前处于开花期，是需水关键期\n4. 历史记录显示上次灌溉已过3天\n因此建议尽快灌溉，保证作物正常生长',
      actionItems: [
        '系统检测到土壤湿度低于30%',
        '自动启动水肥机-01',
        '持续灌溉45分钟',
        '灌溉后系统自动关闭',
        '记录土壤湿度变化曲线',
      ],
      inputData: {
        models: [
          { id: 'output_1', modelName: '土壤湿度预测模型' },
          { id: 'output_2', modelName: '作物需水量模型' },
        ],
        rules: [
          { id: 'rule_1', name: '开花期灌溉规则' },
          { id: 'rule_2', name: '土壤湿度阈值规则' },
        ],
        context: [
          { id: 'ctx_1', name: '地块信息' },
          { id: 'ctx_2', name: '作物品种' },
          { id: 'ctx_3', name: '生长阶段' },
        ],
      },
      fusionProcess: [
        {
          step: '模型输出分析',
          result: '预测土壤湿度: 35%, 需水量: 45L',
          weight: 0.8,
        },
        {
          step: '业务规则匹配',
          result: '匹配到2条相关规则',
          weight: 0.7,
        },
        {
          step: '上下文验证',
          result: '当前处于开花期，需水量大',
          weight: 0.6,
        },
        {
          step: '加权融合计算',
          result: '综合置信度: 0.89',
          weight: 1.0,
        },
        {
          step: '决策生成',
          result: '生成自动灌溉方案',
          weight: 1.0,
        },
      ],
      generatedAt: '2024-10-21 16:30:00',
    },
    {
      id: 'decision_2',
      name: '2号大棚降温决策',
      source: 'manual' as DecisionSource,
      executionMode: 'manual' as ExecutionMode,
      triggerCondition: {
        device: '温度传感器-02',
        parameter: '空气温度',
        operator: '>',
        value: '35',
      },
      execution: {
        device: '排风扇-02',
        action: 'open',
        duration: 20,
      },
      createdBy: '张三',
      level: 'normal',
      confidence: 0.86,
      recommendation: '当大棚温度高于35℃时，手动打开排风扇20分钟进行降温',
      explanation: '根据现场观察，2号大棚在高温天气容易超过35℃，影响作物生长。建议当温度传感器检测到超过35℃时，及时打开排风扇降温。',
      actionItems: [
        '监测温度传感器-02的实时数据',
        '当温度超过35℃时，收到系统提醒',
        '点击执行按钮，启动排风扇-02',
        '持续运行20分钟后自动关闭',
        '记录降温效果',
      ],
      inputData: {
        models: [],
        rules: [],
        context: [],
      },
      fusionProcess: [],
      generatedAt: '2024-10-22 14:20:00',
    },
    {
      id: 'decision_3',
      name: '1号大棚湿度调节决策',
      source: 'auto' as DecisionSource,
      executionMode: 'auto' as ExecutionMode,
      triggerCondition: {
        device: '湿度传感器-01',
        parameter: '空气湿度',
        operator: '<',
        value: '60',
      },
      execution: {
        device: '喷雾器-01',
        action: 'open',
        duration: 15,
      },
      level: 'suggestion',
      confidence: 0.92,
      recommendation: '当空气湿度低于60%时，自动打开喷雾器15分钟增加湿度',
      explanation: '综合分析：\n1. 番茄生长最佳湿度为60-80%\n2. 当前处于开花期，湿度过低会影响授粉\n3. 设置自动触发条件，保持适宜湿度\n因此建议当湿度低于60%时自动喷雾加湿',
      actionItems: [
        '系统检测到湿度低于60%',
        '自动启动喷雾器-01',
        '持续喷雾15分钟',
        '喷雾后系统自动关闭',
        '记录湿度变化曲线',
      ],
      inputData: {
        models: [
          { id: 'output_1', modelName: '番茄生长预测模型' },
        ],
        rules: [
          { id: 'rule_3', name: '开花期湿度规则' },
        ],
        context: [
          { id: 'ctx_1', name: '地块信息' },
          { id: 'ctx_2', name: '作物品种' },
        ],
      },
      fusionProcess: [
        {
          step: '模型输出分析',
          result: '最佳湿度范围: 60-80%',
          weight: 0.7,
        },
        {
          step: '业务规则匹配',
          result: '匹配到"开花期湿度规则"',
          weight: 0.55,
        },
        {
          step: '上下文验证',
          result: '当前处于开花期，湿度控制重要',
          weight: 0.4,
        },
        {
          step: '加权融合计算',
          result: '综合置信度: 0.92',
          weight: 1.0,
        },
        {
          step: '决策生成',
          result: '生成自动湿度控制方案',
          weight: 1.0,
        },
      ],
      generatedAt: '2024-10-23 09:15:00',
    },
  ]);

  // 筛选后的决策结果
  const filteredResults = decisionResults.filter(result => {
    if (activeTab === 'all') return true;
    if (activeTab === 'auto') return result.source === 'auto';
    if (activeTab === 'manual') return result.source === 'manual';
    return true;
  });

  const handleViewDetail = (result: DecisionResult) => {
    setSelectedResult(result);
    setShowResultDialog(true);
  };

  const handleExecuteDecision = (result: DecisionResult) => {
    setExecutingResult(result);
    setShowExecuteConfirmDialog(true);
  };

  const confirmExecute = () => {
    if (!executingResult) return;

    // 模拟执行
    setShowExecuteConfirmDialog(false);

    // 显示执行结果
    setTimeout(() => {
      const mockResult = {
        success: true,
        executedAt: new Date().toLocaleString('zh-CN'),
        details: [
          { step: '检查触发条件', status: 'success', message: `${executingResult.triggerCondition.parameter} ${executingResult.triggerCondition.operator} ${executingResult.triggerCondition.value}` },
          { step: '启动设备', status: 'success', message: `${executingResult.execution.device} ${executingResult.execution.action === 'open' ? '已打开' : '已关闭'}` },
          { step: '设置定时', status: 'success', message: `将在${executingResult.execution.duration}分钟后自动关闭` },
          { step: '记录日志', status: 'success', message: '执行记录已保存' },
        ],
      };
      setExecuteResult(mockResult);
      setShowExecuteResultDialog(true);
      toast.success(`决策"${executingResult.name}"执行成功`);
    }, 1000);
  };

  const handleEditDecision = (result: DecisionResult) => {
    setEditingDecision(result);
    setNewDecision({
      name: result.name,
      level: result.level,
      confidence: result.confidence * 100,
      executionMode: result.executionMode,
      triggerDevice: result.triggerCondition.device,
      triggerParameter: result.triggerCondition.parameter,
      triggerOperator: result.triggerCondition.operator,
      triggerValue: result.triggerCondition.value,
      targetDevice: result.execution.device,
      targetAction: result.execution.action,
      duration: result.execution.duration,
      recommendation: result.recommendation,
      explanation: result.explanation,
      actionItems: result.actionItems.join('\n'),
    });
    setShowEditDecisionDialog(true);
  };

  const handleDeleteDecision = (id: string) => {
    setDeletingDecisionId(id);
    setShowDeleteConfirmDialog(true);
  };

  const confirmDeleteDecision = () => {
    if (!deletingDecisionId) return;

    setDecisionResults(decisionResults.filter(r => r.id !== deletingDecisionId));
    setShowDeleteConfirmDialog(false);
    setDeletingDecisionId(null);
    toast.success('决策已删除');
  };

  const handleSaveNewDecision = () => {
    // 验证必填项
    if (!newDecision.name || !newDecision.recommendation || !newDecision.actionItems) {
      toast.error('请填写完整的决策信息');
      return;
    }

    if (!newDecision.triggerDevice || !newDecision.triggerParameter || !newDecision.triggerValue) {
      toast.error('请设置完整的触发条件');
      return;
    }

    if (!newDecision.targetDevice) {
      toast.error('请选择目标执行设备');
      return;
    }

    const decision: DecisionResult = {
      id: `decision_${Date.now()}`,
      name: newDecision.name,
      source: 'manual',
      executionMode: newDecision.executionMode,
      triggerCondition: {
        device: newDecision.triggerDevice,
        parameter: newDecision.triggerParameter,
        operator: newDecision.triggerOperator,
        value: newDecision.triggerValue,
      },
      execution: {
        device: newDecision.targetDevice,
        action: newDecision.targetAction,
        duration: newDecision.duration,
      },
      level: newDecision.level,
      confidence: newDecision.confidence / 100,
      recommendation: newDecision.recommendation,
      explanation: newDecision.explanation,
      actionItems: newDecision.actionItems.split('\n').filter(item => item.trim()),
      inputData: {
        models: [],
        rules: [],
        context: [],
      },
      fusionProcess: [],
      generatedAt: new Date().toLocaleString('zh-CN'),
      createdBy: '当前用户',
    };

    setDecisionResults([...decisionResults, decision]);
    setShowAddDecisionDialog(false);
    setNewDecision({
      name: '',
      level: 'normal',
      confidence: 80,
      executionMode: 'auto',
      triggerDevice: '',
      triggerParameter: '',
      triggerOperator: '>',
      triggerValue: '',
      targetDevice: '',
      targetAction: 'open',
      duration: 30,
      recommendation: '',
      explanation: '',
      actionItems: '',
    });
    toast.success('决策已创建');
  };

  const handleSaveEditDecision = () => {
    if (!editingDecision) return;

    // 验证必填项
    if (!newDecision.name || !newDecision.recommendation || !newDecision.actionItems) {
      toast.error('请填写完整的决策信息');
      return;
    }

    const updatedDecisions = decisionResults.map(d => {
      if (d.id === editingDecision.id) {
        return {
          ...d,
          name: newDecision.name,
          level: newDecision.level,
          confidence: newDecision.confidence / 100,
          executionMode: newDecision.executionMode,
          triggerCondition: {
            device: newDecision.triggerDevice,
            parameter: newDecision.triggerParameter,
            operator: newDecision.triggerOperator,
            value: newDecision.triggerValue,
          },
          execution: {
            device: newDecision.targetDevice,
            action: newDecision.targetAction,
            duration: newDecision.duration,
          },
          recommendation: newDecision.recommendation,
          explanation: newDecision.explanation,
          actionItems: newDecision.actionItems.split('\n').filter(item => item.trim()),
        };
      }
      return d;
    });

    setDecisionResults(updatedDecisions);
    setShowEditDecisionDialog(false);
    setEditingDecision(null);
    toast.success('决策已更新');
  };

  const getLevelBadge = (level: DecisionLevel) => {
    const config = {
      critical: { label: '紧急', className: 'bg-red-50 text-red-700 border-red-200' },
      important: { label: '重要', className: 'bg-amber-50 text-amber-700 border-amber-200' },
      normal: { label: '一般', className: 'bg-sky-50 text-sky-700 border-sky-200' },
      suggestion: { label: '建议', className: 'bg-emerald-50 text-emerald-700 border-emerald-200' },
    };
    const { label, className } = config[level];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  const getSourceBadge = (source: DecisionSource) => {
    const config = {
      auto: { label: '自动生成', className: 'bg-emerald-50 text-emerald-700 border-emerald-200', icon: Brain },
      manual: { label: '手动添加', className: 'bg-sky-50 text-sky-700 border-sky-200', icon: User },
    };
    const { label, className, icon: Icon } = config[source];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getExecutionModeBadge = (mode: ExecutionMode) => {
    const config = {
      manual: { label: '手动执行', className: 'bg-sky-50 text-sky-700 border-sky-200', icon: User },
      auto: { label: '自动执行', className: 'bg-emerald-50 text-emerald-700 border-emerald-200', icon: Zap },
    };
    const { label, className, icon: Icon } = config[mode];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-accent to-primary/10 border-accent">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-3 flex-1">
            <Merge className="w-6 h-6 text-accent-foreground flex-shrink-0 mt-1" />
            <div className="flex-1">
              <h2 className="mb-2">业务融合</h2>
              <p className="text-sm text-muted-foreground mb-3">
                将AI模型输出、业务规则和上下文信息进行智能融合，生成可执行的决策建议
              </p>
              <div className="flex flex-wrap gap-2">
                <Badge variant="outline" className="bg-white">
                  <Brain className="w-3 h-3 mr-1" />
                  模型融合
                </Badge>
                <Badge variant="outline" className="bg-white">
                  <ListChecks className="w-3 h-3 mr-1" />
                  规则匹配
                </Badge>
                <Badge variant="outline" className="bg-white">
                  <BookOpen className="w-3 h-3 mr-1" />
                  上下文分析
                </Badge>
                <Badge variant="outline" className="bg-white">
                  <Gauge className="w-3 h-3 mr-1" />
                  置信度评估
                </Badge>
              </div>
            </div>
          </div>
          <Button onClick={() => setShowAddDecisionDialog(true)}>
            <Plus className="w-4 h-4 mr-2" />
            新建决策
          </Button>
        </div>
      </Card>

      {/* 决策列表 */}
      <Card className="p-6">
        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)}>
          <div className="flex items-center justify-between mb-6">
            <TabsList>
              <TabsTrigger value="all">
                全部决策
                <Badge variant="secondary" className="ml-2">{decisionResults.length}</Badge>
              </TabsTrigger>
              <TabsTrigger value="auto">
                自动生成
                <Badge variant="secondary" className="ml-2">
                  {decisionResults.filter(r => r.source === 'auto').length}
                </Badge>
              </TabsTrigger>
              <TabsTrigger value="manual">
                手动添加
                <Badge variant="secondary" className="ml-2">
                  {decisionResults.filter(r => r.source === 'manual').length}
                </Badge>
              </TabsTrigger>
            </TabsList>
          </div>

          <TabsContent value={activeTab} className="mt-0">
            {filteredResults.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Lightbulb className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <div>暂无决策结果</div>
              </div>
            ) : (
              <div className="space-y-4">
                {filteredResults.map((result) => (
                  <Card key={result.id} className="p-5 hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between mb-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          {getSourceBadge(result.source)}
                          {getExecutionModeBadge(result.executionMode)}
                          {getLevelBadge(result.level)}
                        </div>
                        <h3 className="mb-2">{result.name}</h3>
                        <p className="text-sm text-muted-foreground">{result.recommendation}</p>
                      </div>
                    </div>

                    {/* 触发条件和执行设置 */}
                    <div className="grid grid-cols-2 gap-4 mb-4 p-4 bg-muted rounded-lg">
                      <div>
                        <div className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                          <Settings className="w-3 h-3" />
                          触发条件
                        </div>
                        <div className="text-sm">
                          当 <strong>{result.triggerCondition.device}</strong> 的
                          <strong className="mx-1">{result.triggerCondition.parameter}</strong>
                          <strong className="mx-1">{result.triggerCondition.operator}</strong>
                          <strong>{result.triggerCondition.value}</strong> 时
                        </div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                          <Zap className="w-3 h-3" />
                          执行操作
                        </div>
                        <div className="text-sm flex items-center gap-2">
                          {result.execution.action === 'open' ? (
                            <Power className="w-4 h-4 text-success" />
                          ) : (
                            <PowerOff className="w-4 h-4 text-error" />
                          )}
                          <strong>{result.execution.action === 'open' ? '打开' : '关闭'}</strong>
                          <strong>{result.execution.device}</strong>
                          <Timer className="w-3 h-3 ml-2 text-info" />
                          <span>{result.execution.duration}分钟</span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center justify-between text-sm text-muted-foreground mb-4">
                      <div className="flex items-center gap-4">
                        <div className="flex items-center gap-1">
                          <Gauge className="w-4 h-4" />
                          <span>置信度: {(result.confidence * 100).toFixed(0)}%</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Clock className="w-4 h-4" />
                          <span>{result.generatedAt}</span>
                        </div>
                        {result.createdBy && (
                          <div className="flex items-center gap-1">
                            <User className="w-4 h-4" />
                            <span>{result.createdBy}</span>
                          </div>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleViewDetail(result)}>
                        <Eye className="w-4 h-4 mr-1" />
                        查看详情
                      </Button>
                      <Button
                        size="sm"
                        onClick={() => handleExecuteDecision(result)}
                        className="bg-success hover:bg-success/90"
                      >
                        <Play className="w-4 h-4 mr-1" />
                        {result.executionMode === 'auto' ? '立即执行' : '手动执行'}
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEditDecision(result)}>
                        <Edit className="w-4 h-4 mr-1" />
                        编辑
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleDeleteDecision(result.id)}
                        className="text-error hover:text-error hover:bg-error/10"
                      >
                        <Trash2 className="w-4 h-4 mr-1" />
                        删除
                      </Button>
                    </div>
                  </Card>
                ))}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </Card>

      {/* 决策详情对话框 */}
      <Dialog open={showResultDialog} onOpenChange={setShowResultDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>决策详情</DialogTitle>
            <DialogDescription>
              查看完整的决策信息和融合过程
            </DialogDescription>
          </DialogHeader>

          {selectedResult && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  {getSourceBadge(selectedResult.source)}
                  {getExecutionModeBadge(selectedResult.executionMode)}
                  {getLevelBadge(selectedResult.level)}
                </div>
                <h3 className="mb-2">{selectedResult.name}</h3>
              </div>

              {/* 触发条件和执行设置 */}
              <Card className="p-4 bg-info/10 border-info/30">
                <h4 className="mb-3">触发条件与执行设置</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-3 bg-white rounded">
                    <div className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                      <Settings className="w-3 h-3" />
                      触发条件
                    </div>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">设备:</span>
                        <strong>{selectedResult.triggerCondition.device}</strong>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">参数:</span>
                        <strong>{selectedResult.triggerCondition.parameter}</strong>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">条件:</span>
                        <strong>
                          {selectedResult.triggerCondition.operator} {selectedResult.triggerCondition.value}
                        </strong>
                      </div>
                    </div>
                  </div>
                  <div className="p-3 bg-white rounded">
                    <div className="text-xs text-muted-foreground mb-2 flex items-center gap-1">
                      <Zap className="w-3 h-3" />
                      执行操作
                    </div>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">设备:</span>
                        <strong>{selectedResult.execution.device}</strong>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">动作:</span>
                        <strong className={selectedResult.execution.action === 'open' ? 'text-success' : 'text-destructive'}>
                          {selectedResult.execution.action === 'open' ? '打开' : '关闭'}
                        </strong>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">时长:</span>
                        <strong>{selectedResult.execution.duration} 分钟</strong>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 推荐建议 */}
              <Card className="p-4">
                <Label>推荐建议</Label>
                <div className="field-value mt-2">{selectedResult.recommendation}</div>
              </Card>

              {/* 详细说明 */}
              {selectedResult.explanation && (
                <Card className="p-4">
                  <Label>详细说明</Label>
                  <div className="field-value whitespace-pre-wrap mt-2">{selectedResult.explanation}</div>
                </Card>
              )}

              {/* 执行步骤 */}
              <Card className="p-4">
                <Label>执行步骤</Label>
                <div className="field-value mt-2">
                  <ol className="list-decimal list-inside space-y-1">
                    {selectedResult.actionItems.map((item, idx) => (
                      <li key={idx}>{item}</li>
                    ))}
                  </ol>
                </div>
              </Card>

              {/* 融合过程 */}
              {selectedResult.fusionProcess.length > 0 && (
                <div>
                  <Label>融合过程</Label>
                  <div className="space-y-2 mt-2">
                    {selectedResult.fusionProcess.map((step, idx) => (
                      <div key={idx} className="flex items-start gap-3 p-3 bg-muted rounded">
                        <div className="w-8 h-8 rounded-full bg-info-muted text-info flex items-center justify-center flex-shrink-0 text-sm font-medium">
                          {idx + 1}
                        </div>
                        <div className="flex-1">
                          <div className="font-medium mb-1">{step.step}</div>
                          <div className="text-sm text-muted-foreground">{step.result}</div>
                          <div className="text-xs text-muted-foreground mt-1">
                            权重: {(step.weight * 100).toFixed(0)}%
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 输入数据 */}
              {(selectedResult.inputData.models.length > 0 ||
                selectedResult.inputData.rules.length > 0 ||
                selectedResult.inputData.context.length > 0) && (
                <div>
                  <Label>输入数据</Label>
                  <div className="grid grid-cols-3 gap-3 mt-2">
                    {selectedResult.inputData.models.length > 0 && (
                      <div className="p-3 bg-accent/20 rounded">
                        <div className="text-xs text-muted-foreground mb-2">模型输出</div>
                        <div className="space-y-1">
                          {selectedResult.inputData.models.map(model => (
                            <div key={model.id} className="text-sm">{model.modelName}</div>
                          ))}
                        </div>
                      </div>
                    )}
                    {selectedResult.inputData.rules.length > 0 && (
                      <div className="p-3 bg-success/10 rounded">
                        <div className="text-xs text-muted-foreground mb-2">业务规则</div>
                        <div className="space-y-1">
                          {selectedResult.inputData.rules.map(rule => (
                            <div key={rule.id} className="text-sm">{rule.name}</div>
                          ))}
                        </div>
                      </div>
                    )}
                    {selectedResult.inputData.context.length > 0 && (
                      <div className="p-3 bg-info/10 rounded">
                        <div className="text-xs text-muted-foreground mb-2">上下文信息</div>
                        <div className="space-y-1">
                          {selectedResult.inputData.context.map(ctx => (
                            <div key={ctx.id} className="text-sm">{ctx.name}</div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 元数据 */}
              <div className="grid grid-cols-3 gap-4 text-sm">
                <div>
                  <div className="text-muted-foreground mb-1">置信度</div>
                  <div className="font-medium">{(selectedResult.confidence * 100).toFixed(0)}%</div>
                </div>
                <div>
                  <div className="text-muted-foreground mb-1">生成时间</div>
                  <div className="font-medium">{selectedResult.generatedAt}</div>
                </div>
                {selectedResult.createdBy && (
                  <div>
                    <div className="text-muted-foreground mb-1">创建人</div>
                    <div className="font-medium">{selectedResult.createdBy}</div>
                  </div>
                )}
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowResultDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 执行确认对话框 */}
      <Dialog open={showExecuteConfirmDialog} onOpenChange={setShowExecuteConfirmDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>确认执行决策</DialogTitle>
            <DialogDescription>
              确认要执行这个决策吗？执行后将立即启动相关设备。
            </DialogDescription>
          </DialogHeader>

          {executingResult && (
            <div className="space-y-4">
              <div className="p-3 bg-muted rounded">
                <div className="font-medium">{executingResult.name}</div>
                <div className="text-sm text-muted-foreground mt-1">
                  {executingResult.recommendation}
                </div>
              </div>
              <div className="text-sm text-muted-foreground">
                <div>• 触发条件: {executingResult.triggerCondition.device} {executingResult.triggerCondition.parameter} {executingResult.triggerCondition.operator} {executingResult.triggerCondition.value}</div>
                <div>• 执行操作: {executingResult.execution.action === 'open' ? '打开' : '关闭'} {executingResult.execution.device}</div>
                <div>• 持续时间: {executingResult.execution.duration}分钟</div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowExecuteConfirmDialog(false)}>
              取消
            </Button>
            <Button onClick={confirmExecute}>
              确认执行
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 执行结果对话框 */}
      <Dialog open={showExecuteResultDialog} onOpenChange={setShowExecuteResultDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>执行结果</DialogTitle>
            <DialogDescription>
              决策执行已完成
            </DialogDescription>
          </DialogHeader>

          {executeResult && (
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-success">
                <CheckCircle className="w-5 h-5" />
                <span className="font-medium">执行成功</span>
              </div>
              <div className="text-sm text-muted-foreground">
                执行时间: {executeResult.executedAt}
              </div>
              <div className="space-y-2">
                {executeResult.details.map((detail: any, idx: number) => (
                  <div key={idx} className="flex items-center gap-2 text-sm">
                    <div className={`w-2 h-2 rounded-full ${
                      detail.status === 'success' ? 'bg-success' : 'bg-error'
                    }`} />
                    <span>{detail.step}: {detail.message}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setShowExecuteResultDialog(false)}>
              确定
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 新建决策对话框 */}
      <Dialog open={showAddDecisionDialog} onOpenChange={setShowAddDecisionDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>新建决策</DialogTitle>
            <DialogDescription>
              创建一个新的业务决策
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>决策名称</Label>
              <Input
                value={newDecision.name}
                onChange={(e) => setNewDecision({ ...newDecision, name: e.target.value })}
                placeholder="输入决策名称"
              />
            </div>
            <div>
              <Label>决策级别</Label>
              <Select value={newDecision.level} onValueChange={(value) => setNewDecision({ ...newDecision, level: value as any })}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="critical">紧急</SelectItem>
                  <SelectItem value="important">重要</SelectItem>
                  <SelectItem value="normal">一般</SelectItem>
                  <SelectItem value="suggestion">建议</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>执行模式</Label>
              <Select value={newDecision.executionMode} onValueChange={(value) => setNewDecision({ ...newDecision, executionMode: value as any })}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="auto">自动执行</SelectItem>
                  <SelectItem value="manual">手动执行</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>置信度 (%)</Label>
              <Input
                type="number"
                min="0"
                max="100"
                value={newDecision.confidence}
                onChange={(e) => setNewDecision({ ...newDecision, confidence: parseInt(e.target.value) || 0 })}
              />
            </div>
          </div>

          <div className="space-y-4">
            <div>
              <Label>触发条件</Label>
              <div className="grid grid-cols-4 gap-2 mt-2">
                <Select value={newDecision.triggerDevice} onValueChange={(value) => setNewDecision({ ...newDecision, triggerDevice: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择设备" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="土壤传感器-01">土壤传感器-01</SelectItem>
                    <SelectItem value="土壤传感器-02">土壤传感器-02</SelectItem>
                    <SelectItem value="土壤传感器-03">土壤传感器-03</SelectItem>
                    <SelectItem value="温度传感器-01">温度传感器-01</SelectItem>
                    <SelectItem value="温度传感器-02">温度传感器-02</SelectItem>
                    <SelectItem value="湿度传感器-01">湿度传感器-01</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={newDecision.triggerParameter} onValueChange={(value) => setNewDecision({ ...newDecision, triggerParameter: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择参数" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="土壤湿度">土壤湿度</SelectItem>
                    <SelectItem value="空气温度">空气温度</SelectItem>
                    <SelectItem value="空气湿度">空气湿度</SelectItem>
                    <SelectItem value="光照强度">光照强度</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={newDecision.triggerOperator} onValueChange={(value) => setNewDecision({ ...newDecision, triggerOperator: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value=">">大于 (&gt;)</SelectItem>
                    <SelectItem value="<">小于 (&lt;)</SelectItem>
                    <SelectItem value=">=">大于等于 (&gt;=)</SelectItem>
                    <SelectItem value="<=">小于等于 (&lt;=)</SelectItem>
                    <SelectItem value="==">等于 (=)</SelectItem>
                  </SelectContent>
                </Select>
                <Input
                  value={newDecision.triggerValue}
                  onChange={(e) => setNewDecision({ ...newDecision, triggerValue: e.target.value })}
                  placeholder="阈值"
                />
              </div>
            </div>

            <div>
              <Label>执行设置</Label>
              <div className="grid grid-cols-3 gap-2 mt-2">
                <Select value={newDecision.targetDevice} onValueChange={(value) => setNewDecision({ ...newDecision, targetDevice: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择设备" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="水肥机-01">水肥机-01</SelectItem>
                    <SelectItem value="水肥机-02">水肥机-02</SelectItem>
                    <SelectItem value="排风扇-01">排风扇-01</SelectItem>
                    <SelectItem value="排风扇-02">排风扇-02</SelectItem>
                    <SelectItem value="喷雾器-01">喷雾器-01</SelectItem>
                    <SelectItem value="喷雾器-02">喷雾器-02</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={newDecision.targetAction} onValueChange={(value) => setNewDecision({ ...newDecision, targetAction: value as any })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="open">打开</SelectItem>
                    <SelectItem value="close">关闭</SelectItem>
                  </SelectContent>
                </Select>
                <Input
                  type="number"
                  min="1"
                  value={newDecision.duration}
                  onChange={(e) => setNewDecision({ ...newDecision, duration: parseInt(e.target.value) || 0 })}
                  placeholder="持续时间(分钟)"
                />
              </div>
            </div>

            <div>
              <Label>推荐建议</Label>
              <Textarea
                value={newDecision.recommendation}
                onChange={(e) => setNewDecision({ ...newDecision, recommendation: e.target.value })}
                placeholder="描述推荐建议"
                rows={3}
              />
            </div>

            <div>
              <Label>推荐理由</Label>
              <Textarea
                value={newDecision.explanation}
                onChange={(e) => setNewDecision({ ...newDecision, explanation: e.target.value })}
                placeholder="详细解释推荐原因"
                rows={4}
              />
            </div>

            <div>
              <Label>执行步骤</Label>
              <Textarea
                value={newDecision.actionItems}
                onChange={(e) => setNewDecision({ ...newDecision, actionItems: e.target.value })}
                placeholder="每行一个执行步骤"
                rows={4}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAddDecisionDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveNewDecision}>
              创建决策
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑决策对话框 */}
      <Dialog open={showEditDecisionDialog} onOpenChange={setShowEditDecisionDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>编辑决策</DialogTitle>
            <DialogDescription>
              修改决策信息和配置
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h4 className="mb-4">基本信息</h4>
              <div className="space-y-4">
                <div>
                  <Label>决策名称 *</Label>
                  <Input
                    placeholder="例如: 3号大棚灌溉决策"
                    value={newDecision.name}
                    onChange={(e) => setNewDecision({...newDecision, name: e.target.value})}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>决策级别</Label>
                    <Select value={newDecision.level} onValueChange={(v) => setNewDecision({...newDecision, level: v as DecisionLevel})}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="critical">紧急</SelectItem>
                        <SelectItem value="important">重要</SelectItem>
                        <SelectItem value="normal">一般</SelectItem>
                        <SelectItem value="suggestion">建议</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>置信度 (%)</Label>
                    <Input
                      type="number"
                      min="0"
                      max="100"
                      value={newDecision.confidence}
                      onChange={(e) => setNewDecision({
                        ...newDecision,
                        confidence: Number(e.target.value)
                      })}
                    />
                  </div>
                </div>

                <div>
                  <Label>执行模式 *</Label>
                  <Select
                    value={newDecision.executionMode}
                    onValueChange={(v) => setNewDecision({...newDecision, executionMode: v as ExecutionMode})}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="manual">手动执行</SelectItem>
                      <SelectItem value="auto">自动执行</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </Card>

            {/* 触发条件设置 */}
            <Card className="p-4 bg-warning/10 border-warning/30">
              <div className="flex items-center gap-2 mb-4">
                <Settings className="w-5 h-5 text-warning" />
                <h4>触发条件设置</h4>
              </div>

              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>选择设备 *</Label>
                    <Select
                      value={newDecision.triggerDevice}
                      onValueChange={(v) => setNewDecision({...newDecision, triggerDevice: v})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="土壤传感器-01">土壤传感器-01</SelectItem>
                        <SelectItem value="土壤传感器-02">土壤传感器-02</SelectItem>
                        <SelectItem value="土壤传感器-03">土壤传感器-03</SelectItem>
                        <SelectItem value="温度传感器-01">温度传感器-01</SelectItem>
                        <SelectItem value="温度传感器-02">温度传感器-02</SelectItem>
                        <SelectItem value="湿度传感器-01">湿度传感器-01</SelectItem>
                        <SelectItem value="光照传感器-01">光照传感器-01</SelectItem>
                        <SelectItem value="CO2传感器-01">CO2传感器-01</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>选择参数 *</Label>
                    <Select
                      value={newDecision.triggerParameter}
                      onValueChange={(v) => setNewDecision({...newDecision, triggerParameter: v})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="土壤湿度">土壤湿度</SelectItem>
                        <SelectItem value="土壤温度">土壤温度</SelectItem>
                        <SelectItem value="空气温度">空气温度</SelectItem>
                        <SelectItem value="空气湿度">空气湿度</SelectItem>
                        <SelectItem value="光照强度">光照强度</SelectItem>
                        <SelectItem value="CO2浓度">CO2浓度</SelectItem>
                        <SelectItem value="EC值">EC值</SelectItem>
                        <SelectItem value="PH值">PH值</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-3">
                  <div className="col-span-1">
                    <Label>条件 *</Label>
                    <Select
                      value={newDecision.triggerOperator}
                      onValueChange={(v) => setNewDecision({...newDecision, triggerOperator: v})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value=">">&gt; 大于</SelectItem>
                        <SelectItem value="<">&lt; 小于</SelectItem>
                        <SelectItem value=">=">&gt;= 大于等于</SelectItem>
                        <SelectItem value="<=">&lt;= 小于等于</SelectItem>
                        <SelectItem value="==">= 等于</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="col-span-2">
                    <Label>值 *</Label>
                    <Input
                      value={newDecision.triggerValue}
                      onChange={(e) => setNewDecision({...newDecision, triggerValue: e.target.value})}
                    />
                  </div>
                </div>
              </div>
            </Card>

            {/* 执行设置 */}
            <Card className="p-4 bg-success/10 border-success/30">
              <div className="flex items-center gap-2 mb-4">
                <Zap className="w-5 h-5 text-success" />
                <h4>执行设置</h4>
              </div>

              <div className="space-y-4">
                <div>
                  <Label>目标设备 *</Label>
                  <Select
                    value={newDecision.targetDevice}
                    onValueChange={(v) => setNewDecision({...newDecision, targetDevice: v})}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="水肥机-01">水肥机-01</SelectItem>
                      <SelectItem value="水肥机-02">水肥机-02</SelectItem>
                      <SelectItem value="灌溉阀门-A1">灌溉阀门-A1</SelectItem>
                      <SelectItem value="灌溉阀门-B2">灌溉阀门-B2</SelectItem>
                      <SelectItem value="排风扇-01">排风扇-01</SelectItem>
                      <SelectItem value="排风扇-02">排风扇-02</SelectItem>
                      <SelectItem value="喷雾器-01">喷雾器-01</SelectItem>
                      <SelectItem value="喷雾器-02">喷雾器-02</SelectItem>
                      <SelectItem value="补光灯-01">补光灯-01</SelectItem>
                      <SelectItem value="加热器-01">加热器-01</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>开关状态 *</Label>
                    <Select
                      value={newDecision.targetAction}
                      onValueChange={(v) => setNewDecision({...newDecision, targetAction: v as 'open' | 'close'})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="open">
                          <div className="flex items-center gap-2">
                            <Power className="w-4 h-4 text-success" />
                            打开
                          </div>
                        </SelectItem>
                        <SelectItem value="close">
                          <div className="flex items-center gap-2">
                            <PowerOff className="w-4 h-4 text-destructive" />
                            关闭
                          </div>
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>持续时间（分钟）*</Label>
                    <Input
                      type="number"
                      min="1"
                      value={newDecision.duration}
                      onChange={(e) => setNewDecision({...newDecision, duration: Number(e.target.value)})}
                    />
                  </div>
                </div>
              </div>
            </Card>

            {/* 决策内容 */}
            <Card className="p-4">
              <h4 className="mb-4">决策内容</h4>
              <div className="space-y-4">
                <div>
                  <Label>推荐建议 *</Label>
                  <Textarea
                    rows={3}
                    value={newDecision.recommendation}
                    onChange={(e) => setNewDecision({...newDecision, recommendation: e.target.value})}
                  />
                </div>

                <div>
                  <Label>详细说明</Label>
                  <Textarea
                    rows={5}
                    value={newDecision.explanation}
                    onChange={(e) => setNewDecision({...newDecision, explanation: e.target.value})}
                  />
                </div>

                <div>
                  <Label>执行步骤 *（每行一个步骤）</Label>
                  <Textarea
                    rows={6}
                    value={newDecision.actionItems}
                    onChange={(e) => setNewDecision({...newDecision, actionItems: e.target.value})}
                  />
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDecisionDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveEditDecision} className="bg-success hover:bg-success/90">
              <CheckCircle className="w-4 h-4 mr-2" />
              保存修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={showDeleteConfirmDialog} onOpenChange={setShowDeleteConfirmDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确认要删除这个决策吗？删除后无法恢复。
            </DialogDescription>
          </DialogHeader>

          <div className="flex items-center gap-2 text-error">
            <AlertCircle className="w-5 h-5" />
            <span>此操作不可撤销</span>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteConfirmDialog(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDeleteDecision}>
              确认删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}