import Vue from 'vue'
import pageLoading from './loading.vue'

const Mask = Vue.extend(pageLoading)

const toggleLoading = (el, binding) => {
  // el拿到loading挂载的元素，binding.value判断是否显示loading
  if (binding.value) {
    Vue.nextTick(() => {
      el.instance.loadingShow = true
      insertDom(el, el, binding)
    })
  } else {
    el.instance.loadingShow = false
  }
}

const insertDom = (parent, el) => {
  parent.appendChild(el.mask)
}

export default {
  bind: function (el, binding) {
    const mask = new Mask({
      el: document.createElement('div'),
      data () { }
    })
    el.instance = mask
    el.mask = mask.$el
    el.maskStyle = {
      position: 'relation'
    }
    el.style.position = 'relative'
    binding.value && toggleLoading(el, binding)
  },
  update: function (el, binding) {
    if (binding.oldValue !== binding.value) {
      toggleLoading(el, binding)
    }
  },
  unbind: function (el, binding) {
    el.instance && el.instance.$destroy()
    el = null
  }
}
