<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm" />
    <template #insertFooter>
      <a-button type="primary" danger @click="handleTest"> {{ t('测试链接') }} </a-button>
    </template>
  </BasicModal>
</template>
<script lang="tsx" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    addDatabaseLink,
    getDatabaseLink,
    updateDatabaseLink,
    testDatabaseLink,
  } from '/@/api/system/databaselink';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { AesEncryption, encryptByBase64, decodeByBase64 } from '/@/utils/cipher';

  const { t } = useI18n();
  const accountFormSchema: FormSchema[] = [
    {
      field: 'dbName',
      label: t('数据库名称'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'dbType',
      label: t('数据库类型'),
      component: 'Select',
      required: true,
      componentProps: {
        options: [
          { label: 'mysql', value: 'mysql' },
          { label: 'sqlserver', value: 'sqlserver' },
          { label: 'oracle', value: 'oracle' },
          { label: 'pgsql', value: 'pgsql' },
          { label: 'dm', value: 'dm' },
          { label: 'mariadb', value: 'mariadb' },
          { label: 'sqlite', value: 'sqlite' },
          { label: 'gbase', value: 'gbase' },
          { label: 'oceanbase', value: 'oceanbase' },
          { label: 'h2', value: 'h2' },
          { label: 'db2', value: 'db2' },
          { label: 'yashan', value: 'yashan' },
        ],
      },
      colProps: { span: 24 },
    },
    {
      field: 'dbVersion',
      label: t('数据库版本'),
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'driver',
      label: '驱动',
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'host',
      label: t('链接'),
      required: true,
      component: 'InputTextArea',
      colProps: { span: 24 },
    },
    {
      field: 'username',
      label: t('账号'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'password',
      label: t('密码'),
      component: 'InputPassword',
      componentProps: {
        visibilityToggle: true,
      },
      required: true,
      colProps: { span: 24 },
    },
  ];

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

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const loading = ref(false);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, width: '40%' });

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getDatabaseLink(data.id);
      if (record.password) {
        try {
          record.password = encryption.decryptByAES(decodeByBase64(record.password));
        } catch (error) {}
      }
      setFieldsValue({
        ...record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增数据库链接') : t('编辑数据库链接')));
  //对称加密
  const encryption = new AesEncryption({
    key: '1234567890123456', //MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAILpJXAOe3EwQfZkbIaUsCCa6J8dqTpEbDpHlB8Yu8N9aMhgjoMcbhMp4cVF9nb3inJIWOmYj4y6Tj4XYCVMd3cCAwEAAQ==
  });

  const handleTest = async () => {
    const values = await validate();
    values.password = encryptByBase64(encryption.encryptByAES(values.password));
    const ok = await testDatabaseLink(values);
    loading.value = true;
    if (!ok) {
      notification.error({
        message: t('提示'),
        type: 'warning',
        description: t('未能连接上数据库'),
      }); //提示消息
    } else {
      notification.success({
        message: t('提示'),
        description: t('成功'),
      }); //提示消息
    }
    loading.value = false;
  };

  async function handleSubmit() {
    try {
      const values = await validate();
      values.password = encryptByBase64(encryption.encryptByAES(values.password));
      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addDatabaseLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接新增成功！'),
        }); //提示消息
      } else {
        values.id = unref(rowId);
        await updateDatabaseLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接修改成功！'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
