import pinia from '~src/store/init'
import website from '~src/config'
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 { getStoreValue, setStoreValue } from '~src/utils/storage'
import { ArrToOneObj, arrIndex, getArrValue, getObjValue } from 'js-fast-way'
import { useOsTheme } from 'hc-vue3-ui'
import { setAppName } from '~uti/tools'
import logoIcon from '~src/assets/logo/icon.png'
import logoName from '~src/assets/logo/name.png'

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

//登录
export const useAppLogin = async (form) => {
    const { error, code, res, msg } = await userLogin(form)
    if (!error && code === 200) {
        const info = await setUserAppInfo(res)
        return { error: info.error, msg: info.msg }
    } else {
        return { error: true, msg: msg }
    }
}

//设置用户信息
export const setUserAppInfo = async (res) => {
    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 getHomeRouter(routerRes)
    //获取配置数据
    await initUserConfigInfo()
    return { error: false, msg: '成功' }
}

//设置租户信息
export const setUserTenantInfo = async (res = {}) => {
    const { tenantAvatar, tenantAvatarText, tenantTitle, tenantId } = res

    //设置标题
    const title = tenantTitle ? tenantTitle : website.title
    store.setTitle(title)
    setAppName(title)

    //设置logo图标
    const icon = tenantAvatar ? tenantAvatar : logoIcon
    store.setLogoIcon(icon)

    //设置logo文字
    const name = tenantAvatarText ? tenantAvatarText : logoName
    store.setLogoName(name)

    //设置租户ID
    const id = tenantId ? tenantId : '000000'
    store.setTenantId(id)

    //返回数据
    return { title, icon, name, id }
}

//获取路由菜单的主入口路径
const getHomeRouter = async () => {
    const routes = getStoreValue('routesArr') ?? []
    //没有菜单路由数据
    if (routes.length <= 0) {
        store.setHomeUrl('home')
        return 'home'
    }
    //设置主入口
    const code = routes[0]
    store.setHomeUrl(code)
    return code
}

//用户信息初始化
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 []
    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)
    setStoreValue('routesArr', routesArr)
    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()
}
