<!--
 * @Author: sjl
 * @Date: 2023-04-18 16:31:23
 * @Descripttion:
-->
<template>
  <div :class="`boxtools ${mapStore.rightSideMenu ? 'boxtools3' : 'boxtools2'}`">
    <div class="rightPanel">
      <img
        src="../../assets/images/leftshou.png"
        :class="{ rotated: !mapStore.rightSideMenu }"
        @click="mapStore.rightSideMenu = !mapStore.rightSideMenu"
        alt=""
    /></div>

    <ul>
      <li title="地图视图截图"><img src="../../assets/images/截图.png" @click="mapScreenshot" alt="" /> </li>
      <li v-show="showSideMenu" title="坐标定位"><img src="../../assets/images/gj/jwd.png" @click="locationClose" alt="" /></li>
      <li v-show="showSideMenu" title="数据播放"><img src="../../assets/images/sjz.png" @click="timeline" alt="" /></li>
      <li title="双屏对比" v-show="showSideMenu" @click="openDoubleScreen"><img src="../../assets/images/jldb.png" alt="" srcset="" /></li>
      <li title="初始范围" @click="flyHome()"><img src="../../assets/images/gj/home.png" alt="" srcset="" /></li>
      <li v-show="showSideMenu" :title="mapStore.sideMenu ? '面板收起' : '面板展开'" @click="sideMenu()">
        <img src="../../assets/images/kh.png" v-if="mapStore.sideMenu" alt="" srcset="" />
        <img src="../../assets/images/zk.png" v-else alt="" srcset="" />
      </li>
    </ul>
  </div>
  <div style="display: flex; height: 100%; width: 100%; position: absolute; z-index: -1" id="farmImage" v-if="showScreenshot">
    <img :src="mainImgSource" alt="" />
    <div v-if="showmaptitels" class="title"
      ><div style="margin-top: -10px">{{ maptitels }}</div></div
    >

    <!-- <div style="padding: 0 10px;background-color: aliceblue;">{{ value }}</div> -->

    <img :src="assistantImgSource" alt="" style="float: right" />
    <div v-if="showdoubletitels" class="title2"
      ><div style="margin-top: -10px">{{ doubletitels }}</div></div
    >

    <div class="zhibeizheng" style="visibility: visible"
      ><div
        style="visibility: visible"
        class="sm-compass"
        data-bind="visible: showCompass, event: { mousedown: handleMouseDown , touchstart : handleMouseDown, mouseup: handleMouseUp, touchend: handleMouseUp}"
        ><div class="sm-compass-tilt" style="visibility: visible"></div
        ><div
          class="sm-compass-tiltbar"
          data-bind="style : { left :  + tiltbarLeft + 'px',top : + tiltbarTop + 'px'}"
          style="left: 89px; top: 15px; visibility: visible"
        ></div
        ><div class="sm-compass-arrows" style="visibility: visible"></div
        ><div
          class="sm-compass-outer-ring"
          data-bind="style: { transform: 'rotate(-' + heading + 'rad)', '-webkit-transform': 'rotate(-' + heading + 'rad)' }"
          style="transform: rotate(-6.28193rad); visibility: visible"
        ></div
        ><div style="visibility: visible" class="arrows_e_active"></div><div class="arrows_n_active"></div><div class="arrows_s_active"></div
        ><div style="visibility: visible" class="arrows_w_active"></div></div
      ><div class="sm-zoom" style="visibility: visible"
        ><div class="sm-zoomin" data-bind="event : {mousedown : handleZoomInMouseDown,touchstart : handleZoomInMouseDown}"></div
        ><div class="sm-zoomout" data-bind="event : {mousedown : handleZoomOutMouseDown, touchstart : handleZoomOutMouseDown}"></div
        ><div
          class="sm-zoombar"
          data-bind="event : {mousedown : handleZoomBarScrollMouseDown, touchstart : handleZoomBarScrollMouseDown},style : {top : + zoombarTop + 'px' }"
          style="top: 65px"
        ></div> </div
    ></div>

    <div
      id="distance-legend"
      class="distance-legend"
      data-bind="visible: distanceLabel &amp;&amp; barWidth"
      style="display: block; visibility: visible; margin-left: 1720px"
      ><div class="distance-legend-label" data-bind="text: distanceLabel" style="visibility: visible">{{ scaleValue }}</div
      ><div
        class="distance-legend-scale-bar"
        data-bind="style: { width: barWidth + 'px', left: (5 + (125 - barWidth) / 2) + 'px' }"
        style="width: 75px; left: 30px; visibility: visible; top: 22px"
      ></div
    ></div>
  </div>
  <!-- <div class="timeline" v-if="timelineShow">
        <img src="../../assets/images/sjzmap.png" alt="" srcset="" />
      </div> -->
  <Timeline v-if="timelineShow" @showTime="showTime" />
  <Location v-if="locaShow" @locaShowWay="locaShowWay" />
</template>

<script>
import { defineComponent, reactive, ref, toRefs } from 'vue';
import { useMapStore } from '/@/store/modules/map';
import Timeline from './Timeline.vue';
import eventBus from '/@/utils/eventBus';
import { session } from '/@/utils/memory';
import Location from './Location/Location.vue';
import html2canvas from 'html2canvas';
export default defineComponent({
  name: 'ToolMenu',
  components: { Timeline, Location },
  setup() {
    const data = reactive({
      searchValue: ref(''),
      dialogVisible: ref(false),
    });
    const scaleValue = ref('30km');
    //坐标定位
    const locaShow = ref(false);
    const maptitels = ref();
    const showmaptitels = ref(false);
    const doubletitels = ref();
    const showdoubletitels = ref(false);
    const locaShowWay = (t) => {
      locaShow.value = t;
    };
    const mapStore = useMapStore();
    eventBus.on('getTitle', (data) => {
      console.log('data--截图', data.zymc, data.type);

      if (data.type === 'map') {
        showmaptitels.value = true;
        maptitels.value = data.zymc;
        console.log('地图标题加载？', maptitels.value);
      } else if (data.type === 'doubleScreenMap') {
        showdoubletitels.value = true;
        console.log('地图标题加载？', doubletitels.value);
        doubletitels.value = data.zymc;
      }
    });
    eventBus.on('closeLocation', (data) => {
      console.log('触发了');
      locaShow.value = data;
    });
    //点击按钮时关闭时间轴，由于在不同的组件中没有使用共同的状态管理，故每次点击都去关闭
    eventBus.on('timelineClose', (data) => {
      timelineShow.value = false;
    });
    //用于记录打开双屏前的状态
    let currentState = undefined;
    //控制展开数据面板按钮及双屏展示按钮
    const showSideMenu = ref(true);
    //中央控制事件,当双屏打开过后屏蔽数据展示，并且不能打开数据面板（doubleScreenControl会被触发多个，可以全局搜索doubleScreenControl）
    // 记录双屏
    let doubleScreenState = true;
    eventBus.on('doubleScreenControl', (data) => {
      doubleScreenState = data;
      console.log('shuangping', data);
      if (!data) {
        //打开双屏，记录当前状态
        currentState = mapStore.sideMenu;
        if (mapStore.sideMenu) {
          //关闭数据面板，并且屏蔽按钮
          sideMenu();
        }
        showSideMenu.value = false;
        timelineShow.value = false;
      } else {
        //关闭双屏
        showSideMenu.value = true; //展示按钮
        if (typeof currentState != 'undefined') {
          if (currentState) {
            sideMenu();
          }
        } else {
          //关闭双屏
          if (typeof currentState != 'undefined') {
            if (currentState) {
              sideMenu();
            }
            currentState = undefined;
          }
        }
      }
    });
    // 地图视图截图
    let showScreenshot = ref(true);
    let mainImgSource = ref('');
    let assistantImgSource = ref('');
    const mapScreenshot = () => {
      var maximumRadius = map.components.viewer.scene.globe.ellipsoid.maximumRadius;
      var scale = maximumRadius / map.components.viewer.camera.positionCartographic.height;
      scaleValue.value = (scale * 2).toFixed(2) + 'km';
      console.log('当前比例尺：' + scale);
      console.log(map.components.levelCoordinates, 'Components');

      var camera = map.components.viewer.scene.camera;
      var heading = Cesium.Math.toDegrees(camera.heading);
      console.log('指北针角度', heading);

      var compassElement = document.querySelector('.sm-compass-outer-ring');

      // 设置指北针的旋转角度
      compassElement.style.transform = `rotate(-${heading}deg)`;
      compassElement.style.webkitTransform = `rotate(-${heading}deg)`;

      // console.log(map.components.viewer.scene,'scene');
      let scene = map.components.viewer.scene;
      const scaleBar = scene.scalebar;

      //  const scale = scaleBar.getScale();
      //  console.log(scale,'scaleBar');
      if (doubleScreenState) {
        // 未打开双屏对比
        map.mapPrint();
      } else {
        // 打开双屏对比
        mainImgSource.value = map.mapPrint(null, null, null, true);
        assistantImgSource.value = doubleScreenMap.mapPrint(null, null, null, true);
        // 下载
        setTimeout(() => {
          downloadImg();
        }, 200);
      }
    };

    /**
     * 下载图片
     */
    function downloadImg() {
      var date = new Date();
      const canvasID = document.getElementById('farmImage');
      const rect = document.getElementById('farmImage').getBoundingClientRect();
      // 生成图片并上传到数据库保存
      html2canvas(canvasID, {
        scale: 1, // 数值越大生成的图片越清晰
        useCORS: true,
        allowTaint: true,
        y: 0, // 滚动条高度修复
        x: 0,
        allowTaint: true, //开启跨域
        useCORS: true,
        scrollX: 0,
        scrollY: rect.top, // 关键代码
        height: rect.height, // 加高度，避免截取不全
        width: rect.width - 1,
      }).then((canvas) => {
        let dataURL = canvas.toDataURL('image/jpeg'); // 拿到数据流
        var aLink = document.createElement('a'); // 创建一个a标签
        var blob = base64ToBlob(dataURL);
        var event = document.createEvent('HTMLEvents');
        event.initEvent('click', true, true);
        aLink.download = '地图视图' + date.getTime() + '.' + blob.type.split('/')[1]; // 使用时间戳给文件命名
        aLink.href = URL.createObjectURL(blob);
        console.log(aLink.href);
        aLink.click();
      });
    }

    /**
     * base64转Blob对象
     */
    function base64ToBlob(code) {
      var parts = code.split(';base64,');
      var contentType = parts[0].split(':')[1];
      var raw = window.atob(parts[1]);
      var rawLength = raw.length;
      var uint8Array = new Uint8Array(rawLength);
      for (var i = 0; i < rawLength; i++) {
        uint8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uint8Array], { type: contentType });
    }

    //
    eventBus.on('controlScreenshot', (data) => {
      showScreenshot.value = data;
    });
    /**
     * 打开双屏展示
     */
    function openDoubleScreen() {
      flyHome();
      showScreenshot.value = true;
      session.setItem('maplocation', map.getView(true));
      eventBus.emit('doubleScreenControl', false);
      var dom = document.getElementById('mapDivlevelCoordinates');
      if (dom) {
        dom.style.bottom = '82px';
        dom.style.paddingLeft = '0px';
      }
    }
    const sideMenu = () => {
      mapStore.setSideMenu();
      // mapStore.setLeftSideMenu();
      // mapStore.setRightSideMenu();
      if (mapStore.sideMenu) {
        mapStore.leftSideMenu = true;
        mapStore.rightSideMenu = true;
      } else {
        mapStore.leftSideMenu = false;
        mapStore.rightSideMenu = false;
      }
      var navigation = document.getElementsByClassName('cesium-viewer-navigationContainer')[0];
      if (mapStore.sideMenu) {
        if (navigation) navigation.style.right = '400px';
      } else {
        if (navigation) navigation.style.right = '-10px';
      }
    };

    const flyHome = () => {
      const tempData = {
        destination: { x: 93.8, y: 26.32060211195423, z: 666896.88999354467 },
        // destination:  { x: 94.44066857601297, y: 26.00104492171595, z: 666896.88999354467 },
        orientation: { heading: 6.283185307179586, pitch: -1.0182023771170687, roll: 6.283185307179586 },
      };
      map.flyTo(tempData, 1);
      // map.setView(tempData, 1);

      //双屏存在的情况下，同时进行初始位置定位
      if (window.doubleScreenMap) {
        window.doubleScreenMap.flyTo(tempData, 1);
      }
    };
    const timelineShow = ref(false);
    const timeline = () => {
      if (!timelineShow.value) {
        eventBus.emit('closeToolMenu', false);
      }
      timelineShow.value = !timelineShow.value;
    };
    //坐标定位

    // 子组件传过来关闭时间轴的参数
    const showTime = (value) => {
      console.log('子组件的值', value);
      timelineShow.value = value;
    };
    function locationClose() {
      locaShow.value = !locaShow.value;
      map.removeOverlay('LocationPoint_only*');
    }
    return {
      scaleValue,
      showmaptitels,
      showdoubletitels,
      maptitels,
      doubletitels,
      locaShowWay,
      locaShow,
      timelineShow,
      timeline,
      flyHome,
      ...toRefs(data),
      sideMenu,
      mapStore,
      showSideMenu,
      openDoubleScreen,
      showTime,
      locationClose,
      mapScreenshot,
      mainImgSource,
      assistantImgSource,
      showScreenshot,
    };
  },
});
</script>
<style scoped>
.timeline {
  position: fixed;
  top: 77px;
  left: 27%;
  z-index: 3;
}

.boxtools {
  position: absolute;
  z-index: 999;
  top: 31rem;
  right: 451px;
}

.boxtools2 {
  animation-name: move;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

@keyframes move {
  0% {
    right: 451px;
  }

  100% {
    right: 36px;
  }
}

.boxtools3 {
  animation-name: move2;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

@keyframes move2 {
  0% {
    right: 36px;
  }

  100% {
    right: 451px;
  }
}

.boxtools li {
  margin: 5px 0;
}
.title {
  padding: 0 10px;
  font-size: 16px;
  padding-top: 0px;
  top: 100px;
  left: 400px;
  /* background-color: white; */
  color: #fff;
  position: absolute;
  z-index: 999;
  height: 28px;

  border: 1px solid #0b5d7c;
  background: #031a26;
  opacity: 0.86;
  border-radius: 3px;
}
.title2 {
  padding: 0 10px;
  font-size: 16px;
  padding-top: 0px;
  top: 100px;
  left: 1350px;
  /* background-color: white; */
  color: #fff;
  position: absolute;
  z-index: 999;
  height: 28px;

  border: 1px solid #0b5d7c;
  background: #031a26;
  opacity: 0.86;
  border-radius: 3px;
}
.zhibeizheng {
  top: 70px;
  left: auto;
  right: 1200px;
}
.rightPanel {
  /* top: -496px; */
  top: -349px;
    right: -32px;
  height: 32px;
  position: absolute;
}
.rotated {
  transform: rotate(180deg);
}
</style>
