<template>
  <div class="widget-viewManagement">
    <div class="header">
      <div class="title">漫游</div>
      <div class="close" @click="closePanel()"><i class="el-icon-close" /></div>
      <div class="edit">
        <span class="icon" @click="playRoamingView()"
          ><img :src="require('@/views/groupPage/images/工具栏/播放.png')"
        /></span>
        <span class="icon" @click="addScreenShot()">
          <el-popover placement="top" width="200" v-model="tipVisible">
            <el-input placeholder="请输入视点名称" v-model="viewName" size="small" clearable ref="viewNameInput">
            </el-input>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="resetRoamingViewAdd()">取消</el-button>
              <el-button type="primary" size="mini" @click="submitRoamingView()">确定</el-button>
            </div>
            <img :src="require('@/views/groupPage/images/工具栏/添加.png')" slot="reference" />
          </el-popover>
        </span>
        <span class="icon" @click="deleteRoamingView()"
          ><img :src="require('@/views/groupPage/images/工具栏/删除.png')"
        /></span>
      </div>
    </div>
    <div class="img-content" id="myBtn">
      <!-- 在HTML5标准中，为了使元素可拖动，把draggable属性设置为true。
    文本、图片和链接是默认可以拖放的，它们的draggable属性自动被设置成了true。
    图片和链接按住鼠标左键选中，就可以拖放。文本只有在被选中的情况下才能拖放。
    如果显示设置文本的draggable属性为true，按住鼠标左键也可以直接拖放。 -->
      <div class="img-item" v-for="(item, i) in roamViewImageList" :key="i">
        <img :src="item.src" :id="i" :class="{ isActive: currentViewIndex == i }" @click="clickToView(item, i)" />
        <el-checkbox v-model="item.checked">{{ item.name }}</el-checkbox>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { Canvas2Image } from '@/utils/mapCommon/tools'
import axios from '@/utils/request'
import CesiumViewTool from '@/utils/mapCommon/CesiumViewTool'
const Cesium = (window as any).Cesium
const getViewListApi = '/tofly-sxgk/views/get' //获取视图接口
const addViewInfoApi = '/tofly-sxgk/views/save' //添加视图接口
const deleteViewApi = '/tofly-sxgk/views/deleteByIds' //删除视图接口
const getImg = '/base/file/loadImg'
@Component({ name: 'viewManagement' })
export default class viewManagement extends Vue {
  viewer
  get isInitViewer() {
    return this.$store.state.bigScreen.isInitViewer
  }
  @Watch('isInitViewer')
  onChangeViewerMethod(val) {
    this.viewer = (window as any).viewer
  }
  //漫游数据
  isRoaming: boolean = false //漫游面板
  viewName = ''
  tipVisible = false
  cameraTemp: {} //相机位置
  roamingViewSrc = '' //屏幕图片
  roamViewImageList = [] //视点列表
  currentViewIndex = null //当前视图
  @Prop({ type: Boolean, default: false }) show!: Boolean
  @Watch('show')
  onChangeMethod(val) {
    if (val) this.init()
  }
  init() {
    this.imgDrag()
    this.getRoamingView()
  }
  //图片拖拽
  imgDrag() {
    let btn = document.getElementById('myBtn') as any
    let that = this
    this.addHandler(btn, 'dragstart', function (e) {
      btn.dragStartEle = that.getTarget(e)
    })
    this.addHandler(btn, 'dragover', function (e) {
      that.preventDefault(e)
      btn.dragEndEle = that.getTarget(e)
    })
    this.addHandler(btn, 'dragenter', function (e) {
      that.preventDefault(e)
    })
    this.addHandler(btn, 'drop', function (e) {
      let target = that.getTarget(e)
      that.preventDefault(e)
      // 拖动元素，放置目标
      if (btn.dragStartEle && target) {
        if (target.nodeName === 'IMG' && btn.dragStartEle.nodeName === 'IMG') {
          // 根据id索引交换数据
          let startI = btn.dragStartEle.id
          let endI = btn.dragEndEle.id
          let temp = that.roamViewImageList[startI]
          that.$set(that.roamViewImageList, startI, that.roamViewImageList[endI])
          that.$set(that.roamViewImageList, endI, temp)
        }
      }
    })
  }
  addHandler(element, type, handler) {
    //  这里是兼容代码，不需要兼容的可以不加
    if (element.addEventListener) {
      element.addEventListener(type, handler, false)
    } else if (element.attachEvent) {
      element.attachEvent('on' + type, handler)
    } else {
      element['on' + type] = handler
    }
  }
  getTarget(event) {
    return event.target || event.srcElement
  }
  preventDefault(event) {
    if (event.preventDefault) {
      event.preventDefault()
    } else {
      event.returnValue = false
    }
  }
  //获取漫游视点
  getRoamingView() {
    this.isRoaming = true
    this.roamViewImageList = []
    axios.request({ url: getViewListApi, method: 'get', params: {} }).then((res) => {
      const result = res.result.records
      result.forEach((item) => {
        this.roamViewImageList.unshift({
          id: item.id,
          name: item.markName,
          src:
            axios.defaults.baseURL +
            getImg +
            '?remotePath=' +
            item.filePath +
            '&access_token=' +
            sessionStorage.getItem('token'),
          checked: true,
          camera: item.camera
        })
      })
    })
  }
  //添加
  addScreenShot() {
    ;(this.$refs['viewNameInput'] as any).focus()
    this.viewName = ''
    let canvas = this.viewer.scene.canvas
    let screenShot = Canvas2Image.convertToImage(canvas, 400, (400 * canvas.height) / canvas.width, 'png')
    this.roamingViewSrc = screenShot.src
    this.cameraTemp = JSON.stringify({
      direction: this.viewer.camera.direction,
      up: this.viewer.camera.up,
      position: this.viewer.camera.position
    })
  }
  //添加保存漫游视点
  submitRoamingView() {
    // this.roamViewImageList = [
    //   ...this.roamViewImageList,
    //   {
    //     name: this.viewName,
    //     src: this.roamingViewSrc,
    //     checked: true,
    //     camera: this.cameraTemp
    //   }
    // ]
    //视点图片
    let scanvas = this.viewer.scene.canvas
    let screenShot = Canvas2Image.convertToImage(scanvas, 400, (400 * scanvas.height) / scanvas.width, 'png')
    this.roamingViewSrc = screenShot.src
    //
    var canvas = document.createElement('CANVAS')
    var ctx = (<any>canvas).getContext('2d')
    var img = new Image()
    img.src = this.roamingViewSrc
    img.onload = function (e) {
      ;(<any>canvas).width = img.width
      ;(<any>canvas).height = img.height
      ctx.drawImage(img, 0, 0)
      ;(<any>canvas).toBlob(
        function (blob) {
          var extent = JSON.stringify(CesiumViewTool.GetViewExtent(this.viewer))
          var cameraTemp = {
            direction: this.viewer.camera.direction,
            up: this.viewer.camera.up,
            position: this.viewer.camera.position
          }
          var camera = JSON.stringify(cameraTemp)
          var option = new FormData()
          if (this.viewName == '') {
            this.$message('请填写视点名称')
            return
          }
          option.append('markName', this.viewName)
          option.append('camera', camera)
          option.append('extent', extent)
          option.append('file', blob, this.viewName + '.png')
          axios.request({ url: addViewInfoApi, method: 'post', data: option }).then((res) => {
            if (res.code == 1) {
              this.$message.success('添加视点成功')
              this.getRoamingView()
              this.tipVisible = false
            } else {
              this.$message.error('添加视点失败')
              this.tipVisible = false
            }
          })
        }.bind(this),
        'image/png'
      )
    }.bind(this)
  }
  //取消添加漫游视点
  resetRoamingViewAdd() {
    this.viewName = ''
    this.roamingViewSrc = ''
    this.tipVisible = false
  }
  //删除视点
  deleteRoamingView() {
    let deleteList = this.roamViewImageList.filter((item) => item.checked)
    if (deleteList.length < 1) {
      this.$message('请选择至少一个视点')
      return
    }
    let ids = []
    deleteList.map((item) => {
      ids.push(item.id)
    })
    this.roamViewImageList = this.roamViewImageList.filter((item) => !item.checked)
    axios.request({ url: deleteViewApi, method: 'DELETE', params: { ids: ids.join(',') } }).then((res) => {
      if (res.code == 1) this.$message.success('删除视点成功')
    })
  }
  //播放视点
  playRoamingView() {
    var playList = this.roamViewImageList.filter((item) => item.checked)
    var that = this
    if (playList.length > 0) {
      var i = 0
      var camera = JSON.parse(playList[i].camera)
      fly(camera)
      function fly(camera) {
        that.currentViewIndex = i
        that.viewer.camera.flyTo({
          destination: new Cesium.Cartesian3(camera.position.x, camera.position.y, camera.position.z),
          orientation: {
            direction: new Cesium.Cartesian3(camera.direction.x, camera.direction.y, camera.direction.z),
            up: new Cesium.Cartesian3(camera.up.x, camera.up.y, camera.up.z)
          },
          complete: () => {
            setTimeout(() => {
              if (i < playList.length - 1) {
                i += 1
                fly(JSON.parse(playList[i].camera))
              } else {
                that.currentViewIndex = null
              }
            }, 3000)
          }
        })
      }
    } else {
      this.$message('当前暂无视点')
    }
  }
  //单击定位至视点
  clickToView(data, index) {
    this.currentViewIndex = index
    let camera = JSON.parse(data.camera)
    this.viewer.camera.flyTo({
      destination: new Cesium.Cartesian3(camera.position.x, camera.position.y, camera.position.z),
      orientation: {
        direction: new Cesium.Cartesian3(camera.direction.x, camera.direction.y, camera.direction.z),
        up: new Cesium.Cartesian3(camera.up.x, camera.up.y, camera.up.z)
      },
      complete: () => {
        this.currentViewIndex = null
      }
    })
    console.log('视点数据', data)
  }
  //关闭面板
  closePanel() {
    this.isRoaming = false
    ;(this.$parent as any).isRoaming = false
  }
}
</script>

<style lang='scss' scoped>
.widget-viewManagement {
  height: 100%;
  width: 100%;
  .header {
    width: 100%;
    height: 0.208333rem /* 40/192 */;
    border-bottom: 1px solid rgba(43, 174, 253, 0.34);
    padding: 0.067708rem /* 13/192 */;
    .title {
      float: left;
      font-size: 0.072917rem /* 14/192 */;
      font-family: Source Han Sans CN-HEAVY;
      font-weight: bold;
      color: #0ea7ff;
      background: linear-gradient(0deg, #a3d3ff 0%, #e4f3ff 100%);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    .edit {
      float: right;
      margin-right: 0.0625rem /* 12/192 */;
      position: relative;
      width: 0.427083rem /* 82/192 */;
      height: 0.098958rem /* 19/192 */;
      display: flex;
      justify-content: space-around;
      align-items: center;
      span {
        cursor: pointer;
      }
    }
    .edit::before {
      content: '';
      position: absolute;
      width: 1px;
      height: 20px;
      background: rgba(43, 167, 255, 0.5);
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto 0;
    }
    .close {
      float: right;
      color: rgba(163, 211, 255, 1);
      font-size: 0.083333rem /* 16/192 */;
      cursor: pointer;
    }
  }
  .img-content {
    width: 100%;
    padding: 10px;
    height: calc(100% - 0.208333rem /* 40/192 */);
    overflow: auto;
    .img-item {
      float: left;
      height: 0.489583rem /* 94/192 */;
      width: 50%;
      img {
        width: 0.541667rem /* 104/192 */;
        height: 0.364583rem /* 70/192 */;
      }
      .isActive {
        border: 1px solid #0ea7ff;
      }
    }
  }
}
</style>