import pinia from "~src/store/init"
import appConfig from '~src/config/app';
import config from '~src/config/index';
import {useAppStore} from "~src/store";
import {getRoutes} from '~api/menu';
import colorData from '~src/config/color';
import {setStoreValue} from "~src/utils/storage";
import {userLogin, refreshToken, logout} from '~api/user';
import {userConfigInfo, userConfigSave} from "~api/other";
import {ArrToOneObj, getArrValue, arrIndex, getObjValue} from "js-fast-way"
import {useOsTheme} from '~src/plugins/useOsTheme';

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

//登录
export const useAppLogin = async (form) => {
    const {error, status, res} = await userLogin(form);
    if (!error && status === 200) {
        store.setTokenVal(res['access_token'])
        store.setRefreshTokenVal(res['refresh_token'])
        store.setUserInfo(res)
        const routerRes = await setRouterData()
        if (!routerRes) {
            return Promise.reject({msg: '路由异常'});
        }
        await initUserConfigInfo()
        return Promise.resolve(res);
    } else {
        return Promise.reject(res);
    }
}

//用户信息初始化
export const initUserConfigInfo = async () => {
    const {error, data} = await userConfigInfo();
    if (error) {
        return Promise.reject(false);
    }
    const res = getObjValue(data)
    if (res?.theme) {
        const {theme, color} = res
        //设置主题
        store.setTheme(theme)
        //设置模式
        if (theme === 'auto') {
            store.setThemeVal(useOsTheme().value)
        } else {
            store.setThemeVal(theme)
        }
        //获取主色调和首页主题数据
        let colorIndex = arrIndex(colorData, 'name', color)
        //设置主色调
        if (colorIndex !== -1) {
            store.setColor(colorData[colorIndex])
        }
        return Promise.resolve(true);
    } else {
        await userConfigSave({
            theme: appConfig?.theme || '',
            color: appConfig?.color?.name || '',
            shotWebRtc: '0',
            fullScreen: '1',
            opinionView: 1
        })
        return Promise.resolve(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)
    //数据缓存
    store.setMenus(resData)
    setStoreValue('route', routesObj)
    setStoreValue('routes', routesArr)
    return Promise.resolve(true);
}

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