<template>
  <transition :name="transitionStyle">
    <div v-show="show" :style="styles" :class="classes" class="popupPanel">
      <slot></slot>
    </div>
  </transition>
</template>
<script>
import Popup from './popup'
let timer;

let touchstartFun = function() {
  var top = document.body.scrollTop
  ,totalScroll = document.body.scrollHeight
  ,currentScroll = top + document.body.offsetHeight;
  if(top === 0) {
      document.body.scrollTop = 1;
  }else if(currentScroll === totalScroll) {
      document.body.scrollTop = top - 1;
  }
}

let touchmoveFun = function(evt) {
  if(document.body.offsetHeight > document.body.scrollHeight){
    evt.preventDefault();
  }
}

export default {
  name: 'Popup',
  props: {
    value: Boolean,
    height: {
      type: String,
      default: 'auto'
    },
    hideOnBlur: {
      type: Boolean,
      default: true
    },
    reverse: {
      type: Boolean,
      default: false
    },
    mask: {
      type: Boolean,
      default: true
    },
    historyModel:{
      type: Boolean,
      default: false
    }
  },
  mounted() {
    window.removeEventListener("popstate",this.popupStateCallback, false);
    window.addEventListener("popstate", this.popupStateCallback, false);
    this.$nextTick(() => {
      const _this = this
      this.popup = new Popup({
        container: _this.$el,
        innerHTML: '',
        reverse: _this.reverse,
        hideOnBlur: _this.hideOnBlur,
        mask: _this.mask,
        onOpen() {
          _this.fixSafariOverflowScrolling('auto')

          _this.show = true
        },
        onClose() {
          _this.show = false

          if (Object.keys(window.__$Popups).length >= 1) return
          _this.fixSafariOverflowScrolling('touch')
        }
      })
      this.$overflowScrollingList = document.querySelectorAll('.fix-safari-overflow-scrolling')
    })

  },
  computed: {
    transitionStyle() {
      if (this.reverse) {
        return 'popup-animate-reverse'
      } else {
        return 'popup-animate'
      }
    },
    classes() {
      if (this.reverse) {
        return "popup popup-reverse"
      } else {
        return "popup"
      }

    },
    styles() {
      if(this.height.indexOf('%') != -1){
        return `height:${this.height}`
      } else {
        return `height:${this.height}px`
      }
      
    }
  },
  methods: {
    /**
     * https://github.com/airyland/vux/issues/311
     * https://benfrain.com/z-index-stacking-contexts-experimental-css-and-ios-safari/
     */
    fixSafariOverflowScrolling(type) {
      if (!this.$overflowScrollingList.length) return
      if (!/iphone/i.test(navigator.userAgent)) return
      for (let i = 0; i < this.$overflowScrollingList.length; i++) {
        this.$overflowScrollingList[i].style.webkitOverflowScrolling = type
      }
    },
    popupStateCallback(){
      this.clickGoBack = true
      this.show = false
    }
  },
  data() {
    return {
      hasFirstShow: false,
      show: this.value,
      clickGoBack:false
    }
  },
  watch: {
    show(val) {
      this.$emit('input', val)
      if (val) {
        this.popup.show()
        this.$emit('on-show')
        this.clickGoBack = false
        if(this.historyModel){
          window.history.pushState(null, null, "#popupShow");
          // location.hash = '#popupShow'
        }
        
        if (!this.hasFirstShow) {
          this.$emit('on-first-show')
          this.hasFirstShow = true
        }
      } else {
        this.popup.hide(false)
        this.$emit('on-hide')

        if(!this.clickGoBack && this.historyModel){
          window.history.back()
        }
      }
      /**
       * 禁止背景滑动
       */
      
      if(this.mask){
        clearTimeout(timer)

        timer = setTimeout(() => {
          if (!!document.body.querySelector('.popup-mask.popup-show')) {
            window.document.body.style.overflow = 'hidden'
            window.document.body.style.position = 'relative'
          } else {
            window.document.body.style.overflow = 'scroll'
            window.document.body.style.position = 'initial'
          }
          if(!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
            if(val){
              document.body.addEventListener('touchstart', touchstartFun);
              document.body.addEventListener('touchmove', touchmoveFun);
            } else {
              document.body.removeEventListener('touchstart', touchstartFun);
              document.body.removeEventListener('touchmove', touchmoveFun);
            }
          }
        }, 200)
      }
    },
    value(val) {
      this.show = val
    }
  },
  beforeDestroy() {
    this.popup.destroy()
    this.fixSafariOverflowScrolling('touch')
  }
}
</script>
