<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { useElementsInfoStore } from '../../stores/elementsInfo.ts';
import { useSelectedInfoStore } from '../../stores/selectedInfo.ts';

defineOptions({ name: 'NormalComponent' });

const lf: any = inject('lf');
const elementsInfoStore = useElementsInfoStore();
const selectedInfoStore = useSelectedInfoStore();

const elementInfo = computed(() => {
  // console.log('selectedInfoStore.selectId:', selectedInfoStore.selectId);
  return elementsInfoStore.getElementById(selectedInfoStore.selectId) || {};
});

const formState = reactive({
  id: '',
  name: '',
});

watch(elementInfo, (val) => {
  formState.id = val.id || '';
  formState.name = val.title || '';
}, { immediate: true });

function handleIdBlur() {
  // console.log('formState.id:', formState.id);
  if (formState.id === elementInfo.value.id) {
    return;
  }
  const element = elementsInfoStore.getElementById(formState.id);
  if (element) {
    // 存在相同id且不是当前节点
    message.error('id已存在');
  }
  else {
    // 更新节点信息
    lf.value.changeNodeId(elementInfo.value.id, formState.id);
    elementsInfoStore.updateElement(elementInfo.value.id, {
      id: formState.id,
    });
    // 更新选中节点
    selectedInfoStore.setSelectId(formState.id);
  }
}

function handleNameBlur() {
  // console.log('formState.name:', formState.name);
  if (formState.name === elementInfo.value.title) {
    return;
  }
  elementsInfoStore.updateElement(formState.id, {
    title: formState.name,
  });

  // 更新选中的边文本
  // if (selectedInfoStore.selectType === 'custom-bezier-edge') {
  //   lf.value.updateText(formState.id, formState.name);
  // }

  lf.value.updateText(formState.id, formState.name);
  lf.value.setProperties(formState.id, {
    title: formState.name,
  });
}
</script>

<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ style: { width: '80px' } }"
    autocomplete="off"
  >
    <a-form-item
      label="ID"
      name="id"
      :rules="[{ required: true, message: '请输入id' }]"
    >
      <a-input v-model:value="formState.id" @blur="handleIdBlur" />
    </a-form-item>
    <a-form-item
      label="名称"
      name="name"
      :rules="[{ required: true, message: '请输入名称' }]"
    >
      <a-input v-model:value="formState.name" @blur="handleNameBlur" />
    </a-form-item>
  </a-form>
</template>
