<template>
  <transition
    appear
    name="animate__animated animate__move"
    enter-active-class="animate__flipInX"
    leave-active-class="animate__flipOutX"
  >
    <div class="widget-ToolBox" ref="widget-ToolBox">
      <div class="tool-list">
        <div
          class="list-item"
          v-for="item of toolList"
          :key="item.name"
          :title="item.name"
          v-show="isFold"
          @click="activeEvent(item.name)"
        >
          <img v-if="item.name == '数据面板'" :src="dataPanelImg" />
          <el-popover v-if="item.name == '基础地图'" placement="left" trigger="hover">
            <div class="baseMapChangePanel">
              <div
                class="baseMapItem"
                v-for="item of baseMapList"
                :key="item.name"
                :class="selectTdtType === item.TdtType ? 'layerselected' : ''"
              >
                <el-checkbox
                  v-model="labelOn"
                  class="baseMapItemLabel"
                  label="注记"
                  @change="layerLabelCheckChange(item.TdtType, item.PoiType, $event)"
                  :class="{ baseMapItemLabelHide: selectTdtType !== item.TdtType }"
                ></el-checkbox>
                <div class="baseMapItemName">{{ item.name }}</div>
                <el-image
                  class="baseMapItemImage"
                  :src="item.url"
                  fit="cover"
                  @click="layerItemClick(item.TdtType, item.PoiType)"
                ></el-image>
              </div>
            </div>
            <img slot="reference" :src="item.imgUrl" />
          </el-popover>
          <img v-if="item.name !== '基础地图' && item.name !== '数据面板'" :src="item.imgUrl" />
        </div>
        <div class="list-item" :title="'工具栏'" @click="isFold = !isFold">
          <img :src="!isFold ? unfoldUrl : foldUrl" />
        </div>
      </div>
      <div class="roam-panel" v-show="isRoaming">
        <ViewManagement :show="isRoaming" />
      </div>
    </div>
  </transition>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import ViewManagement from '@/views/groupPage/districtPageModules/customTools/viewManagement.vue'
const Cesium = (window as any).Cesium
const viewMemoryType = {
  none: 'none',
  pre: 'pre',
  after: 'after'
} //记录视图
//工具栏
@Component({ name: 'ToolBox', components: { ViewManagement } })
export default class ToolBox extends Vue {
  baseMapList: Array<any> = [
    {
      name: '电子地图',
      url: require('@/views/groupPage/images/工具栏/电子地图.png'),
      TdtType: 'vec_w',
      PoiType: 'cva_w'
    },
    {
      name: '影像地图',
      url: require('@/views/groupPage/images/工具栏/影像地图.png'),
      TdtType: 'img_w',
      PoiType: 'cia_w'
    },
    { name: '大屏地图', url: require('@/views/groupPage/images/工具栏/大屏地图.png'), TdtType: 'bs_w', PoiType: '' }
  ]
  labelOn: boolean = true
  selectTdtType = 'bs_w'
  toolList: Array<any> = [
    { name: '数据面板' },
    { imgUrl: require('@/views/groupPage/images/工具栏/基础地图.png'), name: '基础地图' },
    { imgUrl: require('@/views/groupPage/images/工具栏/初始范围.png'), name: '初始范围' },
    { imgUrl: require('@/views/groupPage/images/工具栏/俯视.png'), name: '俯视' },
    { imgUrl: require('@/views/groupPage/images/工具栏/左视图.png'), name: '上一视图' },
    { imgUrl: require('@/views/groupPage/images/工具栏/右视图.png'), name: '下一视图' },
    { imgUrl: require('@/views/groupPage/images/工具栏/漫游.png'), name: '漫游' }
    // { imgUrl: require('@/views/groupPage/images/工具栏/图片.png'), name: '截图' },
    // { imgUrl: require('@/views/groupPage/images/工具栏/鹰眼.png'), name: '鹰眼' }
  ]
  dataPanelImg = null
  unfoldUrl = require('@/views/groupPage/images/工具栏/展开.png')
  foldUrl = require('@/views/groupPage/images/工具栏/收起.png')
  isFold: boolean = true
  isRoaming: boolean = false //漫游面板
  g_preViews = [] //前一视图
  g_afterViews = [] //后一视图
  g_viewType = viewMemoryType.none //前或后视图
  viewer
  get mapConfig() {
    return this.$store.state.bigScreen.mapConfig
  }
  get isInitViewer() {
    return this.$store.state.bigScreen.isInitViewer
  }
  get isDataPanelShow() {
    return this.$store.state.bigScreen.currentActive
  }
  @Watch('isInitViewer')
  onChangeMethod() {
    this.viewer = (window as any).viewer
    this.cameraMoveEvent()
  }
  @Watch('isDataPanelShow', { immediate: true })
  onShowMethod(n) {
    if (n != '') {
      this.dataPanelImg = require('@/views/groupPage/images/工具栏/收起-面板.png')
    } else {
      this.dataPanelImg = require('@/views/groupPage/images/工具栏/展开-面板.png')
    }
  }
  mounted() {
    let target = this.$refs['widget-ToolBox'] as any
    target.style.setProperty('--right', '2.291667rem')
    target.style.setProperty('--bottom', '0.052083rem')
  }
  activeEvent(type) {
    switch (type) {
      case '初始范围':
        this.initPosition()
        break
      case '上一视图':
        this.preView()
        break
      case '下一视图':
        this.afterView()
        break
      case '俯视':
        this.lookDown()
        break
      case '漫游':
        this.roaming()
        break
      case '数据面板':
        this.activePanel()
        break
    }
  }
  activePanel() {
    if (this.$store.state.bigScreen.currentActive != '') {
      this.$store.state.bigScreen.currentActive = ''
    } else {
      this.$store.state.bigScreen.currentActive = 'ProjectPanoramic'
    }
  }
  //初始位置
  initPosition() {
    // const initPosition = this.mapConfig.initPosition
    // const carto = Cesium.Cartographic.fromDegrees(
    //   parseFloat(initPosition.lon),
    //   parseFloat(initPosition.lat),
    //   parseFloat(initPosition.height)
    // )
    // let camera = Cesium.Cartographic.toCartesian(carto)
    // if (!camera) return
    // this.viewer.camera.setView({
    //   destination: new Cesium.Cartesian3(camera.x, camera.y, camera.z),
    //   orientation: {
    //     heading: 0,
    //     pitch: Cesium.Math.toRadians(-90),
    //     roll: 0
    //   }
    // })
    this.viewer.camera.setView({
      destination: { x: -2002099.8064685483, y: 5125053.48587751, z: 3240386.7848629407 },
      orientation: {
        heading: 6.241173904929705,
        pitch: -0.3248275425737035,
        roll: 6.283185307179586
      }
    })
  }
  //前一视图
  preView() {
    if (!this.g_preViews || this.g_preViews.length === 0) {
      return
    }
    this.g_viewType = viewMemoryType.pre
    const camera = this.viewer.camera
    const pos = Cesium.Cartesian3.clone(camera.position)
    const heading = camera.heading
    const pitch = camera.pitch
    const roll = camera.roll
    const currentview = {
      destination: pos,
      orientation: {
        heading: heading,
        pitch: pitch,
        roll: roll
      }
    }
    const view = this.g_preViews[this.g_preViews.length - 1]
    this.g_preViews.pop()
    this.g_afterViews.push(currentview)
    this.viewer.camera.setView({
      destination: view.destination,
      orientation: view.orientation
    })
  }
  //后一视图
  afterView() {
    if (!this.g_afterViews || this.g_afterViews.length === 0) {
      return
    }
    this.g_viewType = viewMemoryType.after
    const camera = this.viewer.camera
    const pos = Cesium.Cartesian3.clone(camera.position)
    const heading = camera.heading
    const pitch = camera.pitch
    const roll = camera.roll
    const currentview = {
      destination: pos,
      orientation: {
        heading: heading,
        pitch: pitch,
        roll: roll
      }
    }
    const view = this.g_afterViews[this.g_afterViews.length - 1]
    this.g_afterViews.pop()
    this.g_preViews.push(currentview)
    this.viewer.camera.setView({
      destination: view.destination,
      orientation: view.orientation
    })
  }
  //地图视图移动事件
  cameraMoveEvent() {
    this.viewer.camera.moveStart.addEventListener((e) => {
      const camera = this.viewer.camera
      const pos = Cesium.Cartesian3.clone(camera.position)
      const heading = camera.heading
      const pitch = camera.pitch
      const roll = camera.roll
      const view = {
        destination: pos,
        orientation: {
          heading: heading,
          pitch: pitch,
          roll: roll
        }
      }
      if (this.g_viewType === viewMemoryType.none) {
        this.g_afterViews.length = 0
        this.g_afterViews = []
        if (this.g_preViews && this.g_preViews.length === 10) {
          this.g_preViews.shift()
        }
        this.g_preViews.push(view)
      } else if (this.g_viewType === viewMemoryType.pre) {
        if (this.g_afterViews && this.g_afterViews.length === 10) {
          this.g_afterViews.shift()
        }
      } else {
        if (this.g_preViews && this.g_preViews.length === 10) {
          this.g_preViews.shift()
        }
      }
      this.g_viewType = viewMemoryType.none
    })
  }
  //俯视
  lookDown() {
    const camera = this.viewer.camera
    camera.flyTo({
      destination: camera.position,
      orientation: {
        // 视角
        heading: 0,
        pitch: Cesium.Math.toRadians(-90),
        roll: camera.roll
      }
    })
  }
  //漫游面板操作
  roaming() {
    this.isRoaming = true
  } //地图选择面板点击事件
  layerItemClick(layerType, poiType) {
    if (layerType === this.selectTdtType) return
    this.initTianditu(layerType, poiType)
    this.labelOn = true
    this.selectTdtType = layerType
  }
  //切换加载天地图
  initTianditu(layerType, poiType) {
    const layerName = layerType.split('_')[0]
    const poiName = poiType.split('_')[0]
    //地形影像高级别无图
    const maximumLevel = layerType === 'ter_w' ? 13 : 17
    const token = this.$store.state.bigScreen.tdttoken
    const url =
      'https://t{s}.tianditu.gov.cn/' +
      layerType +
      '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
      layerName +
      '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
      token
    const poiurl =
      'https://t{s}.tianditu.gov.cn/' +
      poiType +
      '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
      poiName +
      '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
      token
    const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
    const imagelayers = this.viewer.imageryLayers
    const layerlen = imagelayers.length
    //清除所有底图
    const removedLayers = []
    for (let i = 0; i < layerlen; i++) {
      const layer = imagelayers.get(i)
      const provider = layer.imageryProvider
      if (
        provider.credit &&
        (provider.credit.html === 'tianditu_base' ||
          provider.credit.html === 'tianditu_poi' ||
          provider.credit.html === 'chinavec2d')
      ) {
        removedLayers.push(layer)
      }
    }
    removedLayers.forEach((item) => {
      imagelayers.remove(item)
    })
    //添加大屏底图
    if (layerType == 'bs_w') {
      this.initBigScreenBaseMap()
      return
    }
    //添加图层
    const imglayer = new Cesium.WebMapTileServiceImageryProvider({
      //影像底图
      url: new Cesium.Resource({
        url: url,
        headers: {
          Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
        }
      }),
      subdomains,
      credit: 'tianditu_base',
      layer: 'tdtVecLayer',
      style: 'default',
      maximumLevel: maximumLevel,
      format: 'image/jpeg',
      tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
      show: true
    })

    const poilayer = new Cesium.WebMapTileServiceImageryProvider({
      url: new Cesium.Resource({
        url: poiurl,
        headers: {
          Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
        }
      }),
      subdomains: subdomains,
      credit: 'tianditu_poi',
      layer: 'tdtCvaLayer',
      style: 'default',
      format: 'image/jpeg',
      maximumLevel: maximumLevel,
      tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
      show: true
    })
    imagelayers.addImageryProvider(imglayer, 1)

    imagelayers.addImageryProvider(poilayer, 2)
  }
  //注记勾选事件
  layerLabelCheckChange(layerType, poiType, event) {
    const token = this.$store.state.bigScreen.tdttoken
    const poiName = poiType.split('_')[0]
    const poiurl =
      'https://t{s}.tianditu.gov.cn/' +
      poiType +
      '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
      poiName +
      '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
      token

    const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
    const imagelayers = this.viewer.imageryLayers
    const check = event
    if (check) {
      const poilayer2 = new Cesium.WebMapTileServiceImageryProvider({
        url: new Cesium.Resource({
          url: poiurl,
          headers: {
            Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
          }
        }),
        subdomains: subdomains,
        credit: 'tianditu_poi',
        layer: 'tdtCvaLayer',
        style: 'default',
        format: 'image/jpeg',
        maximumLevel: 17,
        tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
        show: true
      })
      imagelayers.addImageryProvider(poilayer2, 2)
    } else {
      for (let i = 0; i < imagelayers.length; i++) {
        const layer = imagelayers.get(i)
        const provider = layer.imageryProvider
        if (provider.credit && provider.credit.html === 'tianditu_poi') {
          imagelayers.remove(layer)
          break
        }
      }
    }
  }
  //初始化加载大屏底图
  initBigScreenBaseMap() {
    const imagelayers = this.viewer.imageryLayers
    const url = this.mapConfig.gisResource.img.config['chinavec2d'].url
    const imglayer = new Cesium.SuperMapImageryProvider({
      url: url,
      credit: 'chinavec2d'
    })
    imagelayers.addImageryProvider(imglayer, 1)
  }
}
</script>
<style lang="scss">
.baseMapChangePanel {
  display: flex;
  .baseMapItem {
    margin: 0 0.03125rem; /* 6/192 */
    width: 0.416667rem /* 80/192 */;
    height: 0.416667rem /* 80/192 */;
    position: relative;
  }
  .baseMapItem.layerselected {
    border: 1px solid rgba(51, 133, 255, 1);
  }
  .baseMapItemLabel {
    width: 100%;
    position: absolute;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 999;
  }
  .baseMapItemLabelHide {
    display: none;
  }
  .baseMapItemImage {
    height: 100%;
    width: 100%;
  }
  .baseMapItemName {
    width: 100%;
    position: absolute;
    bottom: 0;
    text-align: center;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 999;
  }
}
</style>
<style lang="scss" scoped>
.animate__flipInX,
.animate__flipOutX {
  animation-duration: 3s; //动画持续时间
  animation-delay: 0s; //动画延迟时间
}
.widget-ToolBox {
  z-index: 2;
  //position
  bottom: var(--bottom); //0.052083rem /* 10/192 */;
  margin-right: var(--right); //2.291667rem /* 440/192 */;
  position: absolute;
  right: 0;
  //size
  //background
  color: #eee;
  //font
  font-family: Source Han Sans CN;
  .tool-list {
    display: flex;
    flex-flow: column;
    justify-content: center;
    align-items: flex-end;
    .list-item {
      width: 0.177083rem /* 34/192 */;
      height: 0.177083rem /* 34/192 */;
      background: rgba(7, 51, 84, 0.9);
      border-radius: 0.010417rem /* 2/192 */;
      margin: 0.026042rem /* 5/192 */;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transition: width 0.3s;
      img {
        height: 0.09375rem /* 18/192 */;
        width: 0.09375rem /* 18/192 */;
        object-fit: contain; //保持原有尺寸比例。内容被缩放。
      }
    }
    .list-item:hover {
      width: 0.229167rem /* 44/192 */;
      background: rgba(7, 51, 84, 1);
    }
  }
  .roam-panel {
    position: absolute;
    width: 1.354167rem /* 260/192 */;
    height: 1.546875rem /* 297/192 */;
    border: 1px solid rgba(43, 174, 253, 0.34);
    background: rgba(43, 174, 253, 0.34);
    right: 0.416667rem /* 80/192 */;
    bottom: 0.026042rem /* 5/192 */;
  }
}
</style>