<template>
    <layer v-bind="$attrs" :show="show" :style="layer?{}:{bottom:'auto'}" @click.native.self="clickLayerClose&&close()">
        <transition :name="$style.popup" v-bind="$attrs" slot-scope="slot">
            <div :class="[$style.popup,$style[position],slot.className]" :style="slot.styleObj" v-show="show">
                <slot></slot>
            </div>
        </transition>
    </layer>
</template>

<style module>
    .popup {
        position: fixed;
        background: #fff;
    }

    .top {
        left: 0;
        right: 0;
        top: 0;
    }

    .bottom {
        left: 0;
        right: 0;
        bottom: 0;
    }

    .left {
        left: 0;
        top: 0;
        bottom: 0;
    }

    .right {
        right: 0;
        top: 0;
        bottom: 0;
    }

    .popup:global(-enter).top,
    .popup:global(-leave-to).top {
        transform: translate3d(0, -100%, 0);
    }

    .popup:global(-enter).bottom,
    .popup:global(-leave-to).bottom {
        transform: translate3d(0, 100%, 0);
    }

    .popup:global(-enter).left,
    .popup:global(-leave-to).left {
        transform: translate3d(-100%, 0, 0);
    }

    .popup:global(-enter).right,
    .popup:global(-leave-to).right {
        transform: translate3d(100%, 0, 0);
    }
</style>

<script>
    import Layer from '../layer/index.vue'

    export default {
      model: {
        prop: 'show',
        event: 'toggle'
      },
      props: {
        show: {
          type: Boolean,
          default: false
        },
        layer: { // 是否有遮罩层
          type: Boolean,
          default: true
        },
        position: { // 弹出位置
          type: String,
          default: 'bottom',
          validator (value) {
            return ['top', 'bottom', 'left', 'right'].indexOf(value) !== -1
          }
        },
        autoClose: { // 多久自动关闭，单位ms，0表示不自动关闭
          type: Number,
          default: 0
        },
        clickLayerClose: { // 点击遮罩层是否关闭
          type: Boolean,
          default: true
        }
      },
      computed: {
        $style () {
          return this.$options.cssModules
        }
      },
      watch: {
        show: {
          handler (value) {
            if (this.autoClose > 0) {
              if (value) {
                this.timeoutId = setTimeout(this.close, this.autoClose)
              } else { // 清除延时器
                clearTimeout(this.timeoutId)
              }
            }
          },
          immediate: true
        }
      },
      methods: {
        close () {
          this.$emit('toggle', false)
        }
      },
      components: {
        Layer
      }
    }
</script>