"use client"; import React, { Component, useEffect, useState } from "react"; import ReactApexChart from "react-apexcharts"; import dummyData from "../../../../const/dummy.json"; import { getStatisticMonthly, getStatisticMonthlyFeedback, } from "@/services/article"; type WeekData = { week: number; days: number[]; total: number; }; type RemainingDays = { days: number[]; total: number; }; function processMonthlyData(count: number[]): { weeks: WeekData[]; remaining_days: RemainingDays; } { const weeks: WeekData[] = []; let weekIndex = 1; for (let i = 0; i < count.length; i += 7) { const weekData = count.slice(i, i + 7); weeks.push({ week: weekIndex, days: weekData, total: weekData.reduce((sum, day) => sum + day, 0), }); weekIndex++; } const remainingDays: RemainingDays = { days: count.length % 7 === 0 ? [] : count.slice(-count.length % 7), total: count.slice(-count.length % 7).reduce((sum, day) => sum + day, 0), }; return { weeks, remaining_days: remainingDays, }; } const SuggestionsChart = (props: { type: string; date: string; totals: (data: number) => void; }) => { const { date, type, totals } = props; const [categories, setCategories] = useState([]); const [seriesSuggestions, setSeriesSuggestions] = useState([]); useEffect(() => { initFetch(); }, [date, type]); function processYearlyData(data: any) { const months = [ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember", ]; const category = []; const temp = []; let totalData = 0; for (let i = 0; i < data.length; i++) { const total = data[i].suggestions.reduce( (sum: number, list: number) => sum + list, 0 ); temp.push(total); totalData += total; category.push(months[data[i].month - 1]); } return { categories: category, series: temp, total: totalData }; } const initFetch = async () => { const splitDate = date.split(" "); const res = await getStatisticMonthlyFeedback(splitDate[1]); const data = res?.data?.data; // const data = dummyData.data; if (type === "monthly") { const getDatas = data?.filter( (a: any) => a.year === Number(splitDate[1]) ); console.log("teemp,tota", getDatas); if (getDatas) { const temp = processYearlyData(getDatas); setSeriesSuggestions(temp.series); setCategories(temp.categories); totals(temp.total); } else { setSeriesSuggestions([]); totals(0); } } else { const getDatas = data?.find( (a: any) => a.month == Number(splitDate[0]) && a.year === Number(splitDate[1]) ); if (getDatas) { const temp = processMonthlyData(getDatas?.suggestions); const sum = getDatas.suggestions.reduce( (acc: any, curr: any) => acc + curr, 0 ); totals(sum); if (type == "weekly") { setSeriesSuggestions( temp.weeks.map((list) => { return list.total; }) ); const category = []; for (let i = 1; i <= temp.weeks.length; i++) { category.push(`Minggu ke-${i}`); } setCategories(category); } else { setSeriesSuggestions(getDatas.suggestions); } } else { setSeriesSuggestions([]); totals(0); } } }; return (
); }; export default SuggestionsChart;