<script setup lang="ts">
import type { WorkflowStreamEvent } from '#/api/ai-platform/ai-platform';
import type { ChatMessage, ReasoningStep } from '#/components/ChatBox/index';

import { computed, onUnmounted, ref, watch } from 'vue';

import { Settings2, X } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
} from 'element-plus';

import {
  resumeWorkflowStreamApi,
  runWorkflowStreamApi,
} from '#/api/ai-platform/ai-platform';
import { ChatBox } from '#/components/ChatBox/index';

const props = defineProps<{
  nodes: any[];
  workflowId: string;
}>();

const emit = defineEmits([
  'close',
  'node-start',
  'node-complete',
  'node-streaming',
  'loop-iteration',
  'clear-status',
]);

// 状态
const messages = ref<ChatMessage[]>([]);
const running = ref(false);
const streamingContent = ref('');
let cancelStream: (() => void) | null = null;

// 多变量输入对话框
const variablesDialogVisible = ref(false);
const variablesForm = ref<Record<string, any>>({});
const pendingMessage = ref('');

// 对话流交互状态
const waitingForInput = ref(false);
const waitingConfig = ref<any>(null);
const currentRunId = ref('');

// 设计预览编辑面板状态

// 应用设计面板状态

// 应用设置面板状态

// 仪表盘基础信息面板状态

// 仪表盘设计面板状态

// 仪表盘发布面板状态

// 系统总结面板状态

// 查找 Start 节点并提取变量
const startNode = computed(() => props.nodes.find((n) => n.type === 'start'));
const variables = computed(() => startNode.value?.data?.variables || []);
const hasMultipleVariables = computed(() => variables.value.length > 1);

// 初始化变量表单
watch(
  variables,
  (vars) => {
    const newForm: Record<string, any> = {};
    vars.forEach((v: any) => {
      newForm[v.variable] =
        variablesForm.value[v.variable] || v.default_value || '';
    });
    variablesForm.value = newForm;
  },
  { immediate: true },
);

// 生成消息 ID
const generateId = () =>
  `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;

// 发送消息
const handleSend = (text: string) => {
  if (!text || running.value) return;

  // 如果工作流正在等待用户输入，调用恢复而不是重新运行
  if (waitingForInput.value && currentRunId.value) {
    // 移除当前消息的交互配置
    const lastAssistantMsg = messages.value.findLast(
      (m) => m.role === 'assistant',
    );
    if (lastAssistantMsg?.interaction) {
      const msgIndex = messages.value.findIndex(
        (m) => m.id === lastAssistantMsg.id,
      );
      if (msgIndex !== -1) {
        messages.value[msgIndex] = {
          ...lastAssistantMsg,
          interaction: undefined,
        };
      }
    }

    // 添加用户消息
    const userMsg: ChatMessage = {
      id: generateId(),
      role: 'user',
      content: text,
      timestamp: new Date(),
    };
    messages.value.push(userMsg);

    // 重置等待状态
    waitingForInput.value = false;
    waitingConfig.value = null;

    // 恢复工作流
    resumeWorkflow(text);
    return;
  }

  // 如果有多个变量，先弹出表单
  if (hasMultipleVariables.value) {
    pendingMessage.value = text;
    // 将用户输入填入第一个变量（通常是 user_input）
    const firstVar = variables.value[0];
    if (firstVar) {
      variablesForm.value[firstVar.variable] = text;
    }
    variablesDialogVisible.value = true;
    return;
  }

  // 单变量或无变量，直接运行
  runWorkflow(text, { user_input: text });
};

// 确认变量表单后运行
const handleVariablesConfirm = () => {
  variablesDialogVisible.value = false;
  runWorkflow(pendingMessage.value, variablesForm.value);
};

// 当前正在处理的消息 ID
const currentAssistantMsgId = ref<null | string>(null);

// 当前执行步骤
const currentSteps = ref<ReasoningStep[]>([]);

// 获取节点显示名称
const getNodeLabel = (
  nodeId?: string,
  nodeType?: string,
  fallbackLabel?: string,
) => {
  if (!nodeId) return fallbackLabel || nodeType || '';

  // 优先从前端 nodes 中获取配置的 label
  const node = props.nodes.find((n) => n.id === nodeId);
  const label = node?.data?.label;

  if (label) {
    return label;
  }

  // 如果前端没有找到，使用后端传来的 fallbackLabel
  if (fallbackLabel) {
    return fallbackLabel;
  }

  // 最后使用 nodeType
  return nodeType || '';
};

// 运行工作流
const runWorkflow = (userMessage: string, inputs: Record<string, any>) => {
  if (!props.workflowId) return;

  // 添加用户消息
  const userMsg: ChatMessage = {
    id: generateId(),
    role: 'user',
    content: userMessage,
    timestamp: new Date(),
  };
  messages.value.push(userMsg);

  // 添加 AI 消息（pending 状态）
  const assistantMsgId = generateId();
  const assistantMsg: ChatMessage = {
    id: assistantMsgId,
    role: 'assistant',
    content: '',
    timestamp: new Date(),
    status: 'pending',
    reasoning_steps: [],
  };
  messages.value.push(assistantMsg);
  currentAssistantMsgId.value = assistantMsgId;
  currentSteps.value = [];
  streamingContent.value = '';

  running.value = true;

  // 流式运行（编辑器调试模式，使用草稿版本）
  // 系统变量（application_id 等）由 API 层自动注入
  cancelStream = runWorkflowStreamApi(
    props.workflowId,
    inputs,
    (event: WorkflowStreamEvent) => {
      handleStreamEvent(event, assistantMsgId);
    },
    (error) => {
      console.error('Stream error:', error);
      updateAssistantMessage(assistantMsgId, {
        status: 'failed',
        error_message:
          error.message ||
          $t('ai-platform.workflow.editor.chatPanel.execFailed'),
      });
      running.value = false;
      ElMessage.error(
        error.message ||
          $t('ai-platform.workflow.editor.chatPanel.workflowExecFailed'),
      );
    },
    () => {
      cancelStream = null;
    },
    true, // useDraft: 编辑器调试使用草稿版本
  );
};

// 更新助手消息
const updateAssistantMessage = (
  msgId: string,
  updates: Partial<ChatMessage>,
) => {
  const index = messages.value.findIndex((m) => m.id === msgId);
  if (index !== -1) {
    const currentMsg = messages.value[index];
    if (currentMsg) {
      messages.value[index] = { ...currentMsg, ...updates } as ChatMessage;
    }
  }
};

// 处理流式事件
const handleStreamEvent = (event: WorkflowStreamEvent, msgId: string) => {
  switch (event.type) {
    case 'answer': {
      // 消息内容 - 检查是否有空的初始消息可以更新
      const initialMsg = messages.value.find((m) => m.id === msgId);
      if (initialMsg && !initialMsg.content?.trim()) {
        // 更新初始消息（typing indicator -> 实际内容）
        updateAssistantMessage(msgId, {
          status: 'completed',
          content: event.content || '',
        });
      } else {
        // 已有内容，创建新消息
        const answerMsg: ChatMessage = {
          id: generateId(),
          role: 'assistant',
          content: event.content || '',
          timestamp: new Date(),
          status: 'completed',
        };
        messages.value.push(answerMsg);
      }
      break;
    }

    case 'complete': {
      // 从 outputs 中提取结束节点的输出内容
      // 只检查 output 字段（结束节点配置的输出内容）
      let endOutput = '';
      if (
        event.outputs &&
        typeof event.outputs.output === 'string' &&
        event.outputs.output.trim()
      ) {
        endOutput = event.outputs.output;
      }

      // 查找初始消息（用于显示执行状态的消息）
      const initialMsg = messages.value.find((m) => m.id === msgId);
      const initialMsgHasContent = initialMsg?.content?.trim();

      // 只有当结束节点有明确的输出内容时才显示
      if (endOutput) {
        // 检查初始消息是否还是 typing indicator（没有内容）
        if (initialMsg && !initialMsgHasContent) {
          // 更新初始消息为结束节点输出
          updateAssistantMessage(msgId, {
            status: 'completed',
            content: endOutput,
            elapsed_time: event.elapsed_time,
            tokens_used: event.total_tokens,
          });
        } else {
          // 已有内容，追加新消息
          const endMsg: ChatMessage = {
            id: generateId(),
            role: 'assistant',
            content: endOutput,
            timestamp: new Date(),
            status: 'completed',
            elapsed_time: event.elapsed_time,
            tokens_used: event.total_tokens,
          };
          messages.value.push(endMsg);
        }
      } else if (!initialMsgHasContent) {
        // 没有结束节点输出，且初始消息还是 typing indicator
        // 检查是否有其他助手消息（由 answer 或 node_event 创建）
        const otherAssistantMessages = messages.value.filter(
          (m) => m.role === 'assistant' && m.id !== msgId && m.content?.trim(),
        );
        if (otherAssistantMessages.length > 0) {
          // 有其他消息，移除空的初始消息
          const initialMsgIndex = messages.value.findIndex(
            (m) => m.id === msgId,
          );
          if (initialMsgIndex !== -1) {
            messages.value.splice(initialMsgIndex, 1);
          }
        } else {
          // 没有任何消息，显示一个完成提示
          updateAssistantMessage(msgId, {
            status: 'completed',
            elapsed_time: event.elapsed_time,
            tokens_used: event.total_tokens,
            content: $t(
              'ai-platform.workflow.editor.chatPanel.workflowComplete',
            ),
          });
        }
      }
      // 如果初始消息已有内容（由 answer/node_event 更新），不需要额外处理

      running.value = false;
      streamingContent.value = '';
      break;
    }

    case 'error': {
      updateAssistantMessage(msgId, {
        status: 'failed',
        error_message:
          event.message ||
          $t('ai-platform.workflow.editor.chatPanel.execFailed'),
      });
      running.value = false;
      break;
    }

    case 'llm_chunk': {
      // LLM 流式输出
      emit('node-streaming', {
        node_id: event.node_id,
        content: event.content,
        accumulated_content: event.accumulated_content,
      });
      break;
    }

    case 'loop_complete': {
      // 循环执行完成
      const loopEvent = event as any;
      const outputVar = loopEvent.output_variable || 'loop_results';
      const outputs: Record<string, any> = {
        total_iterations: loopEvent.total_iterations,
        results_count: loopEvent.results_count,
      };
      // 将 loop_results 添加到输出中
      if (loopEvent.loop_results) {
        outputs[outputVar] = loopEvent.loop_results;
      }

      emit('node-complete', {
        node_id: loopEvent.node_id,
        node_type: 'loop',
        status: 'success',
        elapsed_time: 0,
        tokens_used: 0,
        outputs,
      });
      break;
    }

    case 'loop_iteration_complete': {
      // 循环迭代完成
      emit('loop-iteration', {
        node_id: event.node_id,
        type: 'complete',
        iteration: event.iteration,
        total: event.total,
        output: event.output,
      });
      break;
    }

    case 'loop_iteration_error': {
      // 循环迭代错误
      emit('loop-iteration', {
        node_id: event.node_id,
        type: 'error',
        iteration: event.iteration,
        error: event.error,
      });
      break;
    }

    case 'loop_iteration_start': {
      // 循环迭代开始
      emit('loop-iteration', {
        node_id: event.node_id,
        type: 'start',
        iteration: event.iteration,
        total: event.total,
        item: event.item,
      });
      break;
    }

    case 'node_complete': {
      // 查找已存在的 node_start 步骤并更新
      const existingIndex = currentSteps.value.findIndex(
        (s) => s.node_id === event.node_id && s.type === 'node_start',
      );
      const nodeLabel = getNodeLabel(
        event.node_id,
        event.node_type,
        event.node_label,
      );
      if (existingIndex === -1) {
        // 如果没有找到对应的 start，添加新的 complete 步骤
        currentSteps.value.push({
          type: 'node_complete',
          content: nodeLabel,
          node_id: event.node_id,
          node_type: event.node_type,
          output: event.outputs,
          status: 'completed',
          timestamp: new Date().toISOString(),
        });
      } else {
        // 更新已存在的步骤
        currentSteps.value[existingIndex] = {
          ...currentSteps.value[existingIndex],
          type: 'node_complete',
          content: nodeLabel,
          output: event.outputs,
          status: 'completed',
        };
      }
      updateAssistantMessage(msgId, {
        reasoning_steps: [...currentSteps.value],
      });

      emit('node-complete', {
        node_id: event.node_id,
        node_type: event.node_type,
        status: event.status,
        elapsed_time: event.elapsed_time,
        tokens_used: event.tokens_used,
        error_message: event.error_message,
        outputs: event.outputs,
        inputs: event.inputs,
        loop_iteration: event.loop_iteration,
        warnings: event.warnings,
      });
      break;
    }

    case 'node_event': {
      // 节点事件（如消息节点发送消息）
      const nodeEvent = event.event;
      if (nodeEvent?.type === 'message') {
        // 检查是否有空的初始消息可以更新
        const initialMsg = messages.value.find((m) => m.id === msgId);
        if (initialMsg && !initialMsg.content?.trim()) {
          // 更新初始消息（typing indicator -> 实际内容）
          updateAssistantMessage(msgId, {
            status: 'completed',
            content: nodeEvent.content || '',
          });
        } else {
          // 已有内容，创建新消息
          const newMsg: ChatMessage = {
            id: generateId(),
            role: 'assistant',
            content: nodeEvent.content || '',
            timestamp: new Date(),
            status: 'completed',
          };
          messages.value.push(newMsg);
        }
      }
      break;
    }

    case 'node_start': {
      // 检查是否已存在相同 node_id 的步骤（避免重复）
      const existingIndex = currentSteps.value.findIndex(
        (s) => s.node_id === event.node_id,
      );
      if (existingIndex === -1) {
        // 添加新的执行步骤
        const nodeLabel = getNodeLabel(
          event.node_id,
          event.node_type,
          event.node_label,
        );
        currentSteps.value.push({
          type: 'node_start',
          content: nodeLabel,
          node_id: event.node_id,
          node_type: event.node_type,
          status: 'running',
          timestamp: new Date().toISOString(),
        });
      }
      updateAssistantMessage(msgId, {
        reasoning_steps: [...currentSteps.value],
      });

      emit('node-start', {
        node_id: event.node_id,
        node_type: event.node_type,
        node_label: event.node_label,
        inputs: event.inputs,
        loop_iteration: event.loop_iteration,
      });
      break;
    }

    case 'start': {
      currentRunId.value = event.run_id || '';
      // 保持 pending 状态以显示 typing indicator（三个点）
      // 只有当有实际内容时才更新状态
      break;
    }

    case 'waiting_input': {
      // 等待用户输入（对话流节点或设计预览）
      waitingForInput.value = true;
      waitingConfig.value = event.waiting_config || event.config;

      const configData = event.waiting_config || (event as any).config;

      // 检查是否是设计预览类型
      const waitingContent = getWaitingPrompt(configData);

      const initialMsg = messages.value.find((m) => m.id === msgId);
      if (initialMsg && !initialMsg.content?.trim()) {
        updateAssistantMessage(msgId, {
          status: 'completed',
          content: waitingContent,
          interaction: configData as any,
        });
      } else {
        const newMsg: ChatMessage = {
          id: generateId(),
          role: 'assistant',
          content: waitingContent,
          timestamp: new Date(),
          status: 'completed',
          interaction: configData as any,
        };
        messages.value.push(newMsg);
      }
      running.value = false;
      break;
    }
  }
};

// 获取等待提示文本
const getWaitingPrompt = (config: any) => {
  if (!config) return $t('ai-platform.workflow.editor.chatPanel.waitingInput');
  switch (config.type) {
    case 'choice': {
      return (
        config.question ||
        $t('ai-platform.workflow.editor.chatPanel.pleaseSelect')
      );
    }
    case 'confirm': {
      return `**${config.title || $t('ai-platform.workflow.editor.chatPanel.confirm')}**\n\n${config.content || $t('ai-platform.workflow.editor.chatPanel.pleaseConfirm')}`;
    }
    case 'question': {
      return (
        config.question ||
        $t('ai-platform.workflow.editor.chatPanel.pleaseInput')
      );
    }
    default: {
      return $t('ai-platform.workflow.editor.chatPanel.waitingInput');
    }
  }
};

// 处理交互提交（来自 ChatBox）
const handleInteractionSubmit = (messageId: string, value: any) => {
  // 找到消息并移除交互配置
  const msgIndex = messages.value.findIndex((m) => m.id === messageId);
  if (msgIndex !== -1) {
    const msg = messages.value[msgIndex];
    if (msg) {
      messages.value[msgIndex] = { ...msg, interaction: undefined };
    }
  }

  // 添加用户回复消息
  const userMsg: ChatMessage = {
    id: generateId(),
    role: 'user',
    content: formatInteractionValue(value),
    timestamp: new Date(),
  };
  messages.value.push(userMsg);

  // 调用后端 API 继续工作流执行
  if (currentRunId.value) {
    resumeWorkflow(value);
  }

  waitingForInput.value = false;
  waitingConfig.value = null;
};

// 处理交互取消（来自 ChatBox）
const handleInteractionCancel = (messageId: string) => {
  // 找到消息并移除交互配置
  const msgIndex = messages.value.findIndex((m) => m.id === messageId);
  if (msgIndex !== -1) {
    const msg = messages.value[msgIndex];
    if (msg) {
      messages.value[msgIndex] = { ...msg, interaction: undefined };
    }
  }

  // 添加用户回复消息
  const userMsg: ChatMessage = {
    id: generateId(),
    role: 'user',
    content:
      waitingConfig.value?.cancel_text ||
      $t('ai-platform.workflow.editor.chatPanel.cancel'),
    timestamp: new Date(),
  };
  messages.value.push(userMsg);

  // 调用后端 API 继续工作流执行（传入 false）
  if (currentRunId.value) {
    resumeWorkflow(false);
  }

  waitingForInput.value = false;
  waitingConfig.value = null;
};

// 恢复工作流执行
const resumeWorkflow = (userInput: any) => {
  if (!currentRunId.value) return;

  // 添加 AI 消息（pending 状态）
  const assistantMsgId = generateId();
  const assistantMsg: ChatMessage = {
    id: assistantMsgId,
    role: 'assistant',
    content: '',
    timestamp: new Date(),
    status: 'pending',
  };
  messages.value.push(assistantMsg);
  currentAssistantMsgId.value = assistantMsgId;

  running.value = true;

  cancelStream = resumeWorkflowStreamApi(
    currentRunId.value,
    userInput,
    (event: WorkflowStreamEvent) => {
      handleStreamEvent(event, assistantMsgId);
    },
    (error) => {
      console.error('Resume stream error:', error);
      updateAssistantMessage(assistantMsgId, {
        status: 'failed',
        error_message:
          error.message ||
          $t('ai-platform.workflow.editor.chatPanel.resumeFailed'),
      });
      running.value = false;
      ElMessage.error(
        error.message ||
          $t('ai-platform.workflow.editor.chatPanel.resumeWorkflowFailed'),
      );
    },
    () => {
      cancelStream = null;
    },
  );
};

// 格式化交互值显示
const formatInteractionValue = (value: any) => {
  if (value === true) {
    return (
      waitingConfig.value?.confirm_text ||
      $t('ai-platform.workflow.editor.chatPanel.confirm')
    );
  }
  if (Array.isArray(value)) {
    const options = waitingConfig.value?.options || [];
    const labels = value.map((v: string) => {
      const opt = options.find((o: any) => o.value === v);
      return opt?.label || v;
    });
    return labels.join(', ');
  }
  if (waitingConfig.value?.type === 'choice') {
    const options = waitingConfig.value?.options || [];
    const opt = options.find((o: any) => o.value === value);
    return opt?.label || value;
  }
  return String(value);
};

// 停止运行
const handleStop = () => {
  cancelStream?.();
  cancelStream = null;
  running.value = false;

  // 更新当前正在处理的 AI 消息状态
  if (currentAssistantMsgId.value) {
    updateAssistantMessage(currentAssistantMsgId.value, {
      status: 'failed',
      error_message: $t('ai-platform.workflow.editor.chatPanel.userStopped'),
    });
    currentAssistantMsgId.value = null;
  }
};

// 清空对话
const handleClear = () => {
  messages.value = [];
  streamingContent.value = '';
  emit('clear-status');
};

// 处理添加消息（来自 ChatBox 内部，如语音消息）
const handleAddMessage = (message: ChatMessage) => {
  messages.value.push(message);
};

// 处理更新消息（来自 ChatBox 内部，如语音识别完成）
const handleUpdateMessage = (
  messageId: string,
  updates: Partial<ChatMessage>,
) => {
  const idx = messages.value.findIndex((m) => m.id === messageId);
  if (idx !== -1) {
    messages.value[idx] = { ...messages.value[idx]!, ...updates };
  }
};

// 处理设计预览确认
onUnmounted(() => {
  cancelStream?.();
});
</script>

<template>
  <div class="flex h-full">
    <!-- 聊天面板 -->
    <div
      class="border-border bg-card flex h-full w-96 flex-col border-l shadow-xl"
    >
      <!-- 头部 -->
      <div
        class="border-border bg-muted/50 flex items-center justify-between border-b px-4 py-3"
      >
        <div class="text-foreground flex items-center gap-2 font-medium">
          {{ $t('ai-platform.workflow.editor.chatPanel.runPreview') }}
        </div>
        <div class="flex items-center gap-1">
          <!-- 变量设置按钮（多变量时显示） -->
          <ElButton
            v-if="hasMultipleVariables"
            link
            :icon="Settings2"
            :title="$t('ai-platform.workflow.editor.chatPanel.configVariables')"
            @click="variablesDialogVisible = true"
          />
          <ElButton link :icon="X" @click="$emit('close')" />
        </div>
      </div>

      <!-- ChatBox 组件 -->
      <ChatBox
        ref="chatBoxRef"
        :messages="messages"
        :loading="running"
        :streaming-content="streamingContent"
        :show-avatar="false"
        :assistant-name="
          $t('ai-platform.workflow.editor.chatPanel.assistantName')
        "
        :placeholder="$t('ai-platform.workflow.editor.chatPanel.placeholder')"
        :enable-attachment="false"
        :enable-image="false"
        :enable-voice="true"
        :show-clear-button="true"
        :empty-text="$t('ai-platform.workflow.editor.chatPanel.emptyText')"
        class="flex-1 rounded-none border-0"
        @send="handleSend"
        @stop="handleStop"
        @clear="handleClear"
        @interaction-submit="handleInteractionSubmit"
        @interaction-cancel="handleInteractionCancel"
        @add-message="handleAddMessage"
        @update-message="handleUpdateMessage"
      />

      <!-- 多变量输入对话框 -->
      <ElDialog
        v-model="variablesDialogVisible"
        :title="$t('ai-platform.workflow.editor.chatPanel.configVariables')"
        width="400px"
        :close-on-click-modal="false"
      >
        <ElForm label-position="top">
          <ElFormItem
            v-for="v in variables"
            :key="v.variable"
            :label="v.variable"
            :required="v.required"
          >
            <ElInput
              v-model="variablesForm[v.variable]"
              :placeholder="
                $t('ai-platform.workflow.editor.chatPanel.inputVariable', {
                  variable: v.variable,
                })
              "
              :type="v.type === 'text' ? 'textarea' : 'text'"
              :rows="v.type === 'text' ? 3 : undefined"
            />
          </ElFormItem>
        </ElForm>
        <template #footer>
          <ElButton @click="variablesDialogVisible = false">
            {{ $t('ai-platform.workflow.editor.chatPanel.cancel') }}
          </ElButton>
          <ElButton type="primary" @click="handleVariablesConfirm">
            {{ $t('ai-platform.workflow.editor.chatPanel.startRun') }}
          </ElButton>
        </template>
      </ElDialog>
    </div>
  </div>
</template>
