package kr.co.compcarecompany.Fragment.Main;

import android.content.Context;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

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 com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.CaptureUtils;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.ConvertTimeZone;
import kr.co.compcarecompany.Util.CustomView.CustomMarkerView2;



public class Monitoring_Report_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private 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_contentTV, report_saveTV, average_powerTV, average_currentTV, average_temperatureTV, average_pressureTV, report_mc_lotTV,
            report_mc_exchange_dtTV, sum_powerTV, cal_consumption_sumTV, cal_chargeTV, report_closeTV;
    private EditText cal_base_chargeET;
    private BarChart power_consumptionBC, currentBC, temperatureBC, pressureBC;
    private String type, mc_idx, cp_name, start_date, end_date, group, ori_start_date, ori_end_date;
    private int year, month, week;
    private ArrayItem_<MachineItem> machine_item;
    private ProgressBar reportPB;
    private RelativeLayout reportRL;
    private LineChart power_consumptionLC;
    private ArrayList<String> time_list;

    protected ScrollView reportSV;
    // 23.08.07 주간, 월간
    public Monitoring_Report_Fragment(Handler handler, String mc_idx, String type, String year, String month, String week, String cp_name) {
        this.handler = handler;
        this.mc_idx = mc_idx;
        this.type = type;
        this.year = Integer.parseInt(year);
        this.month = Integer.parseInt(month);
        this.week = Integer.parseInt(week);
        this.cp_name = cp_name;
    }
    // 23.08.07 기간, 일간
    public Monitoring_Report_Fragment(Handler handler, String mc_idx, String type, String ori_start_date, String ori_end_date, String cp_name) {
        this.handler = handler;
        this.mc_idx = mc_idx;
        this.type = type;
        this.ori_start_date = ori_start_date;
        this.ori_end_date = ori_end_date;
        this.cp_name = cp_name;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_monitoring_report, container, false);

        report_titleTV = v.findViewById(R.id.report_titleTV);

        report_pt_nameTV = v.findViewById(R.id.report_pt_nameTV);
        report_cp_nameTV = v.findViewById(R.id.report_cp_nameTV);
        report_airlineTV = v.findViewById(R.id.report_airlineTV);
        report_pd_nameTV = v.findViewById(R.id.report_pd_nameTV);
        report_mc_specTV = v.findViewById(R.id.report_mc_specTV);
        report_mc_running_timeTV = v.findViewById(R.id.report_mc_running_timeTV);
        report_mc_cycleTV = v.findViewById(R.id.report_mc_cycleTV);
        report_mc_lotTV = v.findViewById(R.id.report_mc_lotTV);
        report_mc_exchange_dtTV = v.findViewById(R.id.report_mc_exchange_dtTV);

        power_consumptionBC = v.findViewById(R.id.power_consumptionBC);
        currentBC = v.findViewById(R.id.currentBC);
        temperatureBC = v.findViewById(R.id.temperatureBC);
        pressureBC = v.findViewById(R.id.pressureBC);

        report_contentTV = v.findViewById(R.id.report_contentTV);
        report_saveTV = v.findViewById(R.id.report_saveTV);

        average_powerTV = v.findViewById(R.id.average_powerTV);
        average_currentTV = v.findViewById(R.id.average_currentTV);
        average_temperatureTV = v.findViewById(R.id.average_temperatureTV);
        average_pressureTV = v.findViewById(R.id.average_pressureTV);

        reportRL = v.findViewById(R.id.reportRL);
        reportPB = v.findViewById(R.id.reportPB);

        cal_chargeTV = v.findViewById(R.id.cal_chargeTV);
        cal_base_chargeET = v.findViewById(R.id.cal_base_chargeET);
        cal_consumption_sumTV = v.findViewById(R.id.cal_consumption_sumTV);

        reportPB.setVisibility(View.VISIBLE);

        power_consumptionLC = v.findViewById(R.id.power_consumptionLC);
        sum_powerTV = v.findViewById(R.id.sum_powerTV);

        report_closeTV = v.findViewById(R.id.report_closeTV);
        reportSV = v.findViewById(R.id.reportSV);

        init_Listener();
        init_Handler();
        Get_Machine();
        return v;
    }

    private void Get_Machine() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mc_idx", mc_idx);
        new ApiClient(data, "proc_admin_get_machine", handler);
    }

    // 소비전력 Influx db 값 가져오기
    void Get_ChartData() {
        //차트데이터
        HashMap<String, String> data = new HashMap<>();
        data.put("mac", machine_item.getArrayitem().getMcIotMac());
        data.put("period", start_date);
        data.put("group_period", end_date);
        data.put("i", "777");
        data.put("k", "777");
        data.put("type", "pdf");
        if (type.equals("day")) data.put("group", "1h"); // get_data4
        else data.put("group", "1d"); // get_data3
        new ApiClient(data, "proc_monitoring3", handler); //data 값을 -> proc_monitoring3에 전달
    }
    // 소비전력 기본 정보
    private void Set_Contents() {
        if (type.equals("week")) {
            report_titleTV.setText(year + "년 " + month + "월 " + week + "주차 주간 보고서");

        } else if (type.equals("month")) {
            report_titleTV.setText(year + "년 " + month + "월 월간 보고서");

        } else if (type.equals("day")) {

            String date = ori_start_date.substring(0, 10);
            String start = ori_start_date.substring(11, 13);
            int end = Integer.parseInt(ori_end_date.substring(11, 13));

            String end_time = (end + 1) + "";
            if (end < 9) end_time = "0" + end_time;
            report_titleTV.setText(date + " " + start + "시 ~" + end_time + "시 일일 보고서");

        } else {
            report_titleTV.setText(ori_start_date + " ~ " + ori_end_date + " 기간 보고서");
        }

        report_pt_nameTV.setText(fa.userItem.getArrayitem().getPartner().getPtName());
        report_cp_nameTV.setText("[ " + cp_name + " - ");
        report_airlineTV.setText(machine_item.getArrayitem().getMcAirline() + " ]");
        report_pd_nameTV.setText(machine_item.getArrayitem().getProductData().getPdShortName());
        report_mc_specTV.setText(machine_item.getArrayitem().getProductData().getPdSpec());
        report_mc_running_timeTV.setText(machine_item.getArrayitem().getMcRunningtime() + "시간");
        report_mc_cycleTV.setText(machine_item.getArrayitem().getMcCycle() + "시간");
        if (machine_item.getArrayitem().getMcLot() != null) {
            report_mc_lotTV.setText(machine_item.getArrayitem().getMcLot());
        } else {
            report_mc_lotTV.setText("-");
        }
        if (machine_item.getArrayitem().getMcExchangedt() != null) {
            report_mc_exchange_dtTV.setText(machine_item.getArrayitem().getMcExchangedt() + "");
        } else {
            report_mc_exchange_dtTV.setText("-");
        }
    }
    // 보고서 기준일
    boolean is_today(int year, int month, int week) {

        Calendar calendar = Calendar.getInstance();
        int this_year = calendar.get(Calendar.YEAR);
        int this_month = calendar.get(Calendar.MONTH) + 1;
        int this_week = calendar.get(Calendar.WEEK_OF_MONTH);

        return this_year == year && this_month == month && this_week == week;
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    // 23.08.06 소비전력 월간 차트
    private void Set_Month_Chart(ArrayItem<MonitoringData> monitoring_array, BarChart barChart, String type) {


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

        float sum_kw = 0;
        float sum_count = 0;

        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;
        float week_cnt_1 = 0, week_cnt_2 = 0, week_cnt_3 = 0, week_cnt_4 = 0, week_cnt_5 = 0, week_cnt_6 = 0;

        int day_of_week = Common.getInstance().getOrderOfWeek(year, month);
        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).getPowerdata() != null) {

                        float value = Float.parseFloat(monitoring_array.get(i).getPowerdata())/1000; // w -> kw 전환
                        float count = Integer.parseInt(monitoring_array.get(i).getPowerDataCnt()); // 분당 kw

                        Log.d("월간 i @@@@", String.valueOf(i)); // 월간 일수 표기
                        Log.d("월간 day_of_week @@@@", String.valueOf(day_of_week)); // 현재까지의 3주차 수
                        Log.d("월간 this_week @@@@", String.valueOf(this_week)); // 현재까지의 3주차 수

                        if (7 - day_of_week >= i) {
                            week_sum_1 = week_sum_1 + value; // 1주일에 소비전력 합계
                            week_cnt_1 = week_cnt_1 + count; // 1주일에 갯수 카운팅

                        } else if (14 - day_of_week >= i) {
                            week_sum_2 = week_sum_2 + value;
                            week_cnt_2 = week_cnt_2 + count;

                        } else if (21 - day_of_week >= i) {
                            week_sum_3 = week_sum_3 + value;
                            week_cnt_3 = week_cnt_3 + count;

                        } else if (28 - day_of_week >= i) {
                            week_sum_4 = week_sum_4 + value;
                            week_cnt_4 = week_cnt_4 + count;

                        } else if (35 - day_of_week >= i) {
                            week_sum_5 = week_sum_5 + value;
                            week_cnt_5 = week_cnt_5 + count;

                        }
                    }
                }

                float avg = 0;


                if (this_week >= 0) {
                    if (week_cnt_1 > 0) {
                        sum_count = sum_count + week_cnt_1;
                        sum_kw = sum_kw + week_sum_1;
                        value_list.add(Float.parseFloat((week_sum_1) + ""));
                        entry_list.add(new Entry(0, sum_kw));
                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(0, 0));
                    }
                }

                if (this_week > 1) {
                    if (week_cnt_2 > 0) {
                        sum_count = sum_count + week_cnt_2;
                        sum_kw = sum_kw + week_sum_2;
                        value_list.add(Float.parseFloat((week_sum_2) + ""));
                        entry_list.add(new Entry(1, sum_kw));

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

                if (this_week > 2) {
                    if (week_cnt_3 > 0) {
                        sum_count = sum_count + week_cnt_3;
                        sum_kw = sum_kw + week_sum_3;

                        value_list.add(Float.parseFloat((week_sum_3) + ""));
                        entry_list.add(new Entry(2, sum_kw));
                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(2, 0));
                    }
                }

                if (this_week > 3) {
                    if (week_cnt_4 > 0) {
                        sum_count = sum_count + week_cnt_4;
                        sum_kw = sum_kw + week_sum_4;

                        value_list.add(Float.parseFloat((week_sum_4) + ""));
                        entry_list.add(new Entry(3, sum_kw));
                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(3, 0));
                    }
                }

                if (this_week > 4) {
                    if (week_cnt_5 > 0 && this_week > 4) {
                        sum_count = sum_count + week_cnt_5;
                        sum_kw = sum_kw + week_sum_5;

                        value_list.add(Float.parseFloat((week_sum_5) + ""));
                        entry_list.add(new Entry(4, sum_kw));

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

                int pay = 0; // 자료형은 인티저로할것!
                float sum_times = 0;
                float avg_kw_consumption =0;
                float ori_value_hour =0;
                float ori_value_min =0;

                pay = (int) sum_kw * 120; // 전력 요금
                sum_times = sum_count/60 ; // 누적 소비시간 hour 기준
                sum_times=Float.parseFloat(String.format("%04.2f", sum_times));
                avg_kw_consumption = sum_kw / sum_times; // 평균소비전력
                avg_kw_consumption=Float.parseFloat(String.format("%.2f", avg_kw_consumption));

                String ori_value = String.valueOf(sum_times);
                ori_value_hour = Integer.parseInt(ori_value.substring(0, ori_value.indexOf(".")));
                ori_value = (ori_value.substring(ori_value.lastIndexOf(".")+1));
                Log.d("length0@@@@", String.valueOf(ori_value.length()));
                if(ori_value.length() >= 2){
                    ori_value_min = Float.parseFloat(ori_value);
                    Log.d("length1@@@@", String.valueOf(ori_value_min));
                }else{
                    ori_value_min = Float.parseFloat(ori_value) * 10;
                    Log.d("length2@@@@", String.valueOf(ori_value_min));
                }

                ori_value_min = (float) (ori_value_min * 0.01);
                ori_value_min = (int) Math.round(ori_value_min * 60);

                float power_output;
                String horse_output = "";
                String output = "- (옵션에서 기계 마력을 설정하세요)";
                if (machine_item.getArrayitem().getMcHorsepower() != null) {
                    if (avg_kw_consumption > 0) {
                        power_output = avg_kw_consumption / Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) * 100;
                        output = Common.getInstance().valueConvert1(power_output + "") + "%";
                    } else {
                        output = "-";
                    }
                    horse_output = " / " + Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) + "kW";
                }

                report_contentTV.setText("◈ " + year + "년 " + month + "월 소비전력 분석 레포트◈\n" +
                        "1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) + "kW/h\n" +
                        "2. 누적 가동시간 : " + (int)ori_value_hour +"시간"+(int)ori_value_min +"분"+"\n" +
                        "3. 시간당 평균 소비전력 : " + avg_kw_consumption + "kw/h"+ "\n" +
                        " -.계산식 : "+ sum_kw+"(kW)/"+sum_times+"(hour)\n" +
                        "4. 부하율 : " + output + horse_output );

                Log.d("월간 value_list @@@@", String.valueOf(value_list));
                Log.d("월간 entry_list @@@@", String.valueOf(entry_list));


                cal_consumption_sumTV.setText(Common.getInstance().moneyFormatToWon((int) sum_kw));
                cal_chargeTV.setText(Common.getInstance().moneyFormatToWon((int) pay));

                average_powerTV.setText("소수점이하 절삭");
                sum_powerTV.setText("누적전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) + "kW/h");
                setBarChart(value_list, barChart, "평균전력", 0f);
                setLineChart(entry_list, 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) {
                    float value = Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + ""));
                    value_list.add(value);
                    sum = sum + Float.parseFloat(Common.getInstance().valueConvert((week_sum_1 / a) + ""));
                    sum_cnt++;
                } else {
                    value_list.add(0f);
                }

                if (this_week > 1) {
                    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 (this_week > 2) {
                    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 (this_week > 3) {
                    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 (this_week > 4) {
                    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 (this_week > 5) {
                    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 + "");
                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 (this_week > 1) {
                    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 (this_week > 2) {
                    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 (this_week > 3) {
                    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 (this_week > 4) {
                    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 (this_week > 5) {
                    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 + "");
                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 (this_week > 1) {
                    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 (this_week > 2) {
                    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 (this_week > 3) {
                    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 (this_week > 4) {
                    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 (this_week > 5) {
                    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 + "");
                average_pressureTV.setText("평균압력 : " + sum_value + "Bar");
                setBarChart(value_list, barChart, "압력", max);
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    // 23.08.07 소비전력 일간/주간 차트
    private void Set_Week_Chart(ArrayItem<MonitoringData> monitoring_array, BarChart barChart, String sensor_type) throws Exception {

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

        float max = 0f;
        float sum = 0f;
        int sum_cnt = 0;

        float sum_kw = 0f;
        float time_sum = 0f;

        
        switch (sensor_type) {
            case "power":

                time_list = new ArrayList<>();

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

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

                       float min_kw = Float.parseFloat(monitoring_array.get(i).getPowerdata())/1000; // w -> kw 전환
                       int min_time_count = Integer.parseInt(monitoring_array.get(i).getPowerDataCnt()); // 분당 kw

                        if(min_kw > 0) {
                            sum_kw = sum_kw + min_kw;
                            time_sum = time_sum + min_time_count;
                            value_list.add(min_kw); // 초단위 소비전력 바차트 그리기 (1)
                            entry_list.add(new Entry(i, sum_kw)); // 누적 소비전력 라인차트 그리기 (2)
                        }else{
                            entry_list.add(new Entry(i, 0)); // 누적소비전력 차트 그리기
                            value_list.add(Float.valueOf(0)); // 초단위 소비전력 바차트 그리기 (1)
                        }

                        Log.d("value@@@@", String.valueOf(min_kw));
                        Log.d("count@@@@", String.valueOf(min_time_count));

                        String time = monitoring_array.get(i).getTime();
                        Log.d("time1@@@@", String.valueOf(time));
                        ConvertTimeZone convertTimeZone = new ConvertTimeZone();
                        time = convertTimeZone.convertKoreaTimeM(time);
                        if (type.equals("week")) time = time.substring(8, 10); // 날짜 구하기
                        else time = String.valueOf(Integer.parseInt(time.substring(11, 13)) + 1); // 시간 +1 추가하기
                        time_list.add(time);
                        Log.d("time2@@@@", String.valueOf(time));

                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(i, 0)); // 누적소비전력 차트 그리기
                    }
                }

               // 전력 요금 계산     
                float avg_power = 0;
                int pay = 0;
                float avg_kw_consumption = 0; // 평균소비전력

                int ori_value_hour = 0;
                float ori_value_min = 0;
                float sum_times = (float) 0.01;

                pay = (int) sum_kw * 120;

                sum_times = time_sum / 60; // 60min / 60 = 1hour
                sum_times = Float.parseFloat(String.format("%04.2f", sum_times)) ;

                avg_kw_consumption = sum_kw / sum_times; // 평균소비전력
                avg_kw_consumption=Float.parseFloat(String.format("%.2f", avg_kw_consumption)); // 평균소비전력 소수점 2자리까지

                String ori_value = String.valueOf(sum_times);
                ori_value_hour = Integer.parseInt(ori_value.substring(0, ori_value.indexOf(".")));
                ori_value = (ori_value.substring(ori_value.lastIndexOf(".")+1));
                Log.d("length0@@@@", String.valueOf(ori_value.length()));
                if(ori_value.length() >= 2){
                    ori_value_min = Float.parseFloat(ori_value);
                    Log.d("length1@@@@", String.valueOf(ori_value_min));
                }else{
                    ori_value_min = Float.parseFloat(ori_value) * 10;
                    Log.d("length2@@@@", String.valueOf(ori_value_min));
                }

                ori_value_min = (float) (ori_value_min * 0.01);
                ori_value_min = (int) Math.round(ori_value_min * 60);


                // 부하율 구하기
                float power_output;
                String horse_output = "";
                String output = "- (옵션에서 기계 마력을 설정하세요)";
                if (machine_item.getArrayitem().getMcHorsepower() != null) {
                    if (avg_kw_consumption > 0) {
                        power_output = avg_kw_consumption / Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) * 100;
                        output = Common.getInstance().valueConvert1(power_output + "") + "%";
                    } else {
                        output = "-";
                    }
                    horse_output = " / " + Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) + "kW";
                }

                // 최종 값들 보여주기
                sum_powerTV.setText("누적전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) + "kW/h"); // 차트용! 하단 누적소비전력

                if (type.equals("week")) {
                    report_contentTV.setText(
                            "◈ " + year + "년 " + month + "월 " + week + "주차 소비전력 분석 레포트 ◈\n" +
                            "1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) +"kW/h\n" +
                            "2. 누적 가동시간 : " + sum_times  +"\n" +
                            "3. 시간당 평균 소비전력 : " + avg_kw_consumption + "kw/h" +"\n" +
                            "4. 부하율 : " + output + horse_output );

                } else {
                    String date = ori_start_date.substring(0, 10);
                    report_contentTV.setText(
                            "◈ " + date + "일 분석 레포트 ◈\n" +
                            "1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) +"kW/h\n" +
                            "2. 누적 가동시간 : " + (int)ori_value_hour +"시간"+(int) ori_value_min +"분"+"\n" +
                            "3. 시간당 평균 소비전력 : " + avg_kw_consumption + "kw/h"+ "\n" +
                            " -.계산식 : "+ sum_kw+"(kW)/"+sum_times+"(hour)\n" +
                            "4. 부하율 : " + output + horse_output );
                   average_powerTV.setText("소수점이하 절삭");
                    setLineChart(entry_list, power_consumptionLC);
                }

                cal_consumption_sumTV.setText(Common.getInstance().moneyFormatToWon((int) sum_kw));
                cal_chargeTV.setText(Common.getInstance().moneyFormatToWon((int) pay));
                setBarChart(value_list, barChart, "전력평균", 0f); // 공통

                Log.d("value_list@@@@", String.valueOf(value_list));
                Log.d("entry_list@@@@", String.valueOf(entry_list));
                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;
                        if (value > 1) sum_cnt++;

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

                    if (monitoring_array.get(i).getCurrent1Max() != null) {
                        max = Float.parseFloat(machine_item.getArrayitem().getMcCurrent1Max());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                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;
                        if (value > 1) sum_cnt++;

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

                    if (monitoring_array.get(i).getTempNtcMax() != null) {
                        max = Float.parseFloat(machine_item.getArrayitem().getMcTempNtcMax());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                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;
                        if (value > 1) sum_cnt++;

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

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

    @RequiresApi(api = Build.VERSION_CODES.N)
    // 23.08.07 소비전력 기간 차트
    void Set_Date_Chart(ArrayItem<MonitoringData> monitoring_array, BarChart barChart, String type) throws Exception {

        ArrayList<Float> value_list = new ArrayList<>(); // bar_chart 데이터
        ArrayList<Entry> entry_list = new ArrayList<>(); // 누적 라인데이터

        float max = 0f;
        int sum_cnt = 0;
        float sum = 0f;

        float sum_kw = 0;
        float time_sum = 0;



        switch (type) {

            case "power":

                time_list = new ArrayList<>();

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

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

                        float min_kw = Float.parseFloat(monitoring_array.get(i).getPowerdata())/1000; // w -> kw 전환
                        int min_time_count = Integer.parseInt(monitoring_array.get(i).getPowerDataCnt()); // 분당 kw

                        String time = monitoring_array.get(i).getTime();

                        ConvertTimeZone convertTimeZone = new ConvertTimeZone();
                        time = convertTimeZone.convertKoreaTimeM(time);
                        time = time.substring(8, 10);
                        time_list.add(time);

                        if(min_kw > 0) {
                            sum_kw = sum_kw + min_kw;
                            time_sum = time_sum + min_time_count;
                            value_list.add(min_kw); // 평균 소비전력 차트
                            entry_list.add(new Entry(i, sum_kw)); // 누적 소비전력 차트
                        }else{
                            value_list.add(0f);
                            entry_list.add(new Entry(i, 0)); // 누적소비전력 차트 그리기
                        }

                    } else {
                        value_list.add(0f);
                        entry_list.add(new Entry(i, 0)); // 누적소비전력 차트 그리기
                    }
                }


                // 전력 요금 계산
                float avg_power = 0;
                int pay = 0;
                float avg_kw_consumption = 0; // 평균소비전력
                float sum_times = 0;
                float ori_value_hour = 0;
                float ori_value_min = 0;

                pay = (int) sum_kw * 120;

                sum_times = time_sum / 60; // 60min / 60 = 1hour
                sum_times=Float.parseFloat(String.format("%04.2f", sum_times));
                avg_kw_consumption = sum_kw / sum_times; // 평균소비전력
                avg_kw_consumption=Float.parseFloat(String.format("%.2f", avg_kw_consumption));


                String ori_value = String.valueOf(sum_times);
                ori_value_hour = Integer.parseInt(ori_value.substring(0, ori_value.indexOf(".")));
                ori_value = (ori_value.substring(ori_value.lastIndexOf(".")+1));
                Log.d("length0@@@@", String.valueOf(ori_value.length()));
                if(ori_value.length() >= 2){
                    ori_value_min = Float.parseFloat(ori_value);
                    Log.d("length1@@@@", String.valueOf(ori_value_min));
                }else{
                    ori_value_min = Float.parseFloat(ori_value) * 10;
                    Log.d("length2@@@@", String.valueOf(ori_value_min));
                }

                ori_value_min = (float) (ori_value_min * 0.01);
                ori_value_min = (int) Math.round(ori_value_min * 60);



                float power_output;
                String horse_output = "";
                String output = "- (옵션에서 기계 마력을 설정하세요)";
                if (machine_item.getArrayitem().getMcHorsepower() != null) {
                    if (avg_kw_consumption > 0) {
                        power_output = avg_kw_consumption / Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) * 100;
                        output = Common.getInstance().valueConvert1(power_output + "") + "%";
                    } else {
                        output = "-";
                    }
                    horse_output = " / " + Common.getInstance().get_horsepower_output(machine_item.getArrayitem().getMcHorsepower()) + "kW";
                }


                average_powerTV.setText("소수점이하 절삭");
                sum_powerTV.setText("누적전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) + "kW/h");
                report_contentTV.setText("◈ " + ori_start_date + " ~ " + ori_end_date + " 소비전력 분석 레포트 ◈\n" +
                        "1. 누적 소비전력 : " + Common.getInstance().moneyFormatToWon((int) sum_kw) + "kW/h\n" +
                        "2. 누적 가동시간 : " + (int)ori_value_hour +"시간"+(int) ori_value_min +"분"+"\n" +
                        "3. 시간당 평균 소비전력 : " + avg_kw_consumption + "kw/h"+ "\n" +
                        " -.계산식 : "+ sum_kw+"(kW)/"+sum_times+"(hour)\n" +
                        "4. 부하율 : " + output + horse_output );

                cal_consumption_sumTV.setText(Common.getInstance().moneyFormatToWon((int) sum_kw));
                cal_chargeTV.setText(Common.getInstance().moneyFormatToWon((int) pay));
                setBarChart(value_list, barChart, "평균전력", 0f);
                setLineChart(entry_list, 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;
                        if (value > 1) sum_cnt++;

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

                    if (monitoring_array.get(i).getCurrent1Max() != null) {
                        max = Float.parseFloat(machine_item.getArrayitem().getMcCurrent1Max());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                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;
                        if (value > 1) sum_cnt++;

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

                    if (monitoring_array.get(i).getTempNtcMax() != null) {
                        max = Float.parseFloat(machine_item.getArrayitem().getMcTempNtcMax());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                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;
                        if (value > 1) sum_cnt++;

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

                    if (monitoring_array.get(i).getPressure1Max() != null) {
                        max = Float.parseFloat(machine_item.getArrayitem().getMcPressure1Max());
                    }
                }
                if (sum_cnt > 0 && sum > 0) sum = sum / sum_cnt;
                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(getContext(), 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 Monitoring_Report_Fragment.ValueCustomFormatter(barChart);
            dataSet.setValueFormatter(formatter);
        } else {
            ValueFormatter formatter = new Monitoring_Report_Fragment.ValueCustomFormatter2(barChart);
            dataSet.setValueFormatter(formatter);
        }

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

        } else if (type.equals("month")) {
            ValueFormatter xAxisFormatter = new Monitoring_Report_Fragment.MonthFormatter(barChart);
            xAxis.setValueFormatter(xAxisFormatter);
            dataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size());

        } else {

            ValueFormatter xAxisFormatter;

            if (valList.size() > 20) {
                xAxis.setLabelCount(valList.size() / 2);
                dataSet.setValueTextSize(6f);
            } else {
                xAxis.setLabelCount(valList.size());
                dataSet.setValueTextSize(8f);
            }

            if (type.equals("day")) {
                xAxisFormatter = new Monitoring_Report_Fragment.dateValueFormatter2(barChart);
            } else {
                xAxisFormatter = new Monitoring_Report_Fragment.dateValueFormatter(barChart);
                //xAxisFormatter = new Monitoring_Report_Fragment.TimeAxisValueFormatter(barChart);

            }

            xAxis.setValueFormatter(xAxisFormatter);
            dataSet.setDrawValues(true);
            barChart.setDrawValueAboveBar(true);
            barChart.setDragEnabled(true);
            barChart.setScaleEnabled(true);
            barChart.setPinchZoom(true);
        }

        //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 Monitoring_Report_Fragment.TimeAxisValueFormatter(lineChart);

        } else if (type.equals("month")) {
            lineDataSet.setDrawValues(true);
            xAxis.setLabelCount(valList.size(), true);
            xAxisFormatter = new Monitoring_Report_Fragment.MonthFormatter(lineChart);

        } else {
            lineDataSet.setDrawValues(false);

            if (valList.size() > 20) {
                xAxis.setLabelCount(valList.size() / 2, false);
            } else {
                xAxis.setLabelCount(valList.size(), true);
            }

            if (type.equals("day")) {
                xAxisFormatter = new Monitoring_Report_Fragment.dateValueFormatter2(lineChart);
            } else {
                xAxisFormatter = new Monitoring_Report_Fragment.dateValueFormatter(lineChart);
            }
            CustomMarkerView2 marker = new CustomMarkerView2(getContext(), R.layout.custom_marker, time_list);
            marker.setChartView(lineChart);
            lineChart.setMarker(marker);

            lineChart.setDragEnabled(true);
            lineChart.setScaleEnabled(true);
            lineChart.setPinchZoom(true);

        }

        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 "";
            }
        }
    }

    void init_Listener() {

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

        report_closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });

        cal_base_chargeET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (i > 0) {
                    int sum = Integer.parseInt(cal_consumption_sumTV.getText().toString().replace(",", ""));
                    int base = Integer.parseInt(cal_base_chargeET.getText().toString());

                    cal_chargeTV.setText(Common.getInstance().moneyFormatToWon(sum * base));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    void init_Handler() {
        handler = new Handler() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) { // 시간의 범위 설정
                    if (url.equals("proc_admin_get_machine")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        machine_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MachineItem>>() {
                        }.getType());

                        if (machine_item.isSuccess()) {
                            String first = null;
                            String last = null;
                                        
                            try {
                                if (type.equals("month")) { // 월간
                                    first = Common.getInstance().getDateOfMonth(year, month, "first");
                                    last = Common.getInstance().getDateOfMonth(year, month, "last");
                                } else if (type.equals("week")) { //주간 23.08.20로 부터 사용안함 기능에 문제가 있음
                                    first = Common.getInstance().getDateOfWeek(year, month, week, "first", false);
                                    last = Common.getInstance().getDateOfWeek(year, month, week, "last", is_today(year, month, week));
                                } else if (type.equals("day")) { //일간
                                    first = Common.getInstance().convert_time2(ori_start_date, true);
                                    int end = Integer.parseInt(ori_end_date.substring(11));
                                    last = Common.getInstance().convert_time2(ori_end_date, false);
                                } else { // 기간
                                    first = Common.getInstance().convert_time(ori_start_date, true);
                                    last = Common.getInstance().convert_time(ori_end_date, false);
                                }

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            start_date = first;
                            end_date = last;
                            Log.d("start_date@@@@", String.valueOf(start_date));
                            Log.d("end_date@@@@", String.valueOf(end_date));

                            Get_ChartData();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            reportPB.setVisibility(View.GONE);
                        }
                    // 23.08.07 influxdb4 소비전력 로드
                    } else if (url.equals("proc_monitoring3")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        ArrayItem<MonitoringData> monitoringArray;
                        monitoringArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                        }.getType());

                        if (monitoringArray.isSuccess()) {

                            if (type.equals("month")) {
                                Set_Month_Chart(monitoringArray, power_consumptionBC, "power");
                                Set_Month_Chart(monitoringArray, currentBC, "current");
                                Set_Month_Chart(monitoringArray, temperatureBC, "temperature");
                                Set_Month_Chart(monitoringArray, pressureBC, "pressure");

                            } else if (type.equals("week") || type.equals("day")) {
                                try { 
                                    Set_Week_Chart(monitoringArray, power_consumptionBC, "power");
                                    Set_Week_Chart(monitoringArray, currentBC, "current");
                                    Set_Week_Chart(monitoringArray, temperatureBC, "temperature");
                                    Set_Week_Chart(monitoringArray, pressureBC, "pressure");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else { 
                                try {
                                    Set_Date_Chart(monitoringArray, power_consumptionBC, "power");
                                    Set_Date_Chart(monitoringArray, currentBC, "current");
                                    Set_Date_Chart(monitoringArray, temperatureBC, "temperature");
                                    Set_Date_Chart(monitoringArray, pressureBC, "pressure");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            Set_Contents();

                        } else {
                            Common.getInstance().toastShow(getContext(), "데이터가 없습니다.");
                            getActivity().finish();
                        }

                        reportPB.setVisibility(View.GONE);

                    }
                } else {
                    reportPB.setVisibility(View.GONE);
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

}