/*
 * @Author: zhangbo
 * @Date: 2021-01-25 17:24:39
 * @E-mail: zhangbo@geovis.com.cn
 * @LastModifiedBy: zhangbo
 * @LastEditTime: 2021-03-01 15:59:47
 * @Desc: 
 */
function loadJs(url = '') {
  if (!url) return
  if (!loadJs.cache) loadJs.cache = {}
  if (loadJs.cache[url]) return Promise.resolve()
  return new Promise((resolve, reject) => {
    _loadjs(
      url,
      () => {
        loadJs.cache[url] = 'cached'
        resolve()
      },
      () => {
        console.error(`${url} 加载失败`)
        reject(new Error(`${url} 加载失败`))
      }
    )
  })

  function _loadjs(url, fn, fail) {
    var script = document.createElement('script')
    script.src = url
    script.async = true
    script.onload = fn
    script.onerror = fail
      ; (document.body || document.head).appendChild(script)
  }
}

var FINGER_PRINT_URL = 'https://cdn.staticfile.org/fingerprintjs2/1.8.0/fingerprint2.min.js'
var STORAGE_KEY = 'YMMFP'

function getFingerPrint() {
  if (!getFingerPrint.promise) {
    getFingerPrint.promise = new Promise((resolve) => {
      var fingerPrint = localStorage.getItem(STORAGE_KEY)
      if (fingerPrint) return resolve(fingerPrint)
      loadJs(FINGER_PRINT_URL).then(() => {
        if (!window.Fingerprint2) resolve('unknown')
        window.Fingerprint2 && new window.Fingerprint2().get((res) => {
          localStorage.setItem(STORAGE_KEY, res)
          resolve(res)
        })
      })
    })
  }
  return getFingerPrint.promise
}
function createEarth(id) {
  return new Cesium.Viewer(id, {
    animation: false,
    timeline: false,
    geocoder: false,
    homeButton: false,
    navigationHelpButton: false,
    baseLayerPicker: false,
    fullscreenElement: "map",
    fullscreenButton: false,
    shouldAnimate: true,
    infoBox: false,
    selectionIndicator: false,
    sceneModePicker: false,
    shadows: false,
    imageryProvider: new Cesium.TileMapServiceImageryProvider({
      url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
      credit: 'Map tiles by CartoDB, under CC BY 3.0. Data by OpenStreetMap, under ODbL.'
    })
  })
}
function removeIMap() {
  const imap = document.getElementById('imap');
  const parent = imap.parentElement;
  parent.removeChild(imap);
}
export function toCartesian(pixel, viewer) {
  const ray = viewer.camera.getPickRay(pixel);
  const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
  return cartesian;
}
export function toDegrees(pixel, viewer) {
  const cartesian = toCartesian(pixel, viewer);
  const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  return {
    lon: Cesium.Math.toDegrees(cartographic.longitude),
    lat: Cesium.Math.toDegrees(cartographic.latitude),
    height: cartographic.height
  }
}
export function pickPosition(viewer, callback) {
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  handler.setInputAction(e => {
    const coord = toDegrees(e.position, viewer);
    if (callback) {
      callback(coord);
    }
    handler.destroy();
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

}
export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.floor((Math.random() * 16));
    // y值限定在[8,B]
    /* eslint-disable */
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
export class CursorTip {
  constructor(viewer, text) {
    this._viewer = viewer;
    this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    this.ele = document.createElement('div');
    this.ele.innerHTML=text;
    this.ele.style.minWidth="150px";
    this.ele.style.backgroundColor='#33333399';
    this.ele.style.color='#ddd';
    this.ele.style.padding="5px";
    this.ele.style.borderRadius='5px'
    this.handler.setInputAction(e => {
      const pixel = e.endPosition;
      this.ele.style.left = pixel.x + 'px';
      this.ele.style.top = pixel.y + 'px';
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    viewer.container.appendChild(this.ele);
    this.ele.style.position = 'absolute';
  }
  destroy() {
    this.handler.destroy();
    this._viewer.container.removeChild(this.ele);
    this._viewer = undefined;
  }
}
export default {
  loadJs,
  getFingerPrint,
  createEarth,
  removeIMap
}

export {
  loadJs,
  getFingerPrint,
  createEarth,
  removeIMap
}
