<script lang="ts">
import { computed, defineComponent, getCurrentInstance, onMounted, ref, unref, useAttrs } from 'vue';
import { deepMerge } from '@/utils/zt';
import { basicModalProps } from './props';
import type { ModalMethods, modalProps } from './types';

export default defineComponent({
  name: 'BasicModal',
  props: { ...basicModalProps },
  emits: ['register', 'close', 'ok'],
  setup(props, { emit }) {
    const attrs = useAttrs();
    const propsRef = ref<Partial<typeof basicModalProps> | null>(null);
    const isModal = ref(false);
    const subLoading = ref(false);
    const loading = ref(false);
    const instance = getCurrentInstance();

    const getProps = computed((): modalProps => {
      return { ...props, ...unref(propsRef) } as unknown as modalProps;
    });

    async function setModalProps(modalProps: Partial<modalProps>): Promise<void> {
      propsRef.value = deepMerge(unref(propsRef) || {}, modalProps);
    }

    const getBindValue = computed(() => {
      return {
        ...attrs,
        ...unref(getProps)
      };
    });

    function setSubLoading(status: boolean) {
      subLoading.value = status;
    }

    function openModal() {
      isModal.value = true;
    }

    function closeModal() {
      isModal.value = false;
      subLoading.value = false;
      emit('close');
    }
    function handleSubmit() {
      // subLoading.value = true;
      emit('ok');
    }
    function setModalLoading(status: boolean) {
      loading.value = status;
    }

    const modalMethods: ModalMethods = {
      setModalProps,
      openModal,
      closeModal,
      setSubLoading,
      setModalLoading
    };

    onMounted(() => {
      if (instance) {
        emit('register', modalMethods);
      }
    });
    return {
      handleSubmit,
      getBindValue,
      isModal,
      closeModal,
      subLoading,
      loading
    };
  }
});
</script>

<template>
  <NModal
    v-bind="getBindValue"
    v-model:show="isModal"
    :style="{ maxWidth: getBindValue.width + 'px' }"
    @close="closeModal"
  >
    <template #header>
      <div id="basic-modal-bar" class="w-full cursor-move">{{ getBindValue.title }}</div>
    </template>
    <template #default>
      <NSpin :show="loading" content-style="--n-opacity-spinning:0">
        <NScrollbar class="px-20px" :style="{ height: getBindValue.height + 'px' }">
          <slot name="default"></slot>
        </NScrollbar>
      </NSpin>
    </template>
    <template v-if="!$slots.action && getBindValue.showFooter" #action>
      <NSpace v-if="!loading" justify="end">
        <NButton @click="closeModal">取消</NButton>
        <NButton type="primary" :loading="subLoading" @click="handleSubmit">{{ getBindValue.subBtuText }}</NButton>
      </NSpace>
    </template>
    <template v-else #action>
      <slot name="action"></slot>
    </template>
  </NModal>
</template>

<style lang="scss">
.cursor-move {
  cursor: move;
}
</style>
