Untitled

 avatar
unknown
plain_text
2 years ago
9.7 kB
2
Indexable
import React, { useEffect, useState } from 'react';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { Text, View } from 'react-native-ui-lib';
import colors from '../../../rb-constants/colors';
import {
  VictoryAxis,
  VictoryBar,
  VictoryChart,
  VictoryGroup,
  VictoryLine,
  VictoryScatter,
  VictoryTooltip,
  VictoryVoronoiContainer,
} from 'victory-native';
import moment from 'moment';

type Props = {
  report: any;
  company?: any;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const FollowerActiveTimeFacebook = ({ report, company }: Props) => {
  const [activeButton, setActiveButton] = useState('Days');

  const handlePress = (buttonName: any) => {
    setActiveButton(buttonName);

  };

  const isButtonActive = (buttonName: any) => {
    return activeButton === buttonName;
  };

  const changeDate = (activeTimes: any) => {
    const result: any[] = [];
    activeTimes.forEach((item: any) => {
      const date = moment(item.endtime).format('MM/DD/YYYY');
      result.push({
        value: item.value,
        name: item.name,
        endtime: date,
      });
    });
    console.log(result);

    return result;
  }

  const setDaysData = (sortDays: any) => {
    const days: any[] = [];
    const map: any[] = [];
    let daysOfAWeek = [['', '']];
    let weekId = 0;
    let tempDate = 0;

    sortDays.forEach((item: any, index: any) => {
      if ((index % 7 === 0 || index === sortDays.length - 1) && index !== 0) {
        if (index === sortDays.length - 1) {
          daysOfAWeek.push([item.name, item.value]);
        }
        days.push(daysOfAWeek);
        daysOfAWeek = [['', '']];
        map.push({
          id: weekId,
          date: `${tempDate} - ${item.endtime}`,
          dateDescription: `${weekId + 1}. Week`,
        });
        weekId += 1;
      }
      if (daysOfAWeek.length === 1) {
        tempDate = item.endtime;
      }
      daysOfAWeek.push([item.name, item.value]);
    });
    return { days, map };
  }

  const setHoursData = (sortHours: any, isMonthyl: any) => {
    const hours: any[] = [];
    const map: any[] = [];
    let hoursOfADay = [['', '']];
    let dateIndex = 0;

    sortHours.forEach((item: any, index: any) => {
      const dateDescription = moment(item.endtime).format('dddd');
      if (index === 0) {
        map.push({
          id: dateIndex,
          date: item.endtime,
          dateDescription,
        });
      }

      if (sortHours.length - 1 === index) {
        hours.push(hoursOfADay);
      }

      if (map.find(obj => obj.id === dateIndex).date !== item.endtime) {
        hours.push(hoursOfADay);
        hoursOfADay = [['', '']];
        dateIndex += 1;

        map.push({
          id: dateIndex,
          date: item.endtime,
          dateDescription,
        });
      }

      let tempName = item.name;
      if (isMonthyl) {
        tempName = `${item.name} - ${item.endtime}`;
      }
      hoursOfADay.push([tempName, item.value]);
    });

    return { hours, map };
  }

  const changeDateMoment = (dataByDate: any) => {
    const result: any[] = [];
    if (dataByDate) {
      dataByDate.forEach((item: any, index: any) => {
        if (index <= 7) {
          const date = moment(item[0]).format('DD MMM dd');
          const value = item[1];
          result.push([date, value]);
        }
      });
    }
    return result;
  }
  const connectionCheck = (connectList: any, type: any) => {
    let isConnection = false;

    if (connectList && connectList.length > 0) {
      connectList.forEach((item: any) => {
        if (item.type === type) {
          isConnection = item.connect;
        }
      });
    }

    return isConnection;
  }



  const reportType = report?.data && report?.data?.type;
  const social = report && report?.data?.score && report?.data?.score?.social;
  const connectList = report && report?.data?.connectList;
  const socialMediaType = 'facebook'
  const isConnectionError = !connectionCheck(
    connectList,
    socialMediaType.toUpperCase(),
  );
  const socialMediaData =
    social && social.find((obj: any) => obj.type === socialMediaType);

  let daysData:any[] = [];
  let hoursData = [];
  let mappingData = [];
  let isError = false;
  let isNoDataError = false;
  let errorMessageType;

  if (isConnectionError) {
    errorMessageType = `${socialMediaType.toLowerCase()}ErrorMessage`;
  } else if (
    !socialMediaData ||
    socialMediaData.status !== 'EXIST' ||
    !reportType
  ) {
    isError = true;
    errorMessageType = 'companySocialNotExist';
  }

  if (!isError && !isConnectionError) {
    const activeTimes = socialMediaData && socialMediaData.activeTimes;

    if (
      !activeTimes ||
      activeTimes.length === 0 ||
      !activeTimes.days ||
      activeTimes.days.length === 0 ||
      !activeTimes.hours ||
      activeTimes.hours.length === 0
    ) {
      isNoDataError = true;
      errorMessageType = 'noDataErrorMessage';
    }

    if (!isNoDataError) {
      const changeEndtimeHoursData = changeDate(activeTimes.hours);
      const changeEndtimeDaysData = activeTimes.days;

      const sortHours = changeEndtimeHoursData.sort(
        (a, b) => (a.endtime > b.endtime || a.endtime === b.endtime ? -1 : 1),
      );
      const sortDays = changeEndtimeDaysData.sort(
        (a: any, b: any) => (a.endtime < b.endtime ? 1 : -1),
      );

      if (reportType === 'WEEKLY') {
       
        sortDays.forEach((item: any) => {
          daysData.push({x:item.endtime, y:item.value});
        });
        const result = setHoursData(sortHours, false);
        hoursData = result.hours;
        mappingData = result.map;
      }
    }
  }
 
  const [itemList, setItemList] = useState < any[] > ([]);


  const weeklyRule =
    (reportType === 'WEEKLY') ||
    !mappingData ||
    mappingData.length === 0;


  const [chartData, setChartData] = useState(daysData);
  console.log(chartData,"dgrjhk")
  console.log(mappingData,"lshdfkjsdkjfnsjkdfnjk")
  return (
    <>
      <View flex spread marginV-5 paddingB-0 centerV>
        <View flex spread marginV-7 paddingB-0>
          <View row centerH>
            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderColor: isButtonActive('Days')
                  ? colors.Orange
                  : colors.gray,
                backgroundColor: isButtonActive('Days')
                  ? colors.Orange
                  : colors.White,
                borderRadius: 40,
                width: 110,
                padding: 10,
                marginRight: 10,
              }}
              onPress={() => handlePress('Days')}>
              <View center spread>
                <Text heading7>Days</Text>
              </View>
            </TouchableOpacity>

            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderColor: isButtonActive('Hours')
                  ? colors.Orange
                  : colors.gray,
                backgroundColor: isButtonActive('Hours')
                  ? colors.Orange
                  : colors.White,
                borderRadius: 40,
                width: 110,
                padding: 10,
                marginRight: 10,
              }}
              onPress={() => handlePress('Hours')}>
              <View center>
                <Text heading7>Hours</Text>
              </View>
            </TouchableOpacity>
          </View>

          <View flex row spread>
            {isButtonActive('Hours') ? (
              <View>
                <VictoryChart
                  height={350}
                  width={380}
                  containerComponent={<VictoryVoronoiContainer />}>
                  <VictoryGroup
                    color="orange"
                    labels={({ datum }) => `y: ${datum.y}`}
                    labelComponent={<VictoryTooltip style={{ fontSize: 10 }} />}
                    data={mappingData.map((item)=>item)}>
                    <VictoryLine />
                    <VictoryScatter size={({ active }) => (active ? 8 : 3)} />
                    <VictoryAxis
                      dependentAxis
                      style={{ grid: { stroke: 'grey' } }}
                      tickFormat={x => ''}
                      label="Number of Instant Active Users"
                    />
                    <VictoryAxis label="Hours" />
                  </VictoryGroup>
                </VictoryChart>
                <View centerH flex-0 marginT-5 spread>
                  <Text
                    initials
                    color={colors.Orange}
                    style={{ fontSize: 28, fontWeight: 'bold' }}>
                    27.05.2023 - Saturday
                  </Text>
                </View>
              </View>
            ) : (
              <VictoryChart
                height={400}
                width={370}
                domainPadding={{ x: 50, y: 20 }}
                scale={{ x: 'time' }}>
                <VictoryAxis
                  dependentAxis
                  style={{
                    grid: {
                      stroke: 'grey',
                      strokeDasharray: 4,
                    },
                  }}
                  tickFormat={x => ''}
                  label="Number of Instant Active Users"
                />
                <VictoryAxis style={{ tickLabels: { angle: 30 } }} />
                <VictoryBar
                  style={{ data: { fill: 'orange' } }}
                  data={daysData}
                />
              </VictoryChart>
            )}
          </View>
        </View>
      </View>
    </>
  );
}
export default FollowerActiveTimeFacebook;
Editor is loading...