<script lang="ts" setup>
import type { WorkflowNodeDto } from '#/api/core';

import { ref, watch } from 'vue';

import { Drawer, Form, Input, message } from 'ant-design-vue';

import { deleteNodeApi, updateNodeApi } from '#/api/core';

const props = defineProps<{
  definitionId: string;
  nodeId: string;
  nodes: WorkflowNodeDto[];
}>();

const emit = defineEmits<{
  close: [];
  updated: [node: WorkflowNodeDto];
}>();

const formState = ref({
  name: '',
  config: '',
});

watch(
  () => props.nodeId,
  () => {
    const node = props.nodes.find((n) => n.id === props.nodeId);
    if (node) {
      formState.value = {
        name: node.name,
        config: node.config ?? '',
      };
    }
  },
  { immediate: true },
);

const loading = ref(false);

async function handleSave() {
  if (!formState.value.name.trim()) {
    message.warning('节点名称不能为空');
    return;
  }
  loading.value = true;
  try {
    const node = props.nodes.find((n) => n.id === props.nodeId);
    if (!node) return;
    const result = await updateNodeApi(props.definitionId, props.nodeId, {
      name: formState.value.name,
      config: formState.value.config || undefined,
      positionX: node.positionX,
      positionY: node.positionY,
    });
    message.success('保存成功');
    emit('updated', result);
  } catch {
    message.error('保存失败');
  } finally {
    loading.value = false;
  }
}

async function handleDelete() {
  loading.value = true;
  try {
    await deleteNodeApi(props.definitionId, props.nodeId);
    message.success('节点已删除');
    emit('close');
  } catch {
    message.error('删除节点失败');
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <Drawer :open="!!nodeId" title="节点属性" :width="360" @close="emit('close')">
    <Form layout="vertical">
      <Form.Item label="节点名称" required>
        <Input v-model:value="formState.name" placeholder="请输入节点名称" />
      </Form.Item>
      <Form.Item label="配置 JSON">
        <Input.TextArea
          v-model:value="formState.config"
          :rows="4"
          placeholder='{"assigneeRule":"role:manager"}'
        />
      </Form.Item>
    </Form>
    <div class="flex gap-2">
      <button
        class="rounded bg-blue-500 px-4 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
        :disabled="loading"
        @click="handleSave"
      >
        保存
      </button>
      <button
        class="rounded bg-red-500 px-4 py-2 text-sm text-white hover:bg-red-600 disabled:opacity-50"
        :disabled="loading"
        @click="handleDelete"
      >
        删除节点
      </button>
    </div>
  </Drawer>
</template>
