<template>
  <div class="widget-maptoolbar closetool">
    <div class="toolbars">
      <div
        class="layerChange toolitem"
        @click="initEvent('layerChange')"
        data-activeid="layerChange"
        title="背景地图切换"
      ></div>
      <div
        class="initPosition toolitem"
        @click="initEvent('initPosition')"
        data-activeid="initPosition"
        title="初始范围"
      ></div>
      <div class="preView toolitem" @click="initEvent('preView')" data-activeid="preView" title="前一视图"></div>
      <div class="afterView toolitem" @click="initEvent('afterView')" data-activeid="afterView" title="后一视图"></div>
      <div class="lookDown toolitem" @click="initEvent('lookDown')" data-activeid="lookDown" title="俯视"></div>
      <div class="legend toolitem" @click="initEvent('legend')" data-activeid="legend" title="图例"></div>
      <div class="measure toolitem" @click="initEvent('measure')" data-activeid="measure" title="测量"></div>
      <div class="screenShot toolitem" @click="initEvent('screenShot')" data-activeid="screenShot" title="截图"></div>
      <div class="infoCheck toolitem" @click="initEvent('infoCheck')" data-activeid="infoCheck" title="属性查看"></div>
      <div class="linkView toolitem" @click="initEvent('linkView')" data-activeid="linkView" title="地图模式切换"></div>
      <!-- <div
        class="linkView toolitem"
        @click="initEvent('linkView')"
        data-activeid="linkView"
        title="地图模式切换"
      ></div> -->
    </div>
    <div class="layerListPanel" v-show="layerSelVisible">
      <div
        class="panel-item"
        :class="selectTdtType === 'vec_w' ? 'layerselected' : ''"
        data-type="vec_w"
        data-poi="cva_w"
      >
        <el-checkbox
          v-model="labelOn"
          class="poi"
          :class="selectTdtType === 'vec_w' ? '' : 'hide'"
          label="注记"
          @change="layerLabelCheckChange('vec_w', 'cva_w', $event)"
        ></el-checkbox>
        <img src="./images/vec.png" @click="layerItemClick('vec_w', 'cva_w')" />
        <span class="title">地图</span>
      </div>
      <div
        class="panel-item"
        :class="selectTdtType === 'img_w' ? 'layerselected' : ''"
        data-type="img_w"
        data-poi="cia_w"
      >
        <el-checkbox
          class="poi"
          :class="selectTdtType === 'img_w' ? '' : 'hide'"
          label="注记"
          v-model="labelOn"
          @change="layerLabelCheckChange('img_w', 'cia_w', $event)"
        ></el-checkbox>
        <img src="./images/img.png" @click="layerItemClick('img_w', 'cia_w')" />
        <span class="title">影像</span>
      </div>
      <div
        class="panel-item"
        :class="selectTdtType === 'ter_w' ? 'layerselected' : ''"
        data-type="ter_w"
        data-poi="cta_w"
      >
        <el-checkbox
          class="poi"
          :class="selectTdtType === 'ter_w' ? '' : 'hide'"
          label="注记"
          v-model="labelOn"
          @change="layerLabelCheckChange('ter_w', 'cta_w', $event)"
        ></el-checkbox>
        <img src="./images/topo.png" @click="layerItemClick('ter_w', 'cta_w')" />
        <span class="title">地形</span>
      </div>
    </div>
    <div class="sceneModePanel" v-show="sceneModelVisible">
      <!-- <div class="panel-item" data-mode="2d">
            <img src="./widgets/MapToolBar/images/2d.png">
            <span>2D视图</span>
        </div> -->
      <div class="panel-item" data-mode="3d">
        <img src="./images/3d.png" @click="initSceneMode('3d')" />
        <span>3D视图</span>
      </div>
      <div class="panel-item" data-mode="2dwith3d">
        <img src="./images/3dand2d.png" @click="initSceneMode('2dwith3d')" />
        <span>2、3D联动</span>
      </div>
    </div>
    <div class="measurePanel" tabindex="1" contenteditable="false" v-show="measureVisible">
      <el-button-group class="toolbarBtns">
        <el-button data-type="measurelen" @click="measureClick('measurelen')"> 距离测量 </el-button>
        <el-button data-type="measurearea" @click="measureClick('measurearea')"> 面积测量 </el-button>
        <el-button data-type="measurez" @click="measureClick('measurez')">高度测量</el-button>
        <el-button data-type="measureangle" @click="measureClick('measureangle')"> 角度测量 </el-button>
        <el-button data-type="measurekj" @click="measureClick('measurekj')"> 管间测量 </el-button>
        <el-button data-type="clear" @click="measureClick('clear')">清除测量</el-button>
      </el-button-group>
    </div>
  </div>
</template>
<script>
const viewMemoryType = {
  none: 'none',
  pre: 'pre',
  after: 'after'
}
import Vue from 'vue'
import $ from 'jquery'
import { createQRCodePdf_api } from '@/api/APIs'
// import PipeUnitNowInfo from '@/views/widgets/PipeUnitNowInfo/index.vue'
import MeasurementBar from './MeasurementBar'
import { Canvas2Image } from '@/utils/mapCommon/tools'
export default {
  name: 'MapToolBar',
  data() {
    return {
      apiUrls: {
        downLoad: '/tofly-sxgk/commonFile/download'
      },
      layerSelVisible: false,
      sceneModelVisible: false,
      measureVisible: false,
      selectTdtType: 'vec_w',
      labelOn: true,
      g_preViews: [], //前一视图
      g_afterViews: [], //后一视图
      g_viewType: viewMemoryType.none //前或后视图
    }
  },
  props: {
    isInit: false //三维场景是否初始化
  },
  computed: {
    AppX() {
      return this.$store.getters.AppX
    }
  },
  watch: {
    isInit() {
      this.viewer = window.viewer
      this.cameraMoveEvent()
      this.measurementTool = new MeasurementBar(window.viewer)
      this.measurementTool.clampMode = Cesium.ClampMode.Ground
    }
  },
  methods: {
    initEvent(type) {
      var id = type
      switch (id) {
        case 'layerChange':
          this.layerChangeEvent()
          break
        case 'initPosition':
          this.initPosition()
          break
        case 'preView':
          this.preView()
          break
        case 'afterView':
          this.afterView()
          break
        case 'lookDown':
          this.lookDown()
          break
        case 'legend':
          this.mapLegend(true)
          break
        case 'screenShot':
          this.snapShotPrinting()
          break
        case 'infoCheck':
          this.lookAttriInfo()
          break
        case 'linkView':
          this.sceneModeChangeEvent()
          break
        case 'measure':
          this.measureTool()
          break
      }
    },
    lookAttriInfo() {
      // const pipeInfoConstructor = Vue.extend(PipeUnitNowInfo);
      // const pipeInfo = new pipeInfoConstructor({
      //   data: {
      //     isInteractive: true,
      //     locateUnit: null,
      //   },
      //   store: this.$store,
      // }).$mount();
    },
    /**
     * 地图选择面板点击事件
     */
    layerItemClick(layerType, poiType) {
      if (layerType === this.selectTdtType) return
      this.initTianditu(layerType, poiType)
      this.labelOn = true
      this.selectTdtType = layerType
    },
    /**
     * 注记勾选事件
     */
    layerLabelCheckChange(layerType, poiType, event) {
      const token = this.$store.state.cesiumMap.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
          }
        }
      }
    },
    layerChangeEvent() {
      if (!this.layerSelVisible) {
        this.layerSelVisible = true
      }
      $(this.viewer.canvas)
        .off('click')
        .on('click', () => {
          if (this.layerSelVisible) this.layerSelVisible = false
        })
    },
    sceneModeChangeEvent() {
      if (!this.sceneModelVisible) {
        this.sceneModelVisible = true
      }
      $(this.viewer.canvas)
        .off('click')
        .on('click', () => {
          if (this.sceneModelVisible) this.sceneModelVisible = false
        })
    },
    /**
     * 系统初始化加载天地图
     */
    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.cesiumMap.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')) {
          removedLayers.push(layer)
        }
      }
      removedLayers.forEach((item) => {
        imagelayers.remove(item)
      })

      //添加图层
      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,
        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)
      this.$store.dispatch('cesiumMap/tdtlayerChange', { base: layerType, poi: poiType })
      //鹰眼地图
      //this.AppX.runtimeConfig.overViewMap.updateTianditu(layerType);
    },
    /**
     * 初始位置
     */
    initPosition() {
      const degre = Cesium.Cartographic.fromCartesian(this.viewer.camera.position)
      console.log({
        lon: Cesium.Math.toDegrees(degre.longitude),
        lat: Cesium.Math.toDegrees(degre.latitude),
        height: degre.height
      })
      const initPosition = this.AppX.appConfig.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
        }
      })
    },
    /**
     * 该方法用于开关图例
     * @param open 开/关
     */
    mapLegend(open) {
      this.$store.dispatch('cesiumMap/mapLegendStatus', open)
    },
    /**
     * 前一视图
     */ 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
      })
    },
    /**
     * 该方法用于添加或删除movestart事件
     */
    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
        }
      })
    },
    /**
     * 快照打印
     */
    snapShotPrinting() {
      const gl = this
      const downloadUrl = this.apiUrls.downLoad
      const scenecanvas = this.viewer.scene.canvas
      const screenShot = Canvas2Image.convertToImage(scenecanvas, scenecanvas.width, scenecanvas.height, 'png')

      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      img.src = screenShot.src
      img.onload = function () {
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)
        canvas.toBlob(function (blob) {
          const option = new FormData()
          option.append('file', blob, '部件管理截图.png')
          createQRCodePdf_api(option)
            .then((res) => {
              if (res.data.code == 1) {
                const pdf = '/api' + downloadUrl + '?fileName=' + res.data.result
                window.open(pdf)
              } else {
                this.$message.error('导出PDF出错')
              }
            })
            .then(() => {
              if (type == 'preview') {
              }
            })
        })
      }
    },
    measureTool(e) {
      if (!this.measureVisible) {
        this.measureVisible = true
      }
      $(this.viewer.canvas)
        .off('click')
        .on('click', () => {
          if (this.measureVisible) this.measureVisible = false
        })
    },
    measureClick(operator, ev) {
      this.measurementTool.newMeasurement(operator, ev != undefined ? ev.currentTarget : null)
    },
    initSceneMode(mode) {
      this.$store.dispatch('cesiumMap/sceneModeChange', mode)
    }
  }
}
</script>
<style lang="scss" scoped>
$fontFamily: Source Han Sans CN;
.widget-maptoolbar {
  position: absolute;
  top: 185px;
  left: 35px;
  z-index: 998;
  .toolbars {
    position: relative;
    display: flex;
    display: -webkit-flex;
    flex-flow: column nowrap;
    align-items: center;
    @media screen and (max-width: 1700px) {
      .toolitem {
        box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
        width: 28px;
        height: 28px;
        margin-top: 10px;
        background-repeat: no-repeat;
        background-color: white;
        background-position: center;
        cursor: pointer;
      }
    }
    @media screen and (min-width: 1701px) {
      .toolitem {
        box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
        width: 36px;
        height: 36px;
        margin-top: 10px;
        background-repeat: no-repeat;
        background-color: white;
        background-position: center;
        cursor: pointer;
      }
    }
    .toolitem:hover {
      background-color: #efefefef;
    }
    .layerChange {
      background-image: url(./images/layerChange.png);
    }
    .initPosition {
      background-image: url(./images/initPosition.png);
    }
    .preView {
      background-image: url(./images/preView.png);
    }
    .afterView {
      background-image: url(./images/afterView.png);
    }
    .lookDown {
      background-image: url(./images/lookDwon.png);
    }
    .legend {
      background-image: url(./images/legend.png);
    }
    .measure {
      background-image: url(./images/measure.png);
    }
    .screenShot {
      background-image: url(./images/screenShot.png);
    }
    .infoCheck {
      background-image: url(./images/infoCheck.png);
    }
    .linkView {
      background-image: url(./images/linkView.png);
    }
  }
  .layerListPanel {
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
    display: flex;
    position: absolute;
    left: 60px;
    bottom: 360px;
    padding: 10px;
    background-color: white;
    div.layerselected {
      background-color: rgba(51, 133, 255, 1);
    }
    div {
      position: relative;
      margin: 6px;
      padding: 3px;
      span.title {
        position: absolute;
        bottom: 3px;
        left: 3px;
        right: 3px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        font-family: $fontFamily;
        background-color: rgba(0, 0, 0, 0.7);
      }
      .hide {
        display: none;
      }
      .poi {
        position: absolute;
        padding-right: 5px;
        top: 3px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        font-family: $fontFamily;
        background-color: rgba(0, 0, 0, 0.7);
      }
      img {
        width: 100px;
        height: 100px;
      }
    }
    .selected {
      span {
        background-color: rgba(51, 133, 255, 0.9);
      }
    }
  }
  .sceneModePanel {
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
    display: flex;
    position: absolute;
    left: 60px;
    bottom: 0;
    padding: 10px;
    background-color: white;
    div {
      position: relative;
      margin: 6px;
      span {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
        color: #fff;
        font-size: 14px;
        font-family: $fontFamily;
        background-color: rgba(0, 0, 0, 0.7);
      }
    }
    .selected {
      span {
        background-color: rgba(51, 133, 255, 0.9);
      }
    }
  }
  .measurePanel {
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
    display: flex;
    position: absolute;
    left: 60px;
    bottom: 135px;
    background-color: white;
    .toolbarBtns {
      width: max-content;
    }
    .toolbarBtns > .btn:not(:last-child)::after {
      content: ' ';
      width: 1px;
      height: 50%;
      background-color: #dedede;
      position: absolute;
      right: 0;
    }
    .el-button-group {
      .el-button {
        font-size: 0.875rem;
        box-shadow: none;
        padding: 0.55rem 0.65rem;
        color: #333333;
        font-size: 0.875rem;
      }
      .el-button:focus {
        color: #606266;
        background-color: #fff;
      }
      .el-button:hover {
        background-color: #fff;
      }
    }
  }
}
</style>