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

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { cdcmTemplateAPI } from '#/cdcm/api/api.js';
import req from '#/cdcm/api/req_code';

interface DataType {
  data: {
    description: string;
    id: Number;
    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: '模板名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模板描述',
      },
      fieldName: 'description',
      label: '模板描述',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

async function onSubmit(values: Record<string, any>) {
  const param = {
    ...values,
    id: modalApi.getData<DataType>().data.id,
  };
  const ret = await cdcmTemplateAPI(param, req.TemplateUpdate);
  if (ret.data.code === 0) {
    ElMessage.success(ret.data.data);
    modalApi.close();
  } else {
    ElMessage.error(ret.data.data || ret.data.msg);
  }
}

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>
