<script setup lang="ts">
import { computed } from 'vue'
import { useAgentsStore, useSelectionStore } from '@/stores'

const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()
const emit = defineEmits<{
  (e: 'click'): void
}>()

const props = defineProps<{
  step?: any
}>()

// 获取分支数量
const branchCount = computed(() => {
  if (!props.step?.Id) return 1

  const taskStepId = props.step.Id
  // 获取该任务的 agent 组合
  const agents = props.step.AgentSelection || []
  const branches = selectionStore.getTaskProcessBranches(taskStepId, agents)
  return branches.length || 1
})

// 判断按钮是否可点击
const isClickable = computed(() => {
  if (!props.step?.Id || !agentsStore.currentTask?.Id) {
    return false
  }
  return props.step.Id === agentsStore.currentTask.Id
})

const handleClick = (event?: MouseEvent) => {
  if (!isClickable.value) {
    return
  }

  // 阻止冒泡，避免触发卡片点击
  if (event) {
    event.stopPropagation()
  }

  emit('click')
  // 设置当前任务
  if (props.step) {
    agentsStore.setCurrentTask(props.step)
  }
  agentsStore.openPlanTask()
}
</script>

<template>
  <div
    class="task-button"
    :class="{ 'has-branches': branchCount > 1, 'is-disabled': !isClickable }"
    @click="handleClick"
    :title="isClickable ? `${branchCount} 个分支` : '请先在任务大纲中选中此任务'"
  >
    <!-- 流程图标 -->
    <svg-icon icon-class="branch" size="20px" class="task-icon" />

    <!-- 分支数量显示 -->
    <span class="branch-count">
      {{ branchCount }}
    </span>
  </div>
</template>

<style scoped lang="scss">
.task-button {
  /* 定位 - 右下角 */
  position: absolute;
  right: 0;
  bottom: 0;

  /* 尺寸 */
  width: 36px;
  height: 32px;

  /* 样式 */
  background-color: #43a8aa;
  border-radius: 10px 0 0 0;
  cursor: pointer;
  user-select: none;
  z-index: 100;

  /* 布局 */
  display: flex;
  align-items: center;
  justify-content: center;

  /* 交互 */
  transition: all 0.2s ease;

  &:hover {
    filter: brightness(0.9);
  }

  // 禁用状态
  &.is-disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
    opacity: 0.6;

    &:hover {
      filter: none;
    }
  }

  &.has-branches::after {
    content: '';
    position: absolute;
    top: -2px;
    right: -2px;
    width: 8px;
    height: 8px;
    background: #ff6b6b;
    border-radius: 50%;
    border: 2px solid white;
  }
}

.task-icon {
  color: white;
}

.branch-count {
  position: absolute;
  right: 4px;
  bottom: 2px;
  font-size: 12px;
  color: white;
  font-weight: 800;
  text-align: right;
  line-height: 1;
}
</style>
