package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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 com.google.zxing.common.reedsolomon.GenericGF;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Company.MachineLogData;
import kr.co.compcarecompany.Data.Product.AlarmData;
import kr.co.compcarecompany.Data.Product.AlarmDatum;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.ProductData;
import kr.co.compcarecompany.Data.Product.ReportData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.MachineLogAdapter;
import kr.co.compcarecompany.Util.Adapter.MachineManagementReportAdapter2;
import kr.co.compcarecompany.Util.Adapter.MachineManagementReportTitleAdapter;
import kr.co.compcarecompany.Util.Adapter.MachineManagementTitleAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AlarmRemoveListDialog;
import kr.co.compcarecompany.Util.CustomView.MonitoringDialog;
import kr.co.compcarecompany.Util.CustomView.NoticeDialog;
import kr.co.compcarecompany.Util.CustomView.ReportDialog;
import kr.co.compcarecompany.Util.CustomView.YearMonthPickerDialog;
import kr.co.compcarecompany.Util.Firebase.MyFirebaseMessagingService;

public class Machine_Management_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView alarm_tapTV, report_tapTV, iot_tapTV, report_dateTV;
    private RecyclerView alarm_listRV, report_listRV;
    private ImageView alarm_all_removeIV;
    private String ag_idx, pt_idx, cp_idx, report_yn, log_yn, type, time, mc_airline, mc_name;
    private ArrayItem<AlarmDatum> alarmList;
    private ArrayItem<ReportData> reportList;
    private ArrayItem<CompanyData> reportList2;
    private ProgressBar managementPB;
    private LinearLayout alarm_all_removeLL, reportLL, report_dateLL, mc_nameLL;
    private MachineManagementTitleAdapter managementAdapter;
    private MachineManagementReportTitleAdapter reportAdapter2;
    private ArrayItem<MachineLogData> logArray;
    private MachineLogAdapter logAdapter;
    private Spinner cp_name_listSN, cp_airlineSN, mc_nameSN;
    private ArrayItem<CompanyData> company_items;
    private ArrayAdapter<String> air_line_adapter, cp_name_adapter;
    private int lastIndex = 0, limitCount = 10, count = 0, select_year = -1, select_month = -1;
    private DatePickerDialog.OnDateSetListener callback;
    boolean cp_name_selected = false, cp_airline_selected = false, mc_name_selected = false;


    @SuppressLint("ValidFragment")
    public Machine_Management_Fragment(Handler handler, String ag_idx, String pt_idx) {
        this.handler = handler;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
    }

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

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

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

        alarm_tapTV = v.findViewById(R.id.alarm_tapTV);
        report_tapTV = v.findViewById(R.id.report_tapTV);
        iot_tapTV = v.findViewById(R.id.iot_tapTV);
        alarm_all_removeIV = v.findViewById(R.id.alarm_all_removeIV);
        alarm_listRV = v.findViewById(R.id.alarm_listRV);
        managementPB = v.findViewById(R.id.managementPB);
        alarm_all_removeLL = v.findViewById(R.id.alarm_all_removeLL);
        reportLL = v.findViewById(R.id.reportLL);
        cp_name_listSN = v.findViewById(R.id.cp_name_listSN);
        cp_airlineSN = v.findViewById(R.id.cp_airlineSN);
        report_listRV = v.findViewById(R.id.report_listRV);
        mc_nameSN = v.findViewById(R.id.mc_nameSN);
        mc_nameLL = v.findViewById(R.id.mc_nameLL);

        report_dateLL = v.findViewById(R.id.report_dateLL);
        report_dateTV = v.findViewById(R.id.report_dateTV);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        alarm_listRV.setLayoutManager(layoutManager);
        managementAdapter = new MachineManagementTitleAdapter(getContext(), handler, fa, new MachineManagementTitleAdapter.alarmClickListener() {
            @Override
            public void clickBtn(Bundle bundle) {
                //알람 >> 알람해제 클릭 리스너
                ArrayList<String> bundle_check = bundle.getStringArrayList("mac_list");
                if (bundle_check.size() < 1) {
                    Common.getInstance().toastShow(getContext(), "해제 할 알람이 없습니다.");
                    return;
                }

                String[] items = {"30", "60"};

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("재알람 시간 선택(분)");
                dialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        int time = Integer.parseInt(items[which]) * 60;

                        ArrayList<String> bundle_mac_lists = bundle.getStringArrayList("mac_list");
                        String mac_list = bundle_mac_lists.toString();
                        mac_list = mac_list.replace("[", "");
                        mac_list = mac_list.replace("]", "");

                        ArrayList<String> bundle_msg_lists = bundle.getStringArrayList("msg_list");
                        String msg_list = bundle_msg_lists.toString();
                        msg_list = msg_list.replace("[", "");
                        msg_list = msg_list.replace("]", "");

                        HashMap<String, String> data = new HashMap<>();
                        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                        data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
                        data.put("mac_list", mac_list);
                        data.put("msg_list", msg_list);
                        data.put("delay_time", time + "");

                        new ApiClient(data, "proc_admin_alarm_remove2", handler);
                        dialog.dismiss();
                    }
                });
                AlertDialog alertDialog = dialogBuilder.create();
                alertDialog.show();
            }
        }, new MachineManagementTitleAdapter.reportClickListener() {
            @Override
            public void clickBtn(Bundle bundle) {
                //알람 >> 작업일지 클릭 리스너
                ReportDialog dialog = new ReportDialog(getContext(), handler, fa.userItem.getArrayitem().getAgIdx(), fa.userItem.getArrayitem().getPtIdx(),
                        fa.userItem.getArrayitem().getMbId(), bundle.getString("mc_airline"), bundle.getString("cp_idx"), fa);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        Set_Alarms();
                    }
                });
                dialog.show();
            }
        }, new MachineManagementTitleAdapter.returnClickListener() {
            @Override
            public void clickBtn() {
                //알람 >> 작업일지 눌렀을 때 해제되지 않은 알람이 있을 경우
                Common.getInstance().toastShow(getContext(), "해제되지 않은 알람이 있습니다.\n알람을 해제 후 재시도 해주세요.");
            }
        }, new MachineManagementTitleAdapter.detailClickListener() {
            @Override
            public void clickBtn(Bundle bundle) {

                managementPB.setVisibility(View.VISIBLE);
                type = bundle.getString("type");
                time = bundle.getString("time");

                HashMap<String, String> data = new HashMap<>();
                data.put("mc_iot_mac", bundle.getString("mc_iot_mac"));
                new ApiClient(data, "proc_admin_get_machine_with_mac", handler);
            }
        }, new MachineManagementTitleAdapter.remove_list_ClickListener() {
            @Override
            public void clickBtn(Bundle bundle) {
                type = bundle.getString("type");
                time = bundle.getString("time");

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("cp_idx", bundle.getString("cp_idx"));
                data.put("mc_airline", bundle.getString("mc_airline"));
                new ApiClient(data, "proc_admin_alarm_remove_list", handler);
            }
        });

        alarm_listRV.setAdapter(managementAdapter);

        report_yn = "N";
        log_yn = "N";

        init_Hdr();
        init_Listener();
        Set_Alarms();
        return v;
    }

    void Set_Alarms() {
        managementPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", pt_idx);
        data.put("report_yn", report_yn);
        new ApiClient(data, "proc_get_management_list", handler);
    }

    void Get_Company() {
        managementPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        new ApiClient(data, "proc_admin_company_info", handler);
    }


    void Set_Reports() {
        managementPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("pt_idx", pt_idx);
        data.put("off_set", lastIndex + "");
        data.put("limit", limitCount + "");

        if (!TextUtils.isEmpty(cp_idx)) data.put("cp_idx", cp_idx);
        if (!TextUtils.isEmpty(mc_airline) && !mc_airline.contains("전체"))
            data.put("mc_airline", mc_airline);
        if (!TextUtils.isEmpty(mc_name)) data.put("pd_name", mc_name);
        if (select_year > 0) {
            data.put("year", select_year + "");
            data.put("month", select_month + "");
        }

        new ApiClient(data, "proc_get_report_and_service_list2", handler);
    }

    void Set_Logs() {
        managementPB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        new ApiClient(data, "proc_get_machine_onoff_log2", handler);
    }

    void init_Listener() {

        //알람 리스트 최상단, 최하단에서 스크롤시 리프레시됨 >> 최하단 리프레시 없애달라하심 22.05.03
        alarm_listRV.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

                if (!alarm_listRV.canScrollVertically(-1) && newState > 1) {

                    if (report_yn.equals("N") && log_yn.equals("N")) {
                        Set_Alarms();

                    } else if (report_yn.equals("Y") && log_yn.equals("N")){
                        lastIndex = 0;
                        count = 0;
                        cp_idx = "";
                        mc_airline = "";
                        Get_Company();

                    } else if (report_yn.equals("N") && log_yn.equals("Y")){
                        Set_Logs();
                    }
                }
            }
        });

        //현황 탭 클릭 리스너
        alarm_tapTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                report_yn = "N";
                log_yn = "N";

                alarm_tapTV.setBackgroundResource(R.drawable.bg_round_purple_except_right);
                alarm_tapTV.setTextColor(Color.WHITE);

                report_tapTV.setBackgroundResource(R.color.white);
                report_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                iot_tapTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                iot_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                alarm_all_removeLL.setVisibility(View.VISIBLE);
                reportLL.setVisibility(View.GONE);
                report_dateLL.setVisibility(View.GONE);
                alarm_listRV.setVisibility(View.VISIBLE);
                alarm_listRV.setAdapter(null);
                Set_Alarms();
            }
        });

        //일지 탭 클릭 리스너
        report_tapTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                report_yn = "Y";
                log_yn = "N";
                lastIndex = 0;
                count = 0;
                cp_idx = "";
                mc_airline = "";

                alarm_tapTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                alarm_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                report_tapTV.setBackgroundResource(R.color.color_bg_purple);
                report_tapTV.setTextColor(Color.WHITE);

                iot_tapTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                iot_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                alarm_all_removeLL.setVisibility(View.GONE);
                report_dateLL.setVisibility(View.VISIBLE);
                reportLL.setVisibility(View.VISIBLE);

//                reportAdapter = new MachineManagementReportAdapter2(getContext(), handler, OnLoadMoreListener);
                reportAdapter2 = new MachineManagementReportTitleAdapter(getContext(), handler, OnLoadMoreListener2, fa);

                report_listRV.setAdapter(reportAdapter2);
                Get_Company();
            }
        });

        //타임라인 탭 클릭 리스너
        iot_tapTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                report_yn = "N";
                log_yn = "Y";

                alarm_tapTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                alarm_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                report_tapTV.setBackgroundResource(R.color.white);
                report_tapTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));

                iot_tapTV.setBackgroundResource(R.drawable.bg_round_purple_except_left);
                iot_tapTV.setTextColor(Color.WHITE);

                alarm_all_removeLL.setVisibility(View.GONE);
                report_dateLL.setVisibility(View.GONE);
                reportLL.setVisibility(View.GONE);
                alarm_listRV.setVisibility(View.VISIBLE);
                alarm_listRV.setAdapter(null);

                Set_Logs();
            }
        });

        //전체 알람해제 클릭 리스너
        alarm_all_removeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alarm_all_stop();
            }
        });

        //지점 스피너
        cp_name_listSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (cp_name_selected) {

                    air_line_adapter.clear();
                    air_line_adapter.add("라인 전체");
                    mc_airline = "";
                    mc_name = "";
                    lastIndex = 0;
                    count = 0;

                    if (i > 0) {
                        cp_idx = company_items.getArrayitem().get(i - 1).getCpIdx();
                        if (company_items.getArrayitem().get(i - 1).getCpAirline() != null) {
                            String[] air_line = company_items.getArrayitem().get(i - 1).getCpAirline().toString().split(",");
                            air_line_adapter.addAll(air_line);
                        }

                    } else {
                        cp_idx = "";
                    }

                    mc_nameLL.setVisibility(View.GONE);
                    mc_name_selected = false;
                    cp_airlineSN.setSelection(0);
                    mc_name_selected = false;

                    Set_Reports();

                } else {
                    cp_name_selected = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //에어라인 스피너
        cp_airlineSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (cp_airline_selected) {
                    if (i > 0) {
                        mc_airline = cp_airlineSN.getSelectedItem().toString();
                        lastIndex = 0;
                        count = 0;

                        HashMap<String, String> data = new HashMap<>();
                        data.put("cp_idx", cp_idx);
                        data.put("mc_airline", mc_airline);
                        new ApiClient(data, "proc_get_product_name", handler);

                    } else {
                        mc_airline = "";
                        lastIndex = 0;
                        count = 0;
                        mc_name = "";
                        mc_nameLL.setVisibility(View.GONE);
                        Set_Reports();

                    }

                } else {
                    cp_airline_selected = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //기기이름 스피너
        mc_nameSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                if (mc_name_selected) {
                    if (i > 0) {
                        mc_name = mc_nameSN.getSelectedItem().toString();
                    } else {
                        mc_name = "";
                    }

                    lastIndex = 0;
                    count = 0;
                    Set_Reports();

                } else {
                    mc_name_selected = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //점검내역 날짜 검색
        report_dateLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YearMonthPickerDialog dialog = new YearMonthPickerDialog();
                dialog.setListener(callback);
                dialog.show(fa.getSupportFragmentManager(), "YearMonthPickerTest");
            }
        });

        callback = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                if (year < 0) {
                    select_year = -1;
                    select_month = -1;
                    report_dateTV.setText("날짜 전체");

                } else {
                    if (monthOfYear < 10) {
                        report_dateTV.setText(year + "년 0" + monthOfYear + " 월");
                    } else {
                        report_dateTV.setText(year + "년 " + monthOfYear + " 월");
                    }
                    select_year = year;
                    select_month = monthOfYear;
                }

                Set_Reports();
            }
        };
    }


    MachineManagementReportAdapter2.OnLoadMoreListener OnLoadMoreListener = new MachineManagementReportAdapter2.OnLoadMoreListener() {
        @Override
        public void onLoadMore(int position) {
            if (count == limitCount) {
                lastIndex += limitCount;
                Set_Reports();
            }
        }
    };

    MachineManagementReportTitleAdapter.OnLoadMoreListener OnLoadMoreListener2 = new MachineManagementReportTitleAdapter.OnLoadMoreListener() {
        @Override
        public void onLoadMore(int position) {
            if (count == limitCount) {
                lastIndex += limitCount;
                Set_Reports();
            }
        }
    };

    void alarm_all_stop(){

        String mac_list = "";
        String msg_list = "";

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

            for (int j = 0; j < alarmList.getArrayitem().get(i).getAlarmList().size(); j++) {

                if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms() != null) {

                    for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().size(); k++) {

                        if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getReadYn().equals("N")) {

                            if (mac_list.equals("")) {
                                mac_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getMcIotMac();
                            } else {
                                mac_list = mac_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getMcIotMac();
                            }

                            if (msg_list.equals("")) {
                                msg_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getSensor();
                            } else {
                                msg_list = msg_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getSensor();
                            }
                        }
                    }
                }

                if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms() != null) {

                    for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().size(); k++) {

                        if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getReadYn().equals("N")) {

                            if (mac_list.equals("")) {
                                mac_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getMcIotMac();
                            } else {
                                mac_list = mac_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getMcIotMac();
                            }

                            if (msg_list.equals("")) {
                                msg_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getSensor();
                            } else {
                                msg_list = msg_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getSensor();
                            }
                        }
                    }
                }

                if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms() != null) {

                    for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().size(); k++) {

                        if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getReadYn().equals("N")) {

                            if (mac_list.equals("")) {
                                mac_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getMcIotMac();
                            } else {
                                mac_list = mac_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getMcIotMac();
                            }

                            if (msg_list.equals("")) {
                                msg_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getSensor();
                            } else {
                                msg_list = msg_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getSensor();
                            }
                        }
                    }
                }

                if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms() != null) {

                    for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().size(); k++) {

                        if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getReadYn().equals("N")) {

                            if (mac_list.equals("")) {
                                mac_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getMcIotMac();
                            } else {
                                mac_list = mac_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getMcIotMac();
                            }

                            if (msg_list.equals("")) {
                                msg_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getSensor();
                            } else {
                                msg_list = msg_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getSensor();
                            }
                        }
                    }
                }
            }
        }

        if (TextUtils.isEmpty(mac_list)) {
            Common.getInstance().toastShow(getContext(), "해제 할 알람이 없습니다.");
            return;
        }

        String finalMac_list = mac_list;
        String finalMsg_list = msg_list;

        NoticeDialog dialog = new NoticeDialog(getContext());
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                int time = 60 * 60;

                HashMap<String, String> data = new HashMap<>();
                data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
                data.put("mac_list", finalMac_list);
                data.put("msg_list", finalMsg_list);
                data.put("delay_time", time + "");

                new ApiClient(data, "proc_admin_alarm_remove2", handler);
            }
        });
        dialog.show();
    }

    public void stop_Alarm(){

        if (MyApplication.alarm_thread != null)
            MyApplication.alarm_thread.stopForever();

        if (MyApplication.notify_manager != null)
            MyApplication.notify_manager.cancelAll();
    }

    public void refresh() {
        fa.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (report_yn.equals("N") && log_yn.equals("N")) {
                    Set_Alarms();
                }
            }
        });
    }

    public void init_Hdr() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == 1) {
                    String url = msg.getData().getString("url");

                    if (url.equals("proc_get_management_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        alarmList = new Gson().fromJson(result_item, new TypeToken<ArrayItem<AlarmDatum>>() {
                        }.getType());

                        if (alarmList.isSuccess()) {
                            alarm_listRV.setAdapter(managementAdapter);
                            managementAdapter.addItem(alarmList.getArrayitem());

                            int cnt = 0;
                            String stop_list = "";
                            for (int i = 0; i < alarmList.size(); i++) {

                                for (int j = 0; j < alarmList.getArrayitem().get(i).getAlarmList().size(); j++) {

                                    if (Integer.parseInt(alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtCnt()) > 0) {
                                        for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().size(); k++) {
                                            if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getCtAlarms().get(k).getReadYn().equals("N")) {
                                                cnt++;
                                            }
                                        }
                                    }

                                    if (Integer.parseInt(alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrCnt()) > 0) {
                                        for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().size(); k++) {
                                            if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrAlarms().get(k).getReadYn().equals("N")) {
                                                cnt++;
                                            }
                                        }
                                    }

                                    if (Integer.parseInt(alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinCnt()) > 0) {
                                        for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().size(); k++) {
                                            if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getPrMinAlarms().get(k).getReadYn().equals("N")) {
                                                cnt++;
                                            }
                                        }
                                    }

                                    if (Integer.parseInt(alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempCnt()) > 0) {
                                        for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().size(); k++) {
                                            if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getTempAlarms().get(k).getReadYn().equals("N")) {
                                                cnt++;
                                            }
                                        }
                                    }

                                    if (Integer.parseInt(alarmList.getArrayitem().get(i).getAlarmList().get(j).getServiceCnt()) > 0) {
                                        for (int k = 0; k < alarmList.getArrayitem().get(i).getAlarmList().get(j).getServiceAlarms().size(); k++) {
                                            if (alarmList.getArrayitem().get(i).getAlarmList().get(j).getServiceAlarms().get(k).getReadYn().equals("N")) {
                                                if (stop_list.equals("")) {
                                                    stop_list = alarmList.getArrayitem().get(i).getAlarmList().get(j).getServiceAlarms().get(k).getMclIdx();
                                                } else {
                                                    stop_list = stop_list + ", " + alarmList.getArrayitem().get(i).getAlarmList().get(j).getServiceAlarms().get(k).getMclIdx();
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (!stop_list.equals("")) {
                                HashMap<String, String> data = new HashMap<>();
                                data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                                data.put("mcl_idx_list", stop_list);
                                new ApiClient(data, "proc_admin_restart_alarm_remove", handler);
                            }

                            if (cnt == 0) {
                                stop_Alarm();

                            } else {
                                alarm_all_stop();
                            }

                        } else {
                            alarm_listRV.setAdapter(managementAdapter);
                            managementAdapter.clearItem();
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_admin_alarm_remove2")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Set_Alarms();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_get_machine_onoff_log2")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        logArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineLogData>>() {
                        }.getType());

                        if (logArray.isSuccess()) {
                            // 정렬 : myDate 내림차순 >> 23.01.05 user 요청으로 오름차순으로 바꿈
                            if (logArray.getArrayitem().size() > 1) {
                                Collections.sort(logArray.getArrayitem(), (o2, o1) ->
                                        o1.getInsDt().compareTo(o2.getInsDt())
                                );
                            }

                            logAdapter = new MachineLogAdapter(getContext());
                            alarm_listRV.setAdapter(logAdapter);
                            logAdapter.addItem(logArray.getArrayitem());

                        } else {
                            logAdapter = new MachineLogAdapter(getContext());
                            alarm_listRV.setAdapter(logAdapter);
                            logAdapter.clearItem();
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_admin_get_machine_with_mac")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        ArrayItem<MachineItem> machineItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                        }.getType());

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            MonitoringDialog dialog = new MonitoringDialog(getContext(), type, machineItem.get(0), time);
                            dialog.show();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_admin_alarm_remove_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        ArrayItem<AlarmData> removeList = new Gson().fromJson(result_item, new TypeToken<ArrayItem<AlarmData>>() {
                        }.getType());

                        if (removeList.isSuccess()) {
                            AlarmRemoveListDialog dialog = new AlarmRemoveListDialog(getContext(), removeList);
                            dialog.show();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_admin_company_info")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        company_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                        }.getType());

                        if (company_items.isSuccess()) {
                            alarm_listRV.setVisibility(View.GONE);
                            reportLL.setVisibility(View.VISIBLE);

                            cp_name_adapter = new ArrayAdapter<>(getContext(), R.layout.custom_spinner_item_black_txt_15);
                            cp_name_listSN.setAdapter(cp_name_adapter);
                            cp_name_adapter.add("지점 전체");
                            air_line_adapter = new ArrayAdapter<>(getContext(), R.layout.custom_spinner_item_black_txt_15);
                            cp_airlineSN.setAdapter(air_line_adapter);
                            air_line_adapter.add("라인 전체");

                            for (int i = 0; i < company_items.getArrayitem().size(); i++) {
                                cp_name_adapter.addAll(company_items.getArrayitem().get(i).getCpName());
                            }

                            Set_Reports();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_get_report_and_service_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        reportList = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ReportData>>() {
                        }.getType());

                        managementPB.setVisibility(View.GONE);
                    } else if (url.equals("proc_get_report_and_service_list2")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        reportList2 = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                        }.getType());

                        if (reportList2.isSuccess()) {
                            count = reportList2.size();
                            if (lastIndex != 0) {
                                reportAdapter2.addItemMore(reportList2.getArrayitem());
                            } else {
                                reportAdapter2.addItem(reportList2.getArrayitem());
                            }
                        } else {
                            reportAdapter2.clearItem();
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                        managementPB.setVisibility(View.GONE);

                    } else if (url.equals("proc_get_product_name")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        ArrayItem<ProductData> productData = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ProductData>>() {
                        }.getType());

                        if (productData.isSuccess()) {
                            ArrayAdapter<String> mc_name_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
                            mc_nameSN.setAdapter(mc_name_adapter);
                            mc_name_adapter.add("기기 전체");
                            mc_nameSN.setVisibility(View.VISIBLE);
                            ArraySet<String> mc_name_list = new ArraySet<>();
                            for (int i = 0; i < productData.size(); i++) {
                                mc_name_list.add(productData.getArrayitem().get(i).getPdName());
                            }
                            mc_name_adapter.addAll(mc_name_list);
                            mc_nameLL.setVisibility(View.VISIBLE);
                            Set_Reports();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            mc_nameLL.setVisibility(View.GONE);
                        }
                        managementPB.setVisibility(View.GONE);
                    }

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