import React, {useEffect, useState} from 'react'
import { Color } from "csstype"
import * as Cesium from 'cesium'
import { WebMapTileServiceImageryProvider, GeographicTilingScheme } from 'cesium'
import * as Ol from 'ol'
import createMVTWithStyle from './mvt'
import style from './style.module.css'

declare global {
  interface Window { CESIUM_BASE_URL: any; }
}

window.CESIUM_BASE_URL = './'

export interface LayerStyle {
  lineColor: Color,
  lineWidth: number,
  fillColor: Color
}

interface Props extends LayerStyle {
  url: string,
  lng: number,
  lat: number,
  height: number
}

function createStyle (style: LayerStyle) {
  let ol = Ol as any
  return new ol.style.Style({
    fill: new ol.style.Fill({
      color: style.fillColor,
      // stroke:"green"
    }),
    stroke: new ol.style.Stroke({
      color: style.lineColor,
      width: style.lineWidth,
      lineCap: "round",

    }),
  });
}

//天地图影像服务
const tdtImagerLayerProvider = new WebMapTileServiceImageryProvider({
  url: "http://{s}.tianditu.gov.cn/img_c/wmts?tk=463a3e5ee4e35c17ae02564f18f95655&service=wmts&request=GetTile&version=1.0.0" +
    "&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
    "&style=default&format=tiles",
  layer: "tdtImg_c",
  style: "default",
  format: "tiles",
  tileMatrixSetID: "c",
  subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
  tilingScheme: new GeographicTilingScheme(),
  tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
  maximumLevel: 50
})

function VectorView(props: Props) {
  const initViewer = void 0 as unknown as Cesium.Viewer
  const [viewer, setViewer] = useState(initViewer)


  useEffect(() => {
    let lviewer = new Cesium.Viewer('cesiumContainer', {
      baseLayerPicker: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      timeline: false,
      animation: false,
      navigationHelpButton: false,
      imageryProvider: tdtImagerLayerProvider
    });
    lviewer.camera.flyTo({
      duration: 1,
      destination: Cesium.Cartesian3.fromDegrees(props.lng, props.lat, props.height)
    });
    lviewer.scene.globe.baseColor = new Cesium.Color(1.0, 1.0, 1.0, 1.0);
    setViewer(lviewer)
  }, [1])


  useEffect(() => {
    if (!viewer) return;

    return;
    const clipLayer = createMVTWithStyle(Cesium, Ol, {
      url: props.url,
      style: createStyle(props)
    }) as any;

    viewer.imageryLayers.addImageryProvider(clipLayer);

    return () => {
      viewer.imageryLayers.remove(clipLayer, true)
    }
  })

  return (
    <div id="cesiumContainer" className={style.layer}></div>
  )
}

export default VectorView