<template>
  <div>
    <div @click.stop="openModal"> <slot></slot></div>
    <ModalPanel
      :visible="open"
      :width="1100"
      :title="props.btnName"
      @submit="submit"
      @close="close"
    >
      <div class="content-box"
        ><ModalDrawer v-if="open" ref="modalDrawerRef" v-bind="$attrs"
      /></div>
    </ModalPanel>
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import ModalDrawer from './ViewModal.vue';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { addFormView, updateFormView } from '/@/api/form/view';
  const { notification } = useMessage();
  const { t } = useI18n();
  const modalDrawerRef = ref();
  const open = ref(false);
  const props = defineProps({
    btnName: {
      type: String,
      default: '',
    },
  });
  const emits = defineEmits(['refresh']);
  async function submit() {
    try {
      let res = await modalDrawerRef.value.handleSubmit();
      if (res) {
        if (res.id) {
          let val = await updateFormView(res);
          if (val) {
            open.value = false;
            notification.success({
              message: t('提示'),
              description: t('编辑成功'),
            });
            emits('refresh', res);
          } else {
            notification.error({
              message: t('提示'),
              description: t('编辑失败'),
            });
          }
        } else {
          let val = await addFormView(res);
          if (val) {
            open.value = false;
            notification.success({
              message: t('提示'),
              description: t('添加成功'),
            });
            emits('refresh', res);
          } else {
            notification.error({
              message: t('提示'),
              description: t('添加失败'),
            });
          }
        }
      }
    } catch (error) {
      notification.error({
        message: t('提示'),
        description: t('添加失败'),
      });
    }
  }
  function close() {
    open.value = false;
  }
  function openModal() {
    open.value = true;
  }
</script>
<style lang="less" scoped>
  .content-box {
    padding: 0 16px;
    height: 100%;
  }
</style>
