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

Page({
  data: {
    spinShow: false,
    buyModel:false,
    code_url:'',
    info:{},
    system: "",
    userInfo:{},
    from:0,
    size: 10,
    type: '',
    courseList: []
  },
  onLoad: function( options ){
    let type= options.type||''
    this.setData({type})
    let that = this
    wx.getSystemInfo({
      success: function(res) {
        that.setData({system: res.system})
      }
    })
    wx.setNavigationBarTitle({
      title: type+'-课程购买'
    })
  },
  gotoCourse( e ){
    let courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/study/course/index?courseId=${courseId}`,
    })
  },
  onShow: function () {
    app.getUserInfo( userInfo =>{
      this.setData({userInfo})
      this.indexLoad()
    })
  },
  onPullDownRefresh() {
    if (!this.loading) {
      this.setData({from:0, courseList:[]})
      this.indexLoad( this.stopPullDownRefresh )
    }
  },
  onReachBottom() {
    if (!this.loading && this.data.from > -1) {
      this.indexLoad(  )
    }
  },
  stopPullDownRefresh(){
    wx.stopPullDownRefresh()
  },
  indexLoad: function( cb ) {
    let param ={ 
      from: this.data.from,
      size: this.data.size,
      type: this.data.type,
    }
    let courseList = this.data.courseList;
    app.formPost('Study.getWxCourseMarket', param).then(res => {
      if (res.code === 200) {
        if( param.from == 0){
          courseList = [];
        }
        this.setData({
          from: res.data.from,
          courseList: courseList.concat(res.data.list),
        });
       cb&&cb() 
      }
    })
  },
  downloadFile: function(){
    let url = this.data.info.code_url
    util.downloadFile( url, res=>{
      this.setData({buyModel:false, code_url:''})
    } )
  },
  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 courseId = +e.currentTarget.dataset.id
    let system = this.data.system
    app.formPost('User.PayCourse', {courseId, 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',
    })
  }
})