import APP from '@/services';
import { getLongTypeLoginID } from '@/services/bus/login';
import { getUsrId } from '@/services/bus/user';
import { commonSearch_go } from '../index';
import * as type from './interface';

/**
 * 获取登录ID
 * @param username 可传入“登录账号”、“登录代码”和“手机号码”
 * @returns
 */
export function GetLoginID(username: string): Promise<string> {
    return commonSearch_go('/User/GetLoginID', { username })
}

/**
 * 获取用户账号信息
 * @param username 用户ID
 * @returns
 */
export function GetUserAccount(userID: number): Promise<type.GetUserAccount> {
    return commonSearch_go('/User/GetUserAccount', { userID })
}

/**
 * 账户登录后信息查询
 * @param loginID 登录账号
 * @returns
 */
export function LoginQuery(): Promise<type.LoginQueryRsp> {
    const id = getLongTypeLoginID();
    return commonSearch_go('/User/LoginQuery', { loginID: Number(id) }).then(res => {
        const {
            areaRoles,
            externalExchanges,
            goodsgroups,
            loginAccount,
            markets,
            systemParams,
            userAccount,
            userInfo,
            username } = res;
        areaRoles && APP.set('areaRoles', areaRoles);
        externalExchanges && APP.set('externalexchange', externalExchanges);
        goodsgroups && APP.set('goodsgroups', goodsgroups);
        loginAccount && APP.set('loginAccount', loginAccount);
        markets && APP.set('markets', markets);
        systemParams && APP.set('systemParams', systemParams);
        userAccount && APP.set('userAccount', userAccount);
        userInfo && APP.set('userInfo', userInfo);
        username && APP.set('username', username);
        console.log('LoginQuery', res);
        QueryRootUserAccount()
        return res
    })
}
/**
 * 获取用户信息
 * @param loginID 登录账号
 * @returns
 */
export function QueryUserInfo(userID: number, isDecrypt?: boolean): Promise<type.Userinfo> {
    const param = isDecrypt ? { isDecrypt, userID } : { userID }
    return commonSearch_go('/User/QueryUserInfo', param)
}

/**
 * 查询顶级用户信息
 * /Ermcp3/QueryRootUserAccount
 */
export function QueryRootUserAccount(): Promise<string> {
    const userid = getUsrId()
    return commonSearch_go('/Ermcp3/QueryRootUserAccount', { userid }).then(res => {
        APP.set('RootUser', res);
        return 'ok'
    }).catch((err) => {
        throw new Error(`查询顶级用户信息: ${err}`);
    });
}
