<template>
  <div>
    <!-- 单选多选判断题(题目描述dom结构一样，只那选项区分) -->
    <template v-if="questionData.question_item_type == 1 || questionData.question_item_type == 2 || questionData.question_item_type == 6">
      <div class="title-type">
        <div class="type">{{ questionData.question_item_title }}</div>
        <div class="num">{{ questionData.q_order }}/{{ questionParams.question.total_question_count }}</div>
      </div>
      <div class="title">
        <div class="num">{{ questionData.q_order }}.</div><div class="des" v-html="questionData.content"></div>
      </div>
      <!-- <div class="describe" ></div> -->
      <ul :class="questionData.question_item_type == 2 ? 'check-option' : 'radio-option'">
        <template v-for="(item, index) in questionData.options">
          <li
            :key="index"
            :class="questionParams.answerRecord[questionData.question_item_id]
              ? questionParams.answerRecord[questionData.question_item_id][questionData.id]
                ? questionParams.answerRecord[questionData.question_item_id][questionData.id].answer.find(id => { return id === item.id })
                  ? 'active'
                  : ''
                : ''
              : ''"
            >
            <div @click="changeOptions(questionData.question_item_type, questionData.question_item_id, questionData.id, item.id)">
              <div class="icon"></div>
              <div class="txt" v-html="item.option"></div>
            </div>
          </li>
        </template>
      </ul>
    </template>
    <!-- 问答题 -->
    <template v-if="questionData.question_item_type == 3">
      <div class="title-type">
        <div class="type">{{ questionData.question_item_title }}</div>
        <div class="num">{{ questionData.q_order }}/{{ questionParams.question.total_question_count }}</div>
      </div>
      <div class="title">
        <div class="num">{{ questionData.q_order }}.</div><div class="des" v-html="questionData.content"></div>
      </div>
      <el-input @input="QAChange(questionData.question_item_id, questionData.id, questionData.textContent)" type="textarea" placeholder="请输入内容" v-model="questionData.textContent"></el-input>
    </template>
    <!-- 复合题 -->
    <template v-if="questionData.question_item_type == 5 || questionData.question_item_type == 7 || questionData.question_item_type == 8">
      <div class="title-type">
        <div class="type">{{ questionData.question_item_title }}</div>
        <div class="num">{{ questionParams.questionIndex + 1 }}/{{ questionParams.question.total_question_count }}</div>
      </div>
      <div class="case-que">
        <div class="stem" v-html="questionData.common_content"></div>
        <!-- <ul class="topics" :style="{height: contentHeight - 60 + 'px'}"> -->
        <ul class="topics">
          <template v-for="(item, index) in questionData.list">
            <li :key="'type5' + index">
              <div :class="item.q_order === questionParams.questionIndex + 1 ? 'active title' : 'title'">
                <div class="num">{{ item.q_order }}.</div><div class="des" v-html="item.content"></div>
              </div>
              <div v-if="item.type == 3" @click="changeIndex(item.q_order)">
                <el-input @input="QAChildChange(questionData.question_item_id, item, item.answer)" type="textarea" placeholder="请输入内容" v-model="item.answer"></el-input>
              </div>
              <!-- <el-input @input="QAChange(questionData.question_item_id, questionData.id)" type="textarea" placeholder="请输入内容" v-model="questionData.textContent"></el-input> -->
              <ul v-else :class="item.type == 2 ? 'check-option' : 'radio-option'"><!-- radio-option check-option -->
                <template v-if="item.options">
                  <template v-for="(items, cIndex) in item.options">
                    <li
                      :id="items.id"
                      :key="'c' + cIndex"
                      :class="questionParams.answerRecord[questionData.question_item_id]
                        ? questionParams.answerRecord[questionData.question_item_id][item.id]
                          ? questionParams.answerRecord[questionData.question_item_id][item.id].answer.find(id => { return id === items.id })
                            ? 'active'
                            : ''
                          : ''
                        : ''"
                      >
                      <div @click="changeOptions(item.type, questionData.question_item_id, item.id, items.id, item.q_order)">
                        <div class="icon"></div>
                        <div class="txt">{{items.option}}</div>
                      </div>
                    </li>
                  </template>
                </template>
              </ul>
            </li>
          </template>
        </ul>
      </div>
    </template>
  </div>
</template>
<script>
import action from '@action'
import Bus from '@/components/common/bus.js'
import _ from 'lodash'
export default {
  components: {
  },
  props: {
    contentHeight: { type: Number, default: () => {} },
    questionParams: { type: Object, default: () => {} }
  },
  data() {
    return {
      questionData: {},
      clearTime: null,
      setCacheTime: null,
      textarea: ''
    }
  },
  beforeDestroy() {
    clearInterval(this.setCacheTime)
  },
  created() {
  },
  mounted() {
    clearInterval(this.setCacheTime)
    this.setCacheTime = setInterval(() => {
      setTimeout(() => {
        this.setCache()
      }, Math.floor(Math.random() * (5 - 0 + 1) + 0) * 1000)
    }, 10000)
    this.dataCombined()
  },
  methods: {
    // 重组数据
    dataCombined() {
      this.questionParams.question.question_items.map((item, index) => {
        if (parseInt(item.question_item_type) === 5 || parseInt(item.question_item_type) === 7 || parseInt(item.question_item_type) === 8) {
          item.question_list.map(cItem => {
            const currentItem = cItem.list.find(items => { return items.q_order === this.questionParams.questionIndex + 1 })
            if (currentItem) {
              this.questionData = {}
              this.questionData.common_content = cItem.common_content
              this.questionData.list = cItem.list.map(k => {
                this.questionData.id = k.id
                this.questionData.q_order = k.q_order
                typeof k.options === 'string' && (k.options = JSON.parse(k.options))
                return k
              })
              const key = ['question_item_id', 'question_item_title', 'question_item_type']
              key.map(k => {
                this.questionData[k] = item[k]
              })
              // 案例题里面的问答题答案回显
              const pId = this.questionData.question_item_id
              setTimeout(() => {
                this.questionData.list.map(el => {
                  if (el.type === 3) {
                    if (this.questionParams.answerRecord[pId]) {
                      this.questionParams.answerRecord[pId][el.id] ? el.answer = this.questionParams.answerRecord[pId][el.id].answer[0] : el.answer = ''
                    } else {
                      el.answer = ''
                    }
                    return el
                  }
                })
                this.$forceUpdate()
              }, 300)
            }
          })
          this.$forceUpdate()
        } else {
          const currentItem = item.question_list.find(items => { return items.q_order === this.questionParams.questionIndex + 1 })
          if (currentItem) {
            this.questionData = currentItem
            const key = ['question_item_id', 'question_item_title', 'question_item_type']
            key.map(k => {
              this.questionData[k] = item[k]
            })
            typeof this.questionData.options === 'string' && (this.questionData.options = JSON.parse(currentItem.options))
            const pId = this.questionData.question_item_id
            const cId = this.questionData.id
            // 问答题答案回显
            if (this.questionParams.answerRecord[pId]) {
              if (this.questionParams.answerRecord[pId][cId]) {
                this.questionData.textContent = this.questionParams.answerRecord[pId][cId].answer[0]
                return
              }
            }
            this.questionData.textContent = ''
          }
        }
      })
    },
    // 案例题下面的问答题
    QAChildChange(pId, item, length) {
      if (length.length < 500) {
        if (this.questionParams.answerRecord[pId]) {
          if (this.questionParams.answerRecord[pId][item.id]) {
            this.questionParams.answerRecord[pId][item.id].answer = [item.answer]
          } else {
            this.questionParams.answerRecord[pId][item.id] = {
              answer: [item.answer],
              sign: false
            }
          }
        } else {
          this.questionParams.answerRecord[pId] = {
            [item.id]: {
              answer: [item.answer],
              sign: false
            }
          }
        }
        this.$forceUpdate()
      } else {
        this.$message({
          message: '最多输入500个字符',
          type: 'warning'
        })
      }
    },
    // 问答题回答
    QAChange(pId, cId, length) {
      if (length.length < 500) {
        this.questionParams.answerRecord[pId]
          ? this.questionParams.answerRecord[pId][cId]
            ? this.questionParams.answerRecord[pId][cId].answer = [this.questionData.textContent]
            : this.questionParams.answerRecord[pId][cId] = {
              answer: [this.questionData.textContent],
              sign: false
            }
          : this.questionParams.answerRecord[pId] = {
            [cId]: {
              answer: [this.questionData.textContent],
              sign: false
            }
          }
        this.$forceUpdate()
      } else {
        this.$message({
          message: '最多输入500个字符',
          type: 'warning'
        })
      }
    },
    changeIndex(order) {
      this.questionParams.questionIndex = order - 1
      this.$forceUpdate()
    },
    // 选项选择
    changeOptions: _.debounce(function(type, pId, cId, optId, order) {
      if (order) {
        this.questionParams.questionIndex = order - 1
      }
      if (parseInt(type) !== 2) {
        this.questionParams.answerRecord[pId]
          ? this.questionParams.answerRecord[pId][cId]
            ? this.questionParams.answerRecord[pId][cId].answer = [optId]
            : this.questionParams.answerRecord[pId][cId] = {
              answer: [optId],
              sign: false
            }
          : this.questionParams.answerRecord[pId] = {
            [cId]: {
              answer: [optId],
              sign: false
            }
          }
      } else {
        this.questionParams.answerRecord[pId]
          ? this.questionParams.answerRecord[pId][cId]
            ? (() => {
              const optChack = this.questionParams.answerRecord[pId][cId].answer.findIndex(item => { return item === optId })
              if (optChack === -1) {
                this.questionParams.answerRecord[pId][cId].answer.push(optId)
              } else {
                this.questionParams.answerRecord[pId][cId].answer.splice(optChack, 1)
              }
            })()
            : this.questionParams.answerRecord[pId][cId] = {
              answer: [optId],
              sign: false
            }
          : this.questionParams.answerRecord[pId] = {
            [cId]: {
              answer: [optId],
              sign: false
            }
          }
      }
      Bus.$emit('monitoringChanges')
      this.$forceUpdate()
    }, 100),
    setCache() {
      const param = {
        answer: JSON.stringify(this.questionParams.answerRecord)
      }
      action.Exam.setCache(this.$route.params.examId, param).then(res => {
      }).catch(err => {
        if (err.message.indexOf('error') !== -1) {
          this.$confirm('网络异常，请保持网络通畅', '提示', {
            confirmButtonText: '退出考试',
            cancelButtonText: '重新提交',
            type: 'warning'
          }).then(() => {
            this.$router.replace({
              path: `/login/${JSON.parse(window.localStorage.getItem('examInfo')).exam_id}`
            })
          }).catch(() => {
            this.endExamRequest()
          })
        } else {
          // this.$alert(err.message, {
          //   callback: action => {}
          // })
          console.log(err.message)
        }
      })
    },
    // 标记
    onSignHandle() {
      const pId = this.questionData.question_item_id
      const cId = this.questionData.id
      if (parseInt(this.questionData.question_item_type) === 5 || parseInt(this.questionData.question_item_type) === 7 || parseInt(this.questionData.question_item_type) === 8) {
        this.questionData.list.forEach(item => {
          if (this.questionParams.answerRecord[pId]) {
            if (this.questionParams.answerRecord[pId][item.id]) {
              if (this.questionParams.answerRecord[pId][item.id].sign) {
                this.questionParams.answerRecord[pId][item.id].sign = false
              } else {
                this.questionParams.answerRecord[pId][item.id].sign = true
              }
            } else {
              this.questionParams.answerRecord[pId][item.id] = { sign: true, answer: [] }
            }
          } else {
            this.questionParams.answerRecord[pId] = { [item.id]: { sign: true, answer: [] } }
          }
        })
      } else {
        this.questionParams.answerRecord[pId]
          ? this.questionParams.answerRecord[pId][cId]
            ? this.questionParams.answerRecord[pId][cId].sign
              ? this.questionParams.answerRecord[pId][cId].sign = false
              : this.questionParams.answerRecord[pId][cId].sign = true
            : this.questionParams.answerRecord[pId][cId] = {
              sign: true,
              answer: []
            }
          : this.questionParams.answerRecord[pId] = {
            [cId]: {
              sign: true,
              answer: []
            }
          }
      }
      this.signCallback()
    },
    signCallback() {
      const pId = this.questionData.question_item_id
      const cId = this.questionData.id
      let isSign = false
      this.questionParams.answerRecord[pId]
        ? this.questionParams.answerRecord[pId][cId]
          ? isSign = this.questionParams.answerRecord[pId][cId].sign
          : isSign = false
        : isSign = false
      this.$emit('isSign', isSign)
      Bus.$emit('monitoringChanges')
    },
    createTag() {
      if ($('math').length) {
        if ($('.MathTag').length) {
          $('.MathTag').remove()
          this.addTag()
        } else {
          this.addTag()
        }
      }
    },
    addTag() {
      const cdn = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=MML_HTMLorMML'
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = cdn
      script.className = 'MathTag'
      const script2 = document.createElement('script')
      script2.type = 'text/javascript'
      script2.innerHTML = 'window.MathJax = { MathML: { extensions: ["mml3.js", "content-mathml.js"]}}'
      script2.className = 'MathTag'
      $('body').append(script2)
      $('body').append(script)
    }
  },
  computed: {
    changeQuestionIndex() {
      return this.questionParams.questionIndex
    }
  },
  watch: {
    changeQuestionIndex(newV, oldV) {
      this.dataCombined()
      this.signCallback()
      this.$nextTick(() => {
        this.createTag()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep{
  .el-textarea__inner{
    height: 150px;
  }
}
.title-type{
  width: 100%;
  height: 45px;
  border-bottom:1px solid #ccc;
  display: flex;
  align-items: center;
  .type{
    font-size: 18px;
    color: #222222;
  }
  .num{
    margin-left: auto;
    font-size: 18px;
    color: #222222;
  }
}

.title{
  font-size: 18px;
  font-weight: bold;
  color: #222222;
  line-height: 25px;
  display: flex;
  .num{
    font-size: 32px;
    font-weight: bold;
    color: #222222;
    line-height: 45px;
    margin-top: 5px;
  }
  .des{
    margin-left: 5px;
    padding-top: 18px;
    &::v-deep p{
      margin: 0;
    }
  }
}
.describe{
  font-size: 18px;
  color: #222222;
  line-height: 25px;
  margin-top: 20px;
}
.radio-option,.check-option{
  padding: 24px 0 0 0;
  margin: 0;
  list-style: none;
  li{
    // cursor: pointer;
    margin-bottom: 20px;
    // display: flex;
    overflow: hidden;
    // align-items: center;
    div {
      float: left;
      cursor: pointer;
      .icon{
        width: 18px;
        height: 18px;
        border: 1px solid #999999;
        border-radius: 50%;
        margin-top: 3px;
        float: left;
      }
      .txt{
        max-width: 95%;
        font-size: 18px;
        color: #222222;
        line-height: 28px;
        margin-left: 10px;
        float: left;
        &::v-deep p{
          margin: 0;
        }
      }
    }
    // .icon{
    //   width: 18px;
    //   height: 18px;
    //   border: 1px solid #999999;
    //   border-radius: 50%;
    //   margin-top: 3px;
    // }
    // .txt{
    //   width: 95%;
    //   font-size: 18px;
    //   color: #222222;
    //   line-height: 28px;
    //   margin-left: 10px;
    // }
    &.active{
      .icon{
        width: 8px;
        height: 8px;
        border: 6px solid #C01540;
      }
    }
  }
}
.check-option{
  .icon{
    border-radius: 3px !important;
  }
}
.case-que{
  ::v-deep{
    img{
      display: block;
      width:100%;
    }
  }
  display: flex;
  .stem{
    flex: 1;
    font-size: 14px;
    font-weight: bold;
    color: #222222;
    line-height: 28px;
  }
  .topics{
    flex: 1;
    margin: 0;
    padding: 0 0 0 20px;
    list-style: none;
    overflow-y: scroll;
    scrollbar-width: none;
    &::-webkit-scrollbar {
      display: none;
    }
    li{
      .title{
        font-size: 18px;
        font-weight: bold;
        color: #222222;
        line-height: 25px;
        &.active{
          color: #c01540;
          .num{
            color: #c01540 !important;
          }
        }
        span{
          font-size: 32px;
          font-weight: bold;
          color: #222222;
          line-height: 45px;
        }
      }
    }
  }
}
</style>
