Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
6.6 kB
0
Indexable
Never
import React, { useEffect, useMemo, useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { View, Text } from 'react-native-ui-lib';
import { Icon } from '../../../components/ui';
import { FinancialsChart } from '../../../components/business/Chart';
import { useNavigation } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../../hooks';
import { GetCompanyCategory, GetMarketBalance } from '../../../api/user';
import ModalController from '../../../components/Modal/ModalController';

export const BalanceSheet = ({ symbolCode }: any) => {
  const navigation = useNavigation();
  const { t } = useTranslation();
  const { colors }: any = useColors();
  const [selectedCurrency, setSelectedCurrency] = useState('TRY');
  const currencyOptions = ['TRY', 'USD', 'EURO'];
  const [showOptions, setShowOptions] = useState(false);

  const [percentageName, setPercentageName] = useState('Özkaynakların Varlıklara Oranı');

  const [label1, setLabel1] = useState('Net Nakit');
  const [label2, setLabel2] = useState('Toplam Özkaynaklar');
  const [label3, setLabel3] = useState('Toplam Varlıklar');

  const [dataBalance, setDataBalance] = useState([]);

  const { mutate: getMarketBalance, data: marketBalanceData } = GetMarketBalance();
  const { mutate: getCompanyCategory, data: marketCompanyCategory } = GetCompanyCategory();

  useEffect(() => {
    getMarketBalance({
      company: symbolCode,
      inputType: '1',
    });
    getCompanyCategory({
      company: symbolCode,
    });
  }, [symbolCode]);

  function findDataByLabel(label: any) {
    return marketBalanceData?.data?.data?.companyFinancialReportRowList?.find((item: any) => item.label === label);
  }
  const dates: any = marketBalanceData?.data?.data?.companyFinancialReportPeriodList
    .slice(0, 5)
    .map((item: any) => item.year);

  const handleSelect = (currency: any) => {
    setSelectedCurrency(currency);
    setShowOptions(false);
  };
  const symbolCategory = marketCompanyCategory?.data?.data?.kategori;

  const percentage = (
    findDataByLabel('TOPLAM ÖZKAYNAKLAR')?.values?.[0] / findDataByLabel('TOPLAM VARLIKLAR')?.values?.[0]
  ).toFixed(2);
  const newDataBalance: any = [];

  useEffect(() => {
    if (symbolCategory === 'Standart' && marketBalanceData) {
      const currencyKey = {
        USD: 'usdValues',
        EURO: 'eurValues',
        TRY: 'values',
      }[selectedCurrency];

      if (currencyKey) {
        let newValue1Sum = 0;

        for (let i = 0; i < 5; i++) {
          const value1 =
            findDataByLabel('Nakit ve Nakit Benzerleri')?.[currencyKey]?.[i] +
            findDataByLabel('Finansal Yatırımlar')?.[currencyKey]?.[i] -
            findDataByLabel('Kısa Vadeli Borçlanmalar')?.[currencyKey]?.[i] -
            findDataByLabel('Uzun Vadeli Borçlanmalar')?.[currencyKey]?.[i];
          const value2 = findDataByLabel('TOPLAM ÖZKAYNAKLAR')?.[currencyKey]?.[i];
          const value3 = findDataByLabel('TOPLAM VARLIKLAR')?.[currencyKey]?.[i];
          newValue1Sum += value1;
          console.log(newDataBalance, 'lkr<');
          newDataBalance.push({ value1, value2, value3 });
        }

        if (newValue1Sum < 0) {
          setLabel1('Net Borç');
        } else {
          setLabel1('Net Nakit');
        }
        setDataBalance(newDataBalance);
        console.log("dataBalance",dataBalance)
      }
    }
  }, [symbolCategory, marketBalanceData, selectedCurrency]);
  
  const renderCurrencyOptions = () => {
    return (
      <>
        {currencyOptions.map((currency, index) => {
          if (currency !== selectedCurrency) {
            return (
              <TouchableOpacity key={index} onPress={() => handleSelect(currency)}>
                <Text>{currency}</Text>
              </TouchableOpacity>
            );
          }
          return null;
        })}
      </>
    );
  };

  const filterRow = (selectedItem: any, isOpen: any, renderDropdownItems: any, toggleDropdown: any) => {
    return (
      <View>
        <TouchableOpacity onPress={toggleDropdown}>
          <View row width={50}>
            <View row center flex-1>
              <Text marginL-10>{selectedItem}</Text>
              <Icon
                name="downArrow"
                width={10}
                height={6}
                fill={colors.secondaryText}
                style={styles(colors).iconStyle}
              />
            </View>
          </View>
        </TouchableOpacity>
        <View>{isOpen && renderDropdownItems()}</View>
      </View>
    );
  };
  return (
    <>
      <View marginT-20 style={styles(colors).cardStyle}>
        <View margin-20>
          <View row marginB-16>
            <Text flex-1 style={styles(colors).fWeight500} primaryText>
              {t('balanceSheet')}
            </Text>
            {filterRow(selectedCurrency, showOptions, renderCurrencyOptions, () => {
              ModalController.showModal({
                type: 'currencyFilter',
                externalHeight: 780,
                props: {
                  onSelectCurrency: handleSelect,
                },
              });
            })}
          </View>

          <FinancialsChart
            data={dataBalance}
            chartType={'balance'}
            tabsSelected={false}
            percentage={percentage}
            percentageName={percentageName}
            financialLabels={[label1, label2, label3]}
            dates={dates}
          />
        </View>
        <TouchableOpacity
          marginL-10
          onPress={() =>
            navigation.navigate('financialChartDetail' as never, {
              chartTitle: 'balanceSheet',
              symbolCode,
              marketBalanceData,
            })
          }>
          <View marginL-10 row>
            <Text style={styles(colors).textColor}>{t('viewMoreDetails')}</Text>
            <Icon style={styles(colors).arrowStyle} name="arrowRight" width={6} height={10} fill={colors.action} />
          </View>
        </TouchableOpacity>
      </View>
    </>
  );
};

const styles = (colors: any) =>
  StyleSheet.create({
    textColor: {
      color: colors.action,
      fontSize: 12,
      marginBottom: 20,
      marginLeft: 20,
    },
    arrowStyle: {
      marginLeft: 10,
      marginTop: 3,
    },
    cardStyle: {
      backgroundColor: colors.donutChartBg,
      borderRadius: 8,
    },
    fWeight500: {
      fontWeight: '500',
    },
    iconStyle: {
      marginHorizontal: 6,
      marginVertical: 8,
    },
  });