/**
 * @description 资产组件
 *
 * @date 创建时间 2022-11-02 15:22
 * @author 开发人员 yena
 */

import React, { useEffect, useMemo } from "react";
import { AccountBalance } from "@components/PlaceOrder/Balance";
import { useFetch, APINameEnum } from "@utils/request";
import { BalancesService, PairsService, BalanceItemProps } from "../../services";
import { useObservable } from "rxjs-hooks";
import { map } from "rxjs/operators";
import { IFormatCurrentPair } from "@shared/types/interface";
import { find } from "ramda";

interface Props {}

const Balance: React.FC<Props> = props => {
  const { data } = useFetch(APINameEnum.TRADING_ACCOUNT);

  const currentPair =
    useObservable(() => PairsService.instance.currentPairs$.pipe(map(val => val))) ?? ({} as IFormatCurrentPair);

  const balances =
    useObservable(() => BalancesService.instance.balances$.pipe(map(val => val))) ?? ([] as BalanceItemProps[]);

  const currentBalance = useMemo(() => {
    return find(item => item.currency === currentPair.settleCurrency, balances) ?? ({} as BalanceItemProps);
  }, [currentPair?.settleCurrency, balances]);

  useEffect(() => {
    if (data && Array.isArray(data)) {
      console.log(data, "资产====");
      // api请求更新资产
      BalancesService.instance.formatAccountBalance(data);
    }
  }, [data]);

  return (
    <AccountBalance
      scale={currentPair?.costSizeScale}
      coin={currentPair?.settleCurrency}
      avb={currentBalance?.marginEquity}
      unPnl={currentBalance?.marginUnPnl}
    />
  );
};

export default Balance;
