<template>
  <div class="task-node-wrapper">
    <!-- 左侧连接点（输入） -->
    <Handle type="target" :position="Position.Left" id="left" />
    <!-- 右侧连接点（输出） -->
    <Handle type="source" :position="Position.Right" id="right" />
    <!-- 底部连接点（用于分支） -->
    <Handle type="source" :position="Position.Bottom" id="bottom" />

    <el-card
      class="task-node-card"
      :class="{
        'is-editing': isEditing,
        'is-active': isActive,
        'is-branch-selected': props.isBranchSelected
      }"
      :shadow="true"
    >
      <!-- 任务名称 -->
      <div class="task-name">{{ task.StepName }}</div>

      <!-- 智能体列表 -->
      <div class="agents-container">
        <el-tooltip
          v-for="agentSelection in task.AgentSelection"
          :key="agentSelection"
          effect="light"
          placement="top"
          :show-after="500"
          popper-class="task-syllabus-tooltip-popper"
        >
          <template #content>
            <div class="agent-tooltip">
              <div class="text-[16px] font-bold">{{ agentSelection }}</div>
              <div class="h-[1px] w-full bg-[#494B51] my-[4px]"></div>
              <div class="text-[12px]">
                {{ task.TaskProcess.find(i => i.AgentName === agentSelection)?.Description }}
              </div>
            </div>
          </template>
          <div class="agent-icon" :style="{ background: getAgentIcon(agentSelection).color }">
            <svg-icon :icon-class="getAgentIcon(agentSelection).icon" color="#fff" size="20px" />
          </div>
        </el-tooltip>
      </div>
    </el-card>

    <!-- 底部添加按钮（卡片外部） -->
    <div v-if="!isAddingBranch" class="external-add-btn" @click="startAddBranch">
      <el-icon :size="20" color="#409eff">
        <CirclePlus />
      </el-icon>
    </div>

    <!-- 取消按钮（输入框显示时） -->
    <div v-else class="external-add-btn cancel-btn" @click="cancelAddBranch">
      <el-icon :size="20" color="#f56c6c">
        <Remove />
      </el-icon>
    </div>

    <!-- 外部输入框 -->
    <div v-if="isAddingBranch" class="external-input-container">
      <el-input
        v-model="branchInput"
        placeholder="输入分支需求..."
        size="small"
        @keydown="handleBranchKeydown"
        ref="branchInputRef"
        class="branch-input"
      >
        <template #suffix>
          <svg-icon
            icon-class="paper-plane"
            size="16px"
            color="#409eff"
            class="submit-icon"
            :class="{ 'is-disabled': !branchInput.trim() }"
            @click="submitBranch"
          />
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import { Handle, Position } from '@vue-flow/core'
import { type IRawStepTask } from '@/stores'
import { getAgentMapIcon } from '@/layout/components/config'
import SvgIcon from '@/components/SvgIcon/index.vue'

interface TaskNodeData {
  task: IRawStepTask
  isEditing: boolean
  editingContent: string
}

// 使用更宽松的类型定义来避免类型错误
const props = defineProps<{
  id: string
  data: TaskNodeData
  isAddingBranch?: boolean
  isBranchSelected?: boolean // 是否属于选中的分支路径
  [key: string]: any
}>()

const emit = defineEmits<{
  (e: 'edit-task', nodeId: string): void
  (e: 'save-task', nodeId: string, content: string): void
  (e: 'cancel-edit', nodeId: string): void
  (e: 'add-branch', nodeId: string, branchContent: string): void
  (e: 'start-add-branch', nodeId: string): void
  (e: 'cancel-add-branch'): void
}>()

const editingContent = ref(props.data.task.TaskContent || '')

// 分支添加相关状态（使用父组件传入的 prop）
const branchInput = ref('')
const branchInputRef = ref<InstanceType<typeof HTMLInputElement>>()

// 计算属性，使用父组件传入的状态
const isAddingBranch = computed(() => props.isAddingBranch || false)

const isEditing = computed({
  get: () => props.data.isEditing,
  set: value => {
    if (!value) {
      emit('cancel-edit', props.id)
    }
  }
})

const isActive = computed(() => {
  return props.data.task.StepName === props.data.task.StepName
})

const task = computed(() => props.data.task)

const getAgentIcon = (agentName: string) => {
  return getAgentMapIcon(agentName)
}

const startEdit = () => {
  emit('edit-task', props.id)
}

const saveEdit = () => {
  emit('save-task', props.id, editingContent.value)
}

const cancelEdit = () => {
  emit('cancel-edit', props.id)
}

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    saveEdit()
  } else if (event.key === 'Escape') {
    cancelEdit()
  }
}

// 分支添加相关方法
const startAddBranch = () => {
  emit('start-add-branch', props.id)
  branchInput.value = ''
  nextTick(() => {
    branchInputRef.value?.focus()
  })
}

const cancelAddBranch = () => {
  emit('cancel-add-branch')
  branchInput.value = ''
}

const submitBranch = () => {
  if (branchInput.value.trim()) {
    emit('add-branch', props.id, branchInput.value.trim())
    branchInput.value = ''
  }
}

const handleBranchKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    submitBranch()
  } else if (event.key === 'Escape') {
    cancelAddBranch()
  }
}
</script>

<style scoped lang="scss">
.task-node-card {
  width: 150px;
  min-height: 100px;
  background-color: var(--color-card-bg-task);
  border: 1px solid var(--color-card-border-task);
  box-sizing: border-box;
  transition: all 0.2s ease;
  cursor: pointer;

  &:hover {
    background-color: var(--color-card-bg-task-hover);
    border-color: var(--color-card-border-hover);
    box-shadow: var(--color-card-shadow-hover);
  }

  &.is-active {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  // 分支选中高亮样式（绿色）
  &.is-branch-selected {
    border-color: #67c23a;
    box-shadow: 0 0 0 3px rgba(103, 194, 58, 0.3);
    background-color: rgba(103, 194, 58, 0.05);

    &:hover {
      border-color: #67c23a;
      box-shadow: 0 0 0 3px rgba(103, 194, 58, 0.4);
      background-color: rgba(103, 194, 58, 0.08);
    }
  }

  &.is-editing {
    cursor: default;
  }

  :deep(.el-card__body) {
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    position: relative;
  }
}

.task-name {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  color: var(--color-text-title-header);
  word-break: break-word;
}

.divider {
  height: 1px;
  width: 100%;
  background: var(--color-border-separate);
  margin: 4px 0;
}

.task-content {
  font-size: 14px;
  color: var(--color-text-secondary);
  min-height: 40px;
  word-break: break-word;
  white-space: pre-wrap;
  line-height: 1.5;
}

.task-content-editing {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.edit-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.agents-container {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: center;
}

.agent-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s ease;

  &:hover {
    transform: scale(1.1);
  }
}

.input-outputs {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  font-size: 12px;
}

.input-label {
  font-weight: bold;
  color: var(--color-text-secondary);
}

.agent-tooltip {
  padding: 8px;
  max-width: 200px;
}

// 编辑器样式
.task-content-editor {
  :deep(.el-textarea__inner) {
    font-size: 14px;
    color: var(--color-text-secondary);
    background: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    resize: none;
  }
}

// 节点包装器（用于容纳外部按钮）
.task-node-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 外部添加按钮
.external-add-btn {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #fff;
  border: 2px solid #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

  &:hover {
    background: #409eff;
    transform: translateX(-50%) scale(1.1);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

    .el-icon {
      color: #fff;
    }
  }

  &:active {
    transform: translateX(-50%) scale(0.95);
  }

  // 取消按钮样式
  &.cancel-btn {
    border-color: #f56c6c;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);

    &:hover {
      background: #f56c6c;
      box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
    }
  }
}

// 外部输入容器
.external-input-container {
  position: absolute;
  bottom: -80px;
  left: 50%;
  transform: translateX(-50%);
  width: 260px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 100;
  animation: slideDown 0.2s ease-out;

  &::before {
    content: '';
    position: absolute;
    top: -6px;
    left: 50%;
    transform: translateX(-50%);
    width: 12px;
    height: 12px;
    background: #fff;
    border-left: 1px solid #dcdfe6;
    border-top: 1px solid #dcdfe6;
    transform: translateX(-50%) rotate(45deg);
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.add-branch-section {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed var(--color-border-separate);
  display: flex;
  justify-content: center;
  align-items: center;
}

.add-branch-btn {
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    transform: scale(1.1);
  }

  &:active {
    transform: scale(0.95);
  }
}

.branch-input-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.branch-input {
  width: 100%;

  :deep(.el-input__wrapper) {
    background: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: none;

    &:hover {
      border-color: #c0c4cc;
    }

    &.is-focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    .el-input__inner {
      font-size: 13px;
      color: var(--color-text-primary);
      padding-right: 40px;
    }
  }
}

// 提交图标样式
.submit-icon {
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;

  &:hover:not(.is-disabled) {
    transform: scale(1.1);
  }

  &:active:not(.is-disabled) {
    transform: scale(0.95);
  }

  &.is-disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
}

.is-adding-branch {
  .task-node-card {
    border-color: #409eff;
  }
}
</style>

<style>
.task-syllabus-tooltip-popper {
  z-index: 4000 !important;
}
</style>
