// pages/lianxi/main.js
const api = require("../../utils/request.js");
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tms:[],
    tm_index: 0,
    ctms:[],
    domain:getApp().globalData.mediahost,
  },
  radioChange: function (e) {
    var that = this
    that.data.tm_current['user_answer'] = e.detail.value
    that.data.tms[that.data.tm_index] = that.data.tm_current
  },
  checkboxChange: function (e) {
    var that = this
    that.data.tm_current['user_answer'] = e.detail.value
    that.data.tms[that.data.tm_index] = that.data.tm_current
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that = this
    try {
      var value = wx.getStorageSync('examtest')
      console.log(value)
      if (value) {
        for(var i=0;i<value.questions.length;i++){
          if(value.questions[i].img){
            value.questions[i].img = getApp().globalData.mediahost + value.questions[i].img
          }
        }
        that.data.examtest = value
        that.data.tms = value.questions
        that.setData({
          tm_total:value.questions.length
        })
        that.showTm(that.data.tm_index)
      }
    } catch (e) { wx.navigateBack({}) }
    try {
      const res = wx.getSystemInfoSync()
      that.setData({
        scrollHeight: res.windowHeight - 78
      })
    } catch (e) {
    }
    try {
      var value = wx.getStorageSync('ctms')
      if (value) {
        that.data.ctms = value
      }
    } catch (e) { }
    let mil = that.data.examtest.limit * 60 * 1000
    let starttimes = (new Date()).getTime() //时间戳
    let endtimes = starttimes + mil
    that.data.starttimes = starttimes
    that.data.endtimes = endtimes
    getApp().globalData.timer = setInterval(function () {
      that.startPass()
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton({})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(getApp().globalData.timer)
    try {
      wx.setStorageSync('ctms', this.data.ctms)
    } catch (e) { }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  startPass: function () {
    var mil = this.data.endtimes - (new Date()).getTime()
    if (mil < 2000) {
      clearInterval(getApp().globalData.timer)
      this.handTest()
    };
    var temp = util.formatmil(mil);
    this.setData({
      countdown: temp,
    });

  },
  showTm: function (index) {
    var that = this
    var tm_current = that.data.tms[index]
    that.setData({
      'tm_index': index,
      'tm_current': tm_current
    })
    that.showOptions()
  },
  panTi: function (tm_current) {
    // 返回当前题目是否正确,得分多少
    let is_right = false, score = 0
    if (tm_current.type == '多选') {
      if (tm_current.user_answer) {
        if (tm_current.user_answer.sort().toString() == tm_current.right.sort().toString()) {
          is_right = true
          score = tm_current.total_score
        }else{
          for(var i=0;i<tm_current.user_answer.length;i++){
            if(tm_current.right.indexOf(tm_current.user_answer[i])!=-1){
              score = score + 1
              if(score==2){
                break;
              }
            }else{
              score = 0
              break;
            }
          }
        }
      }

    } else {
      if(tm_current.right == tm_current.user_answer){
        is_right = true
        score = tm_current.total_score
      }
    }
    return {'is_right':is_right,'score':score}
  },
  next: function () {
    var that = this
    var tm_index = that.data.tm_index + 1
    that.showTm(tm_index)
  },
  previous: function () {
    var that = this
    var tm_index = that.data.tm_index - 1
    that.showTm(tm_index)
  },
  showOptions: function () {
    let tm_current = this.data.tm_current
    let options = []
    for (let key in tm_current.options) {
      let option = {}
      option.key = key
      option.value = tm_current.options[key]
      if (tm_current.user_answer) {
        if (key == tm_current.user_answer || tm_current.user_answer.indexOf(key) != -1) {
          option.checked = true
        }
      } else {
        option.checked = false
      }
      options.push(option)
    }
    this.setData({
      options: options
    })
  },
  sheet: function () {
    wx.navigateTo({
      url: 'sheet',
    })
  },
  hand: function () {
    var that = this
    for (var i = 0, len = that.data.tms.length; i < len; i++) {
      let tm = that.data.tms[i]
      if (tm.user_answer == undefined || tm.length == 0){
        wx.showModal({
          title: '警告',
          content: '答卷未完成,可点击答题卡复查!',
          confirmText: "仍旧提交",
          cancelText: "取消",
          success: function (res) {
            if (res.confirm) {
              that.handTest()
            }
          }
        })
        return
      }
    }
    wx.showModal({
      content: '确定提交?',
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          that.handTest()
        }
      }
    })
  },
  handTest: function (){
    var that = this
    clearInterval(getApp().globalData.timer)
    wx.showLoading({
      title: '正在判卷中...',
      mask:true
    })
    let score = 0;
    for (var i = 0, len = that.data.tms.length; i < len; i++) {
      let tm_result = that.panTi(that.data.tms[i])
      that.data.tms[i].is_right = tm_result.is_right
      if (tm_result.is_right == false && that.data.tms[i].user_answer){
        that.data.ctms.unshift(that.data.tms[i])
          if (that.data.ctms.length > 40) {
            that.data.ctms.length = 40
          }
      }
      that.data.tms[i].score = tm_result.score
      score = score + tm_result.score
    }
    that.data.examtest.score = score
    if (score >= that.data.examtest.pass_score){
      that.data.examtest.is_pass = true
    }else{
      that.data.examtest.is_pass = false
    }
    that.data.examtest.questions = that.data.tms
    that.data.examtest.start_time = util.formatTime(new Date(that.data.starttimes))
    that.data.examtest.end_time = util.formatTime(new Date())
    that.data.examtest.took = Math.floor(((new Date()).getTime() - this.data.starttimes) / 1000)
    api.request('/examtest/examtest/', 'POST', that.data.examtest).then(res => {
      wx.hideLoading()
      getApp().globalData.testData = res.data
      try {
        wx.removeStorageSync('examtest')
      } catch (e) {
      }
      wx.redirectTo({
        url: 'result',
      })
      
    })
  }
})