/**
 * @description 请添加Index组件的描述和注释!!!
 *
 * @date 创建时间 2022-10-29 11:54
 * @author 开发人员
 */

import React, { useEffect, useMemo, useState } from "react";
import CurrentProduct from "@components/NavBar/CurrentProduct";
import TickerList from "@components/TickerList";
import { likesMock } from "../mock/likes";
import { symbolPriceChartMaps } from "../mock/tickers";
import { PairsService } from "../services";
import { useObservable } from "rxjs-hooks";
import { map } from "rxjs/operators";
import { Popover } from "@atomintl/aui-next";
import { TradeTypeEnum } from "@shared/types";
import type { IFormatCurrentPair } from "@shared/types/interface";

interface Props {}

const ProductMenu: React.FC<Props> = () => {
  const currentPair =
    useObservable(() => PairsService.instance.currentPairs$.pipe(map(val => val))) ?? ({} as IFormatCurrentPair);

  const paris = useObservable(() => PairsService.instance.pairs$.pipe(map(val => val))) ?? ([] as IFormatCurrentPair[]);
  const [anchorEl, setAnchorEl] = useState<HTMLDivElement | null>(null);

  const tickerTradeTabList = useMemo(() => {
    return [
      {
        label: "自选",
        value: "FAV"
      },
      {
        label: "U本位合約",
        value: TradeTypeEnum.Linear
      }
    ];
  }, []);
  useEffect(() => {
    PairsService.instance.initLikes(likesMock);
  }, []);

  const likes = useObservable(() => PairsService.instance.likes$.pipe(map(val => val))) ?? [];

  const handleOpen = (event: React.MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
    if (anchorEl) {
      return setAnchorEl(null);
    }
    setAnchorEl(event.currentTarget);
  };

  const handleAddOrMoveLikes = (symbol: string, add: boolean) => {
    PairsService.instance.addOrRemoveLikes(symbol, add);
  };

  const handleChangeTickerPair = (symbol: string, tradeType: TradeTypeEnum) => {
    if (symbol && tradeType) {
      PairsService.instance.switchRouter(symbol, tradeType);
      setAnchorEl(null);
    }
  };
  const open = Boolean(anchorEl);

  const tickersDateSource = useMemo(() => {
    return paris.filter(item => item.tradeType === currentPair?.tradeType);
  }, [paris, currentPair?.tradeType]);

  return (
    <>
      <div onClick={handleOpen} className="h-full">
        <CurrentProduct open={open} symbol={currentPair.symbol} base={currentPair.base} />
      </div>
      <Popover anchorEl={anchorEl} open={open} onClose={() => setAnchorEl(null)} className={"upGreen"}>
        <TickerList
          tradeType={currentPair.tradeType}
          tickerTradeTabList={tickerTradeTabList}
          currentSymbol={currentPair.symbol}
          dataSource={tickersDateSource}
          symbolPriceChartMaps={symbolPriceChartMaps}
          favoritePairs={likes}
          rfColor={true}
          onChangeLikes={handleAddOrMoveLikes}
          onChangeTickerPair={record => handleChangeTickerPair(record.symbol, record.tradeType)}
        />
      </Popover>
    </>
  );
};

export default ProductMenu;
