import { getLayoutAuthority } from '../../../services/api';
import $modal from '../../../utils/modal';
import { getHostByPath } from '../../../utils/config';
import { gup } from '../../../utils/utils';
import store from "store"
export default function () {
  loadMapScript.call(this);
}
function loadMapScript() {
  //基础地图底层
  const script = document.createElement("script");
  script.src =
    "https://webapi.amap.com/maps?v=1.4.15&key=9066916e054aa3083a6f081a2a9f9d7a&plugin=Map3D,AMap.ControlBar,AMap.MarkerClusterer,AMap.CircleEditor";
  document.body.appendChild(script);

  //loca图层
  const script2 = document.createElement("script");
  script2.src =
    "https://webapi.amap.com/loca?v=1.3.0&key=9066916e054aa3083a6f081a2a9f9d7a";
  document.body.appendChild(script2);

  //加载轨迹ui组件库
  const script5 = document.createElement("script");
  script5.src =
    "//webapi.amap.com/ui/1.1/main.js?v=1.1.1";
  document.body.appendChild(script5);

  //视频调度sdk
  const script4 = document.createElement("script");
  script4.src = "https://sqimg.qq.com/expert_qq/webrtc/3.0.6/WebRTCAPI.min.js";
  document.body.appendChild(script4);

  const script3 = document.createElement("script");
  script3.src = "https://cache.amap.com/lbs/static/addToolbar.js";
  //百度地图图层
  const script6 = document.createElement("script");
  script6.src = "https://api.map.baidu.com/getscript?type=webgl&v=1.0&ak=8sVvl6fSdyUfLgIt277nlG6hasAWQ2CA&services=";
  document.body.appendChild(script6);
  // 百度地图样式
  const script7 = document.createElement("link");
  script7.href = "https://api.map.baidu.com/res/webgl/10/bmap.css";
  document.head.appendChild(script7);

  if (!"AMap" in window) {
    document.body.appendChild(script3);
  }
  if (!"AMapUI" in window) {
    document.body.appendChild(script5);
  }
  loading.call(this);
  loadingBMap();
}

function loadAMapUI() {
  //加载轨迹ui组件库
  const script5 = document.createElement("script");
  script5.src =
    "//webapi.amap.com/ui/1.1/main.js?v=1.1.1";
  document.body.appendChild(script5);
  loadAMapUIAgain.call(this)
}

//判断是否已经加载完成Amap
function loading() {
  let _this = this;
  function nextStep() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("AMap" in window);
      }, 500);
    });
  }

  async function ajaxMap() {
    let ifComplete = false;
    for (var i = 0; i < 10; i++) {
      if (!ifComplete) {
        console.log("没有");
        ifComplete = await nextStep();
      } else {
        if (ifComplete) {
          const { AMap, AMapUI } = window;
          console.log("第" + i + "次加载" + "地图初始化中。。。");
          if (!AMap) {
            loadMapScript.call(_this);
          } else {
            _getLayoutAuthority.call(_this)
            // _this.initialMap();
            // if (!AMapUI) {
            //   loadAMapUI.call(_this)
            // } else {
            // }
          }
          break;
        } else {
          message.error("网络超时");
        }
      }
    }
  }
  ajaxMap();
};

//判断是否已经加载完成AMapUI
function loadAMapUIAgain() {
  let _this = this;
  function nextStep() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("AMapUI" in window);
      }, 500);
    });
  }

  async function ajaxMap() {
    let ifComplete = false;
    for (var i = 0; i < 10; i++) {
      if (!ifComplete) {
        console.log("没有");
        ifComplete = await nextStep();
      } else {
        if (ifComplete) {
          const { AMapUI } = window;
          console.log("第" + i + "次加载" + "AMapUI。。。");
          if (!AMapUI) {
            loadAMapUI.call(_this)
          } else {
            // InitTraietory.call(_this)
          }
          break;
        } else {
          message.error("网络超时");
        }
      }
    }
  }
  ajaxMap();
}
//判断是否已经加载完成BMapGL
function loadingBMap() {
  let _this = this;
  function nextStep() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("BMapGL" in window);
      }, 500);
    });
  }

  async function ajaxMap() {
    let ifComplete = false;
    for (var i = 0; i < 10; i++) {
      if (!ifComplete) {
        console.log("没有");
        ifComplete = await nextStep();
      } else {
        if (ifComplete) {
          const { BMapGL } = window;
          console.log("第" + i + "次加载" + "地球初始化中。。。");
          break;
        } else {
          message.error("网络超时");
        }
      }
    }
  }
  ajaxMap();
};
//获取图层权限信息
function _getLayoutAuthority() {
  let app_type = store.get('saas')['app_type'];
  if (app_type == 1) {
    this.props.dispatch({
      type: 'command/setLayoutAuthority',
      payload: {
        defaultLayer: "是",
        defaultLayerName: "基础调度",
      }
    })
    this.setState({
      showEarchMap: false,
    })
    this.initialMap("attendance", "normalMap");
    const { AMapUI } = window;
    if (!AMapUI) {
      loadAMapUI.call(this)
    }
  } else {
    getLayoutAuthority({
      _currpage: 1,
      lines: 1
    }, {
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__jN3d9GetQI3p4DdC5To",
      opentarget: "detail",
      containTitle: "图层权限设置",
    }).then(res => {
      if (res.data && res.data.data) {
        let data = res.data.data[0]
        // attendancePermissions: 助勤点图层
        // basisLayer: 增值图层
        // customLayer: 定制图层
        // defaultLayer: 监管图层
        // domainPermissions: 保安企业图层
        // additionalLayer  附加图层是否开启
        // additionalName  附加图层名称
        // earthLayer: 地图图层
        // hardWarePermissions: 硬件图层
        // peoplePermissions: 保安人员
        // additionalType 附加图层类型
        if (!data) {
          return $modal(
            <span style={{ color: 'orange' }}>您没有权限使用该服务</span>,
            '',
            [],
          );
        }
        if (!data.defaultLayer && !data.basisLayer && !data.customLayer && data.additionalLayer) {
          return $modal(
            <span style={{ color: 'orange' }}>您没有权限使用该服务</span>,
            '',
            [],
          );
        }
        let baseUrl = getHostByPath('v5base')
        //判断logo图片路径如果返回obs，直接用obs路径，否则用/obpm全路径拼接
        let commonLogo=''
        let dataCommonLogo=data.commonLogo && (JSON.parse(data.commonLogo)[0].path)
        if(dataCommonLogo.indexOf('http')>-1){
          commonLogo=dataCommonLogo
        }else{
          commonLogo=`${baseUrl}/obpm${dataCommonLogo}`
        }

        let darkLogo=''
        let datadarkLogo=data.darkLogo && (JSON.parse(data.darkLogo)[0].path)
        if(datadarkLogo.indexOf('http')>-1){
          darkLogo=datadarkLogo
        }else{
          darkLogo=`${baseUrl}/obpm${datadarkLogo}`
        }
        // let commonLogo = data.commonLogo.length > 0 ? `${baseUrl}/obpm${JSON.parse(data.commonLogo)[0].path}` : ""
        // let darkLogo = data.darkLogo.length > 0 ? `${baseUrl}/obpm${JSON.parse(data.darkLogo)[0].path}` : ""
        
        // data.customLayer = ""
        this.props.dispatch({
          type: 'command/setLayoutAuthority',
          payload: {
            attendanceMapShow: data.defaultLayer,
            aPictureMapShow: data.customLayer,
            policeMapShow: data.basisLayer,
            defaultLayer: data.defaultLayer,
            basisLayer: data.basisLayer,
            customLayer: data.customLayer,
            additionalLayer: data.additionalLayer,
            attendancePermissions: data.attendancePermissions,
            basisLayerName: data.basisLayerName || "增值图层",
            customLayerName: data.customLayerName || "定制图层",
            defaultLayerName: data.defaultLayerName || "监管图层",
            additionalName: data.additionalName,
            domainPermissions: data.domainPermissions,
            earthLayer: data.earthLayer,
            hardWarePermissions: data.hardWarePermissions,
            peoplePermissions: data.peoplePermissions,
            commonLogo: commonLogo,
            darkLogo: darkLogo,
            additionalType: data.additionalType
          }
        })
        if (data.customLayer) {
          // this.props.dispatch({
          //   type: 'command/setMapStyle',
          //   payload: 'dark'
          // })
        } else {
          this.setState({
            showEarchMap: false,
          })
        }
        // this.setState({
        //   showEarchMap: false,
        // })
        let layoutName = ''
        let mapName = ''
        if (data.customLayer) {
          layoutName = 'aPicture'
          mapName = 'locaMap'
        } else if (data.defaultLayer) {
          layoutName = 'attendance'
          mapName = 'normalMap'
        } else if (data.twoLayer) {
          layoutName = 'person'
          mapName = 'personMap'
        } else if (data.basisLayer) {
          layoutName = 'police'
          mapName = 'policeMap'
        } else if (data.additionalLayer && data.additionalType == "南宁海康押运") {
          layoutName = 'nanNing'
          mapName = 'nanNingMap'
        }
        this.initialMap(layoutName, mapName);
        const { AMapUI } = window;
        if (!AMapUI) {
          loadAMapUI.call(this)
        }
      }
    })
  }

}
