package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

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.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.MachineLogData;
import kr.co.compcarecompany.Data.Product.AlarmData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.MachineAlarmAdapter;
import kr.co.compcarecompany.Util.Adapter.MachineLogAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.ReportDialog;
import kr.co.compcarecompany.Util.CustomView.ReportModifyDialog;
import kr.co.compcarecompany.Util.MyOnItemClick;

@SuppressLint("ValidFragment")
public class Machine_Alarm_Fragment extends Fragment {

    Handler handler;
    FragmentActivity fa;

    TextView all_alarm_removeTV, reportTV, outstanding_reportTV, complete_reportTV, iot_logTV;
    RecyclerView machine_alarmRV;
    ArrayItem<AlarmData> alarmArray;
    ArrayItem<MachineLogData> logArray;
    MachineAlarmAdapter alarmAdapter;
    MachineLogAdapter logAdapter;
    ArrayList<AlarmData> alarmList, iot_alarmList;
    SwipeRefreshLayout alarmSRL;
    ProgressBar machine_alarmPB;
    LinearLayout all_alarm_removeLL, reportLL;

    int time;
    String all_time, report_yn;
    boolean is_show_log = false;

    List<String> report_list = new ArrayList<>();

    @SuppressLint("ValidFragment")
    public Machine_Alarm_Fragment(Handler handler) {
        this.handler = handler;
    }

    @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_machine_alarm, container, false);

        machine_alarmRV = v.findViewById(R.id.machine_alarmRV);
        all_alarm_removeTV = v.findViewById(R.id.all_alarm_removeTV);
        alarmSRL = v.findViewById(R.id.alarmSRL);
        reportTV = v.findViewById(R.id.reportTV);
        outstanding_reportTV = v.findViewById(R.id.outstanding_reportTV);
        complete_reportTV = v.findViewById(R.id.complete_reportTV);
        iot_logTV = v.findViewById(R.id.iot_logTV);
        machine_alarmPB = v.findViewById(R.id.machine_alarmPB);
        all_alarm_removeLL = v.findViewById(R.id.all_alarm_removeLL);
        reportLL = v.findViewById(R.id.reportLL);

        report_yn = "N";

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

    void Set_Alarms() {

        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        data.put("report_yn", report_yn);
//        new ApiClient(data, "proc_get_alarm_list", handler);
    }

    @Override
    public void onResume() {
        super.onResume();
        outstanding_reportTV.setTextColor(getContext().getResources().getColor(R.color.white));
        outstanding_reportTV.setBackgroundResource(R.drawable.bg_round_purple_except_right);
        complete_reportTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
        complete_reportTV.setBackgroundResource(R.color.white);
        iot_logTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
        iot_logTV.setBackgroundResource(R.drawable.bg_round_white_except_left);

        reportTV.setVisibility(View.VISIBLE);
        reportLL.setVisibility(View.VISIBLE);
        all_alarm_removeLL.setVisibility(View.VISIBLE);
        report_yn = "N";
        Set_Alarms();
    }

    void init_Listener() {

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

        alarmAdapter = new MachineAlarmAdapter(getContext(), new MyOnItemClick() {
            @Override
            public void onClick(Bundle value) {

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

                        HashMap<String, String> data = new HashMap<>();
                        data.put("mac", value.getString("mac"));
                        data.put("msg", value.getString("msg"));
                        data.put("mcl_idx", value.getString("mcl_idx"));
                        data.put("delay_time", time + "");

                        new ApiClient(data, "proc_mqtt_care_push_stop", handler);
                        new ApiClient(data, "proc_machine_alarm_remove", handler);

                        dialog.dismiss();
                    }
                });
                AlertDialog alertDialog = dialogBuilder.create();
                alertDialog.show();
            }
        }, new MachineAlarmAdapter.reportListener() {
            @Override
            public void clickBtn(Bundle bundle) {

                if (bundle.getString("sensor").equals("0") && bundle.get("report_yn").equals("N")) {

                    for (int i = 0; i < alarmArray.size(); i++) {
                        if (alarmArray.getArrayitem().get(i).getMclIdx().equals(bundle.getString("mcl_idx"))) {
                            alarmArray.getArrayitem().get(i).setChecked(true);
                            break;
                        }
                    }

//                    }
//                    ReportDialog dialog = new ReportDialog(getContext(), handler, "[" + bundle.getString("mcl_idx") + "]", fa.userItem.getArrayitem().getAgIdx(), fa.userItem.getArrayitem().getPtIdx(),
////                            fa.userItem.getArrayitem().getMbId(), alarmArray, fa);
////                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
////                        @Override
////                        public void onDismiss(DialogInterface dialog) {
////                            Set_Alarms();
////                        }
////                    });
////                    dialog.show();

                } else {
                    ReportModifyDialog dialog = new ReportModifyDialog(getContext(), handler, bundle.getString("ar_idx"), fa.userItem.getArrayitem().getPtIdx(),
                            fa.userItem.getArrayitem().getAgIdx(), fa.userItem.getArrayitem().getMbId(), fa);
                    dialog.show();
                }
            }
        });

        logAdapter = new MachineLogAdapter(getContext());

        all_alarm_removeLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (machine_alarmPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(getContext(), "데이터를 가져오는 중입니다.");
                }

                if (alarmList.size() == 0) {
                    Common.getInstance().toastShow(getContext(), "이미 알람이 전부 해제되었습니다.");
                    return;
                }

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

                        HashMap<String, String> data = new HashMap<>();
                        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                        data.put("delay_time", time + "");
//                        data.put("delay_time", items[which]);
                        all_time = time + "";

                        new ApiClient(data, "proc_machine_alarm_all_remove", handler);

                        dialog.dismiss();
                    }
                });

                AlertDialog alertDialog = dialogBuilder.create();
                alertDialog.show();
            }
        });

        //최상단, 최하단에서 스와이프 했을 경우 갱신
        alarmSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (is_show_log) {
                    HashMap<String, String> data = new HashMap<>();
                    data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                    new ApiClient(data, "proc_get_machine_onoff_log2", handler);

                } else {
                    Set_Alarms();
                }
                Common.getInstance().toastShow(getContext(), "새로고침 완료");
                alarmSRL.setRefreshing(false);
            }
        });

        //일지작성 클릭 리스너
        reportLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (machine_alarmPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(getContext(), "데이터를 가져오는 중입니다.");
                }

                if (alarmArray == null) {
                    Common.getInstance().toastShow(getContext(), "작성할 업무가 없습니다.");
                    return;
                }

                report_list.clear();

                for (int i = 0; i < alarmArray.size(); i++) {
                    if (alarmArray.getArrayitem().get(i).isChecked()) {

                        if (alarmArray.getArrayitem().get(i).getReadYn().equals("N")) {
                            Common.getInstance().toastShow(getContext(), "알람을 먼저 해제 한 후 일지를 작성해야 합니다.");
                            return;
                        }
                        report_list.add(alarmArray.getArrayitem().get(i).getMclIdx());
                    }
                }

                if (report_list.size() == 0) {
                    Common.getInstance().toastShow(getContext(), "일지를 작성할 알람을 선택해주세요.");
                    return;
                }

//                ReportDialog dialog = new ReportDialog(getContext(), handler, report_list.toString(), fa.userItem.getArrayitem().getAgIdx(), fa.userItem.getArrayitem().getPtIdx(),
//                        fa.userItem.getArrayitem().getMbId(), alarmArray, fa);
//                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                    @Override
//                    public void onDismiss(DialogInterface dialog) {
//                        Set_Alarms();
//                    }
//                });
//                dialog.show();
            }
        });

        //미결버튼 클릭 리스너
        outstanding_reportTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (machine_alarmPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(getContext(), "데이터를 가져오는 중입니다.");
                }
                machine_alarmPB.setVisibility(View.VISIBLE);
                alarmAdapter.clearItem();
                outstanding_reportTV.setTextColor(getContext().getResources().getColor(R.color.white));
                outstanding_reportTV.setBackgroundResource(R.drawable.bg_round_purple_except_right);
                complete_reportTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                complete_reportTV.setBackgroundResource(R.color.white);
                iot_logTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                iot_logTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                reportTV.setVisibility(View.VISIBLE);
                reportLL.setVisibility(View.VISIBLE);
                all_alarm_removeLL.setVisibility(View.VISIBLE);
                report_yn = "N";
                is_show_log = false;
                Set_Alarms();
            }
        });

        //작업함 버튼 클릭 리스너
        complete_reportTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (machine_alarmPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(getContext(), "데이터를 가져오는 중입니다.");
                }
                machine_alarmPB.setVisibility(View.VISIBLE);
                alarmAdapter.clearItem();
                complete_reportTV.setTextColor(getContext().getResources().getColor(R.color.white));
                complete_reportTV.setBackgroundResource(R.color.color_bg_purple);
                outstanding_reportTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                outstanding_reportTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                iot_logTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                iot_logTV.setBackgroundResource(R.drawable.bg_round_white_except_left);
                reportTV.setVisibility(View.GONE);
                reportLL.setVisibility(View.GONE);
                all_alarm_removeLL.setVisibility(View.GONE);
                report_yn = "Y";
                is_show_log = false;
                Set_Alarms();
            }
        });

        //iot
        iot_logTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (machine_alarmPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(getContext(), "데이터를 가져오는 중입니다.");
                }
                machine_alarmPB.setVisibility(View.VISIBLE);
                alarmAdapter.clearItem();
                outstanding_reportTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                outstanding_reportTV.setBackgroundResource(R.drawable.bg_round_white_except_right);
                complete_reportTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_purple));
                complete_reportTV.setBackgroundResource(R.color.white);
                iot_logTV.setTextColor(getContext().getResources().getColor(R.color.white));
                iot_logTV.setBackgroundResource(R.drawable.bg_round_purple_except_left);
                reportTV.setVisibility(View.GONE);
                reportLL.setVisibility(View.GONE);
                all_alarm_removeLL.setVisibility(View.GONE);
                is_show_log = true;

                HashMap<String, String> data = new HashMap<>();
                data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                new ApiClient(data, "proc_get_machine_onoff_log2", handler);
            }
        });
    }

    void Set_Contents() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        machine_alarmRV.setLayoutManager(layoutManager);
        machine_alarmRV.setAdapter(alarmAdapter);
        alarmAdapter.addItem(alarmArray.getArrayitem());

        if (iot_alarmList != null && iot_alarmList.size() > 0) {
            iot_alarm_move();
        }
        machine_alarmPB.setVisibility(View.GONE);
    }

    void Set_log() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        machine_alarmRV.setLayoutManager(layoutManager);
        machine_alarmRV.setAdapter(logAdapter);
        logAdapter.addItem(logArray.getArrayitem());

        machine_alarmPB.setVisibility(View.GONE);
    }

    void iot_alarm_move() {

        String mcl_idx_list = "";
        for (int i = 0; i < iot_alarmList.size(); i++) {
            if (i > 0) {
                mcl_idx_list = mcl_idx_list + ", " + iot_alarmList.get(i).getMclIdx();

            } else {
                mcl_idx_list = iot_alarmList.get(i).getMclIdx();
            }
        }

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

    public void stop_Alarm() {

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

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

    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_alarm_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        //모니터링 데이터를 정상적으로 가져왔을 때
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            alarmArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<AlarmData>>() {
                            }.getType());

                            if (report_yn.equals("N") && !is_show_log) {

                                int cnt = 0;
                                alarmList = new ArrayList<>();
                                iot_alarmList = new ArrayList<>();

                                for (int i = 0; i < alarmArray.size(); i++) {
                                    if (alarmArray.getArrayitem().get(i).getReadYn() != null && alarmArray.getArrayitem().get(i).getReadYn().equals("N")) {
                                        alarmList.add(alarmArray.getArrayitem().get(i));
                                        cnt++;
                                    }

                                    if (alarmArray.getArrayitem().get(i).getSensor().equals("0") && alarmArray.getArrayitem().get(i).getReportYn().equals("N")) {
                                        iot_alarmList.add(alarmArray.getArrayitem().get(i));

                                    } else if (alarmArray.getArrayitem().get(i).getSensor().equals("100") || alarmArray.getArrayitem().get(i).getSensor().equals("200")
                                    || alarmArray.getArrayitem().get(i).getSensor().equals("300") || alarmArray.getArrayitem().get(i).getSensor().equals("400")
                                ||alarmArray.getArrayitem().get(i).getSensor().equals("500") || alarmArray.getArrayitem().get(i).getSensor().equals("600")) {
                                        iot_alarmList.add(alarmArray.getArrayitem().get(i));
                                    }
                                }

                                if (cnt == 0) {
                                    stop_Alarm();
                                }
                            }
                            Set_Contents();
                        }
                        //모니터링 데이터를 가져오는 것을 실패했을 때
                        else {

                            if (report_yn.equals("N") && !is_show_log) {
                                stop_Alarm();
                            }
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            if (alarmArray != null)
                                alarmArray.clear();
                            alarmAdapter.clearItem();
                            logAdapter.clearItem();
                            machine_alarmPB.setVisibility(View.GONE);
                        }
                    } else if (url.equals("proc_machine_alarm_remove")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "성공했습니다.", Toast.LENGTH_SHORT).show();
                            Set_Alarms();

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

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "성공했습니다.", Toast.LENGTH_SHORT).show();

                            for (int i = 0; i < alarmList.size(); i++) {
                                HashMap<String, String> data = new HashMap<>();
                                data.put("mac", alarmList.get(i).getMcIotMac());
                                data.put("msg", alarmList.get(i).getSensor());
                                data.put("delay_time", all_time);
                                new ApiClient(data, "proc_mqtt_care_push_stop", handler);
                            }

                            stop_Alarm();
                            Set_Alarms();

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

                    } else if (url.equals("proc_get_machine_onoff_log")) {
                        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()) {
                            Set_log();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            machine_alarmPB.setVisibility(View.GONE);
                            alarmAdapter.clearItem();
                            logAdapter.clearItem();
                        }
                    } 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 내림차순
                            if (logArray.getArrayitem().size() > 1) {
                                Collections.sort(logArray.getArrayitem(), (o1, o2) ->
                                        o1.getInsDt().compareTo(o2.getInsDt())
                                );
                            }
                            Set_log();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            machine_alarmPB.setVisibility(View.GONE);
                            alarmAdapter.clearItem();
                            logAdapter.clearItem();
                        }
                    }
                } else {
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    machine_alarmPB.setVisibility(View.GONE);
                }
            }
        };
    }
}