import { useState } 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 { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import {
  Activity,
  AlertCircle,
  ArrowRight,
  BookOpen,
  Brain,
  CheckCircle,
  Clock,
  Edit,
  Eye,
  Gauge,
  Lightbulb,
  ListChecks,
  Merge,
  Play,
  Plus,
  Settings,
  Trash2,
  User,
  Zap,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AIBusinessFusionProps {
  activePath?: string;
}

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

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

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

// 决策结果
interface DecisionResult {
  id: string;
  name: string;
  source: DecisionSource; // 决策来源：自动生成或手动添加
  executionMode: ExecutionMode; // 执行模式：手动执行或自动执行
  autoTriggerConditions?: { // 自动执行的触发条件
    type: 'threshold';
    conditions: Array<{
      field: string; // 格式：设备 - 参数
      operator: string;
      value: any;
    }>;
  };
  level: DecisionLevel;
  confidence: number;
  recommendation: string;
  explanation: string;
  actionItems: string[];
  targetDevices?: string[]; // 目标控制设备
  targetAction?: 'open' | 'close'; // 目标设备动作
  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 function AIBusinessFusion({ activePath }: AIBusinessFusionProps) {
  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 [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 [activeTab, setActiveTab] = useState<'all' | 'auto' | 'manual'>('all');

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

  // 决策结果数据
  const [decisionResults, setDecisionResults] = useState<DecisionResult[]>([
    {
      id: 'decision_1',
      name: '3号大棚灌溉决策',
      source: 'auto' as DecisionSource,
      executionMode: 'auto' as ExecutionMode,
      autoTriggerConditions: {
        type: 'threshold' as const,
        conditions: [
          { field: '土壤传感器-01 - 土壤湿度', operator: '<', value: 30 },
        ],
      },
      targetDevices: ['灌溉控制器-01'],
      targetAction: 'open',
      level: 'important',
      confidence: 0.89,
      recommendation: '建议在今天傍晚17:00-18:00进行灌溉，灌溉量120升，持续时间45分钟',
      explanation: '综合分析：\n1. 模型预测土壤湿度为35%，低于开花期最佳湿度(60-70%)\n2. 天气预报未来3天无降雨，蒸发量较大(8.5mm/day)\n3. 当前处于开花期，是需水关键期\n4. 历史记录显示上次灌溉已过3天\n因此建议尽快灌溉，保证作物正常生长',
      actionItems: [
        '准备灌溉设备，检查管道和喷头',
        '在17:00开始灌溉，避开高温时段',
        '灌溉总量控制在120升，持续约45分钟',
        '灌溉后检查土壤湿度，确保达到60%以上',
        '记录灌溉时间和用水量',
      ],
      inputData: {
        models: [
          { id: 'output_3', modelName: '灌溉需求预测模型' },
          { id: 'output_1', modelName: '番茄生长预测模型' },
        ],
        rules: [
          { id: 'rule_2', name: '开花期灌溉规则' },
          { id: 'rule_5', name: '干旱预警规则' },
        ],
        context: [
          { id: 'ctx_4', name: '天气预报' },
          { id: 'ctx_5', name: '历史灌溉记录' },
        ],
      },
      fusionProcess: [
        {
          step: '模型输出分析',
          result: '灌溉需求预测: 120升, 置信度: 0.91',
          weight: 0.6,
        },
        {
          step: '业务规则匹配',
          result: '匹配到"开花期灌溉规则", 权重: 0.9',
          weight: 0.5,
        },
        {
          step: '上下文验证',
          result: '天气晴朗无雨，土壤湿度35%，符合灌溉条件',
          weight: 0.45,
        },
        {
          step: '加权融合计算',
          result: '综合置信度: 0.89 (超过阈值0.75)',
          weight: 1.0,
        },
        {
          step: '决策生成',
          result: '生成可执行灌溉方案',
          weight: 1.0,
        },
      ],
      generatedAt: '2024-10-23 10:35:00',
    },
    {
      id: 'decision_2',
      name: '番茄早疫病防治决策',
      source: 'manual' as DecisionSource,
      executionMode: 'manual' as ExecutionMode,
      targetDevices: ['喷雾设备-01'],
      targetAction: 'open',
      createdBy: '张三',
      level: 'normal',
      confidence: 0.86,
      recommendation: '建议采用生物防治方案，使用枯草芽孢杆菌制剂，每7天喷施一次，连续3次',
      explanation: '根据现场观察，发现早期疫病症状，受感染面积约5%，处于可控范围。建议优先使用生物防治，避免化学农药残留。',
      actionItems: [
        '采购枯草芽孢杆菌生物防治剂',
        '配制药液，按照说明书比例稀释',
        '在傍晚或阴天进行喷施，避免强光',
        '重点喷施发病叶片及周围植株',
        '7天后进行第二次喷施，14天后第三次',
        '持续观察病情发展，如恶化及时调整方案',
      ],
      inputData: {
        models: [],
        rules: [],
        context: [],
      },
      fusionProcess: [],
      generatedAt: '2024-10-22 14:20:00',
    },
    {
      id: 'decision_4',
      name: '1号大棚温度调控决策',
      source: 'auto' as DecisionSource,
      executionMode: 'auto' as ExecutionMode,
      autoTriggerConditions: {
        type: 'threshold' as const,
        conditions: [
          { field: '温度传感器-01 - 空气温度', operator: '>', value: 30 },
        ],
      },
      targetDevices: ['通风设备-01'],
      targetAction: 'open',
      level: 'important',
      confidence: 0.88,
      recommendation: '白天温度偏高，建议开启通风系统，控制温度在25-28℃范围内',
      explanation: '综合分析：\n1. 监测数据显示大棚温度已达32℃，超过适宜范围\n2. 天气预报显示今日晴朗高温，需加强通风\n3. 番茄开花期对温度敏感，过高影响授粉\n4. 根据温控规则，应立即开启通风系统\n因此建议立即采取降温措施',
      actionItems: [
        '立即开启顶部通风口，增加空气流通',
        '适当打开侧窗，形成对流',
        '必要时启动喷雾降温系统',
        '监测温度变化，确保控制在适宜范围',
        '傍晚时逐步关闭通风口，保温',
      ],
      inputData: {
        models: [
          { id: 'output_4', modelName: '环境监测模型' },
        ],
        rules: [
          { id: 'rule_6', name: '温度调控规则' },
        ],
        context: [
          { id: 'ctx_6', name: '实时环境数据' },
          { id: 'ctx_4', name: '天气预报' },
        ],
      },
      fusionProcess: [
        {
          step: '模型输出分析',
          result: '温度32℃, 超出适宜范围, 置信度: 0.95',
          weight: 0.65,
        },
        {
          step: '业务规则匹配',
          result: '匹配到"温度调控规则", 权重: 0.88',
          weight: 0.5,
        },
        {
          step: '上下文验证',
          result: '天气晴朗高温，开花期对温度敏感',
          weight: 0.45,
        },
        {
          step: '加权融合计算',
          result: '综合置信度: 0.88 (超过阈值0.75)',
          weight: 1.0,
        },
        {
          step: '决策生成',
          result: '生成温度调控方案',
          weight: 1.0,
        },
      ],
      generatedAt: '2024-10-23 11:20:00',
    },
  ]);

  // 筛选决策
  const filteredDecisions = decisionResults.filter(d => {
    if (activeTab === 'all') return true;
    if (activeTab === 'auto') return d.source === 'auto';
    if (activeTab === 'manual') return d.source === 'manual';
    return true;
  });

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

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

  const handleEditDecision = (decision: DecisionResult) => {
    setEditingDecision(decision);
    const triggerParts = decision.autoTriggerConditions?.conditions[0]?.field?.split(' - ') || ['', ''];
    setNewDecision({
      name: decision.name,
      level: decision.level,
      confidence: Math.round(decision.confidence * 100),
      executionMode: decision.executionMode,
      recommendation: decision.recommendation,
      explanation: decision.explanation,
      actionItems: decision.actionItems.join('\n'),
      triggerDevice: triggerParts[0] || '',
      triggerParameter: triggerParts[1] || '',
      triggerOperator: decision.autoTriggerConditions?.conditions[0]?.operator || '<',
      triggerValue: decision.autoTriggerConditions?.conditions[0]?.value || '',
      targetDevice: decision.targetDevices?.[0] || '',
      targetAction: decision.targetAction || 'open',
    });
    setShowEditDecisionDialog(true);
  };

  const handleSaveNewDecision = () => {
    // 验证必填字段
    if (!newDecision.name || !newDecision.recommendation || !newDecision.actionItems) {
      toast.error('请填写必填字段');
      return;
    }

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

    const decision: DecisionResult = {
      id: `decision_manual_${Date.now()}`,
      name: newDecision.name,
      source: 'manual',
      executionMode: newDecision.executionMode,
      level: newDecision.level,
      confidence: newDecision.confidence / 100,
      recommendation: newDecision.recommendation,
      explanation: newDecision.explanation,
      actionItems: newDecision.actionItems.split('\n').filter(Boolean),
      targetDevices: [newDecision.targetDevice],
      targetAction: newDecision.targetAction,
      inputData: { models: [], rules: [], context: [] },
      fusionProcess: [],
      generatedAt: new Date().toLocaleString('zh-CN'),
      createdBy: '当前用户',
    };

    // 如果是自动执行，添加触发条件
    if (newDecision.executionMode === 'auto' && newDecision.triggerDevice && newDecision.triggerParameter && newDecision.triggerValue) {
      decision.autoTriggerConditions = {
        type: 'threshold',
        conditions: [
          {
            field: `${newDecision.triggerDevice} - ${newDecision.triggerParameter}`,
            operator: newDecision.triggerOperator,
            value: newDecision.triggerValue,
          },
        ],
      };
    }

    setDecisionResults([decision, ...decisionResults]);
    toast.success('决策添加成功！');
    setShowAddDecisionDialog(false);
    
    // 重置表单
    setNewDecision({
      name: '',
      level: 'normal',
      confidence: 80,
      executionMode: 'manual',
      recommendation: '',
      explanation: '',
      actionItems: '',
      triggerDevice: '',
      triggerParameter: '',
      triggerOperator: '<',
      triggerValue: '',
      targetDevice: '',
      targetAction: 'open',
    });
  };

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

    // 验证必填字段
    if (!newDecision.name || !newDecision.recommendation || !newDecision.actionItems) {
      toast.error('请填写必填字段');
      return;
    }

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

    const updatedDecision: DecisionResult = {
      ...editingDecision,
      name: newDecision.name,
      executionMode: newDecision.executionMode,
      level: newDecision.level,
      confidence: newDecision.confidence / 100,
      recommendation: newDecision.recommendation,
      explanation: newDecision.explanation,
      actionItems: newDecision.actionItems.split('\n').filter(Boolean),
      targetDevices: [newDecision.targetDevice],
      targetAction: newDecision.targetAction,
    };

    // 如果是自动执行，更新触发条件
    if (newDecision.executionMode === 'auto' && newDecision.triggerDevice && newDecision.triggerParameter && newDecision.triggerValue) {
      updatedDecision.autoTriggerConditions = {
        type: 'threshold',
        conditions: [
          {
            field: `${newDecision.triggerDevice} - ${newDecision.triggerParameter}`,
            operator: newDecision.triggerOperator,
            value: newDecision.triggerValue,
          },
        ],
      };
    } else {
      updatedDecision.autoTriggerConditions = undefined;
    }

    setDecisionResults(decisionResults.map(d => d.id === editingDecision.id ? updatedDecision : d));
    toast.success('决策更新成功！');
    setShowEditDecisionDialog(false);
    setEditingDecision(null);
  };

  const handleConfirmExecute = async () => {
    if (!executingResult) return;

    setShowExecuteConfirmDialog(false);
    toast.loading('正在执行决策...', { id: 'execute-decision' });

    // 模拟执行决策
    setTimeout(() => {
      const mockResult = {
        decisionId: executingResult.id,
        decisionName: executingResult.name,
        executionId: `exec_${Date.now()}`,
        executionType: executingResult.executionMode,
        status: 'success',
        startTime: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
        endTime: new Date(Date.now() + 2000).toLocaleTimeString('zh-CN', { hour12: false }),
        duration: '2.3秒',
        affectedDevices: executingResult.targetDevices || ['设备-01'],
        executedActions: executingResult.actionItems.slice(0, 3),
        results: {
          success: true,
          completedSteps: executingResult.actionItems.length,
          totalSteps: executingResult.actionItems.length,
          metrics: executingResult.name.includes('灌溉')
            ? {
                '灌溉量': '120升',
                '持续时间': '45分钟',
                '土壤湿度变化': '35% → 62%',
                '执行状态': '正常完成',
              }
            : executingResult.name.includes('温度')
            ? {
                '温度调整': '32℃ → 28℃',
                '通风状态': '已启动',
                '遮阳程度': '50%',
                '执行状态': '正常完成',
              }
            : {
                '施肥量': '30kg/亩',
                '施肥面积': '5亩',
                '总用量': '150kg',
                '执行状态': '正常完成',
              },
        },
      };

      setExecuteResult(mockResult);
      setShowExecuteResultDialog(true);
      toast.success('决策执行成功！', { id: 'execute-decision' });
    }, 2000);
  };

  const getDecisionLevelBadge = (level: DecisionLevel) => {
    const config = {
      critical: { label: '紧急', className: 'bg-error-muted text-error-foreground border-error' },
      important: { label: '重要', className: 'bg-warning-muted text-warning-foreground border-warning' },
      normal: { label: '一般', className: 'bg-info-muted text-info-foreground border-info' },
      suggestion: { label: '建议', className: 'bg-muted text-muted-foreground border-border' },
    };
    const { label, className } = config[level];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  const getTriggerConditionText = (conditions?: DecisionResult['autoTriggerConditions']) => {
    if (!conditions || conditions.conditions.length === 0) return '';
    const cond = conditions.conditions[0];
    return `${cond.field} ${cond.operator} ${cond.value}`;
  };

  const renderDecisionForm = () => (
    <div className="space-y-6">
      {/* 基本信息 */}
      <Card className="p-4 bg-info/10 border-info/30">
        <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>置信度 (0-100)</Label>
              <Input 
                type="number"
                min="0"
                max="100"
                placeholder="80"
                value={newDecision.confidence}
                onChange={(e) => setNewDecision({
                  ...newDecision, 
                  confidence: Number(e.target.value)
                })}
              />
            </div>
          </div>
        </div>
      </Card>
      
      {/* 执行设置 */}
      <Card className="p-4 bg-success/10 border-success/30">
        <h4 className="mb-4">执行设置</h4>
        <div className="space-y-4">
          <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>
          
          {/* 自动执行时显示触发条件设置 */}
          {newDecision.executionMode === 'auto' && (
            <Card className="p-4 bg-warning/10 border-warning/30">
              <div className="flex items-center gap-2 mb-3">
                <Settings className="w-4 h-4 text-warning" />
                <h5 className="text-sm font-medium">触发条件设置（阈值触发）</h5>
              </div>
              
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label>选择设备 *</Label>
                    <Select 
                      value={newDecision.triggerDevice}
                      onValueChange={(v) => setNewDecision({...newDecision, triggerDevice: v})}
                    >
                      <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>
                        <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 placeholder="请选择参数" />
                      </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-2 gap-3">
                  <div>
                    <Label>操作符 *</Label>
                    <Select 
                      value={newDecision.triggerOperator}
                      onValueChange={(v) => setNewDecision({...newDecision, triggerOperator: v})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value=">">{'>'} 大于</SelectItem>
                        <SelectItem value="<">{'<'} 小于</SelectItem>
                        <SelectItem value=">=">{'>='} 大于等于</SelectItem>
                        <SelectItem value="<=">{'>='} 小于等于</SelectItem>
                        <SelectItem value="==">= 等于</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>阈值 *</Label>
                    <Input 
                      placeholder="如: 20"
                      value={newDecision.triggerValue}
                      onChange={(e) => setNewDecision({...newDecision, triggerValue: e.target.value})}
                    />
                  </div>
                </div>
                
                <div className="text-xs text-muted-foreground bg-card p-2 rounded border border-warning/30">
                  <strong>示例：</strong>当 {newDecision.triggerDevice || '土壤传感器-01'} 的 {newDecision.triggerParameter || '土壤湿度'} {newDecision.triggerOperator} {newDecision.triggerValue || '20'}% 时触发
                </div>
              </div>
            </Card>
          )}
          
          <div>
            <Label>执行目标 *</Label>
            <div className="grid grid-cols-2 gap-3 mt-2">
              <div>
                <Label>选择设备 *</Label>
                <Select 
                  value={newDecision.targetDevice}
                  onValueChange={(v) => setNewDecision({...newDecision, targetDevice: v})}
                >
                  <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>
                    <SelectItem value="遮阳设备-01">遮阳设备-01</SelectItem>
                    <SelectItem value="补光设备-01">补光设备-01</SelectItem>
                    <SelectItem value="加温设备-01">加温设备-01</SelectItem>
                    <SelectItem value="喷雾设备-01">喷雾设备-01</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>执行动作 *</Label>
                <Select 
                  value={newDecision.targetAction}
                  onValueChange={(v) => setNewDecision({...newDecision, targetAction: v as 'open' | 'close'})}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="open">打开</SelectItem>
                    <SelectItem value="close">关闭</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="text-xs text-muted-foreground mt-2">
              <strong>示例：</strong>{newDecision.targetAction === 'open' ? '打开' : '关闭'} {newDecision.targetDevice || '水肥机-01'}
            </div>
          </div>
        </div>
      </Card>
      
      {/* 决策内容 */}
      <Card className="p-4">
        <h4 className="mb-4">决策内容</h4>
        <div className="space-y-4">
          <div>
            <Label>推荐建议 *</Label>
            <Textarea 
              placeholder="简要说明这个决策的推荐建议..."
              rows={3}
              value={newDecision.recommendation}
              onChange={(e) => setNewDecision({...newDecision, recommendation: e.target.value})}
            />
          </div>
          
          <div>
            <Label>详细说明</Label>
            <Textarea 
              placeholder="详细解释这个决策的原因、依据等..."
              rows={5}
              value={newDecision.explanation}
              onChange={(e) => setNewDecision({...newDecision, explanation: e.target.value})}
            />
          </div>
          
          <div>
            <Label>执行步骤 *（每行一个步骤）</Label>
            <Textarea 
              placeholder={'例如:\n准备灌溉设备\n检查管道和喷头\n开始灌溉...'}
              rows={6}
              value={newDecision.actionItems}
              onChange={(e) => setNewDecision({...newDecision, actionItems: e.target.value})}
            />
          </div>
        </div>
      </Card>
    </div>
  );

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-accent/10 to-info/10 border-accent/30">
        <div className="flex items-start gap-3">
          <Merge className="w-6 h-6 text-accent flex-shrink-0 mt-1" />
          <div className="flex-1">
            <div className="flex items-center justify-between mb-2">
              <h2>业务融合功能</h2>
              <Button 
                onClick={() => setShowAddDecisionDialog(true)}
                className="bg-success hover:bg-success/90"
              >
                <Plus className="w-4 h-4 mr-2" />
                手动添加决策
              </Button>
            </div>
            <p className="text-sm text-muted-foreground mb-3">
              自动生成和手动添加决策，支持手动执行或自动执行（达到环境条件时自动控制物联网设备）
            </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">
                <Lightbulb className="w-3 h-3 mr-1" />
                智能决策生成
              </Badge>
              <Badge variant="outline" className="bg-white">
                <BookOpen className="w-3 h-3 mr-1" />
                可解释性
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 决策列表 */}
      <Card className="p-6">
        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'all' | 'auto' | 'manual')}>
          <div className="flex items-center justify-between mb-4">
            <TabsList>
              <TabsTrigger value="all">全部决策</TabsTrigger>
              <TabsTrigger value="auto">自动生成</TabsTrigger>
              <TabsTrigger value="manual">手动添加</TabsTrigger>
            </TabsList>
            <p className="text-sm text-muted-foreground">
              共 {filteredDecisions.length} 条决策
            </p>
          </div>

          <TabsContent value={activeTab} className="space-y-4 mt-4">
            {filteredDecisions.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Merge className="w-12 h-12 mx-auto mb-4 opacity-20" />
                <p>暂无决策</p>
              </div>
            ) : (
              filteredDecisions.map((result) => (
                <Card key={result.id} className="p-6 hover:shadow-lg transition-shadow">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2 flex-wrap">
                        <h4>{result.name}</h4>
                        {getDecisionLevelBadge(result.level)}
                        
                        {/* 来源标识 */}
                        {result.source === 'auto' ? (
                          <Badge variant="outline" className="bg-accent/20 text-accent border-accent/40">
                            <Brain className="w-3 h-3 mr-1" />
                            自动生成
                          </Badge>
                        ) : (
                          <Badge variant="outline" className="bg-info/10 text-info border-info/30">
                            <Edit className="w-3 h-3 mr-1" />
                            手动添加
                          </Badge>
                        )}
                        
                        {/* 执行模式标识 */}
                        {result.executionMode === 'auto' ? (
                          <Badge variant="outline" className="bg-success/10 text-success border-success/30">
                            <Zap className="w-3 h-3 mr-1" />
                            自动执行
                          </Badge>
                        ) : (
                          <Badge variant="outline" className="bg-muted text-muted-foreground border-border">
                            <Play className="w-3 h-3 mr-1" />
                            手动执行
                          </Badge>
                        )}
                        
                        <div className="flex items-center gap-1 text-sm">
                          <Gauge className="w-4 h-4 text-success" />
                          <span className="font-medium">{(result.confidence * 100).toFixed(0)}%</span>
                        </div>
                      </div>
                      
                      <div className="text-sm mb-3 text-muted-foreground">{result.recommendation}</div>
                      
                      {/* 自动执行时显示触发条件 */}
                      {result.executionMode === 'auto' && result.autoTriggerConditions && (
                        <div className="flex items-center gap-2 mb-2 text-xs">
                          <Settings className="w-3 h-3 text-muted-foreground" />
                          <span className="text-muted-foreground">
                            触发条件: {getTriggerConditionText(result.autoTriggerConditions)}
                          </span>
                        </div>
                      )}
                      
                      {/* 目标设备 */}
                      {result.targetDevices && result.targetDevices.length > 0 && (
                        <div className="flex items-center gap-2 mb-2 text-xs">
                          <Activity className="w-3 h-3 text-muted-foreground" />
                          <span className="text-muted-foreground">
                            执行目标: {result.targetAction === 'open' ? '打开' : '关闭'} {result.targetDevices.join(', ')}
                          </span>
                        </div>
                      )}
                      
                      <div className="flex items-center gap-4 text-xs text-muted-foreground flex-wrap">
                        <div className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {result.generatedAt}
                        </div>
                        {result.createdBy && (
                          <div className="flex items-center gap-1">
                            <User className="w-3 h-3" />
                            创建人: {result.createdBy}
                          </div>
                        )}
                        <div className="flex items-center gap-1">
                          <ListChecks className="w-3 h-3" />
                          {result.actionItems.length} 个执行步骤
                        </div>
                      </div>
                    </div>
                    
                    <div className="flex gap-2 ml-4">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleEditDecision(result)}
                      >
                        <Edit 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" />
                        执行
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleViewResult(result)}
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        详情
                      </Button>
                    </div>
                  </div>
                  
                  {/* 只有自动生成的决策才显示融合过程 */}
                  {result.source === 'auto' && result.fusionProcess.length > 0 && (
                    <div className="pt-4 border-t">
                      <div className="text-sm text-muted-foreground mb-2">融合过程:</div>
                      <div className="flex items-center gap-2 overflow-x-auto pb-2">
                        {result.fusionProcess.map((process, idx) => (
                          <div key={idx} className="flex items-center gap-2 flex-shrink-0">
                            <div className="px-3 py-2 bg-muted rounded-lg text-xs">
                              <div className="font-medium mb-1">{process.step}</div>
                              <div className="text-muted-foreground">{process.result}</div>
                            </div>
                            {idx < result.fusionProcess.length - 1 && (
                              <ArrowRight className="w-4 h-4 text-muted-foreground" />
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </Card>
              ))
            )}
          </TabsContent>
        </Tabs>
      </Card>

      {/* 手动添加决策对话框 */}
      <Dialog open={showAddDecisionDialog} onOpenChange={setShowAddDecisionDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>手动添加决策</DialogTitle>
            <DialogDescription>
              填写以下信息创建一个新的决策
            </DialogDescription>
          </DialogHeader>
          
          {renderDecisionForm()}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAddDecisionDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveNewDecision} className="bg-success hover:bg-success/90">
              <Plus className="w-4 h-4 mr-2" />
              保存决策
            </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>
          
          {editingDecision && (
            <div className="space-y-6">
              {/* 如果是自动生成的决策，显示提示 */}
              {editingDecision.source === 'auto' && (
                <Card className="p-3 bg-warning-muted border-warning/30">
                  <div className="flex items-center gap-2 text-sm text-warning-muted-foreground">
                    <AlertCircle className="w-4 h-4" />
                    <span>注意: 这是自动生成的决策，编辑后将无法还原原始融合过程</span>
                  </div>
                </Card>
              )}
              
              {renderDecisionForm()}
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDecisionDialog(false)}>
              取消
            </Button>
            <Button onClick={handleUpdateDecision} className="bg-success hover:bg-success/90">
              <CheckCircle className="w-4 h-4 mr-2" />
              保存修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 决策详情对话框 */}
      <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-4">
                  <h3>{selectedResult.name}</h3>
                  {getDecisionLevelBadge(selectedResult.level)}
                  {selectedResult.source === 'auto' ? (
                    <Badge variant="outline" className="bg-accent/20 text-accent border-accent/40">
                      <Brain className="w-3 h-3 mr-1" />
                      自动生成
                    </Badge>
                  ) : (
                    <Badge variant="outline" className="bg-info/10 text-info border-info/30">
                      <Edit className="w-3 h-3 mr-1" />
                      手动添加
                    </Badge>
                  )}
                </div>
                
                <div className="space-y-4">
                  <div>
                    <div className="font-medium mb-2">推荐建议</div>
                    <p className="text-muted-foreground">{selectedResult.recommendation}</p>
                  </div>
                  
                  <div>
                    <div className="font-medium mb-2">详细说明</div>
                    <p className="text-muted-foreground whitespace-pre-line">{selectedResult.explanation}</p>
                  </div>
                  
                  <div>
                    <div className="font-medium mb-2">执行步骤</div>
                    <div className="space-y-2">
                      {selectedResult.actionItems.map((item, idx) => (
                        <div key={idx} className="flex items-start gap-2">
                          <div className="w-6 h-6 rounded-full bg-success-muted text-success flex items-center justify-center text-xs flex-shrink-0 mt-0.5">
                            {idx + 1}
                          </div>
                          <p className="flex-1 text-muted-foreground">{item}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                  
                  {selectedResult.targetDevices && selectedResult.targetDevices.length > 0 && (
                    <div>
                      <div className="font-medium mb-2">执行目标</div>
                      <div className="flex items-center gap-2 text-muted-foreground">
                        <Activity className="w-4 h-4" />
                        <span>{selectedResult.targetAction === 'open' ? '打开' : '关闭'} {selectedResult.targetDevices.join(', ')}</span>
                      </div>
                    </div>
                  )}
                  
                  {selectedResult.executionMode === 'auto' && selectedResult.autoTriggerConditions && (
                    <div>
                      <div className="font-medium mb-2">触发条件</div>
                      <div className="flex items-center gap-2 text-muted-foreground">
                        <Settings className="w-4 h-4" />
                        <span>{getTriggerConditionText(selectedResult.autoTriggerConditions)}</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
              
              {/* 只有自动生成的决策才显示输入数据和融合过程 */}
              {selectedResult.source === 'auto' && (
                <Card className="p-4">
                  <h4 className="mb-4">输入数据</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <div className="text-muted-foreground mb-2">模型输出</div>
                      {selectedResult.inputData.models.map((model, idx) => (
                        <div key={idx} className="mb-1 flex items-center gap-1">
                          <Brain className="w-3 h-3 text-accent" />
                          <span>{model.modelName}</span>
                        </div>
                      ))}
                      {selectedResult.inputData.models.length === 0 && (
                        <span className="text-muted-foreground">无</span>
                      )}
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-2">业务规则</div>
                      {selectedResult.inputData.rules.map((rule, idx) => (
                        <div key={idx} className="mb-1 flex items-center gap-1">
                          <BookOpen className="w-3 h-3 text-info" />
                          <span>{rule.name}</span>
                        </div>
                      ))}
                      {selectedResult.inputData.rules.length === 0 && (
                        <span className="text-muted-foreground">无</span>
                      )}
                    </div>
                    <div>
                      <div className="text-muted-foreground mb-2">上下文信息</div>
                      {selectedResult.inputData.context.map((ctx, idx) => (
                        <div key={idx} className="mb-1 flex items-center gap-1">
                          <Activity className="w-3 h-3 text-success" />
                          <span>{ctx.name}</span>
                        </div>
                      ))}
                      {selectedResult.inputData.context.length === 0 && (
                        <span className="text-muted-foreground">无</span>
                      )}
                    </div>
                  </div>
                </Card>
              )}
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowResultDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 执行确认对话框 */}
      <Dialog open={showExecuteConfirmDialog} onOpenChange={setShowExecuteConfirmDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>确认执行决策</DialogTitle>
            <DialogDescription>
              请确认以下决策信息，点击确认后将立即执行
            </DialogDescription>
          </DialogHeader>
          
          {executingResult && (
            <div className="space-y-4">
              <div className="p-4 bg-info/10 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <h4>{executingResult.name}</h4>
                  {getDecisionLevelBadge(executingResult.level)}
                </div>
                <p className="text-sm text-muted-foreground">{executingResult.recommendation}</p>
              </div>
              
              {executingResult.targetDevices && executingResult.targetDevices.length > 0 && (
                <div>
                  <div className="font-medium mb-2">将执行以下操作：</div>
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <Activity className="w-4 h-4" />
                    <span>{executingResult.targetAction === 'open' ? '打开' : '关闭'} {executingResult.targetDevices.join(', ')}</span>
                  </div>
                </div>
              )}
              
              <div>
                <div className="font-medium mb-2">执行步骤预览:</div>
                <div className="space-y-1 text-sm">
                  {executingResult.actionItems.slice(0, 3).map((item, idx) => (
                    <div key={idx} className="flex items-center gap-2 text-muted-foreground">
                      <CheckCircle className="w-4 h-4 text-muted-foreground" />
                      <span>{item}</span>
                    </div>
                  ))}
                  {executingResult.actionItems.length > 3 && (
                    <div className="text-muted-foreground pl-6">
                      ...共 {executingResult.actionItems.length} 个步骤
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowExecuteConfirmDialog(false)}>
              取消
            </Button>
            <Button onClick={handleConfirmExecute} className="bg-success hover:bg-success/90">
              <Play className="w-4 h-4 mr-2" />
              确认执行
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 执行结果对话框 */}
      <Dialog open={showExecuteResultDialog} onOpenChange={setShowExecuteResultDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>执行结果</DialogTitle>
            <DialogDescription>
              决策已成功执行完成
            </DialogDescription>
          </DialogHeader>
          
          {executeResult && (
            <div className="space-y-4">
              <div className="p-4 bg-success/10 rounded-lg border border-success/30">
                <div className="flex items-center gap-2 mb-2">
                  <CheckCircle className="w-5 h-5 text-success" />
                  <span className="font-medium text-success">执行成功</span>
                </div>
                <p className="text-sm text-success-muted-foreground">决策 "{executeResult.decisionName}" 已成功执行</p>
              </div>
              
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <div className="text-muted-foreground mb-1">执行ID</div>
                  <div>{executeResult.executionId}</div>
                </div>
                <div>
                  <div className="text-muted-foreground mb-1">执行时长</div>
                  <div>{executeResult.duration}</div>
                </div>
                <div>
                  <div className="text-muted-foreground mb-1">开始时间</div>
                  <div>{executeResult.startTime}</div>
                </div>
                <div>
                  <div className="text-muted-foreground mb-1">结束时间</div>
                  <div>{executeResult.endTime}</div>
                </div>
              </div>
              
              <div>
                <div className="font-medium mb-2">受影响设备:</div>
                <div className="flex flex-wrap gap-2">
                  {executeResult.affectedDevices.map((device: string, idx: number) => (
                    <Badge key={idx} variant="outline">
                      <Activity className="w-3 h-3 mr-1" />
                      {device}
                    </Badge>
                  ))}
                </div>
              </div>
              
              <div>
                <div className="font-medium mb-2">执行指标:</div>
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(executeResult.results.metrics).map(([key, value]) => (
                    <div key={key} className="p-2 bg-muted rounded">
                      <div className="text-xs text-muted-foreground">{key}</div>
                      <div className="text-sm font-medium">{value}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
          
          <DialogFooter>
            <Button onClick={() => setShowExecuteResultDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
