<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';
import { useStaticConfigStore } from '#/store';

const [Modal, modalApi] = useVbenModal();

const template_types = useStaticConfigStore().support_template_types;

const get_template_types = () => {
  return template_types.map((item) => {
    return {
      label: item,
      value: item,
    };
  });
};

const [TemplateForm] = 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: '模板描述',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: get_template_types(),
        placeholder: '选择模板',
        showSearch: true,
      },
      fieldName: 'template_type',
      label: '模板类型',
      rules: 'required',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

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

<template>
  <Modal title="新增模板" :footer="false">
    <TemplateForm />
  </Modal>
</template>
