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 {setStoreData} from "~src/utils/storage";
import {userLogin,refreshToken,logout} from '~api/user';
import {userConfigInfo, userConfigSave} from "~api/other";
import {ArrToOneObj, getArrValue, getIndex, getObjValue, useOsTheme} from "vue-utils-plus"

//初始变量
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.setTenantId(res['tenant_id'])
        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,homeTheme,shotWebRtc,fullScreen,opinionView} = res
        //设置主题
        store.setTheme(theme)
        //设置模式
        if (theme === 'auto') {
            store.setThemeVal(useOsTheme().value)
        } else {
            store.setThemeVal(theme)
        }
        //获取主色调和首页主题数据
        let themeColor = themeData.color, themeHome = themeData.home;
        let colorIndex = getIndex(themeColor,'name',color)
        let homeIndex = getIndex(themeHome,'name',homeTheme)
        //设置主色调
        if (colorIndex !== -1) {
            store.setColor(themeColor[colorIndex])
        }
        //设置首页主题
        if (homeIndex !== -1) {
            store.setHomeTheme(themeHome[homeIndex])
        }
        //设置工单服务的弹出框
        store.setOrderServiceTipModal(opinionView ?? 1)
        store.setShotWebRtc(shotWebRtc)
        store.setShotWebRtc(fullScreen)
        return Promise.resolve(true);
    } else {
        await userConfigSave({
            theme: appConfig?.theme || '',
            color: appConfig?.color?.name || '',
            homeTheme: appConfig?.homeTheme?.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)
    const routes = [...tokenData, ...routesArr] //合并
    //数据缓存
    store.setMenus(resData)
    setStoreData('route', routesObj)
    setStoreData('routes', routes)
    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 tenantId = store.getTenantId;
        const { error, status, res } = await refreshToken(refresh, tenantId, dept_id, role_id);
        if (!error && status === 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();
}
