import { forEach } from "lodash";

/**
 * 延迟执行
 * @param {Number} ms 
 * @returns 
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
/**
 * 解析查询字符串
 * @param {string} urlOrQueryString 
 * @returns {Object} 查询参数对象
 */
export function parseQueryString(urlOrQueryString) {
    // 如果传入的是完整URL（如 "/path?name=value"），提取查询部分
    let queryString = urlOrQueryString;
    const questionMarkIndex = queryString.indexOf('?');
    if (questionMarkIndex !== -1) {
        queryString = queryString.slice(questionMarkIndex + 1);
    }

    const params = {};
    if (!queryString) return params; // 如果没有查询参数，返回空对象

    const pairs = queryString.split('&');
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        // 解码 URI 组件，并处理无值情况（如 "key" 而不是 "key=value"）
        params[key] = value ? decodeURIComponent(value) : '';
    }

    return params;
}

/**
 * 显示确认弹窗
 * @param {Object} options 弹窗选项
 * @param {String} options.title 弹窗标题
 * @param {String} options.content 弹窗内容
 * @param {String} options.confirmText 确认按钮文字
 * @param {String} options.cancelText 取消按钮文字
 * @returns {Promise} 返回Promise对象，resolve中返回{confirm: Boolean}，表示是否点击了确认按钮
 */
export function showModal(options = {}) {
    return new Promise((resolve) => {
        uni.showModal({
            title: options.title || '提示',
            content: options.content || '',
            confirmText: options.confirmText || '确定',
            cancelText: options.cancelText || '取消',
            success(res) {
                resolve(res);
            },
            fail() {
                resolve({
                    confirm: false
                });
            }
        });
    });
}

/**
 * 
 * @param {String} title 
 * @param {String} content 
 * @returns 
 */
export function showModalConfirm(title, content) {
    return new Promise((resolve) => {
        uni.showModal({
            title: title || '提示',
            content: content || '',
            confirmText: '确定',
            cancelText: '取消',
            showCancelButton: true,
            showConfirmButton: true,
            confirmColor: '#1989FA',
            cancelColor: '#9F9F9F',
            success: function (res) {
                if (res.confirm) {
                    resolve(true);
                } else if (res.cancel) {
                    resolve(false);
                }
            }
        });
    });
}
/**
 * 显示提示信息
 * @param {*} title 提示信息
 * @param {*} icon 图标
 * @param {*} duration 提示时长
 * @returns 
 */
export function showToast(title, icon = "none", duration = 1500) {
    return new Promise((resolve) => {
        uni.showToast({
            title: title || '',
            icon: icon || 'none',
            duration: duration,
            success: () => {
                resolve(true);
            }
        });
    });
}

/**
 * 显示加载中
 * @param {String} title 加载中文字
 * @returns {Promise} 返回Promise对象，resolve中返回true
 */
export function showLoading(title = "加载中...") {
    return new Promise((resolve) => {
        uni.showLoading({
            title: title,
            success: () => {
                resolve(true);
            }
        });
    });
}

/**
 * 隐藏加载中
 * @returns {Promise} 返回Promise对象，resolve中返回true
 */
export function hideLoading() {
    return new Promise((resolve) => {
        uni.hideLoading({
            success: () => {
                resolve(true);
            }
        });
    });
}


/**
 * 请求订阅消息
 * @param {Array} tmplIds 模板ID数组
 * @returns {Promise} 返回Promise对象，resolve中返回订阅结果对象
 */
export function requestSubscribeMessage(tmplIds) {
    return new Promise((resolve) => {
        uni.requestSubscribeMessage({
            tmplIds: tmplIds || [],
            success(res) {
                console.log('订阅消息授权结果：', res);
                // if(res[''])
                var data = {};
                for (let i = 0; i < tmplIds.length; i++) {
                    if (res[tmplIds[i]] != null && res[tmplIds[i]] == "accept") {
                        data[tmplIds[i]] = true;
                    } else {
                        data[tmplIds[i]] = false;
                    }
                }
                console.log("订阅消息授权结果：", data);

                resolve({
                    success: true,
                    result: data
                });
            },
            fail(err) {
                console.error('订阅消息授权失败：', err);
                resolve({
                    success: false,
                    result: [],
                    error: err
                });
            }
        });
    });
}

/**
 * 微信支付
 * @param {Object} orderInfo 支付订单信息对象
 * @param {String} orderInfo.appid 微信开放平台应用AppId
 * @param {String} orderInfo.noncestr 随机字符串
 * @param {String} orderInfo.package 固定值 "Sign=WXPay"
 * @param {String} orderInfo.partnerid 微信支付商户号
 * @param {String} orderInfo.prepayid 统一下单订单号
 * @param {Number} orderInfo.timestamp 时间戳（单位：秒）
 * @param {String} orderInfo.sign 签名
 * @returns {Promise} 返回Promise对象，resolve中返回支付结果对象
 */
export function requestPayment(orderInfo) {
    return new Promise((resolve) => {
        uni.requestPayment({
            provider: "weixin",
            ...orderInfo,
            success(res) {
                console.log('微信支付成功：', res);
                resolve({
                    success: true,
                    result: res
                });
            },
            fail(err) {
                console.error('微信支付失败：', err);
                resolve({
                    success: false,
                    result: null,
                    error: err
                });
            }
        });
    });
}

let os = '';
/**
 * 
 */
export function getOS() {
    if (os != '') {
        return os;
    }
    // #ifdef APP-PLUS
    const systemInfo = uni.getSystemInfoSync();
    return systemInfo.platform === 'ios' ? 'ios' : 'android';
    // #endif

    return 'mp';
}