<template>
<div class="play-paper">
  <div class="play-paper-body">
    <div class="play-paper-title"><div><h3>{{chapterName}}</h3></div></div>
    <div class="play-paper-content play-chapter-exam">
      <template v-if="this.exam.id">
        <div class='exam'>
          <div style='text-align: center;'>
            <div class='topic'>
              <!-- <div class='tit'>{{exam.title}}</div> -->
              <template v-if='exam.score'><div class='cur'>正确率：{{exam.score}}%</div></template>
            </div>
          </div>
          <div style=''>
            <template v-for='(item, index) in exam.group'>
              <template v-if='item.type == 1'>
                <div v-bind:key="index" class='q-group' @click="radioClick" :data-index='index'>
                  <div class='q-num'>{{index+1}}.</div><div class='q-title' v-html='item.title'></div><div class='q-type'>(单选题)</div>
                  <el-radio-group class='radio-group' @change='radioChange' v-model="item.sel">
                    <template v-for='(item1, index1) in item.arr'>
                      <!-- checked='{{item1.selected}}' -->
                      <el-radio v-bind:key="index1" :label='index1' :disabled='!!item.cur' :class='["radio", (item.cur && item1.checked && "success"), (item.cur && !item1.checked && item1.selected && "error")]'>{{ index1 == 0 ? "A" : (index1 == 1 ? "B" : (index1 == 2 ? "C" : (index1 == 3 ? "D" : (index1 == 4 ? "E" : (index1 == 5 ? "F" : (index1 == 6 ? "G" : (index1 == 7 ? "H" : (index1 == 8 ? "I" : (index1 == 9 ? "J" : "K"))))))))) }}. {{item1.option}}</el-radio>
                    </template>
                  </el-radio-group>
                  <template v-if='item.cur'><div class='result'>学生答案：<div :class='["stu", (item.is_correct ? "success" : "error")]'>{{item.stuAnswer}}</div>&nbsp;&nbsp;&nbsp;&nbsp;正确答案：{{item.cur}}</div></template>
                </div>
              </template>
              <template v-if='item.type == 2'>
                <div v-bind:key="index" class='q-group' @click="checkboxClick" :data-index='index'>
                  <div class='q-num'>{{index+1}}.</div><div class='q-title' v-html='item.title'></div><div class='q-type'>(多选题)</div>
                  <el-checkbox-group class='checkbox-group' @change='checkboxChange' v-model="item.arrSel">
                    <template v-for='(item1, index1) in item.arr'>
                      <!-- value='{{index1}}' -->
                      <el-checkbox v-bind:key="item1.id" :label='index1' :checked='!!item1.selected' :disabled='!!item.cur' :class='["checkbox", (item.cur && item1.checked && "success"), (item.cur && !item1.checked && item1.selected && "error")]'>{{ index1 == 0 ? "A" : (index1 == 1 ? "B" : (index1 == 2 ? "C" : (index1 == 3 ? "D" : (index1 == 4 ? "E" : (index1 == 5 ? "F" : (index1 == 6 ? "G" : (index1 == 7 ? "H" : (index1 == 8 ? "I" : (index1 == 9 ? "J" : "K"))))))))) }}. {{item1.option}}</el-checkbox>
                    </template>
                  </el-checkbox-group>
                  <template v-if='item.cur'><div class='result'>学生答案：<div :class='["stu", (item.is_correct ? "success" : "error")]'>{{item.stuAnswer}}</div>&nbsp;&nbsp;&nbsp;&nbsp;正确答案：{{item.cur}}</div></template>
                </div>
              </template>
            </template>
          </div>
          <div :class='["btn", (exam.work_contents && "on")]' @click='submitExam' :data-submit='!!exam.work_contents' @mousedown='_SubmitMouseLeftDown()'>{{exam.work_contents ? "已提交" : "提交"}}</div>
          <div class='care'>(注意：测试只有一次提交机会)</div>
          <!-- <div :class='["btn"]' @click='repeatExam($event, true)' v-if="exam.work_contents">重做</div> -->
        </div>
      </template>
    </div>
  </div>
</div>
</template>

<script>
import cAction from '@action'

// import CKEDITOR from 'CKEDITOR'

export default {
  props: {
    chapterId: { type: String, require: false },
    chapterName: { type: String, require: false },
    chapterExam: { type: Object, require: false },
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false }
  },
  data () {
    return {
      exam: {
        // id: '',
        // semester_id: '',
        // title: '家族财富传承第一章试题',
        // score: '100',
        // work_contents: '',
        // group: [{
        //   id: '',
        //   type: 1, // 判别是 单选还是多选
        //   title: '<p>一般延续好几代，采取防御战略维持企业的家族企业类型是（ ）。</p>',
        //   arr: [
        //     { id: '', checked: true, option: '闪电型', selected: 0 },
        //     { id: '', checked: true, option: '不老型', selected: 1 },
        //     { id: '', checked: false, option: '长存型', selected: 1 },
        //     { id: '', checked: false, option: '持续创业型', selected: 0 }
        //   ],
        //   cur: '1',
        //   arrSel: [],
        //   sel: ''
        // }]
      },
      // 提交时，传入的参数值
      param: {
        course_id: '',
        chapter_id: '',
        work_id: '',
        semester_id: '',
        work_contents: '',
        duration: 0,
        score: 0
      },
      /* 进入页面记录初试时间 */
      startTime: '',
      /* 记录所有题目是否都答过 */
      recordAll: [],
      setTime: null,
      /* 当前 radio点击 */
      radioCur: '',
      /* 当前 checkbox点击 */
      checkCur: ''
    }
  },
  mounted () {
    this.loadAjax()
  },
  methods: {
    arrRandomSort (arr) {
      /* 对json.questions 进行一次乱序排列 */
      let tmpJson = null

      tmpJson = arr.shift()
      arr.push(tmpJson)
      tmpJson = arr.shift()
      arr.push(tmpJson)
      tmpJson = arr.shift()
      arr.push(tmpJson)
    },
    unArrRandomSort (arr) {
      /* 取消乱序排列，恢复原顺序 */
      let tmpJson = null

      tmpJson = arr.pop()
      arr.unshift(tmpJson)
      tmpJson = arr.pop()
      arr.unshift(tmpJson)
      tmpJson = arr.pop()
      arr.unshift(tmpJson)
    },
    /**
     * 将返回值 - 对照到对应 data上
     */
    updateData (json) {
      this.param = {
        course_id: json.course_id,
        chapter_id: json.chapter_id,
        work_id: json.work_id,
        semester_id: json.semester_id,
        work_contents: '',
        duration: 0,
        score: 0
      }
      this.startTime = new Date().getTime()
      // this.arrRandomSort(json.questions)
      const _data = {
        id: json.id,
        semester_id: json.semester_id,
        title: json.work_title,
        score: json.score || (json.score === 0 ? '0' : ''),
        work_contents: json.work_contents || '',
        group: json.questions.map(function (_, i) {
          let str = ''
          let stuAnswer = '' // 学生答案
          let stuIsCorrect = 0 // 学生是否答对
          let _json = JSON.parse(_.question_options)
          _json.forEach(function (__, j) {
            if (__.checked) {
              switch (j) {
                case 0: str += 'A,'; break
                case 1: str += 'B,'; break
                case 2: str += 'C,'; break
                case 3: str += 'D,'; break
                case 4: str += 'E,'; break
                case 5: str += 'F,'; break
                case 6: str += 'G,'; break
                case 7: str += 'H,'; break
                case 8: str += 'I,'; break
                case 9: str += 'J,'; break
              }
            }
          })
          let sel = '' // 单选选中
          /* 答过题目时 */
          if (json.work_contents) {
            const a = JSON.parse(json.work_contents)
            for (let i = 0; i < a.length; i++) {
              if (a[i].question_id === _.id) {
                _json = a[i].options
                stuIsCorrect = a[i].is_correct
                break
              }
            }
            /* 单选选中 */
            if (_.question_type === 1) {
              for (let i = 0; i < _json.length; i++) {
                if (_json[i].selected) {
                  sel = i
                  switch (i) {
                    case 0: stuAnswer = 'A,'; break
                    case 1: stuAnswer = 'B,'; break
                    case 2: stuAnswer = 'C,'; break
                    case 3: stuAnswer = 'D,'; break
                    case 4: stuAnswer = 'E,'; break
                    case 5: stuAnswer = 'F,'; break
                    case 6: stuAnswer = 'G,'; break
                    case 7: stuAnswer = 'H,'; break
                    case 8: stuAnswer = 'I,'; break
                    case 9: stuAnswer = 'J,'; break
                  }
                  break
                }
              }
            }
            /* 多选选中 */
            if (_.question_type === 2) {
              for (let i = 0; i < _json.length; i++) {
                if (_json[i].selected) {
                  switch (i) {
                    case 0: stuAnswer += 'A,'; break
                    case 1: stuAnswer += 'B,'; break
                    case 2: stuAnswer += 'C,'; break
                    case 3: stuAnswer += 'D,'; break
                    case 4: stuAnswer += 'E,'; break
                    case 5: stuAnswer += 'F,'; break
                    case 6: stuAnswer += 'G,'; break
                    case 7: stuAnswer += 'H,'; break
                    case 8: stuAnswer += 'I,'; break
                    case 9: stuAnswer += 'J,'; break
                  }
                }
              }
            }
          }
          return {
            id: _.id,
            type: _.question_type,
            title: _.question_content,
            arr: _json,
            cur: (json.work_contents && str.substr(0, str.length - 1)) || '',
            arrSel: [],
            sel: sel,
            stuAnswer: stuAnswer.substr(0, stuAnswer.length - 1),
            is_correct: stuIsCorrect
          }
        })
      }
      return _data
    },
    /**
     * 将返回值 - 对照到对应 data上
     * 增加这个的目的，由于循环改变data对象时，又由于 v-bind:key使用相同
     * 导致，有些选项勾选状态不显示，所有在不改变对象引用的前提下，直接改值
     * 所以 产生当前方法
     * 直接 把数据值 赋值给 exam对象
     */
    updateData1 (json) {
      this.exam.id = json.id
      this.exam.semester_id = json.semester_id
      this.exam.title = json.work_title
      this.exam.score = json.score || '0'
      this.exam.work_contents = json.work_contents || ''
      // this.arrRandomSort(json.questions)  // 蓝星不需要
      for (let i = 0; i < this.exam.group.length; i++) {
        let str = ''
        let stuAnswer = '' // 学生答案
        let stuIsCorrect = 0 // 学生是否答对
        const _ = json.questions[i]
        let _json = JSON.parse(_.question_options)
        _json.forEach(function (__, j) {
          if (__.checked) {
            switch (j) {
              case 0: str += 'A,'; break
              case 1: str += 'B,'; break
              case 2: str += 'C,'; break
              case 3: str += 'D,'; break
              case 4: str += 'E,'; break
              case 5: str += 'F,'; break
              case 6: str += 'G,'; break
              case 7: str += 'H,'; break
              case 8: str += 'I,'; break
              case 9: str += 'J,'; break
            }
          }
        })
        let sel = '' // 单选选中
        /* 答过题目时 */
        if (json.work_contents) {
          const a = JSON.parse(json.work_contents)
          for (let i = 0; i < a.length; i++) {
            if (a[i].question_id === _.id) {
              _json = a[i].options
              stuIsCorrect = a[i].is_correct
              break
            }
          }
          /* 单选选中 */
          if (_.question_type === 1) {
            for (let i = 0; i < _json.length; i++) {
              if (_json[i].selected) {
                sel = i
                switch (i) {
                  case 0: stuAnswer = 'A,'; break
                  case 1: stuAnswer = 'B,'; break
                  case 2: stuAnswer = 'C,'; break
                  case 3: stuAnswer = 'D,'; break
                  case 4: stuAnswer = 'E,'; break
                  case 5: stuAnswer = 'F,'; break
                  case 6: stuAnswer = 'G,'; break
                  case 7: stuAnswer = 'H,'; break
                  case 8: stuAnswer = 'I,'; break
                  case 9: stuAnswer = 'J,'; break
                }
                break
              }
            }
          }
          /* 多选选中 */
          if (_.question_type === 2) {
            for (let i = 0; i < _json.length; i++) {
              if (_json[i].selected) {
                switch (i) {
                  case 0: stuAnswer += 'A,'; break
                  case 1: stuAnswer += 'B,'; break
                  case 2: stuAnswer += 'C,'; break
                  case 3: stuAnswer += 'D,'; break
                  case 4: stuAnswer += 'E,'; break
                  case 5: stuAnswer += 'F,'; break
                  case 6: stuAnswer += 'G,'; break
                  case 7: stuAnswer += 'H,'; break
                  case 8: stuAnswer += 'I,'; break
                  case 9: stuAnswer += 'J,'; break
                }
              }
            }
          }
        }
        this.exam.group[i].id = _.id
        this.exam.group[i].type = _.question_type
        this.exam.group[i].title = _.question_content
        this.exam.group[i].cur = (json.work_contents && str.substr(0, str.length - 1)) || ''
        this.exam.group[i].arrSel = []
        this.exam.group[i].sel = sel
        this.exam.group[i].stuAnswer = stuAnswer.substr(0, stuAnswer.length - 1)
        this.exam.group[i].is_correct = stuIsCorrect
        const _arr = this.exam.group[i].arr
        for (let j = 0; j < _arr.length; j++) {
          _arr[j].selected = _json[j].selected
          _arr[j].id = _arr[j].id + '1'
        }
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    loadAjax () {
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Player.getExamDetail(this.sid, this.cid, this.id).then(_data => {
        const json = _data.homework
        if (json) {
          json.score = _data.score
          json.work_contents = _data.work_contents
          this.exam = this.updateData(json)
        } else {
          this.exam = {}
        }
      }).catch(e => { this.$message.error(e.message) }).finally(() => {
        this.setTime = setInterval(() => {
          // console.log(this.chapterExam.work_id, this.id)
          if (this.chapterExam.work_id && this.chapterExam.work_id === this.id) {
            if (!this.exam.id) {
              this.exam = this.updateData(this.chapterExam)
              /* 滚动到头部 */
              document.querySelector('.play-paper').scrollTop = 0
            }
            clearInterval(this.setTime)
          }
        }, 50)
        loading.close()
      })
    },
    /**
     * 辅助 radio选择
     */
    radioClick (e) {
      this.radioCur = e.currentTarget.dataset.index
    },
    /**
     * radio选择
     * PC端 值会 返回 选择的 值
     */
    radioChange (val) {
      const i = this.radioCur
      const arr = this.exam.group[i].arr
      const value = val
      for (let j = 0; j < arr.length; j++) {
        arr[j].selected = 0
      }
      arr[value].selected = 1
      this.exam.group[i].arr = arr
      this.recordAll.push(i)
    },
    /**
     * 辅助 checkbox选择
     */
    checkboxClick (e) {
      this.checkboxCur = e.currentTarget.dataset.index
    },
    /**
     * checkbox选择
     */
    checkboxChange (val) {
      const i = this.checkboxCur
      const arr = this.exam.group[i].arr
      const value = val
      for (let j = 0; j < arr.length; j++) {
        arr[j].selected = 0
      }
      for (let j = 0; j < value.length; j++) {
        arr[value[j]].selected = 1
      }
      this.exam.group[i].arr = arr
      if (!value.length) {
        this.recordAll = this.recordAll.filter(function (_, m) { return _ !== i })
      } else {
        this.recordAll.push(i)
      }
    },
    /**
     * 提交试题
     */
    submitExam (e) {
      if (e.currentTarget.dataset.submit) {
        this.$message.error('已做过，不能再提交')
        return
      }
      // /* 计算答题时间 */
      this.param.duration = Math.floor((new Date().getTime() - this.startTime) / 1000)
      const group = this.exam.group
      const total = group.length
      const arr = []
      let score = 0
      let correct = 0
      for (let m = 0; m < total; m++) {
        let n = 0
        for (; n < this.recordAll.length; n++) {
          if (this.recordAll[n] === m + '') { break }
        }
        if (n === this.recordAll.length) {
          // console.log(this.recordAll)
          this.$message.error('还有题目未做，不能提交')
          return
        }
      }
      /* 重新定义 - 上传字段 并计算分数 */
      // is_correct
      for (let i = 0; i < group.length; i++) {
        correct = 0
        if (group[i].type === 1) { // 单选的正确 判断
          group[i].arr.forEach(function (_, i) {
            if (_.checked && _.selected) { correct = 1; score += 1 }
          })
        }
        if (group[i].type === 2) { // 多选的正确 判断
          let flag = true
          group[i].arr.forEach(function (_, i) {
            if (_.checked !== !!_.selected) { flag = false }
          })
          if (flag) { correct = 1; score += 1 }
        }
        arr.push({
          question_id: group[i].id,
          is_correct: correct,
          options: group[i].arr
        })
      }
      // this.unArrRandomSort(arr)  // 蓝星不需要
      this.param.work_contents = JSON.stringify(arr)
      this.param.score = (score / total * 100).toFixed(1)

      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Player.submitExamDetail(this.param).then(_res => {
        if (_res.status) {
          cAction.Player.getExamDetail(this.sid, this.cid, this.id).then(_data => {
            const json = _data.homework
            if (json) {
              json.score = _data.score
              json.work_contents = _data.work_contents
              this.updateData1(json) // 特殊处理
            }
          }).catch(e => { this.$message.error(e.message) })
        } else {
          this.$message.error(_res.data.error)
        }
      }).catch(e => { this.$message.error(e.message) }).finally(() => { 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.Player.getExamDetail(this.sid, this.cid, this.id).then(_data => {
        this.exam = {}
      }).catch(e => { this.$message.error(e.message) }).finally(() => {
        this.setTime = setInterval(() => {
          // console.log(this.chapterExam.work_id, this.id)
          if (this.chapterExam.work_id && this.chapterExam.work_id === this.id) {
            if (!this.exam.id) {
              this.exam = this.updateData(this.chapterExam)
              /* 滚动到头部 */
              document.querySelector('.play-paper').scrollTop = 0
            }
            clearInterval(this.setTime)
          }
        }, 50)
        loading.close()
      })
    }
  },
  watch: {
    id: {
      handler () {
        this.loadAjax()
      }
    }
  }
}
</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 { float: right; 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; }

}
</style>
