<template>
  <!-- 本模块是漫游功能 -->
  <div class="wanderClassStyle_only">
    <div class="bottonList">
      <span class="bottonListSpan" style="padding-left: 10px">我的收藏</span>
      <div @click="closeBasinStatus" style="float: right; cursor: pointer; margin-right: 10px; color: #25c7e3">
        <CloseOutlined type="delete-outlined" title="关闭" />
      </div>
      <a-popover :overlayClassName="'wanderDivPop'" v-model:visible="showPop" @visibleChange="fouceViewName" trigger="click" title="新增视点">
        <template #content>
          <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off">
            <a-form-item label="视点名称" name="viewName" :rules="[{ required: true, message: '请输入视点名称!' }]">
              <a-input ref="viewNameDom" v-model:value="formState.viewName" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button type="primary" html-type="submit" style="margin-right: 20px" @click="showPop = false">取消</a-button>
              <a-button type="primary" html-type="submit" @click="addInfo">确认</a-button>
            </a-form-item>
          </a-form>
        </template>
        <PlusOutlined class="bottonListDiv" @click="showPop = true" title="添加视点" />
      </a-popover>
      <CaretRightOutlined class="bottonListDiv" @click="playRoamingView" title="漫游播放" />
    </div>
    <div class="viewsList" id="viewsListId">
      <template v-if="dataList && dataList.length > 0">
        <template v-for="(item, index) in dataList" :key="'viewDiv_' + index">
          <div class="img-item viewDiv" :class="currentIndex == index ? 'isActive' : ''">
            <a-popconfirm title="确认删除当前视图？" ok-text="确认" @confirm="deleteView(index)" cancel-text="取消">
              <CloseOutlined class="bottondeleteDiv" type="delete-outlined" title="删除视点" />
            </a-popconfirm>
            <img class="viewImgDiv" :src="item.notes" :id="index" @click="goto(item, index)" />
            <a-checkbox class="mapControlCheckbox" v-model:checked="item.checked"
              ><span :title="item.markName">{{ item.markName }}</span></a-checkbox
            >
          </div>
        </template>
      </template>
      <template v-else>
        <span>暂无漫游视点</span>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { defHttpFun } from '/@/utils/http/axios';
import { message } from 'ant-design-vue';
import { RightCircleOutlined, PlusCircleOutlined, CloseOutlined, CaretRightOutlined, PlusOutlined } from '@ant-design/icons-vue';
export default {
  name: 'wander', //漫游
  components: {
    RightCircleOutlined,
    PlusCircleOutlined,
    CloseOutlined,
    CaretRightOutlined,
    PlusOutlined,
  },
  setup(props, ctx) {
    let dataList = reactive([]); //临时保存所有的数据
    const formState = reactive({ viewName: '' });
    let viewNameDom = ref(null);
    let viewer = null;
    let showPop = ref(false);
    let currentIndex = ref(-1);
    const addViewInfoApi = '/yxBase/dpviews';
    const getViewInfoApi = '/yxBase/dpviews/page';
    const deleteViewInfoApi = '/yxBase/dpviews';
    const sendSet = { joinPrefix: false, apiUrl: '' };
    const tempEvent = window.setInterval((e) => {
      if (window.map) {
        viewer = window.map.viewer;
        window.clearInterval(tempEvent);
        getViewList();
        imgDrag();
      }
    }, 200);

    /**
     * 添加视图
     */
    function addInfo() {
      const scanvas = viewer.scene.canvas;
      const img = map.mapPrint(50, 50, 'jpg', true);
      const option = new FormData();
      if (formState.viewName == '') {
        return;
      }
      const cameraTemp = {
        direction: viewer.camera.direction,
        up: viewer.camera.up,
        position: viewer.camera.position,
      };
      const camera = JSON.stringify(cameraTemp);
      option.append('markName', formState.viewName);
      option.append('camera', camera);
      option.append('notes', img);
      defHttpFun(sendSet)
        .post({ url: addViewInfoApi, data: option })
        .then((res) => {
          if (res.code == 1) {
            getViewList();
            showPop.value = false;
            formState.viewName = '';
            message.success('添加视点成功');
          } else {
            message.error('添加视点失败');
          }
        });
    }

    /**
     * 获取视点列表
     *
     */
    function getViewList() {
      currentIndex.value = -1;
      defHttpFun(sendSet)
        .get({ url: getViewInfoApi, params: { size: 1000, current: 1 } })
        .then((res) => {
          if (res.code == 1) {
            res.result.records.forEach((item) => {
              item.checked = true;
            });
            console.log(res,'resresres');
            dataList.length = 0;
            dataList.push(...res.result.records);
          } else {
            message.error('获取视点失败');
          }
        });
    }

    /**
     * 移动至选中视图
     *
     */
    function goto(data, index) {
      currentIndex.value = index;
      dataList.forEach((item) => {
        item.isCurrent = false;
      });
      data.isCurrent = true;
      let camera = JSON.parse(data.camera);
      if (camera) {
        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),
          },
        });
      }
    }

    /**
     * 播放视点
     */
    function playRoamingView() {
      var playList = dataList.filter((item) => item.checked);
      const tempData = JSON.parse(JSON.stringify(playList));
      currentIndex.value = 0;
      fly(JSON.parse(tempData[0].camera));
      function fly(camera) {
        var p = new Cesium.Cartesian3(camera.position.x, camera.position.y, camera.position.z);
        viewer.camera.flyTo({
          destination: p,
          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: () => {
            if (tempData.length != 0) {
              // map.rotateAroundPoint(map.getScreenCenter(), null, 5, (e) => {
              //   if (e > 7) {
              //     map.rotateAroundPoint();
              //     tempData.splice(0, 1);
              //     currentIndex.value = currentIndex.value + 1;
              //     fly(JSON.parse(tempData[0].camera));
              //   }
              // });
              setTimeout(() => {
                tempData.splice(0, 1);
                currentIndex.value = currentIndex.value + 1;
                fly(JSON.parse(tempData[0].camera));
              }, 5000);
            }
          },
        });
      }
    }

    /**
     * 图片拖拽
     */
    function imgDrag() {
      let btn = document.getElementById('viewsListId');
      addHandler(btn, 'dragstart', function (e) {
        btn.dragStartEle = getTarget(e);
      });
      addHandler(btn, 'dragover', function (e) {
        preventDefault(e);
        btn.dragEndEle = getTarget(e);
      });
      addHandler(btn, 'dragenter', function (e) {
        preventDefault(e);
      });
      addHandler(btn, 'drop', function (e) {
        let target = getTarget(e);
        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 = dataList[startI];
            dataList[startI] = dataList[endI];
            dataList[endI] = temp;
            currentIndex.value = -1;
          }
        }
      });
    }
    function 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;
      }
    }
    function getTarget(event) {
      return event.target || event.srcElement;
    }
    function preventDefault(event) {
      if (event.preventDefault) {
        event.preventDefault();
      } else {
        event.returnValue = false;
      }
    }

    /**
     * 视点删除
     */
    function deleteView(index) {
      defHttpFun(sendSet)
        .delete({
          url: deleteViewInfoApi + '/' + dataList[index].id,
          data: { id: dataList[index].id },
        })
        .then((res) => {
          if (res.code == 1) {
            currentIndex.value = -1;
            getViewList();
            message.success('删除视点成功');
          } else {
            message.success('删除视点失败');
          }
        });
    }

    /**
     * 添加视点聚焦
     */
    function fouceViewName(data) {
      if (data && viewNameDom) {
        window.setTimeout((e) => {
          if (viewNameDom.value && viewNameDom.value.focus) {
            viewNameDom.value.focus();
          }
        }, 200);
      }
    }

    // 关闭我的收
    let basinStatus = ref(false);
    // const emit = defineEmits(['changeBasinStatus'])
    const closeBasinStatus = () => {
      basinStatus.value = false;
      ctx.emit('changeBasinStatus', basinStatus);
    };

    return {
      showPop,
      viewNameDom,
      fouceViewName,
      playRoamingView,
      deleteView,
      currentIndex,
      formState,
      dataList,
      addInfo,
      goto,
      basinStatus,
      closeBasinStatus,
    };
  },
};
</script>

<style lang="less" scoped>
[data-theme='dark'] .wanderClassStyle_only {
  width: 230px;
  height: 270px;
  padding-left: 0px;
  // box-shadow: inset 0px 0px 2px 2px rgba(4, 143, 231, 0.7);
  // border: 1px solid #1778ab;
  .viewsList {
    margin-left: 5px;
    height: calc(100% - 65px);
    width: 100%;
    overflow: auto;
    position: absolute;
    top: 40px;
  }
  .bottonListDiv {
    font-size: 16px;
    color: #25c7e3;
    padding: 5px 12px 0px 0px;
    position: relative;
    float: right;
  }
  .viewDiv {
    width: 100px;
    height: 100px;
    position: relative;
    float: left;
    margin: 5px;
    border: 2px solid #619eff2e;
  }
  .isActive.isActive {
    border: 4px solid #04f7fa !important;
  }
  label.ant-checkbox-wrapper.mapControlCheckbox {
    background: rgba(0, 0, 0, 0.5);
    // background: rgba(255,255,255,0.5);
    position: absolute;
    bottom: 0px;
    text-align: left;
    padding-left: 4px;
    width: 100%;
    color: white;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .bottonList {
    display: inline-block;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 16px;
    // background: rgba(30, 84, 130, 0.3);
    // opacity: 0.86;
    // border-bottom: 1px solid #0b5d7c;
    // opacity: 0.86;
    border-bottom: 1px solid #0b5d7c;
    width: 100%;
    .bottonListSpan {
      padding-left: 15px;
      top: 4px;
      left: 0px;
      font-size: 16px;
    }
  }
  img.viewImgDiv {
    position: absolute;
    top: 0px;
    width: 100%;
    height: 100%;
  }
  .bottondeleteDiv {
    font-size: 14px;
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 10;
    background: rgba(0, 0, 0, 0.7);
    color: #999999;
  }
  .ant-checkbox-inner {
    border: 1px solid white;
  }
}

[data-theme='dark'] .wanderDivPop {
  .ant-popover-inner {
    // background-color: rgba(8, 39, 55, 0.5) !important ;
    border: 1px solid #0b5d7c;
    background: #031a26;
    opacity: 0.86;
    border-radius: 3px;
  }
  .ant-popover-inner:after {
    content: '';
    position: absolute;
    bottom: 10px;
    left: 0;
    width: 100%;
    border-bottom: 1px solid transparent;
    border-image: linear-gradient(90deg, #0b5d7c 0%, #fff 50%, rgba(255, 255, 255, 0) 99%) 1;
  }
  .ant-input,
  .ant-form-item-label > label,
  .ant-popover-title {
    color: white;
    // border-bottom: 1px solid #0b5d7c !important;
  }
  .ant-popover-title {
    // color: white;
    border-bottom: 1px solid #0b5d7c !important;
  }
}
</style>
