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;
    }, '');
};

/**
 *  * 构建登录后数据查询请求包
 * @param QueryItem 不填返回全部结果集，填写后表示按需查询，多个以“,”隔开
 * 1-账号信息 2-资金账户列表 3- 交易规则和费用规则 4- 最大通知id 5- 更新时间戳
 */
// export const queryAccountInfo = (QueryItem: string | number): Promise<string> => {
//     return new Promise((resolve, reject) => {
//         const LoginID = getLongTypeLoginID();
//         const params = {
//             protobufName: 'LoginQueryReq',
//             funCodeName: 'LoginQueryReq',
//             reqParams: { LoginID, QueryItem },
//         };
//         const package50 = buildProtoReq50(params);
//         APP.sendTradingServer(package50, undefined, {
//             onSuccess: (res) => {
//                 const { isSuccess, result } = parseProtoRsp50(res, 'LoginQueryRsp');
//                 if (isSuccess) {
//                     const { AccountInfo, TAAccountList, ParamValues } = result;
//                     // 数据中心存入用户信息
//                     APP.set('userInfo', AccountInfo);
//                     const accountList = TAAccountList.map((el: any) => {
//                         return el.TaAccountInfo;
//                     });
//                     // 数据中心存入资金账号列表
//                     APP.set('accountList', accountList);
//                     // 时间戳集合
//                     const lastUpdateTime: any = new LastUpdateTimeModel();
//                     ParamValues.forEach((el: any) => {
//                         const { Key, Value } = el;
//                         if (Key) {
//                             const name = LastUpdateTime_enum[Key];
//                             lastUpdateTime[name] = Number(Value);
//                         }
//                     });
//                     APP.set('lastUpdateTime', lastUpdateTime);
//                     // 注意：商品交易规则和费用规则列表 暂未做处理，需要处理在此处理, 具体查看 proto LoginQueryRsp
//                     resolve('ok');
//                 } else {
//                     reject(result);
//                 }
//             },
//             onFail: (err) => {
//                 reject(err.message);
//             },
//         } as Callback);
//     });
// };

/**
 * 查询机构角色市场权限
 */
export const queryAreaRoleMarket = (): Promise<string> => {
    return new Promise((resolve, reject) => {
        const params = {
            statement: 'Client_QueryTAAccountMarket',
            params: {
                areaUserId: String(APP.get('userInfo').MemberUserid), // 机构用户ID
                roleType: '7', // 角色类型 -  6:自营会员 7:纪经会员
            },
        };
        const package50 = buildProtoReq50(params);
        APP.sendTradingServer(package50, undefined, {
            onSuccess: (res) => {
                const { isSuccess, result } = parseProtoRsp50(res);
                if (isSuccess) {
                    APP.set('areaRoleMarketList', result);
                    resolve('ok');
                } else {
                    reject(result);
                }
            },
            onFail: (err) => {
                reject(err.message);
            },
        } as Callback);
    });
};

/**
 * 查询非投资者查资金市场权限
 */
export const queryTaAccountMarket = (): Promise<string> => {
    return new Promise((resolve, reject) => {
        const params = {
            statement: 'Client_QueryTAAccountMarket',
            params: { taAccountIdList: getAccoutIdList() },
        };
        const package50 = buildProtoReq50(params);
        APP.sendTradingServer(package50, undefined, {
            onSuccess: (res) => {
                const { isSuccess, result } = parseProtoRsp50(res);
                if (isSuccess) {
                    APP.set('taAccountMarketList', result);
                    resolve('ok');
                } else {
                    reject(result);
                }
            },
            onFail: (err) => {
                reject(err.message);
            },
        } as Callback);
    });
};
/**
 * 查询全部账户交易费用与规则信息的方法
 */
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 queryTradeDate = (): Promise<string> => {
    return new Promise((resolve, reject) => {
        const params = {
            statement: 'ClientSearchMarketRun',
            params: { marketId: '0' },
        };
        const package50 = buildProtoReq50(params);
        APP.sendTradingServer(package50, undefined, {
            onSuccess: (res) => {
                const { isSuccess, result } = parseProtoRsp50(res);
                if (isSuccess) {
                    APP.set('tradeDate', result[0]);
                    resolve('ok');
                } 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);
    });
};
