/**
 * 原生 动态加载后台资源js,json工具类
 * @author cls
 * @date 2021-01-30
 * import { LoadUtil } from "@birt/funclib/LoadUtil";
 */

export const LoadUtil = {
  loadJs(url) {
    return new Promise((resolve, reject) => {
      let srcArr = document.getElementsByTagName("script");
      let hasLoaded = false;
      for (let i = 0; i < srcArr.length; i++) {
        //判断当前js是否加载上
        hasLoaded = (srcArr[i].src == url) ? true : false;
      }
      if (hasLoaded) {
        resolve();
        return;
      }
      let script = document.createElement('script')
      script.type = 'text/javascript';
      script.src = url;
      document.body.appendChild(script);
      script.onload = () => {
        resolve();
      }
      script.onerror = () => {
        reject();
      }
    })
  },
  // 动态加载报表模型(js)
  loadJsBirtModel({ loadModelUrl, routePath, token,pn }) {
    return new Promise((resolve, reject) => {
      let url = this._getBirtModelUrl(loadModelUrl, routePath, token,pn);
      this.loadJs(url).then((response) => {
        resolve();
      }).catch(() => {
        reject();
      })
    })
  },
  // 获取加载报表模型地址
  _getBirtModelUrl(loadModelUrl, routePath, token,pn) {
    let pi = routePath.lastIndexOf(".");
    if (pi != -1) {
      routePath = routePath.substring(0, pi);
    }
    let url = `${loadModelUrl}?bizpath=/deploy${routePath}.js&access_token=${token}&pn=${pn}`;
    return url;
  }
};