import { generateRandomString } from '@/common/util.js'
document.addEventListener('UniAppJSBridgeReady', function () {
    // alert('aaa1')
    ydsApp.getEnv(function (res) {
        console.log('当前环境：' + JSON.stringify(res));
        ydsApp.postMessage({
            data: {
                action: 'load',
            }
        });
    });

});
const _ydsApp = {
    callback: {}
}
window.yds_postMessage = function (data) {
    // 检查data是否为字符串类型
    console.log('yds_postMessageyds_postMessageyds_postMessageyds_postMessage', data);
    if (typeof data === 'string') {
        try {
            data = JSON.parse(data);
        } catch (e) {
            console.log('数据解析失败:', e);
            return; // 解析失败，退出函数
        }
    }

    if (data.action == "pay") {
        if (_ydsApp.callback[data.callback]) {
            _ydsApp.callback[data.callback](data.data);
            delete _ydsApp.callback[data.callback];
            return;
        }
        console.log('回调不存在');
        return;
    }
    if (_ydsApp.callback[data.callback]) {
        _ydsApp.callback[data.callback](data.data);
        delete _ydsApp.callback[data.callback];
    }
}
//返回按钮
window.yds_backPress = function () {
    uni.navigateBack();
}
export const home = () => {
    if (window.ydsApp) {
        console.log('加载webapp-成功');
    } else {
        console.log('加载webapp-未加载');
    }

}

export const webAppPay = (orderInfo) => {
    return new Promise((resolve, reject) => {
        if (!window.ydsApp) {
            reject('ydsApp未加载');
            return;
        }
        let callback = generateRandomString(16);
        _ydsApp.callback[callback] = resolve;
        ydsApp.postMessage({
            data: {
                action: 'pay',
                data: orderInfo,
                callback: callback
            }
        });
    });
}

export const webAppPageUrl = (url, isHome) => {
    if (!window.ydsApp) {
        reject('ydsApp未加载');
        return;
    }
    ydsApp.postMessage({
        data: {
            action: 'pageUrl',
            data: { page: url, isHome: isHome },
        }
    })
}

export const sendWxAppLogin = () => {
    return new Promise((resolve, reject) => {
        if (!window.ydsApp) {
            reject('ydsApp未加载');
            return;
        }
        let callback = generateRandomString(16);
        _ydsApp.callback[callback] = resolve;
        ydsApp.postMessage({
            data: {
                action: 'wxAppLogin',
                data: {},
                callback: callback
            }
        });
    });
}

/**
 * 分享
 * @param {*} title 标题
 * @param {*} desc  描述
 * @param {*} image 图片
 * @param {*} url 链接
 * @returns 
 */
export const webAppShare = (title, desc, image, url) => {
    if (!window.ydsApp) {
        reject('ydsApp未加载');
        return;
    }
    let shareUrl = url;
    if (shareUrl.indexOf('http') == -1) {
        shareUrl = window.location.origin + url;
    }

    let shareData = {
        content: { //公共的分享参数配置  类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图）
            type: 0,
            href: shareUrl,
            title: title,
            summary: desc,
            imageUrl: image + "?imageMogr2/thumbnail/108x108"
        },
        menus: [{
            "img": "/static/app-plus/sharemenu/icon_wechat.png",
            "text": "微信好友",
            "share": { //当前项的分享参数配置。可覆盖公共的配置如下：分享到微信小程序，配置了type=5
                "provider": "weixin",
                "scene": "WXSceneSession"
            }
        }, {
            "img": "/static/app-plus/sharemenu/wx_quan.png",
            "text": "微信朋友圈",
            "share": {
                "provider": "weixin",
                "scene": "WXSceneTimeline"
            }
        },
        {
            "img": "/static/app-plus/sharemenu/mp_app.png",
            "text": "微信小程序",
            "share": {
                provider: "weixin",
                scene: "WXSceneSession",
                type: 5,
                miniProgram: {
                    id: 'gh_04b8832df741',
                    path: url,
                    webUrl: shareUrl,
                    type: 0
                },
            }
        },
        {
            "img": "/static/app-plus/sharemenu/copy.png",
            "text": "复制",
            "share": "copyurl"
        },
        {
            "img": "/static/app-plus/sharemenu/more.png",
            "text": "更多",
            "share": "shareSystem"
        }
        ],
        cancelText: "取消分享",
    }

    ydsApp.postMessage({
        data: {
            action: 'share',
            data: shareData,
        }
    })
}

