<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="imageText-preview" :style="[getAreaStyle(), getComponentStyle()]">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />
    <div v-if="data.video_list.length > 0" class="interaction-box">
      <!-- <video
        id="interaction-preview-video"
        :src="data.video_list[0].file_url"
        width="100%"
        height="400"
        controls
        controlsList="nodownload"
        @timeupdate="handleTimeUpdate"
      ></video> -->
      <video
        id="interaction-preview-video"
        ref="videoPlayer"
        :src="data.video_list[0].file_url"
        width="100%"
        height="400"
        controls
        class="video-js vjs-default-skin vjs-big-play-centered"
      ></video>
    </div>
    <!-- v-if="Object.keys(this.userAnswer).length === data.file_info_list.length" -->
    <el-button
      v-if="data.property.feed_back === 'total'"
      type="primary"
      :style="{
        background:
          data.unified_attrib && data.unified_attrib.topic_color ? data.unified_attrib.topic_color : '#165dff',
        borderColor:
          data.unified_attrib && data.unified_attrib.topic_color ? data.unified_attrib.topic_color : '#165dff',
        marginTop: '5px',
      }"
      @click="lookReport"
      >{{ convertText('查看答题报告') }}</el-button
    >
    <AnswerCorrect
      :answer-correct="data?.answer_correct"
      :visible.sync="visibleAnswerCorrect"
      @closeAnswerCorrect="closeAnswerCorrect"
    />
    <AnswerAnalysis
      :visible.sync="visibleAnswerAnalysis"
      :answer-list="data.answer_list"
      :analysis-list="data.analysis_list"
      @closeAnswerAnalysis="closeAnswerAnalysis"
    />
    <el-dialog
      v-if="visible"
      :visible.sync="visible"
      :show-close="false"
      :close-on-click-modal="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :lock-scroll="true"
      width="1040px"
    >
      <ExercisePreview
        :exercise_id="exercise_id"
        :feed_back="data.property.feed_back"
        @handleCancle="handleClose"
        @submitAdd="submitAdd"
      />
      <!-- <iframe v-if="visible" :src="newpath" width="100%" :height="iframeHeight" frameborder="0"></iframe> -->
    </el-dialog>
    <el-dialog
      v-if="reportFlag"
      :visible.sync="reportFlag"
      :show-close="true"
      :close-on-click-modal="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :lock-scroll="true"
      :width="isMobile ? '100%' : '1040px'"
      @close="handleClose"
    >
      <Report
        :report-result="reportResult"
        :exercise-list="exerciseList"
        :user-answer="userAnswer"
        :file-list="data.file_info_list"
        @handleCancle="handleClose"
      />
    </el-dialog>
  </div>
</template>

<script>
import ExercisePreview from './ExercisePreview.vue';
import Report from './Report.vue';
import PreviewMixin from '../common/PreviewMixin';
import { getVideoInteractionData } from '@/views/book/courseware/data/videoInteraction';
import { getConfig } from '@/utils/auth';
import 'videojs-markers/dist/videojs.markers.min.css';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import 'videojs-markers';
export default {
  name: 'VideoInteractionPreview',

  components: { ExercisePreview, Report },
  mixins: [PreviewMixin],
  props: {
    isMobile: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      data: getVideoInteractionData(),
      video_info: null,
      file_preview_url: getConfig() ? getConfig().doc_preview_service_address : '',
      visible: false,
      newpath: '',
      iframeHeight: `${window.innerHeight - 100}px`,
      first: '',
      exercise_id: '',
      userAnswer: {}, // 用户答题答案
      exerciseList: {}, // 题目列表
      reportFlag: false,
      reportResult: {
        total: 0,
        right: 0,
        error: 0,
        rightRate: 0,
      },
      player: null,
    };
  },
  watch: {
    isJudgingRightWrong(val) {
      if (!val) return;
      this.userAnswer = this.answer.answer_list[0];
    },
  },
  created() {
    this.initData();
  },
  mounted() {},
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  },
  methods: {
    initData() {
      this.data.file_info_list = this.data.file_info_list.sort((a, b) => Number(a.currentTime) - Number(b.currentTime));
      if (!this.isJudgingRightWrong) {
        this.answer.answer_list[0] = this.userAnswer;
      }
      if (this.data.video_list.length > 0) {
        let _this = this;
        this.$nextTick(() => {
          _this.handleCreatPlayer();
        });
      }
    },
    // 初始化player
    handleCreatPlayer() {
      let _this = this;
      let options = {
        autoplay: false, // 自动播放
        height: 500,
        width: 1000,
        controls: true, // 用户可以与之交互的控件
        loop: true, // 视频一结束就重新开始
        muted: false, // 默认情况下将使所有音频静音
        playsinline: true,
        webkitPlaysinline: true,
        // aspectRatio:"16:9",//显示比率
        playbackRates: [0.5, 1, 1.5, 2],
        fullscreen: {
          options: { navigationUI: 'hide' },
        },
        sources: [
          {
            src: this.data.video_list[0].file_url,
            type: 'video/mp4',
          },
        ],
      };
      this.player = videojs(this.$refs.videoPlayer, options, function onPlayerReady() {
        // console.log('onPlayerReady');
      });
      // 设置标点
      _this.handleMarkers();
      // 获取当前播放时间
      this.player.on('timeupdate', () => {
        this.handleTimeUpdate(this.player.currentTime());
        // console.log(this.currentTime());
      });
    },
    // 设置标点
    handleMarkers() {
      let markers = [];
      this.data.file_info_list.forEach((item) => {
        markers.push({
          time: item.currentTime,
          text: item.file_name ?? item.name,
        });
      });
      this.player.markers({
        // 不显示鼠标悬浮标记提示文字
        markerTip: {
          display: true,
        },
        markerStyle: {
          width: '4px',
          'background-color': 'red',
          'border-radius': '50%',
        },
        markers,
      });
    },
    handleTimeUpdate(currentTime) {
      this.data.file_info_list.forEach((item) => {
        if (
          Number(item.currentTime) > Number(currentTime) - 0.17 &&
          Number(item.currentTime) < Number(currentTime) + 0.17 &&
          item.id !== this.first
        ) {
          this.first = JSON.parse(JSON.stringify(item.id));
          this.player.pause();
          this.exercise_id = JSON.parse(JSON.stringify(item.id));
          this.visible = true;

          // GetFileURLMap({ file_id_list: [item.file_id] }).then(({ url_map }) => {
          //   this.newpath = `${this.file_preview_url}onlinePreview?url=${Base64.encode(url_map[item.file_id])}`;
          //   this.visible = true;
          // });
        }
      });
    },
    handleClose() {
      this.reportFlag = false;
      this.player.play();
      this.first = JSON.parse(JSON.stringify(this.exercise_id));
      setTimeout(() => {
        this.first = '';
      }, 1000);
    },
    submitAdd(id, answer, content, flag) {
      this.first = JSON.parse(JSON.stringify(this.exercise_id));
      setTimeout(() => {
        this.first = '';
      }, 1000);
      this.$set(this.userAnswer, id, answer);
      this.$set(this.exerciseList, id, content);
      if (flag || this.data.property.feed_back === 'total') {
        this.visible = false;
        this.player.play();
      }
    },
    lookReport() {
      this.player.pause();
      let num = 0;
      let total = this.data.file_info_list.length;
      Object.keys(this.userAnswer).forEach((key) => {
        if (this.userAnswer[key].is_right) {
          num += 1;
        }
      });
      this.reportResult = {
        total,
        right: num,
        error: total - num,
        rightRate: `${((num / total) * 100).toFixed(0)}%`,
      };
      this.reportFlag = true;
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

video:full-screen {
  :fullscreen::-webkit-media-controls-fullscreen-button {
    display: none;
  }
}

video::-webkit-media-controls-fullscreen-button {
  display: none;
}
</style>
