import APP from '@/services';
import { getLongTypeLoginID } from '@/services/bus/login';
import { buildProtoReq50, parseProtoRsp50 } from '@/services/socket/protobuf/buildReq';
import { Callback } from '@/utils/websocket/index';
import { sha256 } from 'js-sha256';
import * as accountType from './interface/index';

const getAccoutIdList = () => {
    const accountList = APP.get('accountList');
    return accountList.reduce((prev: string, cur: any, i: number) => {
        const id = String(cur.AccountId);
        const temp = i ? `,${id}` : id;
        prev += temp;
        return prev;
    }, '');
};

/**
 * 查询全部账户交易费用与规则信息的方法
 */
export const queryAccountTradeRuleAndFeeAndMargin = (): Promise<any> => {
    return new Promise((resolve, reject) => {
        const params = {
            statement: 'QueryAccountTradeRuleAndFeeAndMargin',
            params: { accountidlist: getAccoutIdList() },
        };
        const package50 = buildProtoReq50(params);
        APP.sendTradingServer(package50, undefined, {
            onSuccess: (res) => {
                const { isSuccess, result } = parseProtoRsp50(res);
                if (isSuccess) {
                    resolve(result);
                } else {
                    reject(result);
                }
            },
            onFail: (err) => {
                reject(err.message);
            },
        } as Callback);
    });
};

/**
 * 修改密码
 */
export const modifyPwdRequest = (param: accountType.ModifyPwdReq): Promise<any> => {
    return new Promise((resolve, reject) => {
        const params = {
            protobufName: 'ModifyPwdReq',
            funCodeName: 'ModifyPwdReq',
            reqParams: {
                ModifyPwdType: param.ModifyPwdType,
                OldPwd: sha256.hex(`${String(getLongTypeLoginID())}${param.OldPwd}`),
                NewPwd: sha256.hex(`${String(getLongTypeLoginID())}${param.NewPwd}`),
                ModifyPwdID: Number(getLongTypeLoginID()), // 被修改的ID
            },
        };
        const package50 = buildProtoReq50(params);
        APP.sendTradingServer(package50, undefined, {
            onSuccess: (res) => {
                const { isSuccess, result } = parseProtoRsp50(res, 'ModifyPwdRsp');
                if (isSuccess) {
                    resolve(result);
                } else {
                    reject(result);
                }
            },
            onFail: (err) => reject(err.message),
        } as Callback);
    });
};
