import APP from '@/services';
import { getLoginData } from '@/services/bus/login';
import { LongType } from '@/services/socket/login/interface/index';

/**
 * 获取资金账号列表
 * @return string 拼接之后的字符串
 */
export const getAccoutIdList = (): string => {
    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;
    }, '');
};

/**
 * 获取第一个资金账号
 * @rerurn long型 | null
 */
export const getAccount_longType = (): LongType | null => {
    const accountList = APP.get('accountList');
    if (accountList.length > 0) {
        return accountList[0].accountid;
    }
    return null;
};

/**
 *  获取用户id
 */
export const getUserId = (): number => {
    const loginData = getLoginData();
    if (loginData) {
        return loginData.UserID;
    } else {
        console.warn('没有获取到用户id');
        return 0;
    }
};

/**
 * 计算浮动盈亏
 */
function calcHolderSumDynProfit() {
    // const holds = APP.get('quoteDayInfo');
    // const HsbyListingGoods = APP.get('HsbyListingGoods');
    // for (let i = 0; i < holds.length; i++) {
    //     const itemHold = holds[i];
    //     const goodsInfo = HsbyListingGoods.find((e: any) => e.goodsid === itemHold.goodsid);
    //     if (goodsInfo) {
    //     }
    // }
}

/**
 *  计算商品市值计算
 */
export function calcAmount() {
    // 持仓列表（盘面）
    const holds = APP.get('myGoodsHold');
    // 挂牌
    let totalNum = 0;
    for (let i = 0; i < holds.length; i++) {
        const itemHold = holds[i];
        const { last, agreeunit, buycurpositionqty, decimalplace } = itemHold;
        if (last) {
            // 商品市值计算: 最新价*持仓数量*合约单位
            const lastPrice = +last.toFixed(decimalplace);
            totalNum += lastPrice * buycurpositionqty * agreeunit;
        } else {
            totalNum += buycurpositionqty;
        }
    }
    totalNum = +totalNum.toFixed(2);
    APP.set('marketValue', totalNum);
}

/**
 * 获取可用余额
 */
export function getCanUserMoney() {
    const list = APP.get('accountList');
    let result = 0;
    if (list && list.length) {
        const { CurrentBalance, FreezeMargin, UsedMargin, OtherFreezeMargin, FreezeCharge } = list[0];
        result = CurrentBalance - FreezeMargin - UsedMargin - OtherFreezeMargin - FreezeCharge;
        result = +result.toFixed(2);
    } else {
        console.error('获取资金列表错误');
    }
    return result;
}

/**
 * 获取选中的资金账号(目前 写死第一个，后期账号切换的时候在进行修改)
 */
export function getSelectedAccountId(): LongType | null {
    return getAccount_longType()
}