// web端扫码登录

import {apiWxLoginInWeb} from '@/api/common'
import store from '@/store'

let HASLOGIN=false 

// 获取路由中参数
const getRouteParams=()=>{
    const url = location.search; //获取url携带的参数
    let urlParams = new Object();
    if (url.indexOf("?") != -1) {
        let str = url.substr(1);
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
        urlParams[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return urlParams
}

export const webLogin=async ()=>{
    if(HASLOGIN) return
    HASLOGIN=true
    const urlParams=getRouteParams()
    if(urlParams.code){//路由中有code
        const res=await apiWxLoginInWeb({Code:urlParams.code})
        if(res.code===200){
            store.commit('showLogin',false)
            store.commit('getToken',res.data.authorization)
            if(!res.data.is_bind){
                store.commit('showBindAccount',true)
                // 删除路由中的code参数
                history.replaceState(null,null,import.meta.env.VITE_APP_REDIRECT_URI)
            }else{
                window.location.href=import.meta.env.VITE_APP_REDIRECT_URI
            }
        }
    }else{
        store.commit('showLogin',true)
    }
}