import { getWxUserInfo, getWxConfig } from '../api/login'

export async function getWxOpenId() {
    if (localStorage.getItem("courierOpenid") != 'undefined' && localStorage.getItem("courierOpenid") != null && localStorage.getItem("courierOpenid") != '') {
        return;
    }

    var code = getUrlParam("code");
    console.log(code, 'code====++++')
    if (code == 'undefined' || code == null || code == "") {
        // alert("参数异常，请返回首页重试");
        urlredirect();
        return;
    }

    const res = await getWxUserInfo({ code: code, userId: localStorage.getItem("courierUserId") })
    console.log(res, '================================getWxUserInfo')
    if (res.code == '0') {
        console.log('直接走+======', res)
        localStorage.setItem("courierOpenid", res.openId);
        localStorage.setItem("headimgurl", res.headimgurl);
    } else {
        urlredirect();
    }
}


async function urlredirect() {
    const res = await getWxConfig({})
    const href = window.location.href
    window.location.href =
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.wxConfig.appId}&redirect_uri=${encodeURIComponent(href)}` + `&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
}

function getUrlParam(name) {
    var vars = [],
        hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return decodeURIComponent(vars[name]);
}


