<script setup lang="ts">
import type { NodeExecutionResult } from '../components/NodeResultCard.vue';

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

import {
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  Loader2,
  Workflow,
  XCircle,
} from '@vben/icons';

import { Handle, Position } from '@vue-flow/core';
import { ElButton, ElProgress, ElScrollbar, ElTooltip } from 'element-plus';

import { getWorkflowDetailApi } from '#/api/ai-platform/ai-platform';

import NodeResultCard from '../components/NodeResultCard.vue';

const props = defineProps<{
  data: any;
  id: string;
  selected: boolean;
}>();

// 展开状态
const expanded = ref(false);

// 子流程定义（用于展开显示）
const subflowDefinition = ref<any>(null);
const loadingSubflow = ref(false);

// 执行状态
const executionStatus = computed(() => props.data?.executionStatus);
const isRunning = computed(() => executionStatus.value?.status === 'running');
const isSuccess = computed(() => executionStatus.value?.status === 'success');
const isFailed = computed(() => executionStatus.value?.status === 'failed');

// 执行结果
const executionResult = computed<NodeExecutionResult | undefined>(() => {
  return props.data?.executionResult;
});

// 子流程执行日志
const subflowLogs = computed(() => {
  return (
    executionResult.value?.subflow_logs ||
    props.data?.subflow_result?.logs ||
    []
  );
});

// 子流程进度
const progress = computed(() => {
  if (subflowLogs.value.length === 0) return 0;
  const completed = subflowLogs.value.filter(
    (l: any) => l.status === 'completed',
  ).length;
  return Math.round((completed / subflowLogs.value.length) * 100);
});

// 当前执行的节点
const currentNodeLabel = computed(() => {
  const running = subflowLogs.value.find((l: any) => l.status === 'running');
  return running?.node_label || running?.node_type || '';
});

// 切换展开
const toggleExpand = async () => {
  expanded.value = !expanded.value;

  // 展开时加载子流程定义
  if (expanded.value && !subflowDefinition.value && props.data?.subflow_id) {
    await loadSubflowDefinition();
  }
};

// 加载子流程定义
const loadSubflowDefinition = async () => {
  if (!props.data?.subflow_id || loadingSubflow.value) return;

  loadingSubflow.value = true;
  try {
    const workflow = await getWorkflowDetailApi(props.data.subflow_id);
    subflowDefinition.value = workflow;
  } catch (error) {
    console.error('加载子流程定义失败:', error);
  } finally {
    loadingSubflow.value = false;
  }
};

// 获取节点执行状态
const getNodeStatus = (nodeId: string) => {
  const log = subflowLogs.value.find((l: any) => l.node_id === nodeId);
  if (!log) return 'pending';
  return log.status;
};

// 获取节点状态样式
const getNodeStatusClass = (nodeId: string) => {
  const status = getNodeStatus(nodeId);
  return {
    'border-blue-500 bg-blue-50 dark:bg-blue-950': status === 'running',
    'border-green-500 bg-green-50 dark:bg-green-950': status === 'completed',
    'border-red-500 bg-red-50 dark:bg-red-950': status === 'failed',
    'border-border bg-muted/30': status === 'pending',
  };
};

// 子流程节点列表（排除开始和结束节点）
const subflowNodes = computed(() => {
  if (!subflowDefinition.value?.definition?.nodes) return [];
  return subflowDefinition.value.definition.nodes.filter(
    (n: any) => n.type !== 'start' && n.type !== 'end',
  );
});

// 监听子流程ID变化，重新加载
watch(
  () => props.data?.subflow_id,
  (newId, oldId) => {
    if (newId !== oldId) {
      subflowDefinition.value = null;
      if (expanded.value && newId) {
        loadSubflowDefinition();
      }
    }
  },
);
</script>

<template>
  <div class="subflow-node-wrapper flex flex-col">
    <!-- 节点主体 -->
    <div
      class="bg-card group relative min-w-[320px] rounded-xl border shadow-sm transition-all duration-200 hover:shadow-md"
      :class="[
        selected ? 'border-primary ring-primary ring-1' : '',
        isRunning
          ? 'animate-pulse-border !border-blue-500 shadow-lg shadow-blue-500/20 ring-2 ring-blue-500/50'
          : '',
        isSuccess ? '!border-green-500 ring-1 ring-green-500' : '',
        isFailed ? '!border-red-500 ring-2 ring-red-500' : '',
        !selected && !executionStatus?.status ? 'border-border' : '',
      ]"
    >
      <!-- Status Badge -->
      <div
        v-if="executionStatus"
        class="absolute -top-3 right-4 z-10 flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] shadow-sm"
        :class="[
          isRunning
            ? 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400'
            : '',
          isSuccess
            ? 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400'
            : '',
          isFailed
            ? 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400'
            : '',
        ]"
      >
        <Loader2 v-if="isRunning" class="size-3 animate-spin" />
        <CheckCircle2 v-if="isSuccess" class="size-3" />
        <ElTooltip
          v-if="isFailed && executionStatus.error"
          :content="executionStatus.error"
          placement="top"
        >
          <XCircle class="size-3 cursor-help" />
        </ElTooltip>
        <XCircle v-else-if="isFailed" class="size-3" />
        <span v-if="isRunning">Running...</span>
        <span v-else-if="executionStatus.elapsed_time !== undefined">
          {{ executionStatus.elapsed_time }}ms
        </span>
      </div>

      <!-- Header -->
      <div
        class="border-border/50 flex items-center gap-3 rounded-t-xl border-b bg-gradient-to-r from-indigo-50 to-purple-50 px-4 py-3 dark:from-indigo-950 dark:to-purple-950"
      >
        <div
          class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-indigo-200 text-indigo-600 shadow-sm dark:bg-indigo-800 dark:text-indigo-400"
        >
          <Workflow class="size-5" />
        </div>
        <div class="flex flex-1 flex-col overflow-hidden">
          <div class="text-foreground truncate text-sm font-semibold">
            {{ data?.label || $t('ai-platform.workflow.nodes.subflow.label') }}
          </div>
          <div class="text-muted-foreground truncate text-[10px]">
            {{
              data?.subflow_name ||
              $t('ai-platform.workflow.nodes.subflow.desc')
            }}
          </div>
        </div>

        <!-- 展开/折叠按钮 -->
        <ElButton
          v-if="data?.subflow_id"
          link
          size="small"
          class="!p-1"
          @click.stop="toggleExpand"
        >
          <ChevronDown v-if="expanded" class="size-4" />
          <ChevronRight v-else class="size-4" />
        </ElButton>
      </div>

      <!-- Body -->
      <div class="text-muted-foreground space-y-2 p-4 text-xs">
        <!-- 子流程信息 -->
        <div
          v-if="data?.subflow_name"
          class="flex items-center justify-between"
        >
          <span>{{
            $t('ai-platform.workflow.nodes.subflow.subflowLabel')
          }}</span>
          <span class="font-medium text-indigo-600 dark:text-indigo-400">
            {{ data.subflow_name }}
          </span>
        </div>
        <div v-else class="text-muted-foreground">
          {{ $t('ai-platform.workflow.nodes.subflow.notSelected') }}
        </div>

        <!-- 变量传递模式 -->
        <div
          v-if="data?.var_pass_mode"
          class="flex items-center justify-between"
        >
          <span>{{
            $t('ai-platform.workflow.nodes.subflow.varPassMode')
          }}</span>
          <span class="text-muted-foreground">
            {{
              data.var_pass_mode === 'all'
                ? $t('ai-platform.workflow.nodes.subflow.all')
                : data.var_pass_mode === 'selected'
                  ? $t('ai-platform.workflow.nodes.subflow.selected')
                  : $t('ai-platform.workflow.nodes.subflow.none')
            }}
          </span>
        </div>

        <!-- 执行进度 -->
        <div v-if="isRunning && subflowLogs.length > 0" class="space-y-1">
          <div class="flex items-center justify-between">
            <span>{{ $t('ai-platform.workflow.nodes.subflow.progress') }}</span>
            <span>{{ progress }}%</span>
          </div>
          <ElProgress
            :percentage="progress"
            :show-text="false"
            :stroke-width="4"
          />
          <div v-if="currentNodeLabel" class="text-muted-foreground truncate">
            {{
              $t('ai-platform.workflow.nodes.subflow.current', {
                label: currentNodeLabel,
              })
            }}
          </div>
        </div>
      </div>

      <!-- 展开的子流程内容 -->
      <div v-if="expanded" class="border-border border-t">
        <div class="bg-muted/30 px-4 py-2">
          <div class="text-muted-foreground mb-2 text-xs font-medium">
            {{ $t('ai-platform.workflow.nodes.subflow.subflowNodes') }}
          </div>

          <!-- 加载中 -->
          <div
            v-if="loadingSubflow"
            class="flex items-center justify-center py-4"
          >
            <Loader2 class="size-4 animate-spin text-indigo-500" />
            <span class="text-muted-foreground ml-2 text-xs">{{
              $t('ai-platform.workflow.nodes.subflow.loading')
            }}</span>
          </div>

          <!-- 子流程节点列表 -->
          <ElScrollbar v-else-if="subflowNodes.length > 0" max-height="200px">
            <div class="space-y-2 pr-2">
              <div
                v-for="node in subflowNodes"
                :key="node.id"
                class="flex items-center gap-2 rounded border px-3 py-2 text-xs transition-colors"
                :class="getNodeStatusClass(node.id)"
              >
                <!-- 状态图标 -->
                <div class="shrink-0">
                  <Loader2
                    v-if="getNodeStatus(node.id) === 'running'"
                    class="size-3 animate-spin text-blue-500"
                  />
                  <CheckCircle2
                    v-else-if="getNodeStatus(node.id) === 'completed'"
                    class="size-3 text-green-500"
                  />
                  <XCircle
                    v-else-if="getNodeStatus(node.id) === 'failed'"
                    class="size-3 text-red-500"
                  />
                  <div
                    v-else
                    class="border-muted-foreground/30 size-3 rounded-full border-2"
                  ></div>
                </div>

                <!-- 节点信息 -->
                <div class="flex-1 truncate">
                  <span class="font-medium">{{
                    node.data?.label || node.type
                  }}</span>
                </div>

                <!-- 执行时间 -->
                <div
                  v-if="
                    subflowLogs.find((l: any) => l.node_id === node.id)
                      ?.elapsed_time
                  "
                  class="text-muted-foreground text-[10px]"
                >
                  {{
                    subflowLogs.find((l: any) => l.node_id === node.id)
                      ?.elapsed_time
                  }}ms
                </div>
              </div>
            </div>
          </ElScrollbar>

          <!-- 无节点 -->
          <div v-else class="text-muted-foreground py-4 text-center text-xs">
            {{
              data?.subflow_id
                ? $t('ai-platform.workflow.nodes.subflow.emptySubflow')
                : $t('ai-platform.workflow.nodes.subflow.selectSubflow')
            }}
          </div>
        </div>
      </div>

      <!-- Input Handle -->
      <Handle
        type="target"
        :position="Position.Left"
        id="target"
        class="!bg-primary !h-3 !w-3 !border-2 !border-white transition-transform hover:scale-125"
        :style="{ top: '28px' }"
      />

      <!-- Output Handle -->
      <Handle
        type="source"
        :position="Position.Right"
        id="source"
        class="!bg-primary !h-3 !w-3 !border-2 !border-white transition-transform hover:scale-125"
        :style="{ top: '28px' }"
      />
    </div>

    <!-- 执行结果卡片 -->
    <NodeResultCard
      v-if="executionResult"
      :result="executionResult"
      node-type="subflow"
      class="mt-3"
    />
  </div>
</template>

<style scoped>
.subflow-node-wrapper {
  position: relative;
}

/* 运行中边框呼吸动画 */
@keyframes pulse-border {
  0%,
  100% {
    box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.4);
  }
  50% {
    box-shadow: 0 0 0 8px rgba(99, 102, 241, 0);
  }
}

.animate-pulse-border {
  animation: pulse-border 1.5s ease-in-out infinite;
}
</style>
