import Vue from 'vue'
import Cookies from 'js-cookie'

// import { getUserInfo as getInfo } from '@/api/user'
// import { notEmpty } from './tool'

const COOKIE_KEY_TOKEN = 'auth_token'
const COOKIE_KEY_USER = 'auth_info'
const COOKIE_KEY_MENUS = 'auth_menus'

export const auth = {
    isLogin: () => {
        const user = auth.getUserInfo();
        return user != null;
    },
    getToken: () => Cookies.get(COOKIE_KEY_TOKEN),
    saveToken: token => {
        Cookies.set(COOKIE_KEY_TOKEN, token)
        localStorage.setItem(COOKIE_KEY_TOKEN, token);
    },
    removeToken: () => Cookies.remove(COOKIE_KEY_TOKEN),
    initUserInfo: () => {
        return auth.getUserInfo();
    },
    getUserInfo: () => {
        let user = localStorage.getItem(COOKIE_KEY_USER)
        if (user && user.length > 0) {
            user = decodeURIComponent(user)
            return JSON.parse(user) 
        }
        return null
    },
    getUserName: () => {
        const obj = auth.getUserInfo()
        return obj && obj.userInfo.userAccount
    },
    saveUserInfo: userInfo => {
        const info = encodeURIComponent(JSON.stringify(userInfo))
        localStorage.setItem(COOKIE_KEY_USER, info)
    },
    removeUserInfo: () => localStorage.removeItem(COOKIE_KEY_USER),
    saveMenus: (menus) => {
        localStorage.setItem(COOKIE_KEY_MENUS, JSON.stringify(menus));
    },
    getMenus: () => {
        const json = localStorage.getItem(COOKIE_KEY_MENUS);
        if (json) {
            return JSON.parse(json);
        }
        return [];
    },
    removeMenus: () => {
        localStorage.removeItem(COOKIE_KEY_MENUS);
    },
    logout: () => {
        Cookies.remove(COOKIE_KEY_TOKEN);
        localStorage.removeItem(COOKIE_KEY_USER);
        localStorage.removeItem(COOKIE_KEY_MENUS);
    }
}