const wx = require('weixin-js-sdk');
export default {
  wexinPay(data, jumpUrl) {
    return new Promise((r) => {
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timeStamp,
        nonceStr: data.nonceStr,
        signature: data.paySign,
        jsApiList: ['chooseWXPay']
      });
      wx.ready(() => {
        wx.chooseWXPay({
          timestamp: data.timeStamp, //这个字段是为字符串后端返回时需检查
          nonceStr: data.nonceStr,
          package: data.packageValue,
          signType: data.signType,
          paySign: data.paySign,
          success(res) {
            r({
              code: 0,
              msg: '成功'
            });
          },
          cancel() {
            r({
              code: 1,
              msg: '取消'
            });
          },
          fail(err) {
            r({
              code: 2,
              msg: err.errMsg.split(':')[1] || '支付失败!'
            });
          },
          // 无论失败成功都会执行
          complete(e) {
            // e.errMsg三种状态 1.chooseWXPay:ok 支付成功 2: chooseWXPay:cancel 支付取消 3:chooseWXPay:fail 支付失败
            if (e.errMsg === 'chooseWXPay:ok') {
              if (jumpUrl) {
                window.location.href = jumpUrl;
              } else {
                window.location.reload();
              }
            }
          }
        });
      });
      wx.error(function (err) {
        r({
          code: 2,
          msg: '支付失败!'
        });
      });
    });
  }
};
