<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="t('新增数据源')"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="tsx" setup>
  import { h } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { addDatasource } from '/@/api/system/datasource';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const schema: FormSchema[] = [
    {
      field: 'name',
      label: t('数据源名称'),
      component: 'Input',
      required: true,
      title: t('基本信息'),
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请输入数据库名称'),
      },
    },
    {
      field: 'code',
      label: t('数据源编码'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请输入数据库类型'),
      },
    },
    {
      field: 'databaselinkId',
      label: t('选择数据库'),
      component: 'DbSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请选择数据库版本'),
      },
    },
    {
      field: 'sqlScript',
      label: t('SQL脚本'),
      component: 'Input',
      colProps: { span: 24 },
      required: true,
      render: ({ model, field }) => {
        return h(CodeEditor, {
          placeholder: t('请输入'),
          value: model[field],
          mode: MODE.SQL,
          style: {
            border: '1px solid #d9d9d9',
            padding: '5px 0',
          },
          onChange: (e) => {
            model[field] = e;
          },
        });
      },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请输入数据库链接'),
      },
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: schema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async () => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
  });

  async function handleSubmit() {
    try {
      const values = await validate();

      setDrawerProps({ confirmLoading: true });
      await addDatasource(values);
      notification.success({
        message: t('提示'),
        description: t('数据源新增成功！'),
      }); //提示消息
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
