<template>
  <view class="z-index view">
    <varsion-transition
      @click="onMask"
      :mode-class="['fade']"
      :style-custom="maskClass"
      :show="isShow"
    >
    </varsion-transition>
    <varsion-transition
      @change="onChange"
      :mode-class="popupData[direction].modeClass"
      :style-custom="popupData[direction].popupClass"
      :show="isShow"
    >
      <slot></slot>
    </varsion-transition>
  </view>
</template>

<script lang="ts" setup>
/**
 * popup 弹出层
 * @description 弹出层组件
 * @tutorial https://dnvue.dengqichang.cn/component/feedback_component/n-popup.html
 * @property {Boolean} show 控制显示或者隐藏
 * @property {String} direction 弹出层方向
 *  @value top 顶部弹出
 *  @value bottom 底部弹出
 *  @value left 左侧弹出
 *  @value right 右侧弹出
 *  @value center 中间弹出
 * @property {Boolean} mask-close 点击遮罩层是否可关闭
 * @event {Function()} change 当打开或者关闭时返回弹出层状态
 */
import { ref, watch } from 'vue'
import varsionTransition from './varsion-transition.nvue'
interface propsType {
  show?: boolean
  direction?: string
  maskClose?: boolean
}
const props = withDefaults(defineProps<propsType>(), {
  show: false,
  direction: 'bottom',
  maskClose: true,
})

const isShow = ref<boolean>(false)
// 遮罩层
const maskClass = ref<AnyObject>({
  position: 'fixed',
  bottom: 0,
  top: 0,
  left: 0,
  right: 0,
  backgroundColor: 'rgba(0, 0, 0, 0.4)',
})

const popupData = ref<AnyObject>({
  top: {
    modeClass: ['slide-top', 'fade'],
    popupClass: {
      position: 'fixed',
      left: 0,
      right: 0,
      top: 0,
      backgroundColor: '#FFFFFF',
    },
  },
  bottom: {
    modeClass: ['slide-bottom', 'fade'],
    popupClass: {
      position: 'fixed',
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: '#FFFFFF',
    },
  },
  left: {
    modeClass: ['slide-left', 'fade'],
    popupClass: {
      position: 'fixed',
      bottom: 0,
      top: 0,
      left: 0,
      backgroundColor: '#FFFFFF',
    },
  },
  right: {
    modeClass: ['slide-right', 'fade'],
    popupClass: {
      position: 'fixed',
      bottom: 0,
      top: 0,
      right: 0,
      backgroundColor: '#FFFFFF',
    },
  },
  center: {
    modeClass: ['fade', 'zoom-in'],
    popupClass: {
      position: 'fixed',
      bottom: 0,
      left: 0,
      right: 0,
      top: 0,
      justifyContent: 'center',
      alignItems: 'center',
    },
  },
})

// 监听是否有新版本
watch(
  () => props.show,
  (newVal: boolean) => {
    if (newVal) {
      open()
    } else {
      close()
    }
  }
)

//打开弹出层
function open() {
  isShow.value = true
}
//关闭弹出层
function close(e?: AnyObject) {
  if (isShow.value) {
    isShow.value = false
  }
}
//点击关闭弹出层
function onMask(e: AnyObject) {
  if (props.maskClose) {
    isShow.value = false
  }
}

const emit = defineEmits<{
  (e: 'change', data: any): void
}>()

//当打开或者关闭返回信息
function onChange(e: AnyObject) {
  emit('change', {
    detail: e.detail,
  })
}
</script>

<style lang="scss" scoped>
@import '../../css/index.scss';
</style>
