<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';

interface DataType {
  data: {
    description: string;
    name: string;
  };
}

const [TemplateForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '模板名称',
      },

      fieldName: 'name',
      label: '模板名称',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模板描述',
      },
      fieldName: 'description',
      label: '模板描述',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

function onSubmit(values: Record<string, any>) {
  ElMessage.success(`form values: ${JSON.stringify(values)}`);
}

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<DataType>();
      if (data) {
        // 动态更新表单的默认值
        formApi.setValues({
          name: data.data.name,
          description: data.data.description,
        });
      }
    }
  },
});
</script>

<template>
  <Modal title="编辑模板" :footer="false">
    <TemplateForm />
  </Modal>
</template>
