import { Popup, PopupPosition } from 'vant'
import { defineComponent, PropType } from 'vue'
import qs from 'query-string'

export default defineComponent({
  name: 'col-popup',
  props: {
    height: {
      type: String,
      default: '100%'
    },
    destroy: {
      type: Boolean,
      default: false
    },
    modelValue: {
      type: Boolean,
      default: false
    },
    position: {
      type: String as PropType<PopupPosition>,
      default: 'bottom'
    }
  },
  data() {
    return {
      popupShow: false,
      isDestroy: false
    }
  },
  watch: {
    modelValue(val) {
      this.hashState()
    }
  },
  mounted() {
    this.destroy && (this.isDestroy = false)

    window.addEventListener('hashchange', this.onHash, false)
  },
  unmounted() {
    window.removeEventListener('hashchange', this.onHash, false)
  },
  methods: {
    onHash() {
      this.$emit('update:modelValue', false)
      this.isDestroy = false
    },
    onPopupClose(val: boolean) {
      this.$emit('update:modelValue', val)
      this.hashState()
    },
    hashState() {
      // 打开弹窗
      if (this.modelValue) {
        this.isDestroy = false
        const splitUrl = window.location.hash.slice(1).split('?')
        const query = qs.parse(splitUrl[1])
        let times = 0
        for (let key in query) {
          times++
        }
        const origin = window.location.href
        const url = times > 0 ? '&cPop=' + +new Date() : '?cPop=' + +new Date()
        history.pushState('', '', `${origin}${url}`)
      } else {
        const splitUrl = window.location.hash.slice(1).split('?')
        const query = qs.parse(splitUrl[1])
        if (query.cPop) {
          window.history.go(-1)
        }
      }
      if (this.$refs.protocolPopup) {
        ;(this.$refs.protocolPopup as any).scrollTop = 0
      }
    }
  },
  render() {
    return (
      <Popup
        ref="protocolPopup"
        show={this.modelValue}
        transitionAppear={true}
        position={this.position}
        style={{ height: this.height }}
        onClosed={() => {
          if (this.destroy) {
            this.isDestroy = true
          }
        }}
      >
        {this.$slots.default && !this.isDestroy && this.$slots.default()}
      </Popup>
    )
  }
})
