import { ref } from 'vue'

let viewer = null
const model = ref({
  name: null,
  lon: null,
  lat: null,
  level: null,
})
export function usePlaceName() {
  const showPlace = ref(true)
  function addPlaceName() {
    showPlace.value = !showPlace.value
  }

  return {
    model,
    showPlace,
    addPlaceName,
    initViewer,
    clickPoint,
  }
}

async function initViewer() {
  viewer = new Cesium.Viewer('place-earth', {
    selectionIndicator: false,
    animation: false,
    baseLayerPicker: false,
    // geocoder: false,
    timeline: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    infoBox: false,
    fullscreenButton: false,
    homeButton: false,

    imageryProvider: false,
    geocoder: new OpenStreetMapNominatimGeocoder(),
    // geocoder: new Cesium.CartographicGeocoderService(),
  })

  viewer.scene.debugShowFramesPerSecond = true
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(117.48, 30.67, 18000000.0),
  })

  viewer.clock.shouldAnimate = true
  viewer.shadows = false
  // viewer.scene.globe.enableLighting = true

  if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
    viewer.resolutionScale = window.devicePixelRatio
  }

  // 开启抗锯齿
  // viewer.scene.fxaa = true
  viewer.scene.postProcessStages.fxaa.enabled = true
  viewer.scene.skyBox = new Cesium.SkyBox({
    sources: {
      positiveX: 'GV/resources/theme/skyBox/PositiveX.jpg',
      negativeX: 'GV/resources/theme/skyBox/NegativeX.jpg',
      positiveY: 'GV/resources/theme/skyBox/PositiveY.jpg',
      negativeY: 'GV/resources/theme/skyBox/NegativeY.jpg',
      positiveZ: 'GV/resources/theme/skyBox/PositiveZ.jpg',
      negativeZ: 'GV/resources/theme/skyBox/NegativeZ.jpg',
      // positiveX: './images/skybox/skyCube2k_px.jpg',
      // negativeX: './images/skybox/skyCube2k_mx.jpg',
      // positiveY: './images/skybox/skyCube2k_py.jpg',
      // negativeY: './images/skybox/skyCube2k_my.jpg',
      // positiveZ: './images/skybox/skyCube2k_pz.jpg',
      // negativeZ: './images/skybox/skyCube2k_mz.jpg',
    },
  })

  viewer.terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
    'http://192.168.10.201:2022/api/maptilecache/service/terrain/taiwan-HeightMap-4326',
    {
      requestVertexNormals: true,
      requestWaterMask: true,
    }
  )

  viewer.imageryLayers.addImageryProvider(
    new Cesium.UrlTemplateImageryProvider({
      url: window.settings.map[3].url,
      tilingScheme: new Cesium[window.settings.map[3].tilingScheme](),
    })
  )
}

let getPointHandler = null
function clickPoint() {
  if (getPointHandler) {
    return
  }
  getPointHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  viewer._container.style.cursor = 'crosshair'
  getPointHandler.setInputAction(event => {
    const cartesian = viewer.scene.pickPosition(event.position)
    if (Cesium.defined(cartesian)) {
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      const longitude = Cesium.Math.toDegrees(cartographic.longitude)
      const latitude = Cesium.Math.toDegrees(cartographic.latitude)

      model.value.lon = longitude
      model.value.lat = latitude
    }

    getPointHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    getPointHandler = null
    viewer._container.style.cursor = ''
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

function OpenStreetMapNominatimGeocoder() {}
OpenStreetMapNominatimGeocoder.prototype.geocode = function (input) {
  const query = `format=jsonv2&accept-language=zh&polygon_geojson=1&countrycodes=cn&q=${input}`
  const requestString = 'https://nominatim.openstreetmap.org/search?' + query
  return Cesium.Resource.fetchJson(requestString) //请求url获取json数据
    .then(function (results) {
      let bboxDegrees
      return results.map(function (resultObject) {
        bboxDegrees = resultObject.boundingbox
        return {
          displayName: resultObject.display_name,
          destination: Cesium.Rectangle.fromDegrees(
            bboxDegrees[2],
            bboxDegrees[0],
            bboxDegrees[3],
            bboxDegrees[1]
          ),
        }
      })
    })
}

function AMapNominatimGeocoder() {}
AMapNominatimGeocoder.prototype.geocode = function (input) {
  const query = `key=****&keywords=${input}`
  const requestString = 'https://restapi.amap.com/v3/place/text?' + query
  return Cesium.Resource.fetchJson(requestString) //请求url获取json数据
    .then(function (results) {
      return results.pois.map(function (bboxDegrees) {
        let [lng, lat] = bboxDegrees['location'].split(',')
        return {
          displayName: bboxDegrees['name'],
          destination: Cesium.Rectangle.fromDegrees(lng, lat, lng, lat),
        }
      })
    })
}
