<template>
  <div class="play-paper">
    <div class="play-paper-body">
      <template v-if="status.examinationStatus === '00'">
        <div class="no-exam">暂无考试</div>
      </template>
      <template v-else-if="status.examinationStatus === '90'">
        <div class="play-paper-title">
          <div>
            <h3>{{exam.title}}</h3>
          </div>
        </div>

        <template v-if="status.type === 2 && status.isPublished === 1">
          <template v-if="exam.score.total !== undefined">
            <div style="font-size: 18px;">总分：{{exam.score.total}}分</div>
          </template>
        </template>
        <template v-else-if="status.type === 0">
          <div class="no-exam">考试结束 - 尚未进行考试</div>
        </template>
        <template v-else>
          <div class="no-exam">考试结束 - 试卷批改中，请耐心等待</div>
        </template>
      </template>
      <template v-else>
        <div class="play-paper-title">
          <div>
            <h3>{{exam.title}}</h3>
          </div>
        </div>
        <template v-if="status.isStart">
          <div class="play-paper-content">
            <template v-if="exam.id">
              <div class="exam">
                <!-- <div style='text-align: center;'> -->
                <!-- <div class='topic'> -->
                <!-- <div class='tit'>{{exam.title}}</div> -->
                <template v-if="exam.type === 2 && exam.isPublished === 1">
                  <template v-if="exam.score.total !== undefined">
                    <div style="font-size: 18px;">总分：{{exam.score.total}}分</div>
                  </template>
                </template>
                <template v-else-if="exam.type === 1">
                  <div class="no-exam">试卷批改中，请耐心等待</div>
                </template>
                <!-- </div> -->
                <!-- </div> -->
                <template v-if="(exam.type !== 1)">
                  <div style="text-align: center;">考试截止时间为：{{status.terminateTime}}</div>
                  <template v-for="question in exam.examination">
                    <!-- 单选题 -->
                    <template v-if="question.radioList.length">
                      <template v-for="(item, index) in question.radioList">
                        <div v-bind:key="item.id" class="q-group" :data-index="index">
                          <div class="q-num">{{index+1}}.</div>
                          <div class="q-title" v-html="item.content"></div>
                          <div class="q-type">(单选题)</div>
                          <el-radio-group class="radio-group" v-model="item.user_answer">
                            <template v-for="(item1, index1) in item.options">
                              <el-radio
                                v-bind:key="item1.id"
                                :label="item1.id"
                                :disabled="isSubmited"
                                :class="['radio', ((item.right_answer) ? (item1.id === item.right_answer ? 'success' : 'error') : '')]"
                              >{{ index1 | getLetter() }}. {{item1.option}}</el-radio>
                            </template>
                          </el-radio-group>
                          <template v-if="item.right_answer && !!exam.type">
                            <div class="result">
                              学生答案：
                              <div
                                :class="['stu', (item.right_answer === item.user_answer ? 'success' : 'error')]"
                              >{{ item.user_answer | getRadioAnswer(item.options) }}</div>
                              &nbsp;&nbsp;&nbsp;&nbsp;正确答案：{{ item.right_answer | getRadioAnswer(item.options) }}
                            </div>
                          </template>
                          <div class="analysis" v-if="item.analysis">
                            <p>解析：</p>
                            <div v-html="item.analysis"></div>
                          </div>
                        </div>
                      </template>
                    </template>
                    <!-- 多选题 -->
                    <template v-if="question.checkboxList.length">
                      <template v-for="(item, index) in question.checkboxList">
                        <div v-bind:key="item.id" class="q-group" :data-index="index">
                          <div class="q-num">{{question.radioList.length+index+1}}.</div>
                          <div class="q-title" v-html="item.content"></div>
                          <div class="q-type">(多选题)</div>
                          <el-checkbox-group class="checkbox-group" v-model="item.user_answer">
                            <template v-for="(item1, index1) in item.options">
                              <el-checkbox
                                v-bind:key="item1.id"
                                :label="item1.id"
                                :disabled="isSubmited"
                                :class="['checkbox', ((item.right_answer.length) ? (isCheckboxChecked(item1.id, item.right_answer) ? 'success' : 'error') : '')]"
                              >{{ index1 | getLetter() }}. {{item1.option}}</el-checkbox>
                            </template>
                          </el-checkbox-group>
                          <template v-if="item.right_answer.length && !!exam.type">
                            <div class="result">
                              学生答案：
                              <div
                                :class="['stu', ((item.right_answer.length && isCheckboxRight(item.user_answer, item.right_answer)) ? 'success' : 'error')]"
                              >{{ item.user_answer | getCheckboxAnswer(item.options) }}</div>
                              &nbsp;&nbsp;&nbsp;&nbsp;正确答案：{{ item.right_answer | getCheckboxAnswer(item.options) }}
                            </div>
                          </template>
                          <div class="analysis" v-if="item.analysis">
                            <p>解析：</p>
                            <div v-html="item.analysis"></div>
                          </div>
                        </div>
                      </template>
                    </template>
                    <!-- 简答题 -->
                    <template v-if="question.shortAnswerList.length">
                      <template v-for="(item, index) in question.shortAnswerList">
                        <div class="q-group" :key="index">
                          <div
                            class="q-sa-title"
                          >{{question.radioList.length+question.checkboxList.length+index+1}}.&nbsp;&nbsp;简答题</div>
                          <div class="edit_html" v-html="item.content || ''"></div>
                          <v-editor v-model="item.user_answer" :disabled="isSubmited"></v-editor>
                          <div style="height: 10px;"></div>
                          <!-- 利用key值自动更新组件 -->
                          <component
                            :is="item.upload.type"
                            v-bind:key="item.upload.id + new Date().getTime()"
                            :item="item.upload"
                            :formData="item"
                            :isUpload="!exam.type"
                          ></component>
                          <div class="result" v-if="item.check_comment">评语：{{item.check_comment}}</div>
                          <div class="analysis" v-if="item.analysis">
                            <p>解析：</p>
                            <div v-html="item.analysis"></div>
                          </div>
                        </div>
                      </template>
                    </template>
                  </template>
                  <div
                    :class="['btn', (isSubmited && 'on')]"
                    @click="submitExam"
                    :data-submit="isSubmited"
                    @mousedown="_SubmitMouseLeftDown()"
                  >{{isSubmited ? "已提交" : "提交"}}</div>
                  <div class="care">(注意：考试只有一次提交机会)</div>
                  <!-- <div :class='["btn"]' @click='repeatExam($event, true)' v-if="exam.work_contents">重做</div> -->
                </template>
              </div>
            </template>
          </div>
        </template>
        <template v-else>
          <div class="exam">
            <!-- <p>考试须知：</p> -->
            <div style="text-align: left;">考试开始时间为：{{status.startTime}}</div>
            <div style="text-align: left;">考试截止时间为：{{status.terminateTime}}</div>
            <template
              v-if="new Date(status.startTime).getTime() - new Date(status.serverTime).getTime() <= 0"
            >
              <div
                style="width: 25%;"
                :class="['btn']"
                @click="beginExam(true)"
                @mousedown="beginExam(true)"
              >开始考试</div>
            </template>
          </div>
        </template>
      </template>
    </div>
  </div>
</template>

<script>
import cAction from '@action'
import Base64 from 'Base64'

import VEditor from '@/components/editor.vue'

const A_Z = (function() {
  const result = []
  for (let i = 0; i < 26; i++) {
    result.push(String.fromCharCode(65 + i))
  }
  return result
})()
var getLetter = val => {
  return A_Z[val]
}

export default {
  props: {
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false }
  },
  components: { VEditor },
  filters: {
    getLetter: getLetter,
    getRadioAnswer: (val, arr) => {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === val) {
          return getLetter(i)
        }
      }
    },
    getCheckboxAnswer: (val, arr) => {
      let str = ''
      for (let i = 0; i < val.length; i++) {
        const tmpId = val[i]
        for (let j = 0; j < arr.length; j++) {
          if (arr[j].id === tmpId) {
            str += getLetter(j) + ','
            break
          }
        }
      }
      return str.substr(0, str.length - 1)
    }
  },
  data() {
    return {
      _time: null, // 定时器，自动化提交
      exam: {},
      status: {
        isStart: false,
        startTime: '',
        terminateTime: '',
        serverTime: '',
        examinationStatus: '',
        type: 0,
        isPublished: 0
      }
    }
  },
  watch: {
    id: {
      handler() {
        this.init()
      }
    }
  },
  computed: {
    // 考试完成
    isExamComplete() {
      // 考试完成，批改完成并且公布成绩
      return this.exam.is_published === 1 && this.exam.type === 2
    },
    // 是否提交
    isSubmited() {
      return this.exam.type === 1 || this.exam.type === 2
    }
  },
  mounted() {
    this.init()
    this.$emit('changeSideBar', '')
    setTimeout(() => {
      if (window.document.getElementById('switch-btn')) {
        window.document.getElementById('switch-btn').style.display = 'none'
      }
    }, 500)
  },
  destroyed() {
    if (this._time) {
      clearInterval(this._time)
      this._time = null
    }
    if (window.document.getElementById('switch-btn')) {
      window.document.getElementById('switch-btn').style.display = 'block'
    }
  },
  methods: {
    isCheckboxRight: (val, arr) => {
      let flag = true
      for (let i = 0; i < arr.length; i++) {
        const tmpId = arr[i]
        let j = 0
        for (; j < val.length; j++) {
          if (val[j] === tmpId) {
            break
          }
        }
        if (j === val.length) {
          flag = false
          break
        }
      }
      return flag
    },
    isCheckboxChecked: (val, arr) => {
      let i = 0
      for (; i < arr.length; i++) {
        if (arr[i].id === val || arr[i] === val) {
          return true
        }
      }
      return false
    },
    init() {
      this.loadExamStatus()
      this.loadExamInfo()
      if (this._time) {
        clearInterval(this._time)
        this._time = null
      }
      this._time = setInterval(() => {
        this.loadExamStatus()
        if (!this.isSubmited && this.status.isStart) {
          // console.log(11, '暂存')
          this.submitExam({ submitType: true }) // 暂存, submitType: true 暂存；其他或不填为提交
        }
        /* 到时间 自动提交 */
        if (
          !this.isSubmited &&
          this.status.isStart &&
          new Date(this.status.terminateTime).getTime() -
            new Date(this.status.serverTime).getTime() <=
            5000
        ) {
          this.submitExam({ submitType: false, currentTarget: { dataset: {} } })
        }
      }, 10000)
    },
    /* 定时调用 - 考试状态 */
    loadExamStatus() {
      cAction.Player.getExamStatus(this.cid, this.sid, this.id)
        .then(_data => {
          if (_data.status && _data.status === 200) {
            this.status.startTime = this.setTime(_data.start_time)
            this.status.terminateTime = _data.terminate_time
            this.status.serverTime = this.setTime(_data.server_time)
            this.status.examinationStatus = _data.examination_status
          } else {
            this.$message.error('数据异常，请联系管理员')
          }
        })
        .catch(e => {
          this.$message.error(e.message)
        })
        .finally(() => {})
    },
    /* 时间格式化(解决safari时间兼容问题); */
    setTime(time) {
      return time.replace(/-/g, '/')
    },
    /* 开始考试 */
    beginExam(flag) {
      this.status.isStart = true
      this.loadAjax(flag)
    },
    /* 加载题库基本数据 */
    loadExamInfo() {
      const loading = this.$loading({
        lock: true,
        text: '',
        spinner: '',
        background: 'rgba(255, 255, 255, 0.9)'
      })
      cAction.Player.getExamInfo(this.cid, this.sid)
        .then(_data => {
          this.exam = _data
          this.exam.id = this.id
        })
        .catch(e => {
          this.$message.error(e.message)
        })
        .finally(() => {
          loading.close()
          /* 正在考试，考试结束 */
          if (
            this.status.examinationStatus === '20' ||
            this.status.examinationStatus === '90'
          ) {
            this.beginExam()
          }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     * @param flag 通过该字段 判别是点击进入考试 还是 自动调用
     */
    loadAjax(flag) {
      const loading = this.$loading({
        lock: true,
        text: '',
        spinner: '',
        background: 'rgba(255, 255, 255, 0.9)'
      })
      cAction.Player.getExamAnswer(this.cid, this.sid, this.id)
        .then(_data => {
          if (_data.code === 8001) {
            console.log(
              '没有考试内容，认为是第一次答题，并且在答题期间，所以显示考试开始页面'
            )
            if (!flag) {
              this.status.isStart = false
            }
          } else {
            // this.exam.id = _data.id
            this.exam.title = _data.title
            this.$set(this.exam, 'type', _data.type)
            this.exam.score = _data.score
            this.exam.submitted_time = _data.submitted_time
            this.exam.isPublished = _data.isPublished
            this.status.type = _data.type
            this.status.isPublished = _data.isPublished
            this.exam.examination = this.exam.examination.map((exam, index) => {
              const rawExam = _data.examination[index]
              if (!rawExam) {
                return exam
              }
              for (let i = 0; i < exam.radioList.length; i++) {
                for (let j = 0; j < rawExam.radioList.length; j++) {
                  if (rawExam.radioList[j].id === exam.radioList[i].id) {
                    for (const k in rawExam.radioList[j]) {
                      exam.radioList[i][k] = rawExam.radioList[j][k]
                    }
                  }
                }
              }
              for (let i = 0; i < exam.checkboxList.length; i++) {
                for (let j = 0; j < rawExam.checkboxList.length; j++) {
                  if (rawExam.checkboxList[j].id === exam.checkboxList[i].id) {
                    for (const k in rawExam.checkboxList[j]) {
                      exam.checkboxList[i][k] = rawExam.checkboxList[j][k]
                    }
                  }
                }
              }
              for (let i = 0; i < exam.shortAnswerList.length; i++) {
                for (let j = 0; j < rawExam.shortAnswerList.length; j++) {
                  if (
                    rawExam.shortAnswerList[j].id === exam.shortAnswerList[i].id
                  ) {
                    for (const k in rawExam.shortAnswerList[j]) {
                      exam.shortAnswerList[i][k] = rawExam.shortAnswerList[j][k]
                    }
                  }
                }
              }
              return exam
            })
          }
        })
        .catch(e => {
          this.$message.error(e.message)
        })
        .finally(() => {
          // console.log(this.exam.type, this.exam.isPublished)
          loading.close()
          if (
            this.status.isStart &&
            this.exam.type !== 1 &&
            this.exam.type !== 2
          ) {
            /* 滚动到头部 */
            document.querySelector('.play-paper').scrollTop = 0
          }
        })
    },
    /**
     * 提交试题
     */
    submitExam(e) {
      if (!e.submitType && e.currentTarget.dataset.submit) {
        this.$message.error('已做过，不能再提交')
        return
      }
      const body = { answers: [], type: !e.submitType ? 1 : 0 } // type: 0 缓存；type: 1 提交
      for (let k = 0; k < this.exam.examination.length; k++) {
        const exam = this.exam.examination[k]
        const radioList = []
        for (let i = 0; i < exam.radioList.length; i++) {
          const tmp = exam.radioList[i]
          if (!tmp.user_answer && !e.submitType) {
            this.$message.error('还有单选题未做，不能提交')
            return
          }
          radioList.push({ id: tmp.id, user_answer: tmp.user_answer })
        }
        const checkboxList = []
        for (let i = 0; i < exam.checkboxList.length; i++) {
          const tmp = exam.checkboxList[i]
          if (!tmp.user_answer.length && !e.submitType) {
            this.$message.error('还有多选题未做，不能提交')
            return
          }
          checkboxList.push({ id: tmp.id, user_answer: tmp.user_answer })
        }
        const shortAnswerList = []
        for (let i = 0; i < exam.shortAnswerList.length; i++) {
          const tmp = exam.shortAnswerList[i]
          if (!tmp.user_answer && !e.submitType) {
            this.$message.error('还有简答题未做，不能提交')
            return
          }
          shortAnswerList.push({
            id: tmp.id,
            user_answer: Base64.encode(tmp.user_answer),
            attachments: tmp.attachments
          })
        }
        body.answers[k] = { radioList, checkboxList, shortAnswerList }
      }
      body.answers = JSON.stringify(body.answers)
      let loading = null
      if (!e.submitType) {
        loading = this.$loading({
          lock: true,
          text: '',
          spinner: '',
          background: 'rgba(255, 255, 255, 0.9)'
        })
      }
      cAction.Player.submitExam(this.cid, this.sid, this.exam.id, body)
        .then(_res => {
          if (e.submitType) {
            // this.$message.success('暂存成功')
            console.log('暂存成功')
            return
          }
          if (_res.code === 200) {
            this.$message.success('考试答卷提交成功')
            // this.exam.type = 1
            this.init()
            console.log(111, 'this.loadAjax()')
          } else {
            this.$message.error(_res.data.error)
          }
        })
        .catch(e => {
          this.$message.error(e.message)
        })
        .finally(() => {
          if (!e.submitType) {
            loading.close()
          }
        })
    },
    _SubmitMouseLeftDown() {
      const _fn1 = this.repeatExam.bind(this, false)
      document.addEventListener('keydown', _fn1, false)
      const _fn3 = function() {
        document.removeEventListener('keydown', _fn1)
        document.removeEventListener('mouseup', _fn3)
      }
      document.addEventListener('mouseup', _fn3, false)
    },
    /**
     * 重做
     */
    repeatExam(e, flag) {
      let _flag = flag
      /* 字母 f */
      if (e.keyCode === 70) {
        _flag = true
      }
      if (!_flag) {
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '',
        spinner: '',
        background: 'rgba(255, 255, 255, 0.9)'
      })
      cAction.chapterAction
        .getExamDetail(this.sid, this.cid, this.id)
        .then(_data => {
          this.exam = {}
        })
        .catch(e => {
          this.$message.error(e.message)
        })
        .finally(() => {
          loading.close()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.play {
  .exam {
    padding: 0;
  }
  .exam .topic {
    display: inline-block;
    margin-bottom: 0.1rem;
  }
  .exam .topic .tit {
    margin: 0 auto;
    padding: 0 0.2rem;
    text-align: center;
    font-size: 0.24rem;
    color: #313131;
    background: #fff;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
  }
  .exam .topic .cur {
    text-align: center;
    font-size: 0.18rem;
    color: #313131;
    line-height: 0.4rem;
  }
  /* 循环 所有选择题 */
  .exam .q-group {
    padding: 0.1rem 0.1rem;
    border-bottom: 1px solid #c9c9c97a;
    overflow: hidden;
  }
  .exam .q-group .q-num {
    float: left;
    margin-right: 0.1rem;
    font-size: 0.16rem;
    color: #676a6c;
  }
  .exam .q-group .q-title {
    float: left;
    width: 90%;
    font-size: 0.16rem;
    color: #676a6c;
    text-align: justify;
  }
  .exam .q-group .q-type {
    float: right;
    font-size: 0.16rem;
    color: #676a6c;
  }
  .exam .q-group .radio-group {
    float: left;
    margin-top: 0.1rem;
    width: 100%;
  }
  .exam .q-group .radio-group .radio {
    display: block;
    font-size: 0.18rem;
    color: #3f3b3a;
    line-height: 0.3rem;
    margin-bottom: 0.1rem;
  }
  .exam .q-group .checkbox-group {
    float: left;
    margin-top: 0.1rem;
    width: 100%;
  }
  .exam .q-group .checkbox-group .checkbox {
    display: block;
    font-size: 0.18rem;
    color: #3f3b3a;
    line-height: 0.3rem;
    margin-bottom: 0.1rem;
  }
  .exam .q-group .radio-group .radio.error,
  .exam .q-group .checkbox-group .checkbox.error {
    color: #d80000;
  }
  .exam .q-group .radio-group .radio.success,
  .exam .q-group .checkbox-group .checkbox.success {
    color: #090;
  }
  .exam .q-group .result {
    clear: both;
    display: flex;
    justify-content: flex-end;
    font-size: 0.18rem;
    color: #3f3b3a;
    margin-right: 0;
  }
  .exam .q-group .result .stu {
    display: inline-block;
  }
  .exam .q-group .result .stu.error {
    color: #d80000;
  }
  .exam .q-group .result .stu.success {
    color: #090;
  }
  .exam .q-group:last-child {
    border-bottom: none;
  }
  .exam .btn {
    margin: 0.2rem auto;
    width: 60%;
    height: 0.5rem;
    line-height: 0.5rem;
    font-size: 0.16rem;
    text-align: center;
    font-weight: 300;
    color: #fff;
    border-radius: 0.1rem;
    background: #b49441;
    cursor: pointer;
  }
  .exam .btn.on {
    opacity: 0.5;
  }
  .exam .care {
    font-size: 0.16rem;
    color: #d80000;
    text-align: center;
  }

  .exam .q-sa-title {
    float: left;
    width: 100%;
    font-size: 0.16rem;
    color: #676a6c;
    text-align: justify;
  }
}
.no-exam {
  font-size: 0.24rem;
  line-height: 19;
  text-align: center;
}
.analysis {
  clear: both;
  display: flex;
  margin: 20px 0;
  padding: 0 20px;
  border: 1px solid #c9c9c97a;
}
</style>
