const wx = require('weixin-js-sdk');
export default {
  weixinPay(data, jumpUrl) {
    wx.config({
      debug: false,
      appId: data.appId,
      timestamp: data.timeStamp,
      nonceStr: data.nonceStr,
      signature: data.paySign,
      jsApiList: ['chooseWXPay']
    });
    return new Promise((resolve, reject) => {
      wx.ready(() => {
        wx.chooseWXPay({
          timestamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.packageValue,
          signType: data.signType,
          paySign: data.paySign,
          success(res) {
            resolve({ code: 0, msg: '成功' });
            if (e.errMsg === 'chooseWXPay:ok' && jumpUrl) {
              window.location.href = jumpUrl;
            }
          },
          cancel() {
            resolve({ code: 1, msg: '取消' });
          },
          fail(err) {
            reject({ code: 2, msg: err.errMsg.split(':')[1] || '支付失败!' });
          },
          complete(e) {
            if (e.errMsg !== 'chooseWXPay:ok') {
              reject({ code: 2, msg: '支付失败!' });
            }
          }
        });
      });
      wx.error((err) => {
        reject({ code: 2, msg: '支付失败!' });
      });
    });
  }
};
