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

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

  },
  onShow: function () {
    let that = this;
    // 页面显示
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
      if (wx.getStorageSync('storeId')) {
        util.request(api.ChooseStoreId, {
          storeId: wx.getStorageSync('storeId'),
          merchSn: wx.getStorageSync('merchSn'),
          isRefusedLogin: wx.getStorageSync('isRefusedLogin')
        }, 'POST').then(function (res) {
          if (res.errno === 0) {
            wx.setStorageSync('storeId', wx.getStorageSync('storeId'));
            wx.setStorageSync('merchSn', wx.getStorageSync('merchSn'));
            that.reLoad();
          }
        });
      }
    } else {
      wx.navigateTo({
        url: '/pages/auth/btnAuth/btnAuth',
      })
    }
  },
  onHide: function () {
    // 页面隐藏
    console.log('页面隐藏');

  },
  onUnload: function () {
    console.log('页面关闭');
    // 页面关闭
    // wx.switchTab({
    //   url: "/pages/cart/cart"
    // });

  },
  reLoad: function () {
    let that = this;
    if (wx.getStorageSync('storeId')) {
      if (wx.getStorageSync('userId')) {
        wx.request({
          url: api.updateLoginUser,
          data: {
            userId: wx.getStorageSync('userId'), storeId: wx.getStorageSync('storeId'), merchSn: wx.getStorageSync('merchSn')
          },
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          success: function (wxRes) {
            if (wxRes.data.errno === 0) {
              // console.log("用户信息更新成功");
            }
          },
          fail: function (err) {
            console.log("failed");
          }
        });
      }
    }
  },
  //改变支付方式
  changePayType: function (e) {
    console.log(e.currentTarget.id);
    this.setData({
      payType: e.currentTarget.id
    });
  },
  //向服务请求支付参数
  requestPayParam(formId) {
    let that = this;
    let orderBizType10 = that.data.orderBizType10;
    // console.log(orderBizType10)
    if(orderBizType10){
      //校验获取用户id上次活体人脸核身时间是否在可调用范围内
      util.request(api.CheckFaceTimeByUserId, {
        userId: wx.getStorageSync('userId'),
        storeId: wx.getStorageSync('storeId')
      }, 'POST').then(function (checkRes) {
        if (checkRes.errno === 0) {
          //根据用户上次活体人脸核身时间判断出，该用户可以调起人脸接口
          if (checkRes.data === true) {
            //根据订单号获取是否认证成功，认证成功则调起支付，否则提示
            that.checkFace(formId);            
          } else {
            //调起支付
            wx.showLoading({
              title: '加载中...',
            });
            that.requestPay(formId);
          }
        }
      });
    } else {
      //调起支付
      wx.showLoading({
        title: '加载中...',
      });
      that.requestPay(formId);
    }
  },
  /**
   * 根据订单号获取是否认证成功，认证成功则调起支付，否则提示
   */
  checkFace(formId){
    var that = this;
    util.request(api.GetIsFaceCheckByOrderId, {
      orderIds: that.data.orderIds
    }).then(function (res) {
      if (res.errno === 0) {
        if (res.data.isFaceCheck === '1' || res.data.isFaceCheck === '2') {
          wx.showLoading({
            title: '加载中...',
          });
          that.requestPay(formId);
        } else {
          wx.showToast({
            title: '现场速递商品购买需先认证身份信息再进行支付',
            icon: 'none',
            duration: 1500
          })
        }
      }
    });
  },
  /**
   * 调起支付
   */
  requestPay(formId) {
    let that = this;
    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({
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': payParam.package,
          'signType': payParam.signType,
          'paySign': payParam.paySign,
          'success': function (res) {
            if (that.data.orderBizType10) {
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=1&orderIds=' + that.data.orderIds + '&orderBizType10=' + that.data.orderBizType10,
              })
            }else{
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=1&orderIds=' + that.data.orderIds
              })
            }
          },
          'fail': function (res) {
            console.log('支付失败')
            if (that.data.orderBizType10) {
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=0&orderIds=' + that.data.orderIds + '&orderBizType10=' + that.data.orderBizType10,
              })
            } else {
              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) {
    console.log(e.detail.formId);
    this.requestPayParam(e.detail.formId);
  }
})