import { Directive } from 'vue'

// 创建遮罩层
function createMask(): HTMLElement {
  const mask = document.createElement('div')
  mask.className = 'loading-mask'
  mask.style.position = 'absolute'
  mask.style.top = '0px'
  mask.style.left = '0px'
  mask.style.width = '100%'
  mask.style.height = '100%'
  mask.style.backgroundColor = 'rgba(122, 122, 122, 0.8)'

  mask.style.display = 'flex'
  mask.style.justifyContent = 'center'
  mask.style.alignItems = 'center'

  const loadingIcon = document.createElement('div')

  loadingIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
		<path fill="currentColor" d="M12 2A10 10 0 1 0 22 12A10 10 0 0 0 12 2Zm0 18a8 8 0 1 1 8-8A8 8 0 0 1 12 20Z" opacity="0.5" />
		<path fill="currentColor" d="M20 12h2A10 10 0 0 0 12 2V4A8 8 0 0 1 20 12Z">
			<animateTransform attributeName="transform" dur="1s" from="0 12 12" repeatCount="indefinite" to="360 12 12" type="rotate" />
		</path>
	</svg>`
  loadingIcon.style.color = '#000DFF'
  loadingIcon.style.width = '44px'
  loadingIcon.style.height = '44px'
  mask.appendChild(loadingIcon)
  return mask
}

// 自定义指令定义
const loading: Directive<HTMLElement, boolean> = {
  mounted(el, binding) {
    let isBody = false
    if (binding.modifiers.body) {
      isBody = true
    }

    const value = binding.value
    if (value) {
      if (isBody) {
        document.body.appendChild(createMask())
      } else {
        el.appendChild(createMask())
      }
    }
  },
  updated(el, binding) {
    let isBody = false
    if (binding.modifiers.body) {
      isBody = true
    }

    const value = binding.value
    if (value) {
      if (isBody) {
        const mask = document.querySelector('.loading-mask')
        if (!mask) {
          document.body.appendChild(createMask())
        }
      } else {
        const mask = el.querySelector('.loading-mask')
        if (!mask) {
          el.appendChild(createMask())
        }
      }
    } else {
      if (isBody) {
        const mask = document.querySelector('.loading-mask')
        if (mask) {
          document.body.removeChild(mask)
        }
      } else {
        const mask = el.querySelector('.loading-mask')
        if (mask) {
          el.removeChild(mask)
        }
      }
    }
  },
  unmounted(el, binding) {
    let isBody = false
    if (binding.modifiers.body) {
      isBody = true
    }

    if (isBody) {
      const mask = document.querySelector('.loading-mask')
      if (mask) {
        document.body.removeChild(mask)
      }
    } else {
      const mask = el.querySelector('.loading-mask')
      if (mask) {
        el.removeChild(mask)
      }
    }
  },
}

export default loading
