<!--  -->
<template>
  <div class="home">
    <div id="mars3dContainer" class="mars3d-container"></div>
    <!-- 右侧菜单 -->
    <div class="right-panel" :class="{ meanShow: arrowsShow }">
      <!-- 背景装饰 -->
      <div class="zhuangs"></div>
      <div class="zhuangs zhuangs2"></div>
      <!-- 左边箭头 -->
      <div class="arrows" @click="arrowsShow = !arrowsShow">
        <i class="el-icon-arrow-left" v-if="arrowsShow"></i>
        <i class="el-icon-arrow-right" v-else></i>
      </div>
      <div class="top">
        <p>恩施市不可移动文物</p>
        <p>一张图</p>
      </div>
      <!-- 搜索 -->
      <div class="search" @keyup.enter="onSearch">
        <div class="searchBtn" @click="onSearch"></div>
        <el-input
          placeholder="搜索"
          suffix-icon="el-icon-search"
          v-model="searchInput"
        >
        </el-input>
      </div>
      <!-- 下面内容 -->
      <div class="main">
          <div
            class="village-item"
            v-for="village in villageListForShow"
            :key="village.id"
            @click="flyToVillage(village)"
          >
            {{ village.name }}
          </div>
      </div>
    </div>
    <!-- 加载中 -->
    <div
      class="homeLoding"
      :class="{ homeLodingNone: isLoding }"
      v-loading="true"
    ></div>
  </div>
</template>

<script>
// mapIns存储初始化的地图map实例，如果map实例放在vue的data中会导致帧率下降严重
var mapIns = null;

//导入mars3d主库
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";

export default {
  name: "home",
  components: {},
  data() {
    //这里存放数据
    return {
      // 数据加载中
      isLoding: false,

      arrowsShow: false,
      searchInput: "",

      // 各个村的坐标
      villageList: [
        {
          id: 1, // id为0的时候opacity会是0
          name: "施州城墙",
          position: [109.471345476266, 30.264908395999],
          url: 'https://laser.4dkankan.com/index.html?m=SG-5IzoAc92GQ5#/',
        },
        {
          id: 2,
          name: "连珠塔",
          position: [109.477083135606, 30.256295997146],
          url: 'https://laser.4dkankan.com/index.html?m=SG-JxZKhK4V4gC',
        },
        {
          id: 3,
          name: "文昌祠",
          position: [109.47544759156, 30.265243689181],
          url: 'https://laser.4dkankan.com/index.html?m=SG-9JqSJcJsUJD#/',
        },
        {
          id: 4,
          name: "叶挺将军囚居旧址",
          position: [109.469196935811, 30.266042273551],
          url: 'https://laser.4dkankan.com/index.html?m=SG-04XoFHzSjtj',
        },
        {
          id: 5,
          name: "武圣宫",
          position: [109.471112185568, 30.259508411773],
          url: 'https://laser.4dkankan.com/index.html?m=SG-BHpX0QOO6XM',
        },
        {
          id: 6,
          name: "恩施地委、县委办公楼旧址",
          position: [109.472746593168, 30.2640848577],
          url: 'https://laser.4dkankan.com/index.html?m=SG-B5c1qD4RKrF#/',
        },
        {
          id: 7,
          name: "窑湾医院旧址",
          position: [109.490757403451, 30.274690006014],
          url: 'https://laser.4dkankan.com/index.html?m=SG-aMGJobc3Xrb#/',
        },
        {
          id: 8,
          name: "中共鄂西特务旧址",
          position: [109.487338918924, 30.255632116004],
          url: 'https://laser.4dkankan.com/index.html?m=SG-6KqcFGb0z6K#/',
        },
      ],
      // 模型图层
      // tilesetLayer: null,
    };
  },
  //监听属性 类似于data概念
  computed: {
    villageListForShow() {
      return this.villageList.filter((v) => v.name.includes(this.searchInput));
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    onZoom(event) {
      console.log("比例尺发生变化", event);

      const labelToShowAtXHeight = {
        20000: [],
        5000: [],
        3000: [],
        2000: [],
        1000: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      };

      const size = event.distance;

      const sizeArr = size < 1000 ? labelToShowAtXHeight[1000] : labelToShowAtXHeight[size] || [];

      const labelContentElList = document.querySelectorAll(".lableContent");

      const labelWrapperElList = document.querySelectorAll(".mars3d-divGraphic ");

      labelContentElList.forEach((v, i) => {
        const id = Number(v.getAttribute("_id"));

        if (sizeArr.includes(id)) {
          labelWrapperElList[i].style.opacity = "1";
          labelContentElList[i].style.pointerEvents = "auto";
        } else {
          labelWrapperElList[i].style.opacity = "0";
          labelContentElList[i].style.pointerEvents = "none";
        }
      });
    },
    // 初始化地图
    async initMap() {
      // 读取 config.json 配置文件
      const json = await mars3d.Util.fetchJson({ url: "config/config.json" });
      console.log("读取 config.json 配置文件完成", json); // 打印测试信息
      // 创建三维地球场景
      let map = new mars3d.Map("mars3dContainer", json.map3d);
      // 打印测试信息
      // console.log("mars3d的Map主对象构造完成", map);
      // console.log("其中Cesium原生的Cesium.Viewer为", map.viewer);
      mapIns = map;

      // 监听地图缩放
      map.controls.distanceLegend.on(mars3d.EventType.change, this.onZoom);

      // 加载模型
      // this.loadModel();

      // 创建图层，用于添加label
      let graphicLayer = new mars3d.layer.GraphicLayer();

      // 绑定图层得点击标签事件回调
      graphicLayer.on("click", (e) => {
        const attr = e.graphic.attr || {};
        this.$router.push({
          name: 'IframeWrapper',
          query: {
            url: attr.url,
          },
        })
      });

      map.addLayer(graphicLayer);

      // 添加村名label
      this.villageList.forEach((v) => {
        this.drawVillageLabel(graphicLayer, v.id);
      });

      return map;
    },
    drawVillageLabel(graphicLayer, id) {
      const acInfo = this.villageList.find((v) => v.id === id) || {};

      const labelGraphic = new mars3d.graphic.DivGraphic({
        position: new mars3d.LngLatPoint(
          acInfo.position[0],
          acInfo.position[1],
          100
        ),
        style: {
          html: `
            <div class="lableContent" _id=${id} >
              <div class="lableIconArea">
                <img id="lableIcon" src="data/lableIcon.png" />
              </div>
              <div>${acInfo.name}</div>
            </div>
            <div class="lableLine"></div>
          `,
          horizontalOrigin: mars3d.Cesium.HorizontalOrigin.LEFT,
          verticalOrigin: mars3d.Cesium.VerticalOrigin.BOTTOM,
          // distanceDisplayCondition: new mars3d.Cesium.DistanceDisplayCondition(0, 30000), // 按视距距离显示
          scaleByDistance: new mars3d.Cesium.NearFarScalar(
            1000,
            1.5,
            12000,
            0.8
          ),
          clampToGround: true,
        },
        attr: {
          id: acInfo.id,
          name: acInfo.name,
          url: acInfo.url,
        },
      });

      graphicLayer.addGraphic(labelGraphic);
    },
    onSearch() {
      if (this.searchInput === "") {
        return;
      }
      for (let item of this.villageList) {
        if (item.name === this.searchInput) {
          mapIns.flyToPoint(item.position, { radius: 3000 });
          return
        }
      }
      this.$notify({
        title: "错误",
        message: "请输入完整村名",
        type: "warning",
        position: "top-left",
      });
    },
    flyToVillage(village) {
      mapIns.flyToPoint(village.position, { radius: 3000 });
    },
    // 加载倾斜模型
    // loadModel(_map) {
    //   let tilesetLayer = new mars3d.layer.TilesetLayer({
    //     name: "江门模型",
    //     url: this.modelUrl,
    //     maximumScreenSpaceError: 2,
    //     maximumMemoryUsage: 1024,
    //     // position: {
    //     //   lng: 112.574748,
    //     //   lat: 22.376651,
    //     //   alt: 10,
    //     // },
    //     // "skipLevelOfDetail": true,
    //     // "loadSiblings": true,
    //     // "cullRequestsWhileMoving": true,
    //     // "cullRequestsWhileMovingMultiplier": 10,
    //     // "preferLeaves": true,
    //     dynamicScreenSpaceError: true,
    //     // "preloadWhenHidden": true,
    //     flyTo: false,
    //   });
    //   _map.addLayer(this.tilesetLayer);

    //   // 加载的事件 只执行一次
    //   tilesetLayer.on(mars3d.EventType.initialTilesLoaded, function (event) {
    //     console.log("触发initialTilesLoaded事件", event);
    //   });
    // },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    // 移动端和pc端的切换
    if (
      window.navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
    ) {
      // 移动端
      if (window.location.href.includes("web")) {
        window.location.href = window.location.href.replace("web", "webM");
        setTimeout(() => {
          location.reload(true);
        }, 1000);
      }
    }

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 初始化地图实例
    this.initMap().then(
      (map) => {
        setTimeout(() => {
          this.isLoding = true;
        }, 500);
      },
      (error) => {
        console.error("地图初始化失败", error);
      }
    );
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="less" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  background-size: cover;
  overflow: hidden;
  .homeLoding {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background-color: #c2b697;
    transition: all 0.5s;
    /deep/.el-loading-mask {
      background-color: transparent;
    }
    /deep/.path {
      stroke: #412c0c !important;
    }
  }
  .homeLodingNone {
    opacity: 0;
    pointer-events: none;
  }

  .right-panel {
    transform: translateX(0);
    transition: all 0.3s;
    color: #fff;
    padding: 20px;
    z-index: 200;
    position: absolute;
    top: 0;
    right: 0;
    width: 400px;
    height: 100%;
    background: rgba(202, 185, 153, 0.9);
    backdrop-filter: blur(4px);
    display: flex;
    flex-direction: column;
    &.meanShow {
      transform: translateX(400px);
    }
    .zhuangs {
      z-index: -1;
      position: absolute;
      bottom: 10px;
      left: 0;
      width: 307px;
      height: 124px;
      background: url("../assets/img/zhuans2.png");
      background-size: 100% 100%;
    }

    .zhuangs2 {
      top: 36%;
      bottom: auto;
      left: auto;
      right: 0;
      background: url("../assets/img/zhuans1.png");
      background-size: 100% 100%;
    }

    .arrows {
      padding-left: 2px;
      cursor: pointer;
      border-radius: 20px 0 0 20px;
      overflow: hidden;
      position: absolute;
      top: 50%;
      left: -20px;
      transform: translateY(-50%);
      width: 20px;
      height: 80px;
      display: flex;
      justify-content: center;
      align-items: center;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(202, 185, 153, 0.9);
        backdrop-filter: blur(4px);
        z-index: -1;
      }

      & > i {
        color: #fff;
        font-size: 20px;
      }
    }

    .top {
      flex: 0 0 auto;
      & > p {
        text-align: center;
        font-family: "思源宋体";
        font-size: 28px;
      }
    }

    .search {
      flex: 0 0 auto;
      position: relative;
      margin: 15px 0;

      .searchBtn {
        cursor: pointer;
        z-index: 10;
        position: absolute;
        top: 0;
        right: 0;
        width: 40px;
        height: 40px;
      }

      /*修改提示文字的颜色*/
      /deep/input::-webkit-input-placeholder {
        /* WebKit browsers */
        color: #c9a774;
      }

      /deep/input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #c9a774;
      }

      /deep/input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #c9a774;
      }

      /deep/input:-ms-input-placeholder {
        /* Internet Explorer 10+ */
        color: #c9a774;
      }

      /deep/.el-input__inner {
        border-radius: 20px;
        background-color: #efeee8;
        color: #c9a774;
      }

      /deep/.el-input__inner:focus {
        border-color: #c9a774;
      }

      /deep/.el-input__suffix {
        color: #c9a774;
        font-size: 20px;
      }
    }

    .main {
      flex: 1 0 1px;
      padding-left: 10px;
      padding-right: 10px;
      width: 100%;
      overflow: auto;
      >.village-item {
        cursor: pointer;
        margin-bottom: 10px;
        padding: 10px;
        background: rgba(202, 185, 153, 0.9);
        border-radius: 10px;
        font-size: 20px;
        font-family: "思源宋体";
        transition: all 0.3s;
        &:hover {
          background: #c9a774;
        }
      }
    }
  }
}

#mars3dContainer {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
}

/deep/.mars3d-divGraphic  {
  pointer-events: none !important;
}

/deep/.mars3d-divGraphic:hover  {
  z-index: 100 !important;
}

// 不这样写的话，在移动端就不会显示底部栏，从而露出火星科技的logo
/deep/.mars3d-locationbar {
  display: block !important;
}

/deep/.lableContent {
  width: 170px;
  height: 40px;
  background: url(../assets/img/lable.png) no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #fff;
  font-family: "思源宋体";
  cursor: pointer;
}

/deep/.lableContent:hover {
  background: url(../assets/img/lableA.png) no-repeat;
}

/deep/.lableContent:hover + .lableLine {
  border: 1px solid rgb(192, 48, 55);
}

/deep/.lableContent:hover .lableIconArea img {
  content: url(../assets/img/lableIconA.png);
}

/deep/.lableIconArea {
  display: flex;
  align-items: center;
  justify-content: center;
}

/deep/.lableLine {
  width: 0px;
  height: 80px;
  margin-top: -10px;
  border: 1px solid rgb(226, 204, 163);
}


@media screen and (orientation: portrait) {
  .right-panel {
    top: initial !important;
    right: 0 !important;
    bottom: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 66.7% !important;
    .arrows {
      border-radius: 20px 20px 0 0 !important;
      overflow: hidden;
      position: absolute;
      top: -20px !important;
      left: 20% !important;
      transform: translateX(-50%) !important;
      width: 80px !important;
      height: 20px !important;
      >i {
        transform: rotate(90deg);
      }
    }
  }
  .right-panel.meanShow {
    transform: translateY(100%) !important;
  }
}

</style>
