/**
 * 添加script
 * @ctype PROCESS
 * @description 添加script，可以多个
 * @param {string} script - js脚本
 * @param {HTMLElement} [parentNode=document.head] - 父节点
 * @example 一般用法
 * appendScript('function test(text){console.log("text:", text)}')
 * test('hello'); //hello
 */
export function appendScript(script: string, parentNode: HTMLElement = document.head) {
  if (!script) {
    return {
      type: 'failed'
    }
  }

  if (script.indexOf('<script') === 0) {
    let temp = document.createElement('div')
    temp.innerHTML = script

    for (let i = 0, li = temp.children.length; i < li; i++) {
      const child: any = temp.children[i]

      if (child.src) {
        appendJsScript(child.src, parentNode)
        i--
        li--
      } else {
        evalJsScript(child.innerHTML, parentNode)
      }
    }
  } else {
    evalJsScript(script, parentNode)
  }
}

/**
 * 执行js脚本
 * @ctype PROCESS
 * @description 执行js脚本
 * @param {string} script - 脚本文本
 * @param {HTMLElement} [parentNode=document.head] - 父节点
 */
export function evalJsScript(script: string, parentNode: HTMLElement = document.head) {
  let el = document.createElement('script')
  el.innerHTML = script
  document.head.appendChild(el)
  setTimeout(() => {
    document.head.removeChild(el)
  }, 1)
}

/**
 * 动态引入js
 * @ctype PROCESS
 * @description 执行js脚本
 * @param {string} url - js脚本地址
 * @param {HTMLElement} [parentNode=document.head] - 父节点
 */
export function appendJsScript(url: string, parentNode: HTMLElement = document.head) {
  return new Promise((resolve, reject) => {
    let scriptEl = document.createElement('script')
    scriptEl.src = url
    scriptEl.onload = function () {
      document.head.removeChild(scriptEl)
      resolve(true)
    }
    scriptEl.onerror = function () {
      document.head.removeChild(scriptEl)
      reject();
    }
    parentNode.appendChild(scriptEl)
  })
}
