/**
 * 原生 动态加载后台资源js,json工具类
 * @author cls
 * @date 2021-01-30
 * import { LoadUtil } from "@birt/funclib/LoadUtil";
 */
import Cookies from 'js-cookie'
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();
      }
    })
  },
  loadCss(url) {
    let linkArr = document.getElementsByTagName("link");
    let hasLoaded = false;
    for (let i = 0; i < linkArr.length; i++) {
      //判断当前css是否加载上
      hasLoaded = (linkArr[i].href == url) ? true : false;
    }
    if (hasLoaded) {
      return;
    }
    let link = document.createElement('link')
    console.log('link==>', link)
    link.rel = 'stylesheet';
    link.href = url;
    document.body.appendChild(link);
  },
  // 动态加载报表模型(js)
  loadJsBirtModel({ loadModelUrl, routePath, token,pn,vId }) {
    return new Promise((resolve, reject) => {
      let url = this._getBirtModelUrl(loadModelUrl, routePath, token,pn,vId);
      this.loadJs(url).then((response) => {
        resolve();
      }).catch(() => {
        reject();
      })
    })
  },
  // 获取加载报表模型地址
  _getBirtModelUrl(loadModelUrl, routePath, token,pn,vId) {
    // let pi = routePath.lastIndexOf(".");
    // if (pi != -1) {
    //   routePath = routePath.substring(0, pi);
    // }
    if(routePath && routePath.endsWith('.flow')){
      routePath = routePath.replace('.flow', '.js')
    }
    if(routePath && routePath.endsWith('.js')){
      routePath = `/deploy${routePath}`
    }
    let url = `${loadModelUrl}?bizpath=${routePath}&pn=${pn}&locale=${Cookies.get("locale") || "zh-CN"}`;
    if(token){
      url += `&access_token=${token}`
    }
    if(vId){
      url += `&viewItemId=${vId}`
    }
    if(!url.startsWith(window.HIVUI_SETTING.url)){
      url = window.HIVUI_SETTING.url + url
    }
    return url;
  }
};
