import * as Cesium from 'cesium/Cesium';

/**
 * Cesium工具类
 */
const CesiumUtils = {

  /**
   * 定义CGCS2000椭球体
   *
   * @returns {Object}
   */
  defineCGCS2000Ellipsolid() {
    return new Cesium.Ellipsoid(6378137.0, 6378137.0, 6356752.31414035585);
  },

  /**
   * 定义CGCS2000投影
   * @param {Object} cgs2000Ellipsolid -CGCS2000椭球体
   *
   * @returns {Object}
   */
  defineCGCS2000Projection(cgs2000Ellipsolid) {
    return new Cesium.GeographicProjection(cgs2000Ellipsolid);
  },

  /**
   * 定义CGCS2000切片方案
   * @param {Object} cgs2000Ellipsolid -CGCS2000椭球体
   *
   * @returns {Object}
   */
  defineCgcs2000TilingScheme(cgs2000Ellipsolid) {
    return new Cesium.GeographicTilingScheme({
      ellipsoid: cgs2000Ellipsolid,
      rectangle: Cesium.Rectangle.fromDegrees(-180, -90, 180, 90),
      numberOfLevelZeroTilesX: 2,
      numberOfLevelZeroTilesY: 1
    });
  },

  /**
   * 获取CesiumViewer
   *
   * @returns {Object}
   */
  getViewer() {
    return window.viewer;
  },

  /**
   * 世界坐标转经纬度
   * @param {Object} cartesian3 -世界(笛卡尔)坐标
   * @param {Object} ellipsoid -椭球体
   *
   * @returns {Number[]} 经纬度
   */
  cartesian3ToLonLat(cartesian3, ellipsoid = null) {
    let cartographic;
    // 世界坐标转地理坐标(弧度)
    if (ellipsoid) {
      cartographic = ellipsoid.cartesianToCartographic(cartesian3);
    } else {
      cartographic = Cesium.Cartographic.fromCartesian(cartesian3)
    }

    // 地理坐标(弧度)转经纬度
    let lon = Cesium.Math.toDegrees(cartographic.longitude);
    let lat = Cesium.Math.toDegrees(cartographic.latitude);
    let alt = cartographic.height;

    return [lon, lat, alt];
  },

  /**
   * 设置视点
   * @param {Object} viewer
   * @param {Number[]} lonLat -经纬度([longitude, latitude, altitude])
   * @param {Number} orientation -方位(同bearing)([heading, pitch, roll])
   *
   * @summary<参数orientation内的值均为°，其中heading同bearing>
   */
  setView(lonLat, orientation) {
    let viewer = this.getViewer();

    // 摄像机位置: 经度、纬度、高度
    let longitude = lonLat[0];
    let latitude = lonLat[1];
    let altitude = lonLat.length > 2 ? lonLat[2] : 0;
    let initialPosition = new Cesium.Cartesian3.fromDegrees(longitude,latitude,altitude);

    // 飞行方位：方位角、俯仰角、翻滚角
    let heading = orientation[0];
    let pitch = orientation[1];
    let roll = orientation.length > 2 ? orientation[2] : 0;
    let initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(heading, pitch, roll)

    viewer.scene.camera.setView({
      destination: initialPosition,
      orientation: {
        heading: initialOrientation.heading,
        pitch: initialOrientation.pitch,
        roll: initialOrientation.roll,
      },
    });
  }
};

export default CesiumUtils;
