var app = getApp();
var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    orderIds: [],
    actualPrice: 0.00,
    isMergePay: '',
    payType: 'wxGlobal'
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      orderIds: options.orderIds,
      actualPrice: options.actualPrice,
      isMergePay: options.isMergePay
    })
    console.log(this.data.orderIds);
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  //改变支付方式
  changePayType: function (e) {
    console.log(e.currentTarget.id);
    this.setData({
      payType: e.currentTarget.id
    });
  },
  //向服务请求支付参数
  requestPayParam() {
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });

    console.log(this.data.payType);
    let url = '';
    if (this.data.payType == 'wx') {
      url = api.PayPrepayId;
    } else if (this.data.payType == 'pingan') {
      url = api.Payorder;
    } else if (this.data.payType == 'wxGlobal') {
      url = api.GlobalPayorder;
    } 

    // 测试领取优惠券
    // wx.redirectTo({
    //   url: '/pages/payResult/payResult?status=1&orderId=' + that.data.orderId,
    // })
    // todo
    util.request(url, {
      orderIds: that.data.orderIds, payType: 1,
      isMergePay: that.data.isMergePay
      }).then(function (res) {
        wx.hideLoading();
      if (res.errno === 0) {
        let payParam = res.data;
        wx.requestPayment({
          'appId': payParam.appId,
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': payParam.package,
          'signType': 'RSA',
          'paySign': payParam.paySign,
          'success': function (res) {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=1&orderIds=' + that.data.orderIds,
            })
          },
          'fail': function (res) {
            console.log(res)
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=0&orderIds=' + that.data.orderIds,
            })
          }
        })
      }else {
        // util.showErrorToast(res.errmsg)
        wx.showModal({
          title: '',
          content: res.errmsg,
          showCancel: false
        });
      }
    });
  },
  startPay(e) {
    this.requestPayParam();
  }
})