<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    :helpMessage="['用户登录、忘记密码模板平台只提供{code}参数', '初始密码设置平台提供{name}参数']"
    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 './template.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveOrEditMessageTemplate } from '/@/api/message/template';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { findMessageConfig } from '/@/api/message/config';
  export default defineComponent({
    name: 'TemplateDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { validate, setFieldsValue, resetFields, updateSchema }] = 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.config;
          for (const key in config) {
            Reflect.set(data.record, key + '', config[key]);
          }
          await setFieldsValue(data.record);
          const res = await findMessageConfig({});
          const options = res.map((item) => {
            return {
              disabled: item.messageType !== data.record.messageType,
              label: item.configName,
              value: item.id,
            };
          });
          await updateSchema({
            field: 'messageConfigId',
            componentProps: {
              options,
            },
          });
          if (data.record.templatePurpose === 'FOR_LOGIN') {
            updateSchema({
              field: 'templatePurpose',
              helpMessage: `登录模板平台提供如下参数:
              {
                "code":"验证码"
              }`,
            });
          } else if (data.record.templatePurpose === 'FOR_FORGET_PASSWORD') {
            updateSchema({
              field: 'templatePurpose',
              helpMessage: `忘记密码模板平台提供如下参数:
              {
                "code":"验证码"
              }`,
            });
          } else if (data.record.templatePurpose === 'FOR_ALARM_NOTICE') {
            updateSchema({
              field: 'templatePurpose',
              helpMessage: `告警通知模板平台提供如下参数:
              {
                "type":"告警类型",
                "device_name":"设备名称",
                "severity":"告警等级",
                "organization":"设备所属组织",
                "createTime":告警时间
              }`,
            });
          } else if (data.record.templatePurpose === 'FOR_SET_PASSWORD') {
            updateSchema({
              field: 'templatePurpose',
              helpMessage: `清除密码模板平台提供如下参数:
              {
                "code":"验证码"
              }`,
            });
          }
        } else {
          updateSchema({
            field: 'templatePurpose',
            helpMessage: [],
          });
        }
      });

      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 saveOrEditMessageTemplate(values, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

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