/*!
 * @Author: LYT<lyt@hainatravel.com>
 * @Date: 2019-10-29 16:51:18
 */
import { postForm } from '@/utils/request';
import * as common from '@/utils/common';

let Pay = {};

let wxpaySignUrl = common.HOST_NAME + '/wechat-order/wxpay-sign/trippest';
/**
 * 支付的回调
 */
let payCallback;
/**
 * 生成的out_trade_no
 */
let outTradeNo;

/*!
 * @Author: LYT<lyt@hainatravel.com>
 * @Date: 2019-10-29 16:37:21
 * @Desc: 请求微信支付签名, 成功继续支付, 失败回调
 * @param _order_id 传入coli_id
 * @param _payType 支付类型--微信 JSAPI
 * @param _callback 回调 true or false
 */
Pay.done = function (_order_id, _payType, _callback) {
    let postData = new FormData();
    postData.append('order_id', _order_id);
    if (typeof _callback === "function") {
        payCallback = _callback;
    }
    postForm(wxpaySignUrl, postData)
        .then((data) => {
            outTradeNo = data.order_no;
            if (undefined !== data.param.appId) {
                this.doneResponse(data.param);
            }
        }).catch(() => {
            payCallback(false);
        });
};

Pay.doneResponse = function (result) {
    this.callPay(result);
};

Pay.callPay = function (obj) {
    if (typeof window.WeixinJSBridge === "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
        }
    } else {
        this.jsApiCall(obj);
    }
};
/*
 * @param obj :
{
    "appId":"", //公众号名称，由商户传入
    "timeStamp":"", //时间戳，自1970年以来的秒数
    "nonceStr":"", //随机串
    "package":"prepay_id=u802345jgfjsdfgsdg888", // 统一下单接口返回的prepay_id参数值
    "signType":"MD5",   //微信签名方式：
    "paySign":"" //微信签名
}
*/
Pay.jsApiCall = function (obj) {
    window.WeixinJSBridge.invoke('getBrandWCPayRequest', obj, function (res) {
        if (common.isNotEmpty(res)
            && common.isNotEmpty(res.err_msg)
            && res.err_msg.indexOf('ok') > 0) {
            payCallback(outTradeNo);
        } else {
            payCallback(false);
        }
    });
};

export default Pay
