import "core-js/modules/web.dom.iterable";
import _Object$keys from "@babel/runtime-corejs2/core-js/object/keys";
import _Symbol from "@babel/runtime-corejs2/core-js/symbol";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
import Portal from '../portal';
import { createComponentName, componentMixin } from '../../utils/base';
import PopperJs from 'popper.js';
import popupManager from '../../utils/popup-manager';
import { on, off } from '../../utils/dom';

const forEach = (l, fn) => {
  for (let i = 0; i < l.length; i++) {
    fn && fn(l[i], i);
  }
};

const popperJs = _Symbol('popperJs');

const __vue_script__ = {
  name: createComponentName('popover'),
  components: {
    Portal
  },
  mixins: [componentMixin],
  props: {
    tag: {
      type: [String, Object],
      default: 'span'
    },
    popoverClass: {
      type: [String, Array],
      default: ''
    },
    visible: {
      type: Boolean
    },
    defaultVisible: {
      type: Boolean,
      default: false
    },
    transitionName: {
      type: String
    },
    transitionOn: {
      type: Object
    },
    lazy: {
      type: Boolean,
      default: true
    },
    trigger: {
      type: String,
      default: 'hover',
      validator: value => ['click', 'hover', null].indexOf(value) > -1
    },
    placement: {
      type: String,
      default: 'bottom'
    },
    // 延迟多久显示
    delayOver: {
      type: Number,
      default: 100
    },
    modifiers: {
      type: Object
    }
  },

  data() {
    let visible = false;
    if (this.$hasProp('visible')) visible = this.visible;else if (this.$hasProp('defaultVisible')) visible = this.defaultVisible;
    return {
      isShowPopper: visible,
      zIndex: 0,
      hasShow: visible,
      mounted: false
    };
  },

  computed: {
    componentProps() {
      const keys = _Object$keys(this.$attrs);

      const attrs = {};
      keys.forEach(key => {
        if (!(key in this.$options.props)) {
          attrs[key] = this.$attrs[key];
        }
      });
      return attrs;
    }

  },
  watch: {
    isShowPopper(value) {
      if (value) this.hasShow = true;

      if (value) {
        this.$emit('show');
        popupManager.pushStack(this);
        this.updatePopper();
      } else {
        this.$emit('hide');
        popupManager.popStack(this);
      }
    },

    visible(value) {
      this.isShowPopper = value;
    }

  },

  update() {
    this.updatePopper();
  },

  mounted() {
    this.removeOnDestroy = true;
    this.eventsEnabled = true;
    if (this.$isServer) return;

    if (this.isShowPopper) {
      popupManager.pushStack(this);
    }

    this.createPopper();
  },

  beforeDestroy() {
    this.offTrigger();

    if (this[popperJs]) {
      this[popperJs].destroy();
      this[popperJs] = null;
    }
  },

  methods: {
    initTrigger() {
      this.offTrigger();

      switch (this.trigger) {
        case 'click':
          on(this.target, 'click', this.doToggle);
          on(document, 'click', this.handleDocumentClick);
          break;

        case 'hover':
          on(this.target, 'mouseover', this.onMouseOver);
          on(this.target, 'focus', this.onMouseOver);
          on(this.popup, 'mouseover', this.onMouseOver);
          on(this.popup, 'focus', this.onMouseOver);
          on(this.target, 'mouseout', this.onMouseOut);
          on(this.target, 'blur', this.onMouseOut);
          on(this.popup, 'mouseout', this.onMouseOut);
          on(this.popup, 'blur', this.onMouseOut);
          break;
      }
    },

    changeVisible(value) {
      if (this.$hasProp('visible')) {
        this.$emit('update:visible', value);
      } else {
        this.isShowPopper = value;
      }
    },

    doToggle() {
      if (!this.forceShow) {
        this.changeVisible(!this.isShowPopper);
      }
    },

    onMouseOver() {
      clearTimeout(this._timer);
      this._timer = setTimeout(() => {
        this.changeVisible(true);
      }, this.delayOver);
    },

    onMouseOut() {
      clearTimeout(this._timer);
      this._timer = setTimeout(() => {
        this.changeVisible(false);
      }, this.delayOver);
    },

    handleDocumentClick(e) {
      if (!this.$el || !this.target || this.elementContains(this.$el, e.target) || this.elementContains(this.target, e.target) || !this.popup || this.elementContains(this.popup, e.target)) {
        return;
      }

      this.$emit('documentClick', this);
      this.changeVisible(false);
    },

    elementContains(elm, otherElm) {
      if (typeof elm.contains === 'function') {
        return elm.contains(otherElm);
      }

      return false;
    },

    getPopperConfig() {
      let self = this;
      let tmpMap = {
        onCreate(data) {
          data.instance.popper.style.transform = '';
          data.instance.popper.style.left = data.popper.left + 'px';
          data.instance.popper.style.top = data.popper.top + 'px';
          data.instance.popper.style.zIndex = self.zIndex;
          data.instance.popper.style.willChange = '';
          self.$emit('create', data);
        },

        onUpdate(data) {
          if (self.isShowPopper) {
            data.instance.popper.style.transform = '';
            data.instance.popper.style.left = data.popper.left + 'px';
            data.instance.popper.style.top = data.popper.top + 'px';
            data.instance.popper.style.zIndex = self.zIndex;
            data.instance.popper.style.willChange = '';
          }
        }

      }; // 通过 props 属性 设置 Plupload 配置

      forEach(['placement', 'eventsEnabled', 'removeOnDestroy', 'modifiers'], key => {
        this[key] && (tmpMap[key] = this[key]);
      });
      return tmpMap;
    },

    createPopper() {
      if (this.$isServer) return;

      if (!this.$refs.target) {
        throw new Error('没有设置 target 或者 popper');
      }

      this.target = this.$refs.target.$el || this.$refs.target;

      if (this.$refs.popup) {
        this.popup = this.$refs.popup.$el || this.$refs.popup;
        this[popperJs] = new PopperJs(this.target, this.popup, this.getPopperConfig());
      }

      this.initTrigger();
    },

    updatePopper() {
      if (this[popperJs]) {
        this[popperJs].scheduleUpdate();
      } else {
        this.$nextTick(() => {
          this.createPopper();
        });
      }
    },

    offTrigger() {
      off(this.target, 'click', this.doToggle);
      off(this.target, 'mouseup', this.doClose);
      off(this.target, 'mousedown', this.doShow);
      off(this.target, 'focus', this.doShow);
      off(this.target, 'blur', this.doClose);
      off(this.target, 'mouseout', this.onMouseOut);
      off(this.target, 'mouseover', this.onMouseOver);
      off(document, 'click', this.handleDocumentClick);
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c(_vm.tag, _vm._g(_vm._b({
    ref: "target",
    tag: "span"
  }, "span", _vm.componentProps, false), _vm.$listeners), [_vm._t("default"), _vm._v(" "), (_vm.lazy ? _vm.hasShow : true) ? _c("portal", [_c("transition", _vm._g({
    attrs: {
      name: _vm.transitionName
    }
  }, _vm.transitionOn), [_c("span", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.isShowPopper,
      expression: "isShowPopper"
    }],
    ref: "popup",
    class: _vm.popoverClass,
    style: {
      zIndex: _vm.zIndex
    }
  }, [_vm._t("popup")], 2)])], 1) : _vm._e()], 2);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../../utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);