/* eslint-disable no-undef */
import config from "../config";

/**
 * Promise 化小程序 API
 * @param api {function} 小程序 API
 * @param defaults {object} 默认选项
 * @return {function(*=, ...[*]): Promise}
 */
function promisify(api, defaults = {}) {
    return (options, ...params) => {
        return new Promise((resolve, reject) => {
            api(
                Object.assign(defaults, options, {
                    success: resolve,
                    fail: reject,
                }),
                ...params
            );
        });
    };
}

export const wxLogin = promisify(wx.login);
export const wxShowModal = promisify(wx.showModal, {
    confirmColor: config.color.primary,
});
export const wxRequestPayment = function (...args) {
    return promisify(wx.requestPayment)(...args).catch((res) => {
        if (res.err_code === "-1") {
            return Promise.reject({
                message: res.err_desc,
            });
        }
        if (res.errMsg === "requestPayment:fail cancel") {
            return Promise.reject({
                message: "支付已取消",
            });
        } else if (res.errMsg.startsWith("requestPayment:fail")) {
            return Promise.reject({
                message:
                    "支付失败：" +
                    res.errMsg.substr("requestPayment:fail".length),
            });
        }
    });
};

export function wxShowToast(title) {
    wx.showToast({ title, duration: 2000, icon: "none" });
}

export function wxShowSuccessToast(title) {
    wx.showToast({ title, duration: 2000, icon: "success" });
}

export function wxShowMaskLoading(title) {
    wx.showLoading({
        title,
        mask: true,
    });
}
