import pinia from '~src/store/init'
import appConfig from '~src/config/app'
import { useAppStore } from '~src/store'
import { getRoutes } from '~api/menu'
import themeData from '~src/config/theme'
import tokenData from '~src/router/modules/token'
import { logout, refreshToken, userLogin } from '~api/user'
import { userConfigInfo, userConfigSave } from '~api/other'
import { setStoreValue } from '~src/utils/storage'
import { ArrToOneObj, arrIndex, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import { useOsTheme } from 'hc-vue3-ui'


//初始变量
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: '路由异常' }
        }
        //获取路由首页
        const isHomeUrl = await getHomeRouter(routerRes)
        if (isNullES(isHomeUrl)) {
            return { error: true, msg: '菜单权限异常' }
        }
        //获取配置数据
        await initUserConfigInfo()
        return { error, code, res }
    } else {
        return { error, code, res }
    }
}

//获取路由菜单的主入口路径
const getHomeRouter = async (arr) => {
    //判断 arr 数组中的 children 中是否有数据，没数据的话，取下一个元素
    const menus = arr.filter((item) => {
        if (item?.children.length > 0) {
            const menua = item.children.filter((items) => {
                const children = getArrValue(items?.children)
                return children.length > 0
            })
            return menua.length > 0
        } else {
            return false
        }
    })
    //处理数据
    if (menus.length <= 0) return false
    const code = menus[0]?.children[0]?.children[0]?.code
    if (isNullES(code)) return false
    store.setHomeUrl(code)
    return true
}

//用户信息初始化
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)
        //设置模式
        if (theme === 'auto') {
            store.setThemeVal(useOsTheme())
        } else {
            store.setThemeVal(theme)
        }
        //获取主色调和首页主题数据
        let themeColor = themeData.color
        let colorIndex = arrIndex(themeColor, 'name', color)
        //设置主色调
        if (colorIndex !== -1) {
            store.setColor(themeColor[colorIndex])
        }
        return true
    } else {
        await userConfigSave({
            theme: appConfig?.theme || '',
            color: appConfig?.color?.name || '',
        })
        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()
}
