<template>
  <SceneSurveyViewer
    ref="SceneSurveyViewer"
    :shopData="shopData"
    :surveyId="surveyId"
    :hidden="true"
    :page="page"
    :page_shelves="page_shelves"
    @on-loading-completion="onLoadingCompletion"
  />
</template>

<script>
import { BrowsingRecordApi } from '../js/api';
import SceneSurveyViewer from './SceneSurveyViewerPage/Index.vue';

const has3dPages = ['/answer'];

export default {
  components: {
    SceneSurveyViewer
  },
  props: {
    // 问题列表
    questions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      first3DQuestion: null,
      sceneInformation: null,
      // 场景信息
      shopData: null,
      // 场景ID
      surveyId: null,
      // 商品摆放信息
      page: null,
      page_shelves: null
    };
  },
  computed: {
    canUse3D() {
      return has3dPages.includes(this.$route.path);
    }
  },
  watch: {
    questions: {
      async handler(arr) {
        if (!this.canUse3D) return;

        // 3D资源预获取
        try {
          const target = arr.find((question) => question?.config?.is_three_dimensions);
          this.first3DQuestion = target;

          if (!target) return;

          this.sceneInformation = JSON.parse(target?.config?.scene_information);

          if (!this.sceneInformation) {
            // 解决缓存问题，答卷时加载场景信息
            const res = await BrowsingRecordApi.getSurveysScene({
              sn: this.$route.query.sn,
              question_index: target.question_index
            });
            this.sceneInformation = JSON.parse(res.data?.scene_information);
          }

          if (!this.sceneInformation) return;
          // 初始化
          this.surveyId = target.config.scene;
          this.$refs.SceneSurveyViewer.init();
        } catch (e) {
          // console.warn(e);
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async onLoadingCompletion() {
      // 3D资源预获取
      try {
        const target = this.first3DQuestion;

        if (!target) return;

        const scene = this.sceneInformation;
        if (!scene) return;

        scene.shelves.forEach((shelf) => {
          const wares = shelf.wares;
          shelf.cells = shelf.cells.map((cell, index) => {
            return {
              ...cell,
              ...wares[index % wares.length],
              showSign: !!target.config?.is_price_tag,
              showLogo: false
            };
          });
        });
        this.page_shelves = {
          shelves: this.shopData.shelves
        };
      } catch (e) {
        // console.warn(e);
      }
    }
  }
};
</script>
