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

defineOptions({ name: 'FlowNormalComponent' });

const lf: any = inject('lf');

const elementsInfoStore = useElementsInfoStore();
const selectedInfoStore = useSelectedInfoStore();

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

const elementInfo = computed(() => {
  return elementsInfoStore.getElementById(selectedInfoStore.selectId) || {};
});

watch(() => selectedInfoStore.selectId, (val) => {
  // console.log('...selectId', val);
  formState.value.id = elementInfo.value.id || '';
  formState.value.name = elementInfo.value.title || '';
}, { immediate: true });

watch(
  () => formState.value.name,
  (newName) => {
    const targetId = elementInfo.value?.id;
    if (!targetId) {
      return;
    }
    if (elementInfo.value.title === newName) {
      return;
    }
    elementsInfoStore.updateElement(targetId, { id: targetId, title: newName });
  },
);

watch(
  () => formState.value.id,
  (newId) => {
    const oldId = elementInfo.value?.id;
    if (oldId === newId) {
      return;
    }
    elementsInfoStore.updateElement(oldId, { id: newId, title: formState.value.name });
    lf.value.graphModel.flowId = newId;
    selectedInfoStore.setSelectId(newId);
    // selectedInfoStore.setSelectType('flow');
  },
);
</script>

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