<template>
  <view>
    <view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
      <view class="cu-bar fixed bg-gradual-blueness" :style="style">
        <view class="action" @tap="BackPage">
          <text class="cuIcon-back"></text>
          <slot name="backText">返回</slot>
        </view>
        <view class="content" :style="[{top:StatusBar + 'px'}]">
          <slot name="content">{{ titleContext }}</slot>
        </view>
        <view class="right">
          <slot name="right"></slot>
        </view>
        <!-- <slot name="right"></slot> -->
      </view>
    </view>
    <view class="course">
      <!-- <view v-show="!isExamStart" class="course-header">
        <view class="course-name">
          <text>试卷名称:{{ form.EXAMNAME }}</text>
        </view>
        <view class="course-name">
          <text>答卷时间:{{ form.ANSWERSHEETTIME }}</text>
        </view>
        <view class="course-obj">
          <text>试卷总共{{ form.QUESTIONNUM }}道题，答题时间共计{{ form.ANSWERSHEETTIME }}分钟，开始答题后计时到答卷时间后会自动提交试卷，请学员尽快答题。</text>
        </view>

        <view >
          <button class="cu-btn bg-green" @click="$noMultipleClicks(handleBegin)" >开始答题</button>
        </view>
      </view> -->
      <view v-show="isExamStart" class="course-aa">
        <view class="course-items" v-for="(row,i) in form.QUESTIONLIST" :key="row.QUESTION_ID">
          <view class="course-ask">
            {{ i + 1 }}.
            <text v-if="row.QUESTIONTYPE === '1'" class="mark">(单选题)</text>
            <text v-if="row.QUESTIONTYPE === '2'" class="mark">(多选题)</text>
            <text v-if="row.QUESTIONTYPE === '3'" class="mark">(判断题)</text>
            {{ row.QUESTIONDRY }}
          </view>
          <view class="course-answer">
            <radio-group v-if="row.QUESTIONTYPE == '1'" :disabled="isDisabled" v-model="form.ANSWER[i]"
                         @change="radioQuestionChange($event,i)">
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='A'?'checked':''" :checked="form.ANSWER[i]=='A'?true:false"
                       value="A"></radio>
                <text class="title">A.{{ row.OPTIONA }}</text>
              </label>
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='B'?'checked':''" :checked="form.ANSWER[i]=='B'?true:false"
                       value="B"></radio>
                <text class="title">B.{{ row.OPTIONB }}</text>
              </label>
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='C'?'checked':''" :checked="form.ANSWER[i]=='C'?true:false"
                       value="C"></radio>
                <text class="title">C.{{ row.OPTIONC }}</text>
              </label>
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='D'?'checked':''" :checked="form.ANSWER[i]=='D'?true:false"
                       value="D"></radio>
                <text class="title">D.{{ row.OPTIOND }}</text>
              </label>
            </radio-group>
            <checkbox-group v-if="row.QUESTIONTYPE == '2'" class="checkbox" :disabled="isDisabled"
                            v-model="form.ANSWER[i]" @change="checkQuestionChange($event,i)">
              <label class="answer-lable">
                <checkbox :id="'checkA'+i" value="A"></checkbox>
                <text class="title">A.{{ row.OPTIONA }}</text>
              </label>
              <label class="answer-lable">
                <checkbox :id="'checkB'+i" value="B" :checked="form.ANSWER[i].includes('B')?true:false"></checkbox>
                <text class="title">B.{{ row.OPTIONB }}</text>
              </label>
              <label class="answer-lable">
                <checkbox :id="'checkC'+i" value="C" :checked="form.ANSWER[i].includes('C')?true:false"></checkbox>
                <text class="title">C.{{ row.OPTIONC }}</text>
              </label>
              <label class="answer-lable">
                <checkbox :id="'checkD'+i" value="D" :checked="form.ANSWER[i].includes('D')?true:false"></checkbox>
                <text class="title">D.{{ row.OPTIOND }}</text>
              </label>
            </checkbox-group>
            <radio-group v-if="row.QUESTIONTYPE == '3'" :disabled="isDisabled" v-model="form.ANSWER[i]"
                         @change="radioQuestionChange($event,i)">
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='A'?'checked':''" :checked="form.ANSWER[i]=='A'?true:false"
                       value="A"></radio>
                <text class="title">A.{{ row.OPTIONA }}</text>
              </label>
              <label class="answer-lable">
                <radio class="blue" :class="form.ANSWER[i]=='B'?'checked':''" :checked="form.ANSWER[i]=='B'?true:false"
                       value="B"></radio>
                <text class="title">B.{{ row.OPTIONB }}</text>
              </label>
            </radio-group>
          </view>
        </view>
      </view>
    </view>
    <view class="cu-tabbar-height"></view>
    <view v-show="isExamStart" class="bottom-fixed">
      <button class="cu-btn bg-green" @click="$noMultipleClicks(confirm)">提交</button>
    </view>
  </view>
</template>

<script>
import {
  basePath,
  corpinfoId,
  deptId,
  loginSession,
  formatDate,
  loginUser
} from '@/common/tool.js'

export default {
  components: {},
  data() {
    return {
      StatusBar: this.StatusBar,
      CustomBar: this.CustomBar,
      bgImage: '',
      isExamStart: false,
      isDisabled: true,
      titleContext: '课程考试',
      CURRICULUM_ID: '',
      COURSESTUDENTRELATION_ID: '',
      timer: '',
      hour: 0,
      minutes: 0,
      seconds: 0,
      showRight: false,
      dataFlag: 'noData',
      sTop: 0,
      totalHeight: 0,
      form: {
        CURRICULUMID: '', // 课程ID
        EXAMNAME: '', // 试卷名称
        EXAMTIME: '', // 考试时间（开始时间）
        ANSWERSHEETTIME: '', // 答卷时间（持续时间）
        EXAMSCORE: 100, // 试卷分数
        QUESTIONNUM: '', // 试题数量（10、20、50、100）
        QUESTION_ID: [], // 试题ID数组
        QUESTIONTYPE: [], // 试题类型数组
        ANSWER: [], // 学员答案
        ANSWERRIGHT: [],// 正确答案
        QUESTIONLIST: []	//考题List
      },	//页面数据
      subForm: {},	//交卷数据
      list: [], //返回数据
      page: 1, //分页参数--页数
      rows: 10, //分页参数--每页数据条数
      totalCount: 0, //分页参数--初始化页数
      isEnd: false, //防止多次刷新
      totalPage: 0, //分页参数--分页数量
      noClick: true
    }
  },
  computed: {
    style() {
      var StatusBar = this.StatusBar;
      var CustomBar = this.CustomBar;
      var bgImage = this.bgImage;
      var style = `height:${CustomBar}px;padding-top:${StatusBar}px;`;
      if (this.bgImage) {
        style = `${style}background-image:url(${bgImage});`;
      }
      return style
    }
  },
  onReady() {
  },
  onLoad(event) {
    this.CURRICULUM_ID = event.CURRICULUM_ID
    this.COURSESTUDENTRELATION_ID = event.COURSESTUDENTRELATION_ID
    this.getData();
    loginSession();
  },
  onBackPress(options) {
    this.BackPage()
    return true
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer) // 满足条件时 停止计时
      this.timer = null
      this.seconds = 0
      this.minutes = 0
    }
  },
  methods: {
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/coursepapers/findByCurriculumExam',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          CURRICULUMID: this.CURRICULUM_ID,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          if ("success" == res.data.result) {
            uni.hideLoading();
            // _this.pd = res.data.pd;
            _this.form = Object.assign(_this.form, res.data.pd)
            _this.handleBegin()
          }
        }
      });
    },
    handleBegin() {
      if (this.timer) {
        clearInterval(this.timer) // 满足条件时 停止计时
        this.timer = null
        this.seconds = 0
        this.minutes = 0
      }
      this.form.EXAMTIME = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      this.isExamStart = true
      this.isDisabled = false
      this.titleContext = '00:00'
      this.timer = setInterval(this.startTimer, 1000)
    },
    startTimer() {
      this.seconds += 1
      if (this.seconds >= 60) {
        this.seconds = 0
        this.minutes = this.minutes + 1
      }
      this.titleContext = (this.minutes < 10 ? '0' + this.minutes : this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds)
      if (this.titleContext == this.form.ANSWERSHEETTIME + ':00') {
        if (this.timer) {
          clearInterval(this.timer) // 满足条件时 停止计时
          this.timer = null
          this.seconds = 0
          this.minutes = 0
        }
        this.subForm = Object.assign({}, this.form)
        for (let i = 0; i < this.subForm.ANSWER.length; i++) {
          if (this.subForm.QUESTIONTYPE[i] == '2') {
            this.subForm.ANSWER[i] = this.trimSpace(this.subForm.ANSWER[i])
            this.subForm.ANSWER[i] = this.subForm.ANSWER[i].length > 0 ? this.subForm.ANSWER[i].sort() : []
            if (this.subForm.ANSWER[i].length == 0) {
              this.subForm.ANSWER[i] = '-'
            }
          } else {
            if (this.subForm.ANSWER[i].length == 0) {
              this.subForm.ANSWER[i] = '-'
            }
          }
        }
        this.assignSubFormData()

        uni.showModal({
          title: '',
          content: '计时时间已到提交试卷！',
          showCancel: false,
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              this.submitForm()
            }
          }
        })
      }
    },
    radioQuestionChange(e, i) {
      this.form.ANSWER[i] = e.detail.value;
    },
    checkQuestionChange(e, i) {
      this.form.ANSWER[i] = e.detail.value;
    },
    confirm() {
      var confirmMsg = '试卷试题第'
      this.subForm = Object.assign({}, this.form)
      for (let i = 0; i < this.subForm.ANSWER.length; i++) {
        if (this.subForm.QUESTIONTYPE[i] == '2') {
          this.subForm.ANSWER[i] = this.trimSpace(this.subForm.ANSWER[i])
          this.subForm.ANSWER[i] = this.subForm.ANSWER[i].length > 0 ? this.subForm.ANSWER[i].sort() : []
          if (this.subForm.ANSWER[i].length == 0) {
            confirmMsg += (i + 1) + ','
            this.subForm.ANSWER[i] = '-'
          }
        } else {
          if (this.subForm.ANSWER[i].length == 0) {
            confirmMsg += (i + 1) + ','
            this.subForm.ANSWER[i] = '-'
          }
        }
      }
      confirmMsg = confirmMsg.length == 5 ? '确定要提交试卷吗？' : (confirmMsg.slice(0, confirmMsg.length - 1) + '题还没有作答，确定要提交试卷吗？')
      this.assignSubFormData()
      uni.showModal({
        title: '',
        content: confirmMsg,
        cancelColor: '#000000',
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            this.submitForm()
          }
        }
      })
    },
    assignSubFormData() {
      var ANSWER_STR = ''
      for (let i = 0; i < this.subForm.ANSWER.length; i++) {
        if (this.subForm.QUESTIONTYPE[i] == '2') {
          ANSWER_STR += (this.subForm.ANSWER[i] == '-' ? '-' : this.subForm.ANSWER[i].join('')) + ','
        } else {
          ANSWER_STR += this.subForm.ANSWER[i] + ','
        }
      }
      this.subForm.ANSWER = ANSWER_STR.length > 0 ? ANSWER_STR.slice(0, ANSWER_STR.length - 1) : ''
      this.subForm.QUESTION_ID = this.subForm.QUESTION_ID.join(',')
      this.subForm.QUESTIONTYPE = this.subForm.QUESTIONTYPE.join(',')
      this.subForm.COURSEWAREID = this.subForm.COURSEWAREID.join(',')
      this.subForm.COURSEWARETYPE = this.subForm.COURSEWARETYPE.join(',')
      this.subForm.ANSWERRIGHT = this.subForm.ANSWERRIGHT.join(',')
      this.subForm.QUESTIONLIST = ''
      this.subForm.CORPINFO_ID = corpinfoId
      this.subForm.USER_ID = loginUser.USER_ID
      this.subForm.USERNAME = loginUser.USERNAME
      this.subForm.COURSESTUDENTRELATION_ID = this.COURSESTUDENTRELATION_ID
    },
    submitForm() {
      uni.showLoading({
        title: '处理中'
      })
      if (this.timer) {
        clearInterval(this.timer) // 满足条件时 停止计时
        this.timer = null
        this.seconds = 0
        this.minutes = 0
      }
      this.isDisabled = true
      uni.request({
        url: basePath + '/app/courseexam/submit',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          ...this.subForm,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          const examScore = res.data.pd.EXAMSCORE
          var modelContent = '本次考试成绩' + examScore + '分'
          if (examScore >= 60) {
            modelContent += '，考试通过'
          } else {
            modelContent += '，考试未通过'
          }
          uni.showModal({
            title: '考试结果',
            content: modelContent,
            showCancel: false,
            confirmText: '确定',
            success: res => {
              if (res.confirm) {
                uni.redirectTo({
                  url: '/pages/application/onlinexxks/my-curriculum',
                })
              }
            }
          })
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
    trimSpace(array) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] == '' || array[i] == null || typeof (array[i]) == 'undefined') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    BackPage() {
      if (!this.isDisabled) {
        uni.showModal({
          title: '',
          content: '课程考试已开始，确定要退出考试么？',
          cancelColor: '#000000',
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              if (this.timer) {
                clearInterval(this.timer) // 满足条件时 停止计时
                this.timer = null
                this.seconds = 0
                this.minutes = 0
              }
              uni.redirectTo({
                url: '/pages/application/onlinexxks/my-curriculum',
              })
            }
          }
        })
      } else {
        uni.redirectTo({
          url: '/pages/application/onlinexxks/my-curriculum',
        })
      }
    }
  }
}

</script>

<style>
.course {
  background-color: #fff;
}

.course-header {
  padding: 20upx;
  border-bottom: 1upx solid #F1F1F1;
  line-height: 1.6;
}

.course-name {
  font-weight: bold;
  font-size: 30upx;
}

.course-int {
  color: #888;
}

.course-obj {
  color: #888;
}

.course-aa {
  padding: 0 20upx;
}

.course-items {
  border-bottom: 1px dashed #F1F1F1;
  padding: 20upx 0;
}

.course-items .course-ask {
  line-height: 1.6;
  font-size: 28upx;
  /* margin-bottom: 10upx; */
}

.course-answer {
  padding-left: 40upx;
  margin-top: 20upx;
}

.answer-lable {
  display: block;
  margin-bottom: 20upx;
}

.answer-lable:last-child {
  margin-bottom: 0;
}

.answer-lable radio {
  margin-right: 20upx;
}
</style>
