import pinia from '~src/store/init'
import { useAppStore } from '~src/store'
import { getRoutes } from '~api/menu'
import { getRefreshToken, setRefreshToken, setToken } from 'hc-vue3-ui'
import { ArrToOneObj, getArrValue, isNullES } from 'js-fast-way'
import { logout, refreshToken } from '~api/user'
import { getStore, setStore } from '~src/utils/storage'

//初始变量
const store = useAppStore(pinia)

//设置路由信息
export const setRouterData = async (type) => {
    const { error, data } = await getRoutes({ systemType: type })
    if (error) {
        return Promise.reject(false)
    }
    const resData = getArrValue(data)
    console.log(resData, 'resData')
    
    //数据转换
    let routesObj = {}, routesArr = []
    await ArrToOneObj(resData, 'code', routesObj, routesArr)
    //数据缓存
    setStore('menus', resData)
    setStore('route', routesObj)
    setStore('routes', routesArr)
    return resData
}

//获取路由菜单的主入口路径
export const getHomeRouter = async () => {
    const menus = getArrValue(getStore('menus'))
    //没有菜单路由数据
    if (menus.length <= 0) {
        store.setHomePage('index')
        store.setPage('anomaly')
    } else {
        const code = await getRoutesHomeUrl(menus, 0)
        console.log(code, 'code')
        
        store.setHomePage(code)
        store.setPage(code)
        if (code === 'index') {
            const pageCode = await getRoutesHomeUrl(menus, 1)
            store.setPage(pageCode)
        }
    }
}

//递归获取最子级的菜单
const getRoutesHomeUrl = async (arr, index = 0) => {
    const item = arr[index]
    if (!isNullES(item.children) && item.children.length > 0) {
        return await getRoutesHomeUrl(item.children, index)
    } else {
        return item.code
    }
}

//刷新token
export const RefreshToken = async () => {
    try {
        const { dept_id, role_id } = store.getUserInfo
        const refresh = getRefreshToken()
        const { error, code, res } = await refreshToken(refresh, dept_id, role_id)
        if (!error && code === 200) {
            setToken(res['access_token'])
            setRefreshToken(res['refresh_token'])
            store.setUserInfo(res)
            return Promise.resolve(res)
        } else {
            return Promise.reject(res)
        }
    } catch (e) {
        window.console.warn('token 刷新失败: ', e)
        return Promise.reject(e)
    }
}

//登出
export const LogOut = async () => {
    return await logout()
}
