<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    destroyOnClose
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <div class="model-box">
      <ModalModal v-if="open" ref="modalModalRef" :editId="editId" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import ModalModal from './Modal.vue';
  import { add, edit } from '/@/api/system/generator/messageTemplate';
  const { t } = useI18n();
  const isUpdate = ref<boolean>(false);
  const open = ref(false);
  const editId = ref('');
  const modalModalRef = ref();
  export default defineComponent({
    name: 'FormModal',
    components: {
      BasicModal,
      ModalModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { notification } = useMessage();

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        editId.value = '';
        if (isUpdate.value) {
          editId.value = data.id;
        }
        open.value = true;
      });

      const getTitle = computed(() => (!isUpdate.value ? t('新增消息模板') : t('编辑消息模板')));
      async function handleSubmit() {
        try {
          let formState = await modalModalRef.value.handleSubmit();
          if (formState) {
            setModalProps({ confirmLoading: true });
            if (!isUpdate.value) {
              //新增
              await add(formState);
              notification.success({
                message: t('提示'),
                description: t('新增消息模板成功'),
              }); //提示消息
            } else {
              // 编辑
              await edit(formState);
              notification.success({
                message: t('提示'),
                description: t('修改消息模板成功'),
              }); //提示消息
            }
            closeModal();
            emit('success');
          } else {
            setModalProps({ confirmLoading: false });
          }
        } catch (error) {
          setModalProps({ confirmLoading: false });
        }
      }
      return {
        registerModal,
        getTitle,
        handleSubmit,
        t,
        open,
        editId,
        modalModalRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  .model-box {
    padding: 16px;
  }
</style>
