<!--  -->
<template>
  <div class="Book_questionBox_answer">
    <template v-if="contextData">
      <div v-if="contextData.content.guide" class="guide" v-html="contextData.content.guide" />
      <div v-if="contextData.content.article_pdf_file_url" class="pdf">
        <pdf
          v-for="i in article_pdf_file_numPages"
          :key="i"
          ref="pdf"
          :page="i"
          :src="article_pdf_file_id"
        />
      </div>

      <div
        v-if="contextData.content.article"
        class="article"
        @click="chinaDict"
        v-html="contextData.content.article"
      />
      <template v-if="contextData.content.question">
        <div :class="['question', screenClass]">
          <component
            :is="getViewCom"
            :answer="answer"
            :bookClientWidth="bookClientWidth"
            :cur="cur"
            :getAnswer="getAnswer"
            :handleChildSrcList="handleChildSrcList"
            :moduleType="moduleType"
            :previewSrcList="previewSrcList"
            :queIndex="queIndex"
            :uiType="uiType"
            :watchIndex="watchIndex"
            :bookTaskModel="bookTaskModel"
            :bookAnswerShowFlag="bookAnswerShowFlag"
            :bookExamAnswer="bookExamAnswer"
            :BookWavAnswerWav="BookWavAnswerWav"
            @downloadBookWrite="downloadBookWrite"
          />

          <a class="btn-prev-big" @click="handlePrev" />
          <a class="btn-next-big" @click="handleNext" />
        </div>
      </template>
    </template>
    <div v-if="articleSrc" class="bookPreviewList">
      <i class="el-icon-circle-close" @click="closeBookPreview" />
      <!-- <i
                @click="handleBookPreviewLeft"
                class="el-icon-arrow-left"
                v-if="previewSrcListIndex!=0"
            ></i>
            <i
                @click="handleBookPreviewRight"
                class="el-icon-arrow-right"
                v-if="previewSrcListIndex!=previewSrcList.length - 1"
            ></i>-->
      <div class="bookPreviewList-inner">
        <img :src="articleSrc" class="previewImg">
      </div>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import Cookies from 'js-cookie'
import Single from './SingleAnswer/index' // 选择
import Record from './dialogueAnswer/index' // 录音题
import Blank from './BlankAnswer/index' // 选择
import Match from './MatchAnswer/index' // 匹配题
import Sort from './SortAnswer/index' // 匹配题
import Write from './WriteAnswer/index' // 手写题
import Judge from './JudgeAnswer/index' // 判断题
import Checkoutbox from './CheckoutBoxAnswer/index' // 多选题
import Writing from './WritingAnswer/index' // 写作题
import { getContentFile } from "@/api/ajax";
import { getToken } from '@/utils/auth'
export default {
  name: 'QuestionAnswer',
  components: {
    pdf,
    Single,
    Record,
    Blank,
    // Drag,
    // SelectCorrect,
    Match,
    Sort,
    Write,
    Judge,
    Checkoutbox,
    Writing
  },
  props: {
    context: {
      type: Object,
      default: null
    },
    bookClientWidth: {
      type: Number,
      default: 800
    },
    bookAnswerContent: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      contextData: null,
      answer: [],
      queType: '', // 题型的类型
      moduleType: '', // 模版的类型
      queList: [], // 题目数组
      queTotal: [], // 题目总数
      queIndex: -1, // 题目的索引
      cur: [], // 当前的题目
      uiType: '', // 题型+模板
      watchIndex: -1, // 监听的值
      previewSrcList: [],
      replaceList: [],
      articleSrc: '',
      previewSrcListIndex: 0, // 点击放大照片index
      screenClass: '', // 不同尺寸屏幕宽度对应的class
      article_pdf_file_id: '', // pdf地址
      article_pdf_file_numPages: null, // pdf页数
      // bookClientWidth: 800,// 写死的值记得去掉
      bookTaskModel: 'EXAMRESULT', // 当前答题模式
      bookAnswerShowFlag: null, // 是否显示标准答案
      // bookExamAnswer:localStorage.getItem('exam_answer')?JSON.parse(localStorage.getItem('exam_answer')):[], // 用户答题答案
      bookExamAnswer: [], // 用户答题答案
      BookWavAnswerWav:[]
    }
  },
  computed: {
    getViewCom() {
      switch (this.queType) {
        case 'SINGLE':
          return Single
        case 'JUDGE':
          return Judge
        case 'RECORD':
          return Record
        case 'BLANK':
          return Blank
        case 'CHECKOUTBOX':
          return Checkoutbox
        case 'DRAG':
          return Drag
        case 'MATCH':
          return Match
        case 'SORT':
          return Sort
        case 'WRITE':
          return Write
        case 'WRITING':
          return Writing
      }
    }
  },
  watch: {
    context: {
      handler: function(val, oldVal) {
        const _this = this
        if (val) {
          _this.initContextData()
        }
      },
      // 深度观察监听
      deep: true
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    const _this = this
    if (_this.context) {
      _this.initContextData()
    }
    window.onresize = () => {
      _this.handleClientwidth()
    }
  },
  beforeCreate() { }, // 生命周期 - 创建之前
  beforeMount() { }, // 生命周期 - 挂载之前
  beforeUpdate() { }, // 生命周期 - 更新之前
  updated() { }, // 生命周期 - 更新之后
  beforeDestroy() { }, // 生命周期 - 销毁之前
  destroyed() { }, // 生命周期 - 销毁完成
  activated() { },
  // 方法集合
  methods: {
    chinaDict(e) {
      if (e.target.nodeName === 'SPAN') {
        const val = e.target.innerHtml()
      } else if (e.target.tagName == 'IMG') {
        // 图片地址 e.target.attributes[0].nodeValue
        this.articleSrc = e.target.attributes[0].nodeValue
        // this.handleSrcListIndex()
      }
    },
    // 子组件调用父级查看图片
    handleChildSrcList(src) {
      this.articleSrc = src
      // this.handleSrcListIndex()
    },
    // 点击查看图片index
    handleSrcListIndex() {
      for (let i = 0; i < this.previewSrcList.length; i++) {
        if (this.previewSrcList[i] === this.articleSrc) {
          this.previewSrcListIndex = i
          return false
        }
      }
    },
    handleBookPreviewLeft() {
      if (this.previewSrcListIndex > 0) {
        this.previewSrcListIndex--
        this.articleSrc = this.previewSrcList[this.previewSrcListIndex]
      }
    },
    handleBookPreviewRight() {
      if (this.previewSrcListIndex < this.previewSrcList.length - 1) {
        this.previewSrcListIndex++
        this.articleSrc = this.previewSrcList[this.previewSrcListIndex]
      }
    },
    getAnswer() {
      const _this = this
      _this.$emit('getData', _this.cur)
    },
    handlePrev() {
      const _this = this
      if (_this.queIndex == 0) {
        this.$message({
          message: '已经是第一题',
          type: 'success'
        })
      } else {
        _this.queIndex = _this.queIndex - 1
        _this.watchIndex = _this.queIndex + new Date().getTime()
        _this.cur = _this.queList[_this.queIndex]
      }
    },
    handleNext() {
      const _this = this
    //   if (_this.cur) {
    //     const answer = _this.cur.Bookanswer
    //     _this.getAnswer(answer)
    //   }
      if (_this.queIndex == _this.queTotal - 1) {
        this.$message({
          message: '已经是最后一题',
          type: 'success'
        })
      } else {
        _this.queIndex = _this.queIndex + 1
        _this.watchIndex = _this.queIndex + new Date().getTime()
        _this.cur = _this.queList[_this.queIndex]
      }
    },
    initContextData() {
      const _this = this
      _this.contextData = JSON.parse(JSON.stringify(_this.context))
      _this.bookExamAnswer = JSON.parse(_this.bookAnswerContent)
      _this.previewSrcList = []
      _this.handlePreImg()
      _this.queIndex = 0
      _this.watchIndex = _this.queIndex + new Date().getTime()
      if (_this.contextData && _this.contextData.ui_type) {
        const queType = _this.contextData.ui_type.split('_')
        _this.uiType = _this.contextData.ui_type
        _this.queType = queType[0]
        _this.moduleType = queType[1]
      }
      if (_this.contextData && _this.contextData.content.question) {
        const list = _this.contextData.content.question.data_list
        if (list && list.length > 0) {
          _this.queList = list
          _this.cur = list[_this.queIndex]
          _this.queTotal = list.length
        }
      }

      _this.handleClientwidth()
      _this.article_pdf_file_id = process.env.VUE_APP_BASE_API + _this.contextData.content.article_pdf_file_url
      if (_this.article_pdf_file_id) _this.getPdfNumPages()
    },
    // 富文本img的地址以及替换img标签
    handlePreImg() {
      const _this = this
      const content = _this.contextData.content.article.replace(
        /<img [^>]*src=['"]([^'"]+)[^>]*>/g,
        function(match, capture) {
          _this.previewSrcList.push(capture)
        }
      )
    },
    // 关闭预览图片
    closeBookPreview() {
      this.articleSrc = ''
    },
    // 根据不同尺寸的宽设定不同的class
    handleClientwidth() {
      const clientWidth = this.bookClientWidth ? this.bookClientWidth : document.documentElement.clientWidth
      if (clientWidth < 1000) {
        this.screenClass = 'questionSmall'
      } else if (clientWidth >= 1000 && clientWidth < 1460) {
        this.screenClass = 'questionMiddle'
      } else {
        this.screenClass = ''
      }
    },
    // 获取pdf的页数
    getPdfNumPages() {
      const _this = this
      const loadingTask = pdf.createLoadingTask(_this.article_pdf_file_id)
      loadingTask.promise
        .then((pdf) => {
          _this.article_pdf_file_numPages = pdf._pdfInfo.numPages
        })
        .catch((err) => {

        })
    },
    // 是否显示标准答案
    bookAnswerShow(flag) {
      this.bookAnswerShowFlag = flag
    },
    downloadBookWrite(idList){
        debugger
        let MethodName = "file_store_manager-StartCreateFileCompressPack"
        let data = {
            file_id_list:JSON.parse(idList)
        }
        getContentFile(MethodName, data)
          .then((res) => {
              let id = res.file_compress_task_id
              let _this = this
              this.bookDownTimer = setInterval(()=>{_this.checkTaskProgress(id)}, 2000);
          })
          .catch((error) => {
          });
    },
    //成功后调用打包进度
    checkTaskProgress(taskId){
        let userInfor = getToken();
            let UserCode = '',
                UserType = '',
                SessionID = ''
            if (userInfor) {
                let user = JSON.parse(getToken());
                UserCode = user.user_code;
                UserType = user.user_type;
                SessionID = user.session_id;
            }
        let MethodName = "file_store_manager-GetFileCompressTaskProgress"
        let data = {
            file_compress_task_id:taskId
        }
        getContentFile(MethodName, data)
          .then((res) => {
              if(res.is_finish=='true'){
                  clearInterval(this.bookDownTimer)
                  window.open(process.env.VUE_APP_BASE_API +
                    `/GCLSFileServer/WebFileDownload?UserCode=${UserCode}&UserType=${UserType}&SessionID=${SessionID}&FileID=${res.compress_pack_file_id}`) 
              }
          })
          .catch((error) => {
          });
    },
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
.Book_questionBox_answer {
    width: 100%;
    height: 100%;
    .guide {
        font-size: 20px;
        margin-bottom: 10px;
    }
    .article {
        margin-bottom: 10px;
        img {
            cursor: pointer;
        }
    }
    .question {
        position: relative;
        width: 1440px;
        // height: 100%;
        margin:0 auto;
        background: #ffd66b url('../assets/single/bg.png') center no-repeat;
        background-size: 100% 100%;
        padding: 20px 0px 0 0;
        &.questionMiddle {
            width: 960px;
            > div {
                padding: 0 30px;
                height: 600px;
                overflow-y: auto;
            }
            .btn-prev-big,
            .btn-next-big {
                width: 48px;
                height: 116px;
                margin-top: -58px;
            }
        }
        &.questionSmall {
            width: 720px;
            > div {
                padding: 0 20px;
                height: 450px;
                overflow-y: auto;
            }
            .btn-prev-big,
            .btn-next-big {
                width: 36px;
                height: 87px;
                margin-top: -44px;
            }
        }
        > div {
            padding: 0 40px;
            height: 900px;
            overflow-y: auto;
        }
        .btn-prev-big,
        .btn-next-big {
            width: 72px;
            height: 174px;
            position: absolute;
            left: 0;
            top: 50%;
            margin-top: -87px;
            background: url('../assets/single/btn-prev.png') center no-repeat;
            background-size: 100% 100%;
        }
        .btn-next-big {
            right: 0;
            left: auto;
            background: url('../assets/single/btn-next.png') center no-repeat;
            background-size: 100% 100%;
        }
        .btn-prev-big:active {
            background: url('../assets/single/btn-prev-click.png') center
                no-repeat;
            background-size: 100% 100%;
        }
        .btn-next-big:active {
            background: url('../assets/single/btn-next-click.png') center
                no-repeat;
            background-size: 100% 100%;
        }
    }
    .bookPreviewList {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(44, 44, 44, 0.7);
        z-index: 999;
        .el-icon-circle-close {
            cursor: pointer;
            position: absolute;
            right: 40px;
            top: 40px;
            &:before {
                font-size: 40px;
                color: rgba(255, 255, 255, 1);
                font-weight: blod;
            }
        }
        .el-icon-arrow-left {
            cursor: pointer;
            position: absolute;
            left: 40px;
            top: 50%;
            margin-top: -40px;
            &:before {
                font-size: 80px;
                color: rgba(255, 255, 255, 1);
                font-weight: blod;
            }
        }
        .el-icon-arrow-right {
            cursor: pointer;
            position: absolute;
            right: 40px;
            top: 50%;
            margin-top: -40px;
            &:before {
                font-size: 80px;
                color: rgba(255, 255, 255, 1);
                font-weight: blod;
            }
        }
        .bookPreviewList-inner {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        img.previewImg {
            max-width: 100%;
            max-height: 100%;
        }
    }
}
</style>
