<template>
  <slot></slot>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { BrowsingRecordApi } from '../js/api';

const has3dPages = ['/answer'];

export default defineComponent({
  components: {},
  props: {
    isStemMiddle: {
      type: Boolean,
      default: false
    },
    // 题干
    stem: {
      type: String,
      default: ''
    },
    // 配置
    config: {
      type: Object,
      default: () => ({})
    },
    // 样本SN
    answerSn: {
      type: String,
      default: ''
    },
    // 问卷SN
    answerSurveySn: {
      type: String,
      default: ''
    },
    question: {
      type: Object,
      default: () => ({})
    },
    cartWaresLength: {
      type: Number,
      default: 0
    },
    // 是否移动端
    isMobile: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      scene: null,

      shopData: null,
      page: null,
      page_shelves: null,
      sceneAction: null,
      elCart: null,
      hold: null,

      // 用于控制下一页点击
      pager: {
        // 判断能否点击
        activate: false,
        timeoutId: 0,
        // 初始化点击延迟
        init(time = 3000) {
          this.activate = false;
          if (this.timeoutId) {
            clearTimeout(this.timeoutId);
            this.timeoutId = 0;
          }
          this.timeoutId = setTimeout(() => {
            this.activate = true;
          }, time);
        },
        // 清空延迟
        clear() {
          if (this.timeoutId) {
            clearTimeout(this.timeoutId);
            this.timeoutId = 0;
          }
        }
      },

      showTimeTimeoutId: 0
    };
  },
  computed: {
    canUse3D() {
      return this.config.is_three_dimensions && has3dPages.includes(this.$route.path);
    },
    surveyId() {
      return this.config.scene;
    },
    // scene() {
    //   return this.config.scene_information;
    // },
    shelves() {
      if (!this.scene) return [];
      return this.scene.shelves || [];
    },
    shelf() {
      if (!this.config.shelf) return this.shelves[0];
      return this.shelves.find((x) => x.planetid === this.config.shelf);
    },
    wares() {
      if (!this.shelf) return [];
      return this.shelf.wares;
    },
    ware() {
      return this.wares.find((x) => x.planetid === this.config.ware);
    },
    options() {
      let options = [];
      try {
        this.question.list.forEach((item) => {
          item.options.forEach((option) => {
            // question_index为0代表当前题型，为了支持复制题时引用的question_index错误的问题
            const questionIndex = item.relation_question_index || 0;
            options.push({
              ...option,
              question_index: questionIndex
            });
          });
        });
        if (this.question.hideOptions) {
          options = options.filter(
            (option) => !this.question.hideOptions.includes(option.option_key)
          );
        }
      } catch (e) {
        return [];
      }
      return options;
    },
    defaultWare() {
      return this.ware;
    }
  },
  beforeUnmount() {
    this.pager.clear();
    if (this.showTimeTimeoutId) clearTimeout(this.showTimeTimeoutId);
  },
  async mounted() {
    if (!this.canUse3D) return;

    if (this.config.is_binding_goods) {
      this.$refs.SceneGuidance?.show({
        isSelect: true,
        isMobile: this.isMobile
      });
    } else {
      this.$refs.SceneGuidance?.show({
        isSelect: false,
        isMobile: this.isMobile
      });
    }

    this.pager.init();

    this.scene = JSON.parse(this.config.scene_information);

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

    // console.log('scene', this.scene);

    this.shopData = buildShopDataDemo(this.scene);
    this.$refs.SceneSurveyViewer.init();

    if (this.config.is_show_time && this.config.show_time) {
      this.showTimeTimeoutId = setTimeout(() => {
        this.showTimeTimeoutId = 0;
        this.$emit('next');
      }, this.config.show_time * 1000);
    }
  },
  methods: {
    next() {
      // console.log(this.pager.activate);
      if (!this.pager.activate) {
        return;
      }
      this.pager.init();

      this.$emit(
        'next',
        () =>
          new Promise((resolve) => {
            this.sceneAction = {
              action: 'hold_to_shelf'
            };
            setTimeout(() => resolve(), 100);
          })
      );
    },
    previous() {
      if (!this.pager.activate) {
        return;
      }
      this.pager.init();

      this.sceneAction = {
        action: 'hold_to_shelf'
      };
      setTimeout(() => {
        this.$emit('previous');
      }, 100);
    },
    onLoadingCompletion() {
      this.shopData.shelves.forEach((shelf) => {
        let wares = shelf.wares;

        // 选项随机
        if (this.options && this.options.length && this.config.is_binding_goods) {
          wares = this.options
            .filter((option) => !option.is_other)
            .map((option) => {
              return this.wares.find(
                (ware) =>
                  ware.question_index === option.question_index &&
                  ware.option_index === option.option_index
              );
            });
          wares = wares.filter((x) => x);
        }

        if (shelf.layoutType === 'multiCols') {
          shelf.cells = shelf.cells.map((cell, index) => {
            return {
              ...cell,
              ...wares[Math.floor(index / shelf.originCells.length) % wares.length],
              showSign: !!this.config.is_price_tag,
              showLogo: !!this.config.is_brand
            };
          });
        } else {
          shelf.cells = this.shelf.cells.map((cell, index) => {
            return {
              ...cell,
              ...wares[index % this.wares.length],
              showSign: !!this.config.is_price_tag,
              showLogo: !!this.config.is_brand
            };
          });
        }
      });

      this.page_shelves = {
        shelves: this.shopData.shelves
      };
    },
    onFromSceneHoldToShelf() {
      this.hold = null;
      // this.sceneAction = {
      //   action: "hold_to_shelf",
      // };
    },
    onPageCompletion() {
      this.elCart = this.$refs.cart;
    },
    onUiHoldToCart() {
      if (!this.hold) return;
      this.sceneAction = {
        action: 'hold_to_cart'
      };
      const hold = this.hold;
      this.hold = null;

      const ware = this.wares.find((ware) => ware.planetid === hold.data.surveyWare.id);
      if (!ware) return;

      let option = null;
      this.question.list.forEach((qgroup) => {
        // 获取question_index，考虑到关联选项
        const questionIndex = qgroup.relation_question_index || 0;
        if (questionIndex !== ware.question_index) return;
        qgroup.options.forEach((qoption) => {
          if (qoption.option_index !== ware.option_index) return;
          option = qoption;
        });
      });

      if (!option) return;

      this.$emit('onHoldToCart', option);
    },
    onHold(hold) {
      this.hold = hold;
    },
    // 用户行为记录
    onBehaviorFlush(data) {
      // 判断是否记录
      if (!this.config.is_behavior) return;

      if (!data[0]) return;

      if (!this.answerSn || !this.answerSurveySn) return;

      BrowsingRecordApi.browsingRecordSurveys({
        sn: this.answerSurveySn,
        data: {
          sn: this.answerSn,
          question_index: this.question.question_index,
          question_type: this.question.question_type,
          planet_id: data[0].wareId,
          shelve_planet_id: data[0].shelfId,
          action_info: data
        }
      }).catch(/* (e) => console.error(e) */);
    }
  }
});
</script>

<style lang="scss" scoped>
@import 'viewer.utils';

.answerviewer {
  top: 0;
  left: 0;

  // width: 100vw;
  // height: 100vh;
  // position: fixed;
  background-color: #fff;

  // z-index: 99;
}

// .answerviewerVague {
//   .q-content-mask {
//     position: fixed;
//     left: 0;
//     right: 0;
//     top: 0;
//     bottom: 0;
//     background-color: rgba($color: #000000, $alpha: 0.3);
//   }
//   :deep(canvas) {
//     filter: blur(5px);
//   }
// }
</style>
