<template>
  <div style="display: inline-block； width: 100%" ref="mainRef">
    <slot />
    <el-popup ref="popupRef" :popup-style="popupStyle" :auto-width="autoWidth" v-bind="propData" @onClick="handlePopupClick" >
      <slot name="popup" />
    </el-popup>
  </div>
</template>
<script>
import Popup from './popper';
import util from '../../utils';
export default {
  componentName: 'FbgPopper',
  components: {
    'el-popup': Popup
  },
  props: {
    popupStyle: {
      type: String,
      defualt: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    placement: {
      type: String,
      default: 'bottom-center'
    },
    autoWidth: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default() {
        return {
          boundariesElement: 'body'
        }
      }
    },
    visibleArrow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      instance: null,
    };
  },
  inject: {
    getMainPopperElement: {
      default: null
    }
  },
  provide() {
    return {
      getMainPopperElement: () => {
        return typeof this.getMainPopperElement === 'function' ? this.getMainPopperElement() : this.$refs.mainRef;
      }
    }
  },
  computed: {
    propData() {
      return {
        visible: this.visible,
        options: this.options,
        placement: this.placement,
        visibleArrow: this.visibleArrow
      }
    }
  },
  mounted() {
    const el = this.$refs.mainRef;
    const parentEl = util.getBoundariesElement(el, this.options.boundariesElement) || document.body;
    if (parentEl) {
      parentEl.appendChild(this.$refs.popupRef.$el);
    }
    this.$nextTick(() => {
      if(this.$refs.popupRef){
        this.$refs.popupRef.init(this.$refs.mainRef);
      }
    });
  },
  methods: {
    handlePopupClick() {
      this.$emit('popupClick');
    },
    updatePositoin() {
      this.$refs.popupRef.updatePositoin(this.$refs.mainRef);
    }
  },
  beforeDestroy() {
    this.$refs.popupRef.$el.remove();
  }
}
</script>