/*
 * @Author: 陈智伟 9459156+chen-kaitao@user.noreply.gitee.com
 * @Date: 2021-10-05 11:34:34
 * @LastEditors: 陈智伟 9459156+chen-kaitao@user.noreply.gitee.com
 * @LastEditTime: 2022-07-23 10:20:28
 * @FilePath: /glxt/src/util/remoteLoad.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
export default function remoteLoad (url, hasCallback) {
  return createScript(url)
  /**
	 * 创建script
	 * @param url
	 * @returns {Promise}
	 */
  function createScript (url) {
    const scriptElement = document.createElement('script')
    document.body.appendChild(scriptElement)
    const promise = new Promise((resolve, reject) => {
      scriptElement.addEventListener(
        'load',
        (e) => {
          removeScript(scriptElement)
          if (!hasCallback) {
            resolve(e)
          }
        },
        false
      )

      scriptElement.addEventListener(
        'error',
        (e) => {
          removeScript(scriptElement)
          reject(e)
        },
        false
      )

      if (hasCallback) {
        window.____callback____ = function () {
          resolve()
          window.____callback____ = null
        }
      }
    })

    if (hasCallback) {
      url += '&callback=____callback____'
    }

    scriptElement.src = url

    return promise
  }

  /**
	 * 移除script标签
	 * @param scriptElement script dom
	 */
  function removeScript (scriptElement) {
    document.body.removeChild(scriptElement)
  }
}
