import {Loading, Message} from 'element-ui';
import { getOpenId, getAppID} from '../api'

export default {
    getOpenId(callback) {
        let  loading = Loading.service();
        if (window.localStorage.getItem('openId')) {
            loading.close();
            callback();
        } else {
            this.getAppid(loading,callback);
        }

    },
    async getAppid (loading,callback){
        let result = await getAppID({cid: 'oauth'}, "GET");
        if (result.code === 0) {
            this.getCode(result.data.appid,loading,callback);
        }else{
            loading.close();
        }
    },
    getCode(appid,loading,callback) { // 非静默授权，第一次有弹框
        let local = window.location.href; // 获取页面url
        let code = this.getUrlCode().code;// 截取code
        if (code && code !== '') { // 如果有code
            // 拿到code去请求openId并存在本地 ?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
            this.requestNet(code,loading,callback);
        } else {
            loading.close();
            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
        }
    },
    getUrlCode() { // 截取url中的code方法
        let url = location.search;
        let theRequest = {};
        if (url.indexOf("?") !== -1) {
            let str = url.substr(1);
            let strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
            }
        }
        return theRequest
    },
    async requestNet(code,loading,callback) {
        let result = await getOpenId({cid: 'oauth', code: code}, "GET");
        if (!result.data.errcode && result.data.openid && result.data.openid !== 'null') {
            window.localStorage.setItem("openId", result.data.openid);
            callback();
            loading.close();
        }else{
            loading.close();
        }
    },


}







