package kr.co.compcarecompany.Util.Adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;

import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.CaptureUtils;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.ConvertTimeZone;

public class ReportPublishAdapter extends RecyclerView.Adapter<ReportPublishAdapter.ItemViewHolder> {

    private Context context;
    private String type;
    private int year, month, week;
    private ArrayList<MachineItem> items = new ArrayList<>();
    private ArrayList<String> time_list;

    public ReportPublishAdapter(@NonNull Context context, String type, int year, int month, int week) {
        this.context = context;
        this.type = type;
        this.year = year;
        this.month = month;
        this.week = week;
    }

    @NonNull
    @Override
    public ReportPublishAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_report_publish, viewGroup, false);

        return new ReportPublishAdapter.ItemViewHolder(v);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onBindViewHolder(@NonNull ReportPublishAdapter.ItemViewHolder itemViewHolder, int position) {

        itemViewHolder.onBind(items.get(position));
        ArrayList<MonitoringData> monitoringData = items.get(position).getPowerConsumptionData();

        if (type.equals("week")) {
            itemViewHolder.report_titleTV.setText(year + "년 " + month + "월 " + week + "주차 주간 보고서");
            try {
                Set_Week_Chart(monitoringData, itemViewHolder.power_consumptionBC, "power", itemViewHolder, items.get(position));
                Set_Week_Chart(monitoringData, itemViewHolder.currentBC, "current", itemViewHolder, items.get(position));
                Set_Week_Chart(monitoringData, itemViewHolder.temperatureBC, "temperature", itemViewHolder, items.get(position));
                Set_Week_Chart(monitoringData, itemViewHolder.pressureBC, "pressure", itemViewHolder, items.get(position));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            itemViewHolder.report_titleTV.setText(year + "년 " + month + "월 월간 보고서");
            try {
                int charge = Integer.parseInt(Common.getInstance().getPref(context, items.get(position).getCpIdx()+"report_publish"));
                Set_Month_Chart(monitoringData, itemViewHolder.power_consumptionBC, "power", itemViewHolder, charge);
                Set_Month_Chart(monitoringData, itemViewHolder.currentBC, "current", itemViewHolder,  charge);
                Set_Month_Chart(monitoringData, itemViewHolder.temperatureBC, "temperature", itemViewHolder,  charge);
                Set_Month_Chart(monitoringData, itemViewHolder.pressureBC, "pressure", itemViewHolder,  charge);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        itemViewHolder.report_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CaptureUtils.captureView(itemViewHolder.reportSV, context);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void Set_Month_Chart(ArrayList<MonitoringData> monitoring_array, BarChart barChart, String type, ItemViewHolder itemViewHolder, int charge) {

        ArrayList<Float> value_list = new ArrayList<>(); // ArrayList 선언
        float max = 0f;
        float sum = 0f;
        int sum_cnt = 0;
        String sum_value;

        int day_of_week = Common.getInstance().getOrderOfWeek(year, month);

        int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
        float week_sum_1 = 0, week_sum_2 = 0, week_sum_3 = 0, week_sum_4 = 0, week_sum_5 = 0, week_sum_6 = 0;

        ArrayList<Entry> entry_list = new ArrayList<>();

        long week_cnt_1 = 0, week_cnt_2 = 0, week_cnt_3 = 0, week_cnt_4 = 0, week_cnt_5 = 0, week_cnt_6 = 0;
        long week_mul_1 = 0, week_mul_2 = 0, week_mul_3 = 0, week_mul_4 = 0, week_mul_5 = 0, week_mul_6 = 0;

        int week_cnt = 0;
        long avg_power = 0;
        long sum_count = 0;

        Calendar calendar = Calendar.getInstance();
        int this_week = 7;
        if (year == calendar.get(Calendar.YEAR) && month == (calendar.get(Calendar.MONTH) + 1))
            this_week = calendar.get(Calendar.WEEK_OF_MONTH);

        switch (type) {
            case "power":

                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (monitoring_array.get(i).getRealPowerConsumption() != null) {

                        int value = Integer.parseInt(Common.getInstance().valueConvert(monitoring_array.get(i).getRealPowerConsumption()));
                        int count = Integer.parseInt(monitoring_array.get(i).getSensorCnt());

                        if (7 - day_of_week >= i) {
                            week_mul_1 = week_mul_1 + (value * count / 720);
                            a++;
                            week_sum_1 = week_sum_1 + value;
                            week_cnt_1 = week_cnt_1 + count;

                        } else if (14 - day_of_week >= i) {
                            week_mul_2 = week_mul_2 + (value * count / 720);
                            week_sum_2 = week_sum_2 + value;
                            b++;
                            week_cnt_2 = week_cnt_2 + count;

                        } else if (21 - day_of_week >= i) {
                            week_mul_3 = week_mul_3 + (value * count / 720);
                            week_sum_3 = week_sum_3 + value;
                            c++;
                            week_cnt_3 = week_cnt_3 + count;

                        } else if (28 - day_of_week >= i) {
                            week_mul_4 = week_mul_4 + (value * count / 720);
                            week_sum_4 = week_sum_4 + value;
                            d++;
                            week_cnt_4 = week_cnt_4 + count;

                        } else if (35 - day_of_week >= i) {
                            week_mul_5 = week_mul_5 + (value * count / 720);
                            week_sum_5 = week_sum_5 + value;
                            e++;
                            week_cnt_5 = week_cnt_5 + count;

                        } else if (42 - day_of_week >= i) {
                            week_mul_6 = week_mul_6 + (value * count / 720);
                            week_sum_6 = week_sum_6 + value;
                            f++;
                            week_cnt_6 = week_cnt_6 + count;

                        }
                    }
                }

                float avg = 0;

                if (week_mul_1 > 1) {
                    week_cnt++;
                    avg_power = avg_power + (long) week_mul_1;
                    sum_count = sum_count + week_cnt_1;
                    avg = avg + (week_sum_1 / a);
                    value_list.add(Float.parseFloat((week_sum_1 / a) + ""));
                    entry_list.add(new Entry(0, avg_power));
                } else {
                    value_list.add(0f);
                    entry_list.add(new Entry(0, 0));
                }

                if (this_week > 1) {
                    if (week_mul_2 > 1) {
                        week_cnt++;
                        avg_power = avg_power + (long) week_mul_2;
                        sum_count = sum_count + week_cnt_2;
                        value_list.add(Float.parseFloat((week_sum_2 / b) + ""));
                        entry_list.add(new Entry(1, avg_power));
                        avg = avg + (week_sum_2 / b);

                    } else {
                        value_list.add(0f);
                        if (avg_power > 0) entry_list.add(new Entry(1, avg_power));
                        else entry_list.add(new Entry(1, 0));
                    }
                }

                if (this_week > 2) {
                    if (week_mul_3 > 1) {
                        week_cnt++;
                        avg_power = avg_power + (long) week_mul_3;
                        sum_count = sum_count + week_cnt_3;
                        value_list.add(Float.parseFloat((week_sum_3 / c) + ""));
                        entry_list.add(new Entry(2, avg_power));
                        avg = avg + (week_sum_3 / c);
                    } else {
                        value_list.add(0f);
                        if (avg_power > 0) entry_list.add(new Entry(2, avg_power));
                        else entry_list.add(new Entry(2, 0));
                    }
                }

                if (this_week > 3) {
                    if (week_mul_4 > 1) {
                        week_cnt++;
                        avg_power = avg_power + (long) week_mul_4;
                        sum_count = sum_count + week_cnt_4;
                        value_list.add(Float.parseFloat((week_sum_4 / d) + ""));
                        entry_list.add(new Entry(3, avg_power));
                        avg = avg + (week_sum_4 / d);
                    } else {
                        value_list.add(0f);
                        if (avg_power > 0) entry_list.add(new Entry(3, avg_power));
                        else entry_list.add(new Entry(3, 0));
                    }
                }

                if (this_week > 4) {
                    if (Common.getInstance().getWeekOfMonth(year, month) >= 5) {
                        if (week_mul_5 > 1) {
                            week_cnt++;
                            avg_power = avg_power + (long) week_mul_5;
                            sum_count = sum_count + week_cnt_5;
                            value_list.add(Float.parseFloat((week_sum_5 / e) + ""));
                            entry_list.add(new Entry(4, avg_power));
                            avg = avg + (week_sum_5 / e);
                        } else {
                            value_list.add(0f);
                            if (avg_power > 0) entry_list.add(new Entry(4, avg_power));
                            else entry_list.add(new Entry(4, 0));
                        }
                    }
                }

                if (this_week > 5) {
                    if (Common.getInstance().getWeekOfMonth(year, month) >= 6) {
                        if (week_mul_6 > 1) {
                            week_cnt++;
                            avg_power = avg_power + (long) week_mul_6;
                            sum_count = sum_count + week_cnt_6;
                            value_list.add(Float.parseFloat((week_sum_6 / f) + ""));
                            entry_list.add(new Entry(5, avg_power));
                            avg = avg + (week_sum_6 / f);
                        } else {
                            value_list.add(0f);
                            if (avg_power > 0) entry_list.add(new Entry(5, avg_power));
                            else entry_list.add(new Entry(5, 0));
                        }
                    }
                }

                itemViewHolder.sum_powerTV.setText("누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) avg_power) + "kW/h");
                long pay = 0;

                if (avg_power > 0) {
                    avg_power = avg_power / week_cnt;
                    pay = avg_power * week_cnt * charge;
                    avg = avg / week_cnt;
                }

                itemViewHolder.average_powerTV.setText("평균 소비전력 : " + Common.getInstance().moneyFormatToWon((int) avg) + "kW/h");
                itemViewHolder.report_contentTV.setText("◈ " + year + "년 " + month + "월 소비전력 분석 레포트◈\n1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) avg_power * week_cnt) +
                        "kW/h\n2. 누적 가동 시간 : " + sum_count / 720 +
                        "h\n3. 기본 전기요금 : " + charge + "원\n4. 예상 전기요금 : " + Common.getInstance().moneyFormatToWon((int) pay) + "원");
                setBarChart(value_list, barChart, "소비전력", 0f);
                setLineChart(entry_list, itemViewHolder.power_consumptionLC);
                break;

            case "current":

                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (7 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            a++;
                            week_sum_1 = week_sum_1 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }

                    } else if (14 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            b++;
                            week_sum_2 = week_sum_2 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }

                    } else if (21 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            c++;
                            week_sum_3 = week_sum_3 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }

                    } else if (28 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            d++;
                            week_sum_4 = week_sum_4 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }

                    } else if (35 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            e++;
                            week_sum_5 = week_sum_5 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }

                    } else if (42 - day_of_week >= i) {
                        if (monitoring_array.get(i).getCurrent1() != null && !monitoring_array.get(i).getCurrent1().equals("0")) {
                            f++;
                            week_sum_6 = week_sum_6 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getCurrent1()));
                        }
                    }
                }

                if (a > 0 && week_sum_1 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (b > 0 && week_sum_2 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_2 / b) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_2 / b) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (c > 0 && week_sum_3 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_3 / c) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_3 / c) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (d > 0 && week_sum_4 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_4 / d) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_4 / d) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }

                if (Common.getInstance().getWeekOfMonth(year, month) >= 5) {
                    if (e > 0 && week_sum_5 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_5 / e) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_5 / e) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }

                if (Common.getInstance().getWeekOfMonth(year, month) >= 6) {
                    if (f > 0 && week_sum_6 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_6 / f) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_6 / f) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }

                if (sum_cnt > 0) sum = sum / sum_cnt;

                sum_value = Common.getInstance().valueConvert(sum + "");
                itemViewHolder.average_currentTV.setText("평균전류 : " + sum_value + "A");
                setBarChart(value_list, barChart, "전류", max);
                break;

            case "temperature":
                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (7 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            a++;
                            week_sum_1 = week_sum_1 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }

                    } else if (14 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            b++;
                            week_sum_2 = week_sum_2 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }

                    } else if (21 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            c++;
                            week_sum_3 = week_sum_3 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }

                    } else if (28 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            d++;
                            week_sum_4 = week_sum_4 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }

                    } else if (35 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            e++;
                            week_sum_5 = week_sum_5 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }

                    } else if (42 - day_of_week >= i) {
                        if (monitoring_array.get(i).getTempNtc() != null && !monitoring_array.get(i).getTempNtc().equals("0")) {
                            f++;
                            week_sum_6 = week_sum_6 + Float.parseFloat(Common.getInstance().valueConvert(monitoring_array.get(i).getTempNtc()));
                        }
                    }
                }

                if (a > 0 && week_sum_1 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (b > 0 && week_sum_2 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_2 / b) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_2 / b) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (c > 0 && week_sum_3 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_3 / c) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_3 / c) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (d > 0 && week_sum_4 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_4 / d) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_4 / d) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }

                if (Common.getInstance().getWeekOfMonth(year, month) >= 5) {
                    if (e > 0 && week_sum_5 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_5 / e) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_5 / e) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }
                if (Common.getInstance().getWeekOfMonth(year, month) >= 6) {
                    if (f > 0 && week_sum_6 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert((week_sum_6 / f) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_6 / f) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }


                if (sum_cnt > 0) sum = sum / sum_cnt;

                sum_value = Common.getInstance().valueConvert(sum + "");
                itemViewHolder.average_temperatureTV.setText("평균온도 : " + sum_value + "℃");
                setBarChart(value_list, barChart, "온도", max);
                break;
            case "pressure":
                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (7 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            a++;
                            week_sum_1 = week_sum_1 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }

                    } else if (14 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            b++;
                            week_sum_2 = week_sum_2 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }

                    } else if (21 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            c++;
                            week_sum_3 = week_sum_3 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }

                    } else if (28 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            d++;
                            week_sum_4 = week_sum_4 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }

                    } else if (35 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            e++;
                            week_sum_5 = week_sum_5 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }

                    } else if (42 - day_of_week >= i) {
                        if (monitoring_array.get(i).getPressure1() != null && !monitoring_array.get(i).getPressure1().equals("0")) {
                            f++;
                            week_sum_6 = week_sum_6 + Float.parseFloat(Common.getInstance().valueConvert1(monitoring_array.get(i).getPressure1()));
                        }
                    }
                }

                if (a > 0 && week_sum_1 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_1 / a) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_1 / a) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (b > 0 && week_sum_2 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_2 / b) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_2 / b) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (c > 0 && week_sum_3 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_3 / c) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_3 / c) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }
                if (d > 0 && week_sum_4 > 0) {
                    value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_4 / d) + "")));
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_4 / d) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }

                if (Common.getInstance().getWeekOfMonth(year, month) >= 5) {
                    if (e > 0 && week_sum_5 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_5 / e) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_5 / e) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }
                if (Common.getInstance().getWeekOfMonth(year, month) >= 6) {
                    if (f > 0 && week_sum_6 > 0) {
                        value_list.add(Float.parseFloat(Common.getInstance().valueConvert1((week_sum_6 / f) + "")));
                        sum = sum + Float.parseFloat(Common.getInstance().valueConvert1((week_sum_6 / f) + ""));
                        sum_cnt++;
                    } else {
                        value_list.add(0f);
                    }
                }

                if (sum_cnt > 0) sum = sum / sum_cnt;

                sum_value = Common.getInstance().valueConvert1(sum + "");
                itemViewHolder.average_pressureTV.setText("평균압력 : " + sum_value + "Bar");
                setBarChart(value_list, barChart, "압력", max);
                break;
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void Set_Week_Chart(ArrayList<MonitoringData> monitoring_array, BarChart barChart, String sensor_type, ItemViewHolder itemViewHolder, MachineItem machineItem) throws Exception {

        ArrayList<Float> value_list = new ArrayList<>(); // ArrayList 선언
        ArrayList<Entry> entry_list = new ArrayList<>(); // ArrayList 선언

        float max = 0f;
        float sum = 0f;
        int count_sum = 0;
        int sum_cnt = 0;
        long multi_sum = 0;

        switch (sensor_type) {
            case "power":

                time_list = new ArrayList<>();

                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (monitoring_array.get(i).getRealPowerConsumption() != null) {
                        float value = Float.parseFloat(monitoring_array.get(i).getRealPowerConsumption());
                        int count = Integer.parseInt(monitoring_array.get(i).getRealPowerCount());
                        long multi = (long) value * count / 720;

                        value_list.add(value);
                        sum = sum + value;
                        count_sum = count_sum + count;
                        multi_sum = multi_sum + multi;

                        entry_list.add(new Entry(i, multi_sum));
                        if (value > 1) sum_cnt++;

                        String time = monitoring_array.get(i).getTime();
                        ConvertTimeZone convertTimeZone = new ConvertTimeZone();
                        time = convertTimeZone.convertKoreaTimeM(time);
                        if (type.equals("week")) time = time.substring(8, 10);
                        else time = time.substring(11, 13);
                        time_list.add(time);

                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(i, multi_sum));
                    }
                }

                float avg_power = 0;
                float pay = 0;

                if (sum > 0) {
                    avg_power = sum / sum_cnt;
                    pay = (int) multi_sum * Integer.parseInt(Common.getInstance().getPref(context, machineItem.getCpIdx()+"report_publish"));
                }

                itemViewHolder.average_powerTV.setText("평균 소비전력 : " + Common.getInstance().moneyFormatToWon((int) avg_power) + "kW/h");
                itemViewHolder.sum_powerTV.setText("누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) multi_sum) + "kW/h");
                itemViewHolder.report_contentTV.setText("◈ " + year + "년 " + month + "월 " + week + "주차 소비전력 분석 레포트 ◈\n1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) multi_sum) +
                        "kW/h\n2. 누적 가동시간 : " + count_sum / 720 + "h" +
                        "\n3. 기본 전기요금 : " + Common.getInstance().getPref(context, machineItem.getCpIdx()+"report_publish") + "원" +
                        "\n4. 예상 전기요금 : " + Common.getInstance().moneyFormatToWon((int) pay) + "원");
                setBarChart(value_list, barChart, "소비전력", 0f);
                setLineChart(entry_list, itemViewHolder.power_consumptionLC);
                break;

            case "current":

                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (monitoring_array.get(i).getCurrent1() != null) {
                        float value = Float.parseFloat(monitoring_array.get(i).getCurrent1());
                        value_list.add(value);
                        sum = sum + value;
                        sum_cnt++;

                    } else {
                        value_list.add(0f);
                    }

                    if (monitoring_array.get(i).getCurrent1Max() != null) {
                        max = Float.parseFloat(machineItem.getMcCurrent1Max());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                itemViewHolder.average_currentTV.setText("평균전류 : " + (int) sum + "A");
                setBarChart(value_list, barChart, "전류", max);
                break;

            case "temperature":
                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (monitoring_array.get(i).getTempNtc() != null) {
                        float value = Float.parseFloat(monitoring_array.get(i).getTempNtc());
                        value_list.add(value);
                        sum = sum + value;
                        sum_cnt++;

                    } else {
                        value_list.add(0f);
                    }

                    if (monitoring_array.get(i).getTempNtcMax() != null) {
                        max = Float.parseFloat(machineItem.getMcTempNtcMax());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                itemViewHolder.average_temperatureTV.setText("평균온도 : " + (int) sum + "℃");
                setBarChart(value_list, barChart, "온도", max);
                break;

            case "pressure":
                for (int i = 0; i < monitoring_array.size(); i++) {

                    if (monitoring_array.get(i).getPressure1() != null) {
                        float value = Float.parseFloat(monitoring_array.get(i).getPressure1());
                        value_list.add(value);
                        sum = sum + value;
                        sum_cnt++;

                    } else {
                        value_list.add(0f);
                    }

                    if (monitoring_array.get(i).getPressure1Max() != null) {
                        max = Float.parseFloat(machineItem.getMcPressure1Max());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                itemViewHolder.average_pressureTV.setText("평균압력 : " + Common.getInstance().valueConvert1(sum + "") + "Bar");
                setBarChart(value_list, barChart, "압력", max);
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setBarChart(ArrayList<Float> valList, BarChart barChart, String sensor_type, Float max) {

        ArrayList<BarEntry> bar_entries = new ArrayList<>();
        for (int i = 0; i < valList.size(); i++) {
            bar_entries.add(new BarEntry(i, valList.get(i)));
        }

        // 변수로 받아서 넣어줘도 됨
        BarDataSet dataSet = new BarDataSet(bar_entries, sensor_type);
        dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        dataSet.setColor(ContextCompat.getColor(context, R.color.bar_chart_green));
        dataSet.setBarShadowColor(Color.parseColor("#EAEAEA"));
        barChart.setDrawBarShadow(false); // 그래프 그림자
        barChart.setTouchEnabled(false); // 차트 터치 막기
        barChart.setDrawGridBackground(false); // 격자구조
        barChart.setDescription(null); // 그래프 오른쪽 하단에 라벨 표시
        barChart.getLegend().setEnabled(false); // 차트 범례 설정(legend object chart)

        //x축
        XAxis xAxis = barChart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        dataSet.setValueTextSize(13f);
        xAxis.setTextSize(8f);

        if (!sensor_type.equals("압력")) {
            ValueFormatter formatter = new ReportPublishAdapter.ValueCustomFormatter(barChart);
            dataSet.setValueFormatter(formatter);
        } else {
            ValueFormatter formatter = new ReportPublishAdapter.ValueCustomFormatter2(barChart);
            dataSet.setValueFormatter(formatter);
        }

        if (type.equals("week")) {
            ValueFormatter xAxisFormatter = new ReportPublishAdapter.TimeAxisValueFormatter(barChart);
            xAxis.setValueFormatter(xAxisFormatter);
            dataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size());

        } else {
            ValueFormatter xAxisFormatter = new ReportPublishAdapter.MonthFormatter(barChart);
            xAxis.setValueFormatter(xAxisFormatter);
            dataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size());
        }

        //y축
        YAxis yAxisL = barChart.getAxisLeft();
        YAxis yAxisR = barChart.getAxisRight();
        yAxisL.setDrawAxisLine(true);
        yAxisL.setDrawLabels(true);
        yAxisL.setDrawGridLines(false);
        yAxisR.setDrawGridLines(false);
        yAxisR.setDrawAxisLine(false);
        yAxisR.setDrawLabels(false);
        yAxisL.setLabelCount(5, true);

        BarData data = new BarData(dataSet);
        valList.sort(Comparator.naturalOrder());
        data.setBarWidth(0.45f);
        yAxisL.setAxisMinimum(0);

        if (valList.get(0) < 0) {
            yAxisL.setAxisMinimum(valList.get(0) - 20);
            yAxisL.setDrawZeroLine(true);
        }

        if (max > valList.get(valList.size() - 1)) {
            yAxisL.setAxisMaximum(max + 20);
        } else {
            yAxisL.setAxisMaximum(valList.get(valList.size() - 1) + 20);
        }

        if (max > 0) {
            LimitLine limit;
            if (type.equals("압력")) {
                limit = new LimitLine(max, "Max : " + Common.getInstance().valueConvert1(max + ""));
            } else {
                limit = new LimitLine(max, "Max : " + Common.getInstance().valueConvert(max + ""));
            }
            limit.setLineWidth(1f);
            limit.enableDashedLine(10f, 10f, 0f);
            limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
            limit.setTextSize(10f);
            limit.setTextColor(Color.BLACK);
            yAxisL.addLimitLine(limit);
        }

        barChart.setData(data);
        barChart.invalidate();
    }


    private void setLineChart(ArrayList<Entry> valList, LineChart lineChart) {

        String line_color = "#82bb6b";

        LineDataSet lineDataSet = new LineDataSet(valList, null);
        lineDataSet.setLineWidth(1);
        lineDataSet.setCircleRadius(1);

        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSet.setCubicIntensity(0.2f);
        lineDataSet.setDrawFilled(true);

        lineDataSet.setCircleColor(Color.parseColor("#368dd2"));
        lineDataSet.setColor(Color.parseColor(line_color));
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawHorizontalHighlightIndicator(false);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setValueTextSize(8f);

        LineData lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);

        XAxis xAxis = lineChart.getXAxis();
        ValueFormatter xAxisFormatter;
        xAxis.setTextSize(8f);

        if (type.equals("week")) {
            lineDataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size(), true);
            xAxisFormatter = new ReportPublishAdapter.TimeAxisValueFormatter(lineChart);

        } else {
            lineDataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size(), true);
            xAxisFormatter = new ReportPublishAdapter.MonthFormatter(lineChart);
        }

        xAxis.setGranularityEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setGridDashedLine(new DashPathEffect(new float[]{3, 3}, 0));

        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.setAxisLineColor(Color.BLACK);
        xAxis.setGranularity(0f);

        YAxis yLAxis = lineChart.getAxisLeft();
        yLAxis.setTextColor(Color.BLACK);
        yLAxis.setDrawAxisLine(false);
        yLAxis.setDrawGridLines(false);
        yLAxis.setAxisLineColor(Color.BLACK);
        yLAxis.setLabelCount(5, true);
        yLAxis.setAxisMinimum(0f);

        YAxis yRAxis = lineChart.getAxisRight();
        yRAxis.setDrawLabels(false);
        yRAxis.setDrawAxisLine(false);
        yRAxis.setDrawGridLines(false);

        lineChart.setVisibleXRange(valList.size(), valList.size());
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.setScaleXEnabled(false);
        lineChart.setScaleYEnabled(false);

        lineChart.setDescription(null);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.setTouchEnabled(true);
        lineChart.invalidate();

    }

    class ValueCustomFormatter extends ValueFormatter {

        ValueCustomFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            return Common.getInstance().moneyFormatToWon((int) value);

        }
    }

    class ValueCustomFormatter2 extends ValueFormatter {

        ValueCustomFormatter2(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            return Common.getInstance().valueConvert1(value + "");

        }
    }

    class MonthFormatter extends ValueFormatter {
        MonthFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            int i = (int) value;
            return (i + 1) + "주차";
        }
    }

    public class TimeAxisValueFormatter extends ValueFormatter {

        TimeAxisValueFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            int i = (int) value;
            String[] week = new String[]{"일", "월", "화", "수", "목", "금", "토"};
            int day = Integer.parseInt(time_list.get(i));
            return week[i] + "(" + day + "일)";
        }
    }

    public class dateValueFormatter extends ValueFormatter {

        dateValueFormatter(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            int i = (int) value;
            if (type.equals("day")) {
                if (i > -1) {
                    return time_list.get(i) + "시";
                } else {
                    return "";
                }
            } else {
                return time_list.get(i) + "일";
            }
        }
    }

    public class dateValueFormatter2 extends ValueFormatter {

        dateValueFormatter2(BarLineChartBase<?> chart) {
        }

        @Override
        public String getFormattedValue(float value) {
            int i = (int) value;
            if (i > -1) {
                return time_list.get(i) + "시";
            } else {
                return "";
            }
        }
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public void addItem(ArrayList<MachineItem> data) {

        // 외부에서 item을 추가시킬 함수입니다.
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearItem() {
        items.clear();
        notifyDataSetChanged();
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        ScrollView reportSV;
        TextView report_titleTV, report_pt_nameTV, report_cp_nameTV, report_airlineTV, report_pd_nameTV, report_mc_specTV,
                report_mc_running_timeTV, report_mc_cycleTV, report_mc_lotTV, report_mc_exchange_dtTV, sum_powerTV,
                average_powerTV, average_currentTV, average_temperatureTV, average_pressureTV, report_contentTV, report_saveTV;
        BarChart power_consumptionBC, currentBC, temperatureBC, pressureBC;
        LineChart power_consumptionLC;


        ItemViewHolder(@NonNull View itemView) {
            super(itemView);

            reportSV = itemView.findViewById(R.id.reportSV);
            report_titleTV = itemView.findViewById(R.id.report_titleTV);
            report_pt_nameTV = itemView.findViewById(R.id.report_pt_nameTV);
            report_cp_nameTV = itemView.findViewById(R.id.report_cp_nameTV);
            report_airlineTV = itemView.findViewById(R.id.report_airlineTV);
            report_pd_nameTV = itemView.findViewById(R.id.report_pd_nameTV);
            report_mc_specTV = itemView.findViewById(R.id.report_mc_specTV);
            report_mc_running_timeTV = itemView.findViewById(R.id.report_mc_running_timeTV);
            report_mc_cycleTV = itemView.findViewById(R.id.report_mc_cycleTV);
            report_mc_lotTV = itemView.findViewById(R.id.report_mc_lotTV);
            report_mc_exchange_dtTV = itemView.findViewById(R.id.report_mc_exchange_dtTV);
            sum_powerTV = itemView.findViewById(R.id.sum_powerTV);
            average_powerTV = itemView.findViewById(R.id.average_powerTV);
            average_currentTV = itemView.findViewById(R.id.average_currentTV);
            average_temperatureTV = itemView.findViewById(R.id.average_temperatureTV);
            average_pressureTV = itemView.findViewById(R.id.average_pressureTV);
            report_contentTV = itemView.findViewById(R.id.report_contentTV);
            report_saveTV = itemView.findViewById(R.id.report_saveTV);
            power_consumptionBC = itemView.findViewById(R.id.power_consumptionBC);
            currentBC = itemView.findViewById(R.id.currentBC);
            temperatureBC = itemView.findViewById(R.id.temperatureBC);
            pressureBC = itemView.findViewById(R.id.pressureBC);
            power_consumptionLC = itemView.findViewById(R.id.power_consumptionLC);

        }

        void onBind(MachineItem data) {

            report_pt_nameTV.setText(data.getPtName());
            report_cp_nameTV.setText(data.getCpName());
            report_airlineTV.setText("[ "+data.getMcAirline() + " ]");
            report_pd_nameTV.setText(data.getPdShortName());
            report_mc_specTV.setText(data.getPdSpec());
            report_mc_running_timeTV.setText(data.getMcRunningtime() + "시간");
            report_mc_cycleTV.setText(data.getMcCycle() + "시간");
            if (data.getMcLot() != null) {
                report_mc_lotTV.setText(data.getMcLot());
            } else {
                report_mc_lotTV.setText("-");
            }
            if (data.getMcExchangedt() != null) {
                report_mc_exchange_dtTV.setText(data.getMcExchangedt() + "");
            } else {
                report_mc_exchange_dtTV.setText("-");
            }
        }
    }
}



