<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form';
import type { FormExpose } from 'ant-design-vue/es/form/Form';
import type { Field } from '../../../../ts/flow.d';
import { useToggle } from '@vueuse/core';

defineOptions({
  name: 'DrawerExpand',
});

const emit = defineEmits(['submit']);

const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }],
  type: [{ required: true, message: '请选择字段类型', trigger: ['blur', 'change'] }],
};

const [open, setOpen] = useToggle(false);
const formRef = ref<FormExpose>();
const form = ref<Field>({});

async function onOpen(key: string, record?: Field, index?: number) {
  setOpen(true);
  if (key === 'add') {
    form.value = {};
  }
  else if (key === 'edit' && record) {
    form.value = { ...record };
    form.value.index = index;
  }
}
const [loading, setLoading] = useToggle(false);

function onSubmit() {
  formRef.value?.validate().then(() => {
    setLoading(true);
    const params: Field = { ...form.value };
    emit('submit', params);
    setLoading(false);
    setOpen(false);
  });
}

function close() {
  setOpen(false);
}

defineExpose({
  open: onOpen,
});
</script>

<template>
  <a-drawer
    v-model:open="open"
    title="字段配置"
    placement="right"
    :width="420"
    destroy-on-close
    :footer-style="{ textAlign: 'right' }"
    @close="close"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 5 }"
    >
      <a-form-item label="字段名称" name="name">
        <a-input v-model:value="form.name" :maxlength="60" />
      </a-form-item>
      <a-form-item label="字段类型" name="type">
        <a-select v-model:value="form.type" placeholder="请选择字段类型">
          <a-select-option value="字符串">
            字符串
          </a-select-option>
          <a-select-option value="表达式">
            表达式
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="form.type === '字符串'" label="字段值" name="value" :rules="[{ required: true, message: '请输入字段值', trigger: ['blur', 'change'] }]">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.type === '表达式'" label="表达式" name="value" :rules="[{ required: true, message: '请输入表达式', trigger: ['blur', 'change'] }]">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="close">
          取消
        </a-button>
        <a-button type="primary" :loading="loading" @click="onSubmit()">
          提交
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
