<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @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 { saveOrEditAlarmContact } from '/@/api/alarm/contact/alarmContact';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'ContactDrawer',
    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)) {
          if (data.record.organizationDTO) {
            await setFieldsValue(data.record);
          } else {
            Reflect.deleteProperty(data.record, 'organizationId');
            await setFieldsValue(data.record);
          }
        }
      });

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

      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();
          const values = await validate();
          let saveMessage = '添加成功';
          let updateMessage = '修改成功';
          await saveOrEditAlarmContact(values, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

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