<template>
  <div class="base">
    <div ref="target" class="container-viewer-1-"></div>
    <div ref="elCart" style="position: absolute; right: 80px; bottom: 80px"></div>
    <div
      v-if="spinning"
      style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: #fff"
    >
      <a-spin style="position: absolute; top: 50%; left: 50%" />
    </div>
    <div v-if="freezeRotY" style="position: absolute; top: 0; right: 0; bottom: 0; left: 0"></div>
  </div>
</template>

<script>
const viewer_ = null;

export default {
  components: {
    // JoyStick,
    // WayPointsList
  },
  data() {
    return {
      surveyId: null,
      shopData: null,
      page: null,
      page_shelves: null,
      sceneAction: null,
      elCart: null,
      defaultWare: null,

      isLocked: null,
      freezeRotY: false,

      spinning: true,

      // 此变量只是
      hold: null,

      isWayPointMode: false,
      useJoyStick: false
    };
  },

  watch: {
    page(newVal /* oldVal */) {
      // console.log('page ........', newVal, oldVal)
      if (viewer_) {
        viewer_.flyAnimation = !(this.defaultWare?.planetid && this.isLocked);
        viewer_.frostFarScene = this.isLocked;

        viewer_.arrange(newVal).then(() => {
          // this.$emit("onPageCompletion");
          setTimeout(() => {
            this.spinning = false;
          }, 200);
          window.parent.postMessage(
            JSON.stringify({
              command: 'onPageCompletion'
            }),
            '*'
          );

          // #20221018
          viewer_.hold({
            wareId: this.defaultWare?.planetid,
            keepHold: this.isLocked
            // 组件内置的固定角度有问题，单独通过遮罩实现
            // freezeRotY: this.freezeRotY ? "0" : undefined,
          });
        });
      }
    },

    page_shelves(newVal /* oldVal */) {
      // console.log('page ........', newVal, oldVal);
      if (viewer_) {
        viewer_.arrange_shelves(newVal).then(() => {
          // this.$emit("onPageCompletion");
          setTimeout(() => {
            this.spinning = false;
          }, 200);
          window.parent.postMessage(
            JSON.stringify({
              command: 'onPageCompletion'
            }),
            '*'
          );

          // #20221018
          viewer_.hold({
            wareId: this.defaultWare?.planetid,
            keepHold: this.isLocked
            // 组件内置的固定角度有问题，单独通过遮罩实现
            // freezeRotY: this.freezeRotY ? "0" : undefined,
          });
        });
      }
    },

    sceneAction(newVal /* oldVal */) {
      if (viewer_ && newVal) {
        viewer_.action(newVal.action);
      }
    },
    elCart(newVal /* oldVal */) {
      if (viewer_ && newVal) {
        // viewer_.elCart = newVal;
        viewer_.elCart = this.$refs.elCart;
      }
    }
  },
  mounted() {
    window.addEventListener('message', (e) => {
      let data = null;
      try {
        data = JSON.parse(e.data);
      } catch (e) {
        // mark
      }
      if (data?.command === 'setData') {
        Object.keys(data.data).forEach((key) => {
          this[key] = data.data[key];
        });
        this.$nextTick(() => this.tryInitView());
      }
    });

    window.parent.postMessage(
      JSON.stringify({
        command: 'getData'
      }),
      '*'
    );
  },
  // beforeUnmount: function () {
  //   if (viewer_) {
  //     viewer_.dispose();
  //     viewer_ = null;
  //   }
  // },

  methods: {
    debounce(func, wait) {
      let timeout;
      return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
      };
    },
    joyChange(e) {
      if (viewer_) {
        viewer_.doJoystick(e);
      }
    },

    gotoWayPoint(e) {
      if (viewer_) {
        viewer_.gotoWayPoint(e.wayPoint);
      }
    },

    tryInitView() {
      if (!viewer_) {
        // const isHall = this.shopData.type === 'hall';
        // this.useJoyStick = this.shopData.type == "hall";
        // useJoyStick: isHall && this.shopData?.hall.useRoaming // #20230802
        // #20230811
        /* useJoyStick: isHall; */ /* && isHallCanWalk(this.shopData.hall); */

        const sd = JSON.parse(JSON.stringify(this.shopData || {}));
        sd.shelves.forEach((shelve) => {
          // hideWhenSurvey 改成 true 时，不显示展台的紫色边框
          shelve.hideWhenSurvey = true;
        });

        // viewer_ = new SurveyViewer({
        //   container: this.$refs.target,
        //   surveyId: this.surveyId,
        //   shopData: sd,
        //
        //   prefixAsset: '/shelves-v5-asset' // v5, #20230104
        // });
        viewer_.on('loadingCompletion', () => {
          // this.$emit("onLoadingCompletion");
          window.parent.postMessage(
            JSON.stringify({
              command: 'onLoadingCompletion'
            }),
            '*'
          );
        });

        const changeHoldDebounce = this.debounce((d) => (this.hold = d), 500);
        viewer_.on('hold', (d) => {
          this.hold = null;
          // this.$emit("onHold", d);
          window.parent.postMessage(
            JSON.stringify({
              command: 'onHold',
              data: d
            }),
            '*'
          );

          changeHoldDebounce(d);
        });
        viewer_.on('from_scene_hold_to_shelf', () => {
          // this.$emit("onFromSceneHoldToShelf");

          if (!this.hold) return;

          this.sceneAction = {
            action: 'hold_to_shelf'
          };
          window.parent.postMessage(
            JSON.stringify({
              command: 'onFromSceneHoldToShelf'
            }),
            '*'
          );

          this.hold = null;
        });
        viewer_.on('behavior_flush', (q1) => {
          // this.$emit("onBehaviorFlush", q1);
          window.parent.postMessage(
            JSON.stringify({
              command: 'onBehaviorFlush',
              data: q1
            }),
            '*'
          );
        });

        viewer_.startup();
      }
      return viewer_;
    }
  }
};
</script>

<style>
html,
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}
</style>

<style scoped lang="scss">
.base {
  position: relative;
  width: 100%;
  height: 100%;
}

div.container-viewer-1- {
  width: 100%;
  height: 100%;
}

div.container-viewer-1-:focus {
  outline: none;
}

//div.container-viewer-1- > > > canvas:focus {
//  outline: none;
//}

.bottom-points-list {
  bottom: 140px;

  :deep(.yo-thumb .yo-obj-fit-cover) {
    object-fit: cover;
    width: 100% !important;
    height: 100%;
  }

  :deep(.yo-thumb) {
    cursor: pointer;
  }
}
</style>
