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%'
    },
    width: {
      type: String,
      default: '100%'
    },
    teleport: {
      type: String,
      default: ''
    },
    destroy: {
      type: Boolean,
      default: false
    },
    modelValue: {
      type: Boolean,
      default: false
    },
    position: {
      type: String as PropType<PopupPosition>,
      default: 'bottom'
    },
    zIndex: {
      type: Number,
      default: 2018
    }
  },
  emits: ['close', 'update:modelValue'],
  data() {
    return {
      popupShow: false,
      isDestroy: false
    };
  },
  watch: {
    modelValue() {
      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;
      this.$emit('close');
    },
    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;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        for (const key in query) {
          times++;
        }
        const origin = window.location.href;
        const url = times > 0 ? '&sPop=' + +new Date() : '?sPop=' + +new Date();
        history.pushState('', '', `${origin}${url}`);
      } else {
        const splitUrl = window.location.hash.slice(1).split('?');
        const query = qs.parse(splitUrl[1]);
        if (query.sPop) {
          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}
        teleport={this.teleport}
        style={{ height: this.height, width: this.width }}
        zIndex={this.zIndex}
        onClosed={() => {
          if (this.destroy) {
            this.isDestroy = true;
          }
        }}>
        {this.$slots.default && !this.isDestroy && this.$slots.default()}
      </Popup>
    );
  }
});
