import pinia from '~src/store/init'
import website from '~src/config/index'
import { useAppStore } from '~src/store'
import { getRoutes } from '~api/menu'
import { setStoreValue } from '~src/utils/storage'
import tokenData from '~src/router/modules/token'
import { ArrToOneObj, getArrValue, getObjValue } from 'js-fast-way'
import { userConfigInfo, userConfigSave } from '~api/other'
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) {
        store.setTokenVal(res['access_token'])
        store.setRefreshTokenVal(res['refresh_token'])
        store.setTenantId(res['tenant_id'])
        store.setUserInfo(res)
        //获取路由菜单
        const routerRes = await setRouterData()
        if (routerRes.length <= 0) {
            return { error: true, msg: '路由异常' }
        }
        //获取配置数据
        await initUserConfigInfo()
        return { error, code, res }
    } else {
        return { error, code, res }
    }
}

//用户信息初始化
export const initUserConfigInfo = async () => {
    const { error, data } = await userConfigInfo()
    if (error) return false
    const res = getObjValue(data)
    if (res?.theme) {
        const { theme, color } = res
        //设置主题
        store.setTheme(theme ?? website.theme)
        //设置主色调
        store.setColor(color ?? website.color)
        return true
    } else {
        await userConfigSave({
            theme: website.theme,
            color: website.color,
        })
        return true
    }
}

//设置路由信息
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)
    setStoreValue('route', routesObj)
    setStoreValue('routes', routes)
    return resData
}

//刷新token
export const RefreshToken = async () => {
    try {
        window.console.log('刷新 token')
        const { dept_id, role_id } = store.getUserInfo
        const refresh = store.getRefreshToken
        const tenantId = store.getTenantId
        const { error, code, res } = await refreshToken(refresh, tenantId, dept_id, role_id)
        if (!error && code === 200) {
            store.setTokenVal(res['access_token'])
            store.setRefreshTokenVal(res['refresh_token'])
            store.setTenantId(res['tenant_id'])
            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()
}
