import "./index.css";
/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import merge from 'lodash/merge';
import { createComponentName, componentMixin } from '../_utils/component';
import PopperJs from 'popper.js';
import popupManager from '../_utils/popup-manager';
import { on, off } from '../_utils/dom';
import Event from 'eventemitter3';
const popperJs = 'POPPERJS';
const eventBus = new Event();
const __vue_script__ = {
  name: createComponentName('popover'),
  mixins: [componentMixin],

  update() {
    eventBus.emit('update');
  },

  props: {
    tag: {
      type: [String, Object],
      default: 'span'
    },
    appendToBody: {
      type: Boolean,
      default: true
    },
    animation: {
      type: [Object, String],
      default: 'gd-fade'
    },
    popoverClass: {
      type: [String, Array],
      default: ''
    },
    visible: {
      type: Boolean
    },
    // 主题色
    theme: {
      // 'dark' / ‘light’
      type: String,
      default: 'light'
    },
    arrow: {
      type: Boolean,
      default: true
    },
    defaultVisible: {
      type: Boolean,
      default: false
    },
    lazy: {
      type: Boolean,
      default: true
    },
    trigger: {
      type: String,
      default: 'hover',
      validator: value => ['click', 'hover', null].indexOf(value) > -1
    },
    placement: {
      type: String,
      default: 'bottom'
    },
    // 延迟多久消失
    delayOnMouseOut: {
      type: Number,
      default: 50
    },
    // 延迟多久显示
    delayOnMouseOver: {
      type: Number,
      default: 0
    },
    modifiers: {
      type: Object,
      default: () => {}
    }
  },

  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
    };
  },

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

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

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

  },

  mounted() {
    if (this.$isServer) return;
    eventBus.on('update', this.updatePopper);
    this.eventsEnabled = true;
    this.mounted = true;
    this.initReferenceEvent();

    if (this.appendToBody && this.$refs.content) {
      this.$refs.content.parentNode.removeChild(this.$refs.content);
    }

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

  beforeDestroy() {
    eventBus.off('update', this.updatePopper);
    this.offReferenceEvent();
    this.doDestroy();
  },

  methods: {
    afterLeave() {
      popupManager.popStack(this);
    },

    doDestroy() {
      this.offPopperEvent();

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

      if (this.appendToBody && this.appendedToBody && this.$refs.content) {
        this.appendedToBody = false;
        document.body.removeChild(this.$refs.content);
      }
    },

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

    initPopperEvent() {
      switch (this.trigger) {
        case 'hover':
          on(this.$refs.content, 'mouseover', this.onMouseOver);
          on(this.$refs.content, 'focus', this.onMouseOver);
          on(this.$refs.content, 'mouseout', this.onMouseOut);
          on(this.$refs.content, 'blur', this.onMouseOut);
          break;
      }
    },

    offReferenceEvent() {
      switch (this.trigger) {
        case 'click':
          off(document, 'click', this.handleDocumentClick);
          break;
      }
    },

    offPopperEvent() {
      off(this.$refs.content, 'mouseover', this.onMouseOver);
      off(this.$refs.content, 'focus', this.onMouseOver);
      off(this.$refs.content, 'mouseout', this.onMouseOut);
      off(this.$refs.content, 'blur', this.onMouseOut);
    },

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

    doToggle() {
      if (this.trigger !== 'click') return;

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

    onMouseOver() {
      if (this.trigger !== 'hover') return;
      clearTimeout(this._timer);
      this._timer = setTimeout(() => {
        this.updatePopper();
        this.changeVisible(true);
      }, this.delayOnMouseOver);
    },

    onMouseOut() {
      if (this.trigger !== 'hover') return;
      clearTimeout(this._timer);
      this._timer = setTimeout(() => {
        this.changeVisible(false);
      }, this.delayOnMouseOut);
    },

    handleDocumentClick(e) {
      if (!this.$el || this.elementContains(this.$el, e.target) || !this.$refs.content || this.elementContains(this.$refs.content, 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;
      const config = merge({
        onCreate(data) {
          data.instance.popper.style.zIndex = self.zIndex;
          self.$emit('create', data);
        },

        onUpdate(data) {
          if (self.isShowPopper) {
            data.instance.popper.style.zIndex = self.zIndex;
          }
        }

      }, {
        modifiers: {
          offset: {
            offset: 0
          },
          preventOverflow: {
            padding: 0
          }
        }
      }, {
        placement: this.placement,
        positionFixed: true,
        eventsEnabled: true,
        removeOnDestroy: false,
        modifiers: this.modifiers
      });
      return config;
    },

    createPopper() {
      if (!this.$el || !this.$refs.content) return;

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

      this[popperJs] = new PopperJs(this.$el, this.$refs.content, this.getPopperConfig());

      if (this.appendToBody && !this.appendedToBody) {
        this.appendedToBody = true;
        document.body.appendChild(this.$refs.content);
      }

      this.initPopperEvent();
    },

    updatePopper() {
      if (!this.isShowPopper) return;

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

  }
};
/* 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({
    tag: "span",
    on: {
      click: _vm.doToggle,
      mouseover: _vm.onMouseOver,
      mouseout: _vm.onMouseOut
    },
    nativeOn: {
      click: function ($event) {
        return _vm.doToggle($event);
      },
      mouseover: function ($event) {
        return _vm.onMouseOver($event);
      },
      mouseout: function ($event) {
        return _vm.onMouseOut($event);
      }
    }
  }, "span", _vm.$attrs, false), _vm.$listeners), [_vm._t("default"), _vm._v(" "), _c("transition", _vm._g({
    attrs: {
      name: typeof _vm.animation === "string" ? _vm.animation : undefined
    },
    on: {
      "after-leave": _vm.afterLeave
    }
  }, typeof _vm.animation === "object" ? _vm.animation : undefined), [(_vm.lazy ? _vm.hasShow : true) ? _c("span", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.isShowPopper,
      expression: "isShowPopper"
    }],
    ref: "content",
    class: [_vm.bem([_vm.theme]), _vm.popoverClass],
    style: {
      zIndex: _vm.zIndex
    }
  }, [[_vm._t("content"), _vm._v(" "), _vm.arrow ? _c("div", {
    class: _vm.bem("arrow"),
    attrs: {
      "x-arrow": ""
    }
  }) : _vm._e()]], 2) : _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);