<template>
  <div class="workflow-designer">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>{{ isAgentMode ? 'Agent编排设计器' : '工作流设计器' }}</h2>
          <div class="header-actions">
            <el-button v-if="isAgentMode" type="success" @click="handleTestAgent" :disabled="!agentLoaded">
              <el-icon><VideoPlay /></el-icon>
              测试运行
            </el-button>
            <el-button v-if="isAgentMode && currentAgent" type="primary" @click="handlePublishAgent" :disabled="!agentLoaded || currentAgent.status === 'published'">
              <el-icon><Upload /></el-icon>
              {{ currentAgent.status === 'published' ? '已发布' : '发布' }}
            </el-button>
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </el-header>
      <el-main style="padding: 0; height: calc(100vh - 60px); overflow: hidden;">
        <div v-if="isAgentMode && agentLoaded" class="agent-designer-layout">
          <!-- 左侧：编排区域 -->
          <div class="editor-panel">
            <WorkflowEditor
              :workflow-id="undefined"
              :initial-nodes="initialNodes"
              :initial-edges="initialEdges"
              :execution-status="executionStatus"
              @save="handleSaveWorkflow"
              @node-test="handleNodeTest"
            />
          </div>
          <!-- 右侧：预览与调试 -->
          <div class="preview-panel">
            <AgentChatPreview
              :agent-id="agentId"
              :agent-name="currentAgent?.name"
              :opening-message="openingMessage"
              :preset-questions="presetQuestions"
              :node-test-result="nodeTestResult"
              @execution-status="handleChatExecutionStatus"
            />
          </div>
        </div>
        <div v-else-if="isAgentMode" style="display: flex; align-items: center; justify-content: center; height: 100%;">
          <el-loading :loading="true" text="加载中..." />
        </div>
        <WorkflowEditor
          v-else
          :workflow-id="workflowId"
          :initial-nodes="initialNodes"
          :initial-edges="initialEdges"
          :execution-status="executionStatus"
          @save="handleSaveWorkflow"
        />
      </el-main>
    </el-container>
    
    <!-- Agent测试对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="测试Agent"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-form-item label="输入参数">
          <el-input
            v-model="testInput"
            type="textarea"
            :rows="8"
            placeholder='请输入JSON格式的输入参数，例如：{"query": "你好"}'
          />
        </el-form-item>
               <el-form-item v-if="testResult" label="执行结果">
                 <el-alert
                   :type="testResult.status === 'success' ? 'success' : 'error'"
                   :closable="false"
                   show-icon
                 >
                   <template #title>
                     <div v-if="testResult.status === 'success'">
                       <div><strong>状态：</strong>执行成功</div>
                       <div v-if="testResult.execution_time"><strong>执行时间：</strong>{{ testResult.execution_time }}ms</div>
                       <div style="margin-top: 10px;"><strong>输出：</strong></div>
                       <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin-top: 5px; max-height: 300px; overflow: auto;">{{ JSON.stringify(testResult.output, null, 2) }}</pre>
                     </div>
                     <div v-else>
                       <div><strong>状态：</strong>执行失败</div>
                       <div style="margin-top: 10px;"><strong>错误信息：</strong></div>
                       <pre style="background: #fef0f0; padding: 10px; border-radius: 4px; margin-top: 5px; max-height: 300px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; color: #f56c6c;">{{ testResult.error }}</pre>
                       <div v-if="testResult.failed_nodes && testResult.failed_nodes.length > 0" style="margin-top: 10px;">
                         <div><strong>失败的节点：</strong></div>
                         <div v-for="(node, index) in testResult.failed_nodes" :key="index" style="margin-top: 8px; padding: 8px; background: #fef0f0; border-left: 3px solid #f56c6c; border-radius: 4px;">
                           <div><strong>节点ID：</strong>{{ node.node_id }}</div>
                           <div><strong>节点类型：</strong>{{ node.node_type }}</div>
                           <div v-if="node.error_message"><strong>错误信息：</strong>{{ node.error_message }}</div>
                           <div v-if="node.error_type"><strong>错误类型：</strong>{{ node.error_type }}</div>
                         </div>
                       </div>
                     </div>
                   </template>
                 </el-alert>
               </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="testDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleRunTest" :loading="testing">
          {{ testing ? '执行中...' : '开始测试' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay, Upload } from '@element-plus/icons-vue'
import WorkflowEditor from '@/components/WorkflowEditor/WorkflowEditor.vue'
import AgentChatPreview from '@/components/AgentChatPreview.vue'
import { useWorkflowStore } from '@/stores/workflow'
import { useAgentStore } from '@/stores/agent'
import api from '@/api'

const route = useRoute()
const router = useRouter()
const workflowStore = useWorkflowStore()
const agentStore = useAgentStore()

// 判断是否是Agent模式
const isAgentMode = computed(() => route.name === 'AgentDesigner')
const agentId = ref<string | undefined>(isAgentMode.value ? route.params.id as string : undefined)
const workflowId = ref<string | undefined>(!isAgentMode.value ? route.params.id as string : undefined)

// Agent模式下的初始数据
const agentLoaded = ref(false)
const initialNodes = ref<any[]>([])
const initialEdges = ref<any[]>([])
const currentAgent = ref<any>(null)

// 开场白和预设问题（从Agent配置中提取）
const openingMessage = ref('')
const presetQuestions = ref<string[]>([])

// 节点测试结果
const nodeTestResult = ref<any>(null)

// 测试对话框
const testDialogVisible = ref(false)
const testInput = ref('{}')
const testing = ref(false)
const testResult = ref<any>(null)
const executionStatus = ref<any>(null) // 执行状态，包含当前执行的节点信息

// 加载Agent数据
const loadAgentData = async () => {
  if (!isAgentMode.value || !agentId.value) return
  
  try {
    const agent = await agentStore.fetchAgent(agentId.value)
    currentAgent.value = agent
    if (agent && agent.workflow_config) {
      initialNodes.value = agent.workflow_config.nodes || []
      initialEdges.value = agent.workflow_config.edges || []
      agentLoaded.value = true
    }
    
    // 提取开场白和预设问题（可以从Agent的配置中获取，这里使用默认值）
    openingMessage.value = agent.description || '你好，我是 ' + agent.name + '，很高兴为您服务！'
    presetQuestions.value = [
      '你好',
      '你能做什么？',
      '介绍一下你自己'
    ]
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载Agent数据失败')
    router.push('/agents')
  }
}

// 加载工作流数据
const loadWorkflowData = async () => {
  if (isAgentMode.value || !workflowId.value) return
  
  try {
    const workflow = await workflowStore.fetchWorkflow(workflowId.value)
    if (workflow) {
      // 工作流数据中的nodes和edges字段
      initialNodes.value = workflow.nodes || []
      initialEdges.value = workflow.edges || []
      console.log('[WorkflowDesigner] 加载工作流数据:', {
        nodes: initialNodes.value.length,
        edges: initialEdges.value.length,
        workflow
      })
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载工作流数据失败')
    router.push('/')
  }
}

// 处理聊天界面的执行状态更新
const handleChatExecutionStatus = (status: any) => {
  console.log('[rjb] WorkflowDesigner received execution status from chat:', JSON.stringify(status, null, 2))
  executionStatus.value = status
}

// 测试Agent
const handleTestAgent = () => {
  testInput.value = '{}'
  testResult.value = null
  testDialogVisible.value = true
}

// 执行测试
const handleRunTest = async () => {
  if (!agentId.value) return
  
  testing.value = true
  testResult.value = null
  
  // 轮询超时时间（5分钟，复杂工作流可能需要更长时间）
  const maxPollingTime = 5 * 60 * 1000  // 5分钟 = 300000毫秒
  const startTime = Date.now()
  let pollingInterval: any = null
  
  try {
    // 解析输入数据
    let inputData: any = {}
    try {
      inputData = JSON.parse(testInput.value || '{}')
    } catch (error) {
      ElMessage.error('输入参数格式错误，请输入有效的JSON格式')
      testing.value = false
      return
    }
    
    // 调用执行API
    const response = await api.post('/api/v1/executions', {
      agent_id: agentId.value,
      input_data: inputData
    })
    
    const execution = response.data
    ElMessage.success('Agent执行已启动')
    
    // 轮询执行状态
    const checkStatus = async () => {
      try {
        // 检查超时
        if (Date.now() - startTime > maxPollingTime) {
          testResult.value = {
            status: 'error',
            error: '执行超时，请检查工作流配置或查看执行日志'
          }
          testing.value = false
          if (pollingInterval) {
            clearInterval(pollingInterval)
          }
          return
        }
        
        // 获取执行状态和节点信息
        const statusResponse = await api.get(`/api/v1/executions/${execution.id}/status`)
        const status = statusResponse.data
        console.log('[rjb] Execution status response:', JSON.stringify(status, null, 2))
        executionStatus.value = status
        
        // 同时获取执行详情（如果失败，使用状态信息）
        let exec: any = null
        try {
          const execResponse = await api.get(`/api/v1/executions/${execution.id}`)
          exec = execResponse.data
        } catch (execError: any) {
          // 如果获取执行详情失败，使用状态信息
          console.warn('[rjb] 获取执行详情失败，使用状态信息:', execError)
          exec = {
            id: execution.id,
            status: status.status,
            error_message: status.failed_nodes?.[0]?.error_message || '执行失败'
          }
        }
        
        if (exec.status === 'completed') {
          testResult.value = {
            status: 'success',
            output: exec.output_data,
            execution_time: exec.execution_time
          }
          testing.value = false
          // 延迟清除执行状态，让用户能看到最终的执行结果
          setTimeout(() => {
            executionStatus.value = null
          }, 3000) // 3秒后清除
          if (pollingInterval) {
            clearInterval(pollingInterval)
          }
          ElMessage.success(`执行成功 (${exec.execution_time}ms)`)
        } else if (exec.status === 'failed') {
          // 收集所有失败节点的错误信息
          const failedNodes = status.failed_nodes || []
          let errorDetails = exec.error_message || '执行失败'
          
          if (failedNodes.length > 0) {
            // 尝试从 WorkflowEditor 的 nodes 中获取节点标签，如果没有则使用 initialNodes
            const getNodeLabel = (nodeId: string) => {
              // 这里无法直接访问 WorkflowEditor 的 nodes，所以使用 initialNodes
              const node = initialNodes.value.find((n: any) => n.id === nodeId)
              return node?.data?.label || nodeId
            }
            
            const nodeErrors = failedNodes.map((node: any) => {
              const nodeLabel = getNodeLabel(node.node_id)
              const errorMsg = node.error_message || '执行失败'
              const errorType = node.error_type ? ` (${node.error_type})` : ''
              return `节点 "${nodeLabel}" (${node.node_id})${errorType}: ${errorMsg}`
            }).join('\n')
            errorDetails = `执行失败，失败的节点：\n${nodeErrors}`
          }
          
          testResult.value = {
            status: 'error',
            error: errorDetails,
            failed_nodes: failedNodes
          }
          testing.value = false
          // 延迟清除执行状态，让用户能看到失败节点的状态
          setTimeout(() => {
            executionStatus.value = null
          }, 5000) // 5秒后清除，给用户更多时间查看失败节点
          if (pollingInterval) {
            clearInterval(pollingInterval)
          }
          ElMessage.error('执行失败，请查看详细错误信息')
        } else if (exec.status === 'pending' || exec.status === 'running') {
          // 继续轮询，状态为 pending 或 running
          // 不需要做任何操作，等待下次轮询
        } else {
          // 未知状态，停止轮询
          testResult.value = {
            status: 'error',
            error: `未知的执行状态: ${exec.status}`
          }
          testing.value = false
          if (pollingInterval) {
            clearInterval(pollingInterval)
          }
        }
      } catch (error: any) {
        // 如果之前已经获取到了执行状态，尝试使用它
        if (executionStatus.value && executionStatus.value.failed_nodes && executionStatus.value.failed_nodes.length > 0) {
          const failedNodes = executionStatus.value.failed_nodes
          const nodeErrors = failedNodes.map((node: any) => {
            const nodeLabel = initialNodes.value.find((n: any) => n.id === node.node_id)?.data?.label || node.node_id
            const errorMsg = node.error_message || '执行失败'
            const errorType = node.error_type ? ` (${node.error_type})` : ''
            return `节点 "${nodeLabel}" (${node.node_id})${errorType}: ${errorMsg}`
          }).join('\n')
          testResult.value = {
            status: 'error',
            error: `执行失败，失败的节点：\n${nodeErrors}`,
            failed_nodes: failedNodes
          }
        } else {
          testResult.value = {
            status: 'error',
            error: error.response?.data?.detail || '获取执行状态失败，请检查网络连接或查看执行日志'
          }
        }
        testing.value = false
        // 不清除执行状态，让用户能看到失败节点的状态
        if (pollingInterval) {
          clearInterval(pollingInterval)
        }
        ElMessage.error('获取执行状态失败')
      }
    }
    
          // 使用 setInterval 进行轮询，每500毫秒检查一次（更频繁，能捕获快速执行的节点）
          pollingInterval = setInterval(checkStatus, 500)
          // 立即执行一次
          checkStatus()
    
  } catch (error: any) {
    console.error('执行Agent失败:', error)
    testResult.value = {
      status: 'error',
      error: error.response?.data?.detail || error.message || '执行失败'
    }
    testing.value = false
    if (pollingInterval) {
      clearInterval(pollingInterval)
    }
    ElMessage.error(error.response?.data?.detail || '执行失败')
  }
}

// 发布Agent
const handlePublishAgent = async () => {
  if (!agentId.value || !currentAgent.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要发布Agent "${currentAgent.value.name}" 吗？发布后其他用户可以使用此Agent。`,
      '确认发布',
      {
        type: 'warning'
      }
    )
    
    await agentStore.deployAgent(agentId.value)
    ElMessage.success('Agent发布成功')
    
    // 重新加载Agent数据
    await loadAgentData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '发布失败')
    }
  }
}

const handleSaveWorkflow = async (workflow: { nodes: any[]; edges: any[] }) => {
  try {
    if (isAgentMode.value && agentId.value) {
      // Agent模式：更新Agent的workflow_config
      await agentStore.updateAgent(agentId.value, {
        workflow_config: {
          nodes: workflow.nodes,
          edges: workflow.edges
        }
      })
      ElMessage.success('Agent工作流已保存')
    } else if (workflowId.value) {
      // 工作流模式：更新现有工作流
      await workflowStore.updateWorkflow(workflowId.value, {
        nodes: workflow.nodes,
        edges: workflow.edges
      })
      ElMessage.success('工作流已保存')
    } else {
      // 创建新工作流
      const result = await workflowStore.createWorkflow({
        name: `工作流_${Date.now()}`,
        description: '',
        nodes: workflow.nodes,
        edges: workflow.edges
      })
      workflowId.value = result.id
      ElMessage.success('工作流已创建')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '保存失败')
  }
}

// 处理节点测试
const handleNodeTest = (data: { node: any; result: any; input: any }) => {
  nodeTestResult.value = {
    node: data.node,
    result: data.result,
    input: data.input,
    timestamp: Date.now()
  }
  
  // 3秒后自动清除测试结果
  setTimeout(() => {
    nodeTestResult.value = null
  }, 5000)
}

const handleBack = () => {
  if (isAgentMode.value) {
    router.push('/agents')
  } else {
    router.push('/')
  }
}

onMounted(async () => {
  if (isAgentMode.value) {
    await loadAgentData()
  } else {
    await loadWorkflowData()
  }
})

// 监听路由变化，重新加载数据
watch(() => route.params.id, async (newId) => {
  if (isAgentMode.value) {
    agentId.value = newId as string
    await loadAgentData()
  } else {
    workflowId.value = newId as string
    await loadWorkflowData()
  }
})
</script>

<style scoped>
.workflow-designer {
  width: 100%;
  height: 100vh;
}

.el-header {
  background-color: #409eff;
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.el-header h2 {
  margin: 0;
  font-size: 20px;
}

/* Agent模式下的左右分栏布局 */
.agent-designer-layout {
  display: flex;
  height: 100%;
  width: 100%;
}

.editor-panel {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.preview-panel {
  width: 400px;
  min-width: 400px;
  max-width: 500px;
  height: 100%;
  overflow: hidden;
  background: #f5f5f5;
}

/* 响应式：小屏幕时预览面板可以折叠 */
@media (max-width: 1200px) {
  .preview-panel {
    width: 350px;
    min-width: 350px;
  }
}
</style>
