import {formatUrl} from '@js/utils';

/**
 * 微信授权
 * @param {*} userId 用户id
 */
const wxAuth = (userId, extParam , serverUrl = '/youtui/temporary/getWxUserInfo4url')=>{
    let wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize`;
    let appid = `wx231876932416d2c7`;
    // 预发：youtui-pre.tuia.cn/youtui/temporary/getWxUserInfo
    // 线上：activity.qushaio.com/youtui/temporary/getWxUserInfo
    let redirectUrl = encodeURIComponent(`${location.origin}${serverUrl}`);
    
    let frags = location.href.split('#');

    let url = '';
    if (frags.length > 1) {
        // 存在#
        url = formatUrl(frags[0], {
            wxAuthed: 1,
            ...extParam
        }) + '#' + frags[1];
    } else {
        url = formatUrl(location.href, {
            wxAuthed: 1,
            ...extParam
        });
    }
    let state = {
        userId: userId,
        url: encodeURIComponent(url)
    };

    var stateStr = JSON.stringify(state);
    setTimeout(() => {
        console.log('wxAuth redirect', `${wxAuthUrl}?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=${stateStr}#wechat_redirect`);
        
        location.href = `${wxAuthUrl}?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=${stateStr}#wechat_redirect`
    }, 10);
}

export default wxAuth;



