Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
10 kB
2
Indexable
import React, { useRef, useState, useCallback, useEffect, memo, useMemo } from 'react';
import { Dimensions, FlatList, StyleSheet, Animated, Platform } from 'react-native';
import { Colors } from 'react-native-ui-lib';
import LinearGradient from 'react-native-linear-gradient';
import Carousel, { Pagination } from 'react-native-snap-carousel';
import { useTranslation } from 'react-i18next';
import { useIsFocused } from '@react-navigation/native';

import { InstantPositionProfitLoss } from '../../../api/customer';
import { useColors } from '../../../hooks';
import { ErrorPage } from '../ErrorPage';
import { TotalEquityView, TotalCard } from '.';
import { useEtrader } from '../../../context';

const WIDTH = Dimensions.get('window').width;
const HEIGHT = 112;

const TotalCarousel = () => {
  const isFocused = useIsFocused();
  const {
    store: { postLogin, theme },
  } = useEtrader();
  const [data, setData] = useState([]);
  const flatlistRef = useRef(null);
  const [totalCarouselElementCount, setTotalCarouselElementCount] = useState(0);
  const [activeIndex, setactiveIndex] = useState(0);
  const { colors } = useColors();
  const [onHiddenBalance, setOnHiddenBalance] = useState(false);
  const [animatedHeight] = useState(new Animated.Value(112));
  const isAnimating = useRef(false);
  const { t } = useTranslation();

  const [totalEquityWidth] = useState(new Animated.Value(0));

  const {
    mutate: eqGetInstantPositionProfitLoss,
    isLoading: eqIsFetchingInstantPositionProfitLoss,
    isIdle: eqIsIdle,
    status: eqStatusInstantPositionProfitLoss,
    data: eqInstantPositionProfitLoss,
  } = InstantPositionProfitLoss();

  const {
    mutate: dtGetInstantPositionProfitLoss,
    isLoading: dtIsFetchingInstantPositionProfitLoss,
    isIdle: dtIsIdle,
    status: dtStatusInstantPositionProfitLoss,
    data: dtInstantPositionProfitLoss,
  } = InstantPositionProfitLoss();

  const eqAccount = useMemo(() => {
    return postLogin?.subAccounts?.subAccountList.find(x => x.subAccountName === 'EQ')?.subAccountNumber;
  }, [postLogin, isFocused]);

  const dtAccount = useMemo(() => {
    return postLogin?.subAccounts?.subAccountList.find(x => x.subAccountName === 'DT')?.subAccountNumber;
  }, [postLogin, isFocused]);

  const isLoading = eqAccount
    ? eqIsFetchingInstantPositionProfitLoss || eqIsIdle
    : dtAccount
    ? dtIsFetchingInstantPositionProfitLoss || dtIsIdle
    : false;

  useEffect(() => {
    if (postLogin && isFocused) {
      const eqAccountNumber = eqAccount?.split('-')[0];
      const eqChosenSubAccount = eqAccount?.includes('*') ? eqAccount?.slice(0, -1) : eqAccount;

      const dtAccountNumber = dtAccount?.split('-')[0];
      const dtChosenSubAccount = dtAccount?.includes('*') ? dtAccount?.slice(0, -1) : dtAccount;

      const eqFetchInstantPositionProfitLoss = (accountInfo: { accountNumber: string; chosenSubAccount: string }) => {
        eqGetInstantPositionProfitLoss(accountInfo);
      };

      const dtFetchInstantPositionProfitLoss = (accountInfo: { accountNumber: string; chosenSubAccount: string }) => {
        dtGetInstantPositionProfitLoss(accountInfo);
      };

      if (eqAccount) {
        eqFetchInstantPositionProfitLoss({
          accountNumber: eqAccountNumber,
          chosenSubAccount: eqChosenSubAccount,
        });
      }

      if (dtAccount) {
        dtFetchInstantPositionProfitLoss({
          accountNumber: dtAccountNumber,
          chosenSubAccount: dtChosenSubAccount,
        });
      }
    }
  }, [postLogin, isFocused]);

  useEffect(() => {
    if (!isLoading) {
      let carouselData;
      const totalEquityViewData = eqInstantPositionProfitLoss?.data?.data?.instantPosProfLoss?.profitLossItemList?.find(
        el => el.accountExtId === 'ALL',
      );
      const eqList = eqInstantPositionProfitLoss?.data?.data?.instantPosProfLoss?.profitLossItemList;
      const dtList = dtInstantPositionProfitLoss?.data?.data?.instantPosProfLoss?.profitLossItemList;

      if (eqList || dtList) {
        if (eqList) {
          carouselData = eqList.concat(dtList || []);
        } else {
          carouselData = dtList;
        }
      }

      const filteredCarouselData = carouselData?.filter(el => el.accountExtId !== 'ALL');

      const result = [];

      if (totalEquityViewData) {
        result.push({ type: 'totalEquity', data: totalEquityViewData });
      }

      if (filteredCarouselData) {
        result.push({ type: 'carousel', data: filteredCarouselData });
      }

      setTotalCarouselElementCount(filteredCarouselData?.length || 0);
      setData(result);
    }
  }, [eqInstantPositionProfitLoss, dtInstantPositionProfitLoss]);

  const toggleHiddenBalance = useCallback(
    isCarousel => {
      if (isAnimating.current) {
        return;
      }

      const finalValue = onHiddenBalance ? 112 : 44;
      setOnHiddenBalance(!onHiddenBalance);
      const delay = isCarousel ? 0 : !onHiddenBalance ? 900 : 0;

      isAnimating.current = !isCarousel;

      setTimeout(() => {
        Animated.timing(animatedHeight, {
          toValue: finalValue,
          duration: 400,
          useNativeDriver: false,
        }).start(() => {
          isAnimating.current = false;
        });
      }, delay);
    },
    [animatedHeight, onHiddenBalance],
  );

  const handleScroll = event => {
    const scrollX = event.nativeEvent.contentOffset.x;
    const index = Math.round(scrollX / (WIDTH - 32));
    setactiveIndex(index);
    if (Platform.OS === 'android') {
      Animated.spring(totalEquityWidth, {
        toValue: index ? 32 : 0,
        useNativeDriver: true,
      }).start();
    }
  };

  useEffect(() => {
    if (Platform.OS === 'ios') {
      Animated.spring(totalEquityWidth, {
        toValue: activeIndex ? 32 : 0,
        useNativeDriver: true,
      }).start();
    }
  }, [activeIndex]);

  const headerData = data?.filter(item => item.type === 'totalEquity')[0]?.data;
  const flatListData = data?.filter(item => item.type === 'carousel')[0]?.data;

  const isError =
    (eqAccount &&
      !dtAccount &&
      (eqInstantPositionProfitLoss?.data?.error || eqStatusInstantPositionProfitLoss === 'error')) ||
    (eqAccount &&
      dtAccount &&
      (eqInstantPositionProfitLoss?.data?.error || eqStatusInstantPositionProfitLoss === 'error') &&
      (dtInstantPositionProfitLoss?.data?.error || dtStatusInstantPositionProfitLoss === 'error'));

  return (
    <>
      {isError ? (
        <ErrorPage pageSize="component" message={t('errorComponentMessage')} />
      ) : (
        <LinearGradient
          start={{ x: 0, y: 0.5 }}
          end={{ x: 1, y: 0.5 }}
          colors={[colors.secondaryBgStart, colors.secondaryBgEnd]}>
          <Animated.View
            style={{
              height: animatedHeight,
              marginTop: 24,
            }}>
            {/* <FlatList
              data={flatListData}
              horizontal={true}
              ref={flatlistRef}
              onScroll={handleScroll}
              ListHeaderComponent={
                headerData && (
                  <TotalEquityView
                    overview
                    {...headerData}
                    title={t('totalEquityValue')}
                    HEIGHT={HEIGHT}
                    MAINCARDWIDTH={WIDTH - 32}
                    onHiddenBalance={onHiddenBalance}
                    toggleHiddenBalance={toggleHiddenBalance}
                  />
                )
              }
              renderItem={({ item, index }) => (
                <Animated.View
                  style={
                    index === 0
                      ? { width: WIDTH + 32, transform: [{ translateX: totalEquityWidth }] }
                      : { width: WIDTH }
                  }>
                  <TotalCard
                    key={index}
                    item={item}
                    onHiddenBalance={onHiddenBalance}
                    toggleHiddenBalance={toggleHiddenBalance}
                    theme={theme}
                    activeIndex={activeIndex}
                  />
                </Animated.View>
              )}
              ListEmptyComponent={isLoading && <TotalEquityView isLoading={true} />}
              showsHorizontalScrollIndicator={false}
              pagingEnabled
            /> */}
            <Carousel
              data={flatListData}
              ref={flatlistRef}
              layout="stack"
          
              renderItem={({ item, index }) => (
                <TotalCard
                  key={index}
                  item={item}
                  onHiddenBalance={onHiddenBalance}
                  toggleHiddenBalance={toggleHiddenBalance}
                  theme={theme}
                  activeIndex={activeIndex}
                />
              )}
              sliderWidth={WIDTH} // Adjust this value as needed
              itemWidth={WIDTH - 32}
          
            />
          </Animated.View>
          <Pagination
            dotsLength={totalCarouselElementCount + (data.length > 1 ? 1 : 0)}
            inactiveDotScale={0.6}
            inactiveDotOpacity={0.4}
            dotStyle={styles.dotStyle}
            activeDotIndex={activeIndex}
            inactiveDotStyle={styles.inactiveDotStyle}
            containerStyle={styles.paginationContainer}
            dotContainerStyle={styles.dotContainerStyle}
          />
        </LinearGradient>
      )}
    </>
  );
};
export default memo(TotalCarousel);

const styles = StyleSheet.create({
  paginationContainer: {
    alignSelf: 'flex-start',
    paddingVertical: 0,
    marginTop: 16,
    marginBottom: 24,
  },
  inactiveDotStyle: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginHorizontal: -4,
    backgroundColor: Colors.action,
  },
  dotStyle: {
    width: 22,
    height: 5,
    borderRadius: 5,
    marginHorizontal: -4,
    backgroundColor: Colors.action,
  },
  dotContainerStyle: {
    marginVertical: -18,
  },
});