<script lang="ts" setup>
import { message } from 'ant-design-vue';

import { createNodeApi, NodeType } from '#/api/core';

const props = defineProps<{
  definitionId: string;
}>();

const emit = defineEmits<{
  created: [];
}>();

interface NodeTypeInfo {
  color: string;
  defaultName: string;
  label: string;
  type: NodeType;
}

const nodeTypes: NodeTypeInfo[] = [
  {
    type: NodeType.Start,
    label: '开始',
    color: '#52c41a',
    defaultName: '开始',
  },
  { type: NodeType.End, label: '结束', color: '#ff4d4f', defaultName: '结束' },
  {
    type: NodeType.Approval,
    label: '审批',
    color: '#1890ff',
    defaultName: '审批节点',
  },
  {
    type: NodeType.Cc,
    label: '抄送',
    color: '#8c8c8c',
    defaultName: '抄送节点',
  },
  {
    type: NodeType.Condition,
    label: '条件',
    color: '#fa8c16',
    defaultName: '条件节点',
  },
  {
    type: NodeType.Parallel,
    label: '并行',
    color: '#722ed1',
    defaultName: '并行节点',
  },
  {
    type: NodeType.SubProcess,
    label: '子流程',
    color: '#13c2c2',
    defaultName: '子流程节点',
  },
];

async function handleAddNode(info: NodeTypeInfo) {
  try {
    const x = 200 + Math.floor(Math.random() * 200);
    const y = 200 + Math.floor(Math.random() * 200);
    await createNodeApi(props.definitionId, {
      name: info.defaultName,
      nodeType: info.type,
      positionX: x,
      positionY: y,
    });
    message.success(`已添加${info.label}节点`);
    emit('created');
  } catch {
    message.error('添加节点失败');
  }
}
</script>

<template>
  <div class="h-full w-48 border-r bg-gray-50 p-3">
    <div class="mb-3 text-sm font-semibold text-gray-600">节点面板</div>
    <div class="flex flex-col gap-2">
      <button
        v-for="info in nodeTypes"
        :key="info.type"
        class="flex items-center gap-2 rounded border border-gray-200 px-3 py-2 text-left text-sm transition-colors hover:border-blue-300 hover:bg-blue-50"
        @click="handleAddNode(info)"
      >
        <span
          :style="{ backgroundColor: info.color }"
          class="inline-block h-3 w-3 rounded-sm"
        />
        <span>{{ info.label }}</span>
      </button>
    </div>
  </div>
</template>
