import pinia from '~src/store/init'
import { useAppStore } from '~src/store'
import { getRoutes } from '~api/menu'
import { getRefreshToken, setRefreshToken, setStore, setToken } from 'hc-vue3-ui'
import tokenData from '~src/router/modules/token'
import { ArrToOneObj, getArrValue } from 'js-fast-way'
import { logout, refreshToken, userLogin } from '~api/user'

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

//登录
export const useAppLogin = async (form) => {
    const { error, code, res } = await userLogin(form)
    if (!error && code === 200) {
        setToken(res['access_token'])
        setRefreshToken(res['refresh_token'])
        store.setUserInfo(res)
        //获取路由菜单
        const routerRes = await setRouterData()
        if (routerRes.length <= 0) {
            return { error: true, msg: '路由异常' }
        }
        return { error, code, res }
    } else {
        return { error, code, res }
    }
}

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

//刷新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()
}
