// 用户相关请求模块
import APP from '@/services';
import { getLongTypeLoginID, isLogin } from '@/services/bus/login';
import { getToken } from '@/services/bus/token';
import { LongType } from '@/services/socket/login/interface/index';
import { buildProtoReq50, parseProtoRsp50, protoMiddleware } from '@/services/socket/protobuf/buildReq';
import { Callback } from '@/utils/websocket/index';
import { sha256 } from 'js-sha256';
import moment from 'moment';
import { v4 as uuidv4 } from 'uuid';
import { LoginResponse } from './interface/index';

let preDate = Date.now();

export const loginAction = (logidCode: string, password: string, ClientSystemInfo: Uint8Array[], isEncryt = false): Promise<LoginResponse> => {
    const LoginPWD = isEncryt ? password : sha256.hex(`${logidCode}${password}`);
    const reqParams = {
        LoginPWD,
        LoginID: logidCode,
        GUID: uuidv4(),
        LoginType: 0,
        ClientType: 4,
        Version: '2.0.0.0',
        DeviceID: '',
    }
    if (ClientSystemInfo.length) {  // 与qt交互消息
        Object.assign(reqParams, { ClientSystemInfo, ClientAppID: 'muchinfo_mtpclient_5.0.1' })
    }
    return protoMiddleware(reqParams, 'LoginReq', 'LoginRsp', 1)
};

/**
 * 退出 登录 不等服务响应
 */
export const logoutResponse = (): Promise<void> => {
    return new Promise((resolve, reject) => {
        if (isLogin()) {
            const loginId = getLongTypeLoginID() as LongType;
            const token = getToken();
            const params = {
                protobufName: 'LogoutReq',
                funCodeName: 'LogoutReq',
                reqParams: { LoginID: loginId, Token: token },
            };
            const package50 = buildProtoReq50(params);
            APP.sendTradingServer(package50, undefined, {
                onSuccess: (res) => {
                    const { isSuccess, result } = parseProtoRsp50(res, 'LogoutRsp');
                    if (isSuccess) {
                        resolve(result);
                    } else {
                        reject(result);
                    }
                },
                onFail: (err) => {
                    // reject(err);
                },
            } as Callback);
        }
    });
};

export const tokenCheck = (): Promise<string> => {
    return new Promise((resolve, reject) => {
        if (isLogin()) {
            const loginId = getLongTypeLoginID() as LongType;
            const token = getToken();
            console.log('token::::::', token)
            const systemDate = APP.get('systemDate');
            const targetDate = Date.parse(systemDate) + Date.now() - preDate;
            const params = {
                protobufName: 'TokenCheckReq',
                funCodeName: 'TokenCheckReq',
                reqParams: { LoginID: loginId, Token: token, SystemTime: targetDate },
            };
            const package50 = buildProtoReq50(params);
            APP.sendTradingServer(package50, undefined, {
                onSuccess: (res) => {
                    const { isSuccess, result } = parseProtoRsp50(res, 'TokenCheckRsp');
                    if (isSuccess) {
                        const systemTime = Number(result.SystemTime);
                        const time = moment(new Date(systemTime)).format('YYYY-MM-DD HH:mm:ss');
                        APP.set('systemDate', time);
                        preDate = Date.now();
                        resolve('ok');
                    } else {
                        reject(result);
                    }
                },
                onFail: (err) => {
                    reject(err);
                },
            } as Callback);
        } else {
            reject('用户已登出！');
        }
    });
};
