//index.js

const util = require("../../../utils/util")

//获取应用实例
const app = getApp()

Page({
  data: {
    spinShow: false,
    buyModel:false,
    code_url:'',
    info:{},
    system: "",
    groups: [],
    pushPaper: [],
    timeLimitPaper: [],
    userInfo:{},
    taskList: []
  },
  onLoad: function(){
    let that = this
    wx.getSystemInfo({
      success: function(res) {
        that.setData({system: res.system})
      }
    })
  },
  onShow: function(){
    app.getUserInfo( userInfo =>{
      this.setData({userInfo})
      // 已经实名认证
      if( userInfo.identify ){
        this.indexLoad()
      }
    })
  },
  onPullDownRefresh() {
    if (!this.loading) {
      this.indexLoad( this.stopPullDownRefresh )
    }
  },
  stopPullDownRefresh(){
    wx.stopPullDownRefresh()
  },
  indexLoad: function( cb ) {
    let _this = this
    app.formPost('Exam.index', {}).then(res => {
      if (res.code === 200) {
        _this.setData({
          groups: res.data.groups
        });
       cb&&cb() 
      }
    })
  },
  downloadFile: function(){
    let url = this.data.info.code_url
    util.downloadFile( url, res=>{
      this.setData({buyModel:false, code_url:''})
    } )
  },
  gotoHistory: function(){
    wx.navigateTo({
      url: '/pages/exam/record/index',
    })
  },
  gotoExam:function( e ){
    let groupId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/exam/do/index?id=${groupId}`
    })
  },
  gotoCollection(){
    wx.navigateTo({
      url: '/pages/exam/collection/index',
    })
  },
  doWxPay( data ){
    let that = this
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package, 
      signType: data.signType,
      paySign: data.paySign,
      success: function (event) {
        wx.showModal({
          title: '支付成功',
          showCancel: false,
          content: '本次共支付费用￥'+(data.fee/100)+'元'+ `\n\n试卷更新可能延迟，请耐心等待`,
          success(res) {
            that.indexLoad()
          }
        })
      }
    })
  },
  startWxpay(e){
    let groupId = +e.currentTarget.dataset.id
    let system = this.data.system
    app.formPost('User.PayExam', {groupId, system}).then(res => {
      if (res.code === 200) {
        if( res.data.payType=="free" ){
          this.indexLoad()
        }else if (res.data.payType=="qrcode"){
          this.setData({info: res.data, buyModel:true})
        }else{
          this.doWxPay( res.data )
        }
      }
    })
  },
  onShareAppMessage: function(){

  },
  gotoError: function(){
    wx.navigateTo({
      url: '/pages/exam/error/index',
    })
  }
})