<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveOrEditMessageConfig } from '/@/api/message/config';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'ConfigDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          const { config } = data.record;
          for (const key in config) {
            Reflect.set(data.record, key + '', config[key]);
          }
          const editRecord = JSON.parse(JSON.stringify(data.record));
          Reflect.deleteProperty(editRecord, 'config');
          await setFieldsValue(editRecord);
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增消息配置' : '编辑消息配置'));

      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const values = await validate();
          const { createMessage } = useMessage();
          let config = {};
          if (values.messageType === 'PHONE_MESSAGE') {
            config = {
              accessKeyId: values.accessKeyId,
              accessKeySecret: values.accessKeySecret,
            };
          } else if (values.messageType === 'EMAIL_MESSAGE') {
            config = {
              host: values.host,
              port: values.port,
              username: values.username,
              password: values.password,
            };
          }
          Reflect.set(values, 'config', config);
          let saveMessage = '添加成功';
          let updateMessage = '修改成功';
          await saveOrEditMessageConfig(values, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
