<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 { useI18n } from '/@/hooks/web/useI18n';
  import { addIotLink, getIotLink, testIotLink, updateIotLink } from '/@/api/iot';
  const { t } = useI18n();
  const accountFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('链接名称'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'protocolType',
      label: t('协议类型'),
      component: 'Select',
      required: true,
      componentProps: {
        options: [
          { label: 'MQTT', value: 0 },
          { label: 'OPC.UA', value: 1 },
        ],
      },
      colProps: { span: 24 },
    },
    {
      field: 'hostUrl',
      label: t('数据源地址'),
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'clientId',
      label: t('客户端id'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'topic',
      label: t('订阅主题'),
      component: 'Input',
      componentProps: {
        visibilityToggle: true,
      },
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'Input',
      componentProps: {
        visibilityToggle: 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;
      console.log(rowId.value);
      const record = await getIotLink(data.id);

      setFieldsValue({
        ...record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增数据库链接') : t('编辑数据库链接')));

  const handleTest = async () => {
    const values = await validate();
    console.log('handleTest');

    const ok = await testIotLink(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();

      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addIotLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接新增成功！'),
        }); //提示消息
      } else {
        values.id = unref(rowId);
        await updateIotLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接修改成功！'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
