package kr.co.compcarecompany.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
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.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.SnapHelper;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
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.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.ortiz.touchview.TouchImageView;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import info.mqtt.android.service.MqttAndroidClient;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.FileDatum;
import kr.co.compcarecompany.Data.Product.AlMachineDatum;
import kr.co.compcarecompany.Data.Product.ExchangeData;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.Fragment.FragmentIntentIntegrator;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ContentAdapter;
import kr.co.compcarecompany.Util.Adapter.IoTProdDetailRecyclerAdapter;
import kr.co.compcarecompany.Util.Adapter.MainTapListAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.BackPressCloseHandler;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AddIotDialog;
import kr.co.compcarecompany.Util.CustomView.AirLeakDialog;
import kr.co.compcarecompany.Util.CustomView.ExchangeLogDialog;
import kr.co.compcarecompany.Util.CustomView.MonitoringDialog;
import kr.co.compcarecompany.Util.CustomView.MonitoringReportDialog;
import kr.co.compcarecompany.Util.CustomView.RelayProgressDialog;
import kr.co.compcarecompany.Util.Firebase.MyFirebaseMessagingService;
import kr.co.compcarecompany.Util.MyOnItemClick;
import kr.co.compcarecompany.Util.Service.MonitoringThread;

public class MainActivity extends ActivityBasic implements MyOnItemClick {

    TextView main_pt_nameTV, main_cp_nameTV, main_pt_ceoTV, main_pt_codeTV, main_pt_addressTV, main_pt_address_subTV,
            main_service_listTV, main_photo_memoTV, main_no_dataTV, main_add_placeTV, alarm_countTV, service_countTV;
    LinearLayout main_my_pageLL, main_service_centerLL, main_pt_infoLL, main_pt_info_topLL, main_lock_settingLL, main_alarmLL, main_serviceLL, main_add_machineLL, main_company_managementLL;
    RecyclerView main_tap_listRV, main_tap_contentRV;
    ArrayItem<CompanyData> companyItems;
    CompanyData companyData;
    MainTapListAdapter tap_list_adapter;
    ArrayItem_<CompanyData> machineData;
    ProgressBar mainPB;
    ImageView main_pt_info_toggleIV;
    Handler hdr;
    MonitoringThread thread;
    ArrayList<AlMachineDatum> arr;
    NestedScrollView mainSV;
    private BackPressCloseHandler backPressCloseHandler;
    int air_line_position;
    SwipeRefreshLayout mainSRL;
    ContentAdapter contentAdapter;
    LinearLayoutManager content_manager;
    ArrayList<MachineItem> machineItems;
    MainActivity.MonitoringServiceHandler holder_hdr;
    Bundle iot_bundle;
    ProgressDialog progressDialog;
    int finalPosition;
    int relay = -1;
    boolean relay_setting = false;
    boolean pressed_emergency = false;
    private Thread timer_thread;
    boolean is_tap_first_item = true;
    String mc_idx, mc_iot_mac;
    boolean pressed_option = false;
    boolean is_show_dlg = false;
    //    MqttHelper mqttHelper;
    boolean is_horizontal = false;
    SnapHelper snapHelper;
    ImageView main_slide_modeIV;
    RelayProgressDialog relay_dialog;
    IoTProdDetailRecyclerAdapter ioTProdRecyclerAdapter;
    MqttAndroidClient mqttAndroidClient;
    int before_i = -1, before_k = -1;
    MachineItem report_machine_data;

    @Override
    protected void init() {

        main_pt_info_topLL = findViewById(R.id.main_pt_info_topLL);
        main_pt_info_toggleIV = findViewById(R.id.main_pt_info_toggleIV);
        main_pt_infoLL = findViewById(R.id.main_pt_infoLL);
        main_pt_nameTV = findViewById(R.id.main_pt_nameTV);
        main_cp_nameTV = findViewById(R.id.main_cp_nameTV);

        mainSV = findViewById(R.id.mainSV);
        mainSRL = findViewById(R.id.mainSRL);

        main_pt_ceoTV = findViewById(R.id.main_pt_ceoTV);
        main_pt_codeTV = findViewById(R.id.main_pt_codeTV);
        main_pt_addressTV = findViewById(R.id.main_pt_addressTV);
        main_pt_address_subTV = findViewById(R.id.main_pt_address_subTV);
        main_service_listTV = findViewById(R.id.main_service_listTV);
        main_photo_memoTV = findViewById(R.id.main_photo_memoTV);
        main_add_placeTV = findViewById(R.id.main_add_placeTV);
        main_my_pageLL = findViewById(R.id.main_my_pageLL);
        main_alarmLL = findViewById(R.id.main_alarmLL);
        main_serviceLL = findViewById(R.id.main_serviceLL);
        main_add_machineLL = findViewById(R.id.main_add_machineLL);
        main_service_centerLL = findViewById(R.id.main_service_centerLL);
        main_tap_listRV = findViewById(R.id.main_tap_listRV);
        main_tap_contentRV = findViewById(R.id.main_tap_contentRV);
        mainPB = findViewById(R.id.mainPB);
        main_no_dataTV = findViewById(R.id.main_no_dataTV);
        main_lock_settingLL = findViewById(R.id.main_lock_settingLL);
        alarm_countTV = findViewById(R.id.alarm_countTV);
        service_countTV = findViewById(R.id.service_countTV);
        main_company_managementLL = findViewById(R.id.main_company_managementLL);
        main_slide_modeIV = findViewById(R.id.main_slide_modeIV);

        backPressCloseHandler = new BackPressCloseHandler(this);

        mainPB.setVisibility(View.VISIBLE);

        MyApplication.my_thread.clear();

        Intent intent = getIntent();

        companyData = (CompanyData) intent.getSerializableExtra("companyData");
        snapHelper = new PagerSnapHelper();

        Set_Contents();
        init_Listener();
        init_Hdr();

    }

    void Set_Contents() {
        //상단 회사정보 탭
        main_pt_nameTV.setText(companyData.getPtName());
        main_cp_nameTV.setText(companyData.getCpName());
        main_pt_ceoTV.setText(companyData.getPtCeo());
        main_pt_codeTV.setText(companyData.getPtCode());
        main_pt_addressTV.setText(companyData.getCpAddr());
        main_pt_address_subTV.setText(companyData.getCpAddrSub());

    }

    void Set_TapList() {
        //지점 탭 리스트
        tap_list_adapter = new MainTapListAdapter(context, this::onClick);
        main_tap_listRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        main_tap_listRV.setItemViewCacheSize(companyItems.size());
        main_tap_listRV.setAdapter(tap_list_adapter);
        tap_list_adapter.addItems(companyItems.getArrayitem());

        if (!Common.getInstance().getPref(context, "saved_alarm_setting", true)) {
            for (int i = 0; i < companyItems.size(); i++) {
                Common.getInstance().setPref(context, companyItems.get(i).getCpIdx(), true);
            }
            Common.getInstance().setPref(context, "saved_alarm_setting", true);
        }
    }

    void Set_Machine() {

        //메인화면 로딩시 첫번째 아이템이 mac주소가 있으면 데이터를 가져온다.
        holder_hdr = new MainActivity.MonitoringServiceHandler();

        if (is_tap_first_item) {

            //전체 탭일 경우
            ioTProdRecyclerAdapter = new IoTProdDetailRecyclerAdapter(this, handler);
            ioTProdRecyclerAdapter.addAll(machineData.getArrayitem().getMachineAll());
            main_tap_contentRV.setAdapter(ioTProdRecyclerAdapter);

            snapHelper.attachToRecyclerView(null);
            main_slide_modeIV.setVisibility(View.GONE);
            content_manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
            main_tap_contentRV.setLayoutManager(content_manager);

            contentAdapter = null;

            main_no_dataTV.setVisibility(View.GONE);
            main_tap_contentRV.setVisibility(View.VISIBLE);
            mainPB.setVisibility(View.GONE);
            main_tap_contentRV.setItemViewCacheSize(machineData.getArrayitem().getMachineAll().size());

            RecyclerView.ItemAnimator animator = main_tap_contentRV.getItemAnimator();
            if (animator instanceof SimpleItemAnimator) {
                ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
            }

            is_horizontal = false;

            if (machineData.getArrayitem().getMachineAll() != null && machineData.getArrayitem().getMachineAll().size() > 0 && machineData.getArrayitem().getMachineAll().get(0).getMcIotMac() != null) {
                start_thread(0, 0, holder_hdr, machineData);
                air_line_position = -1;
                finalPosition = 0;

            } else {
                main_no_dataTV.setVisibility(View.VISIBLE);
                main_tap_contentRV.setVisibility(View.GONE);
                main_no_dataTV.setText("IoT가 등록된 기기가 없습니다.");
            }

        } else {
            //전체 탭이 아닐 경우

            if (MyApplication.serviceThreads.size() > 0) {

                for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                    MyApplication.serviceThreads.get(i).stopForever();

                    if (ioTProdRecyclerAdapter != null) {
                        int thread_position = MyApplication.serviceThreads.get(i).getPosition();
                        machineData.getArrayitem().getMachineAll().get(thread_position).setRunning(false);
                        machineData.getArrayitem().getMachineAll().get(thread_position).setMonitoring(null);
                        ioTProdRecyclerAdapter.notifyItemChanged(thread_position, null);
                    }
                }
                MyApplication.serviceThreads = new ArrayList<>();
            }

            if (thread != null) {

                if (contentAdapter != null) {
                    machineItems.get(air_line_position).setRunning(false);
                    machineItems.get(air_line_position).setMonitoring(null);
                    contentAdapter.notifyItemChanged(air_line_position, null);
                }
                thread.stopForever();
                thread = null;
            }

            machineItems = new ArrayList<>();

            for (int i = 0; i < machineData.getArrayitem().getAlMachineData().size(); i++) {
                machineItems.addAll(machineData.getArrayitem().getAlMachineData().get(i).getItems());
            }

            String cp_air_line = machineData.getArrayitem().getCpAirline().toString();
            String[] air_lines = cp_air_line.split(",");

            for (String air_line : air_lines) {

                int cnt = 1;
                for (int i = 0; i < machineItems.size(); i++) {

                    if (machineItems.get(i).getMcAirline().equals(air_line)) {
                        machineItems.get(i).setIndex(cnt);

                        if (cnt == 1) {
                            machineItems.get(i).setShow_position(true);
                            machineItems.get(i).setLast_position(true);

                        } else if (cnt > 1) {
                            machineItems.get(i - 1).setLast_position(false);
                            machineItems.get(i).setLast_position(true);
                        }
                        cnt++;
                    }
                }
            }

            if (machineItems != null && machineItems.get(0).getMcIotMac() != null) {
                thread = new MonitoringThread(holder_hdr, "monitoring", machineItems.get(0).getMcIotMac(), "0");
                air_line_position = 0;
                finalPosition = 0;
                thread.start();
            }

            if (machineItems != null && machineItems.size() > 0) {
                main_slide_modeIV.setVisibility(View.VISIBLE);

            } else {
                main_slide_modeIV.setVisibility(View.GONE);
            }

            ioTProdRecyclerAdapter = null;
            contentAdapter = new ContentAdapter(context, is_horizontal, new ContentAdapter.clickListener() {
                @Override
                public void option_clickBtn(Bundle bundle) {
                    Intent intent = new Intent(context, FragmentActivity.class);
                    intent.putExtra("title", "기계 옵션설정");
                    intent.putExtra("type", "option_machine");
                    intent.putExtra("value1", bundle.getString("mc_idx"));
                    intent.putExtra("value2", machineData.getArrayitem().getCpAirline().toString());
                    startActivity(intent);
                }

                @Override
                public void chart_clickBtn(Bundle bundle) {
                    String mc_idx = bundle.getString("mc_idx");
                    String mac = bundle.getString("mac");
                    MachineItem machineItem = new MachineItem();

                    for (int i = 0; i < machineItems.size(); i++) {
                        if (machineItems.get(i).getMcIdx().equals(mc_idx)) {
                            machineItem = machineItems.get(i);
                        }
                    }

                    if (TextUtils.isEmpty(mac) || mac.equals("0")) {
                        Toast.makeText(context, "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();

                    } else {

                        MonitoringDialog dialog = new MonitoringDialog(context, userItem.getArrayitem().getAgIdx(), bundle.getString("pt_idx"), bundle.getString("cp_idx"),
                                mc_idx, bundle.getString("chart_type"), mac, machineItem);
                        dialog.show();
                    }
                }

                @Override
                public void power_clickBtn(Bundle bundle) {
                    String mac = bundle.getString("mac");
                    String del_flag = bundle.getString("del_flag"); // ON, OFF 상태
                    String return_yn = bundle.getString("return");
                    //String inverter_error = bundle.getString("inverter_error");
                    //String power_error = bundle.getString("power_error");

                    if (!TextUtils.isEmpty(return_yn) && return_yn.equals("true")) {
                        Toast.makeText(getApplicationContext(), "IoT의 인터넷 연결상태를 확인해주세요.", Toast.LENGTH_LONG).show();
                        return;
                    }

                    // 23-03-27 인버터, 파워 error 시 on/off disable 해제 요청하심
                    /*
                    if (!TextUtils.isEmpty(inverter_error) && inverter_error.equals("true")) {
                        Toast.makeText(getApplicationContext(), "기계 고장이 발생하였습니다. 기계 점검이 필요합니다.", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (!TextUtils.isEmpty(power_error) && power_error.equals("true")) {
                        Toast.makeText(getApplicationContext(), "전력공급에 문제가 발생하였습니다. 기계 점검이 필요합니다.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    */

                    if (mqttAndroidClient == null) {
                        Toast.makeText(getApplicationContext(), "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.", Toast.LENGTH_LONG).show();
                        mqtt_connect();
                        return;
                    }

                    if (del_flag.equals("MM")) {
                        relay = 1;
                    } else {
                        relay = 0;
                    }

                    if (TextUtils.isEmpty(mac) || mac.equals("0")) {
                        Toast.makeText(context, "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    String msg = "{'MAC':'" + mac + "', 'opt' : 5, 'control' :{'relay_control':" + relay + "}}";
                    JsonParser parser = new JsonParser();
                    Object obj = parser.parse(msg);

                    Common.getInstance().publishMessage("control/" + mac, obj.toString(), mqttAndroidClient);
                    Common.getInstance().subscribeTopic("check/" + mac, mqttAndroidClient);
                    relay_setting = true;

                    relay_dialog = new RelayProgressDialog(context, mac, new RelayProgressDialog.clickListener() {
                        @Override
                        public void clickBtn() {

                            pressed_emergency = true;
                            relay = -1;

                            String msg = "{'MAC':'" + mac + "', 'opt' : 5, 'control' :{'relay_control': 0 }}";
                            JsonParser parser = new JsonParser();
                            Object obj = parser.parse(msg);

                            Common.getInstance().publishMessage("control/" + mac, obj.toString(), mqttAndroidClient);
                            Common.getInstance().publishMessage("control/" + mac, obj.toString(), mqttAndroidClient);
                            Common.getInstance().publishMessage("control/" + mac, obj.toString(), mqttAndroidClient);
                        }
                    });
                    relay_dialog.show();

                    timer_thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);

                                if (relay_setting) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Common.getInstance().unSubscribeTopic("check/" + mac, mqttAndroidClient);
                                            Common.getInstance().toastShow(context, "원격제어에 실패했습니다.\nIoT 기기의 인터넷 연결을 확인해주세요.");
                                            relay_dialog.dismiss();
                                            MyApplication.stop_ui_change = false;
                                            start_thread(finalPosition);
                                        }
                                    });
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    });

                    timer_thread.start();
                }

                @Override
                public void iot_clickBtn(Bundle bundle) {
                    is_show_dlg = true;

                    Bundle new_bundle = new Bundle();
                    new_bundle.putString("mc_idx", bundle.getString("mc_idx"));
                    new_bundle.putString("pt_idx", bundle.getString("pt_idx"));
                    new_bundle.putString("cp_idx", bundle.getString("cp_idx"));
                    new_bundle.putString("mc_airline", bundle.getString("mc_airline"));

                    iot_bundle = new_bundle;

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("QR 코드를 등록하시겠습니까?");
                    dialogBuilder.setPositiveButton("등록", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
                            integrator.setCaptureActivity(QRCodeActivity.class);
                            integrator.setBarcodeImageEnabled(true);
                            integrator.setOrientationLocked(false);
                            integrator.initiateScan();
                        }
                    });

                    dialogBuilder.setNegativeButton("등록 안함", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            AddIotDialog dialog = new AddIotDialog(context, hdr, companyData.getAgIdx(), bundle.getString("pt_idx"), bundle.getString("cp_idx"),
                                    bundle.getString("mc_idx"), bundle.getString("mc_airline"));
                            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    if (thread != null) {
                                        thread.stopForever();
                                        thread = null;
                                    }

                                    if (MyApplication.serviceThreads.size() > 0) {
                                        for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                                            MyApplication.serviceThreads.get(i).stopForever();
                                        }
                                        MyApplication.serviceThreads = new ArrayList<>();
                                    }

                                    MyApplication.my_thread.clear();
                                    Get_Company();
                                }
                            });
                            dialog.show();
                        }
                    });
                    dialogBuilder.show();
                }

                @Override
                public void schedule_clickBtn(Bundle bundle) {
                    String return_yn = bundle.getString("return");
                  //  String inverter_error = bundle.getString("inverter_error");
                  //  String power_error = bundle.getString("power_error");

                    if (!TextUtils.isEmpty(return_yn) && return_yn.equals("true")) {
                        Toast.makeText(getApplicationContext(), "IoT의 인터넷 연결상태를 확인해주세요.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 23-03-27 인버터, 파워 error 시 on/off disable 해제 요청하심
                    /*
                    if (!TextUtils.isEmpty(inverter_error) && inverter_error.equals("true")) {
                        Toast.makeText(getApplicationContext(), "기계 고장이 발생하였습니다. 기계 점검이 필요합니다.", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (!TextUtils.isEmpty(power_error) && power_error.equals("true")) {
                        Toast.makeText(getApplicationContext(), "전력공급에 문제가 발생하였습니다. 기계 점검이 필요합니다.", Toast.LENGTH_LONG).show();
                        return;
                    }
                     */

                    Intent intent = new Intent(context, FragmentActivity.class);
                    intent.putExtra("title", "원격운전 스케줄 설정");
                    intent.putExtra("type", "relay_schedule");
                    intent.putExtra("value1", bundle.getString("mc_idx"));
                    intent.putExtra("value2", bundle.getString("mc_iot_mac"));
                    intent.putExtra("value3", bundle.getString("mc_schedule_yn"));
                    startActivity(intent);
                }

                @Override
                public void image_clickBtn(ArrayList<FileDatum> photo_data) {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                    AlertDialog dig = dialogBuilder.create();
                    dig.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

                    View view = LayoutInflater.from(context).inflate(R.layout.dlg_image, null);
                    TouchImageView iv = view.findViewById(R.id.imageview);
                    dig.setView(view);

                    String machine_uri = "https://www.compcare.co.kr/uploads/machine/" + photo_data.get(0).getPfiFilename();
                    Glide.with(Objects.requireNonNull(context)).load(Uri.parse(machine_uri)).into(iv);
                    dig.show();
                }

                @Override
                public void report_clickBtn(MachineItem item) {
                    report_machine_data = item;

                    HashMap<String, String> data = new HashMap<>();
                    data.put("ag_idx", companyData.getAgIdx());
                    data.put("pt_idx", userItem.getArrayitem().getPtIdx());
                    data.put("mc_idx", item.getMcIdx());
                    new ApiClient(data, "proc_get_partner_machines", handler);
                }

                @Override
                public void initial_clickBtn(String mc_iot_mac) {
                    mainPB.setVisibility(View.VISIBLE);

                    String msg = "{'MAC' : '" + mc_iot_mac + "', 'opt' : 8}";
                    JsonParser parser = new JsonParser();
                    Object obj = parser.parse(msg);

                    Toast.makeText(context, "차트를 생성하고 있습니다. 잠시 기다려주세요...", Toast.LENGTH_SHORT).show();

                    if (mqttAndroidClient != null) {
                        Common.getInstance().publishMessage("control/" + mc_iot_mac, obj.toString(), mqttAndroidClient);

                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Common.getInstance().subscribeTopic("get_val/" + mc_iot_mac, mqttAndroidClient);
                            }
                        }, 500);

                        timer_thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(3000);
                                    Common.getInstance().unSubscribeTopic("get_val/" + mc_iot_mac, mqttAndroidClient);
                                    Handler handler1 = new Handler(Looper.getMainLooper());
                                    handler1.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Common.getInstance().toastShow(context, "IoT의 인터넷 연결을 확인해주세요.");
                                            mainPB.setVisibility(View.GONE);

                                        }
                                    }, 0);

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

                            }
                        });

                        timer_thread.start();

                    } else {
                        Common.getInstance().toastShow(context, "IoT의 인터넷 연결을 확인해주세요.");
                    }
                }

                @Override
                public void running_time_clickBtn(MachineItem item) {
                    //dialog show
                    HashMap<String, String> data = new HashMap<>();
                    data.put("ag_idx", item.getAgIdx());
                    data.put("cp_idx", item.getCpIdx());
                    data.put("mc_idx", item.getMcIdx());
                    Log.d("데이터 확인@@@@", data.toString());
                    new ApiClient(data, "proc_get_exchange_log", handler);

                }
            });

            main_tap_contentRV.setAdapter(contentAdapter);

            if (is_horizontal) {
                content_manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
                main_slide_modeIV.setImageResource(R.drawable.icon_slide_vertical_white);
                snapHelper.attachToRecyclerView(main_tap_contentRV);

            } else {
                content_manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
                main_slide_modeIV.setImageResource(R.drawable.icon_slide_horizontal_white);
                snapHelper.attachToRecyclerView(null);

            }
            main_tap_contentRV.setLayoutManager(content_manager);
            contentAdapter.addItem(machineItems);

            main_no_dataTV.setVisibility(View.GONE);
            main_tap_contentRV.setVisibility(View.VISIBLE);
            mainPB.setVisibility(View.GONE);
            main_tap_contentRV.setItemViewCacheSize(machineItems.size());

            RecyclerView.ItemAnimator animator = main_tap_contentRV.getItemAnimator();
            if (animator instanceof SimpleItemAnimator) {
                ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
            }
        }

        main_tap_contentRV.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                mainSRL.setRefreshing(false);
                View child;

                if (is_tap_first_item && contentAdapter == null) {
                    child = recyclerView.findChildViewUnder(dx, dy);

                } else {
                    child = recyclerView.findChildViewUnder(dx+100, dy+500);
                }

                int position = recyclerView.getChildAdapterPosition(child);
                if (position < 0) position = 0;
                finalPosition = position;

                recyclerView.post(new Runnable() {
                    public void run() {

                        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        int firstVisible = layoutManager.findFirstVisibleItemPosition();
                        int lastVisible = layoutManager.findLastVisibleItemPosition();
                        if (firstVisible < 0) firstVisible = 0;
                        if (lastVisible < 0) lastVisible = 0;

                        if (is_horizontal) {

                            if (machineItems.get(firstVisible).getMcIotMac() != null) {
                                start_thread(firstVisible);
                            } else {
                                air_line_position = firstVisible;
                            }

                        } else if (is_tap_first_item && contentAdapter == null) {

                            start_thread(firstVisible, lastVisible, holder_hdr, machineData);

                        } else if (!is_tap_first_item && ioTProdRecyclerAdapter == null) {

                            if (!recyclerView.canScrollVertically(1)) {
                                finalPosition = machineItems.size() - 1;

                            } else if (!recyclerView.canScrollVertically(-1)) {
                                finalPosition = 0;
                            }

                            if (machineItems.get(finalPosition).getMcIotMac() != null) {
                                start_thread(finalPosition);

                            } else {
                                air_line_position = finalPosition;
                            }
                        }
                    }
                });
            }
        });

        mainPB.setVisibility(View.GONE);
    }

    void start_thread(int position) {

        if (air_line_position != position && !MyApplication.stop_ui_change) {

            if (MyApplication.serviceThreads.size() > 0) {

                for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                    MyApplication.serviceThreads.get(i).stopForever();
                    int thread_position = MyApplication.serviceThreads.get(i).getPosition();
                    machineData.getArrayitem().getMachineAll().get(thread_position).setRunning(false);
                    machineData.getArrayitem().getMachineAll().get(thread_position).setMonitoring(null);
                    if (ioTProdRecyclerAdapter != null) {
                        ioTProdRecyclerAdapter.notifyItemChanged(thread_position, null);
                    }
                }
                MyApplication.serviceThreads = new ArrayList<>();
            }

            if (thread != null) {

                if (contentAdapter != null) {
                    machineItems.get(air_line_position).setRunning(false);
                    machineItems.get(air_line_position).setMonitoring(null);
                    contentAdapter.notifyItemChanged(air_line_position, null);
                }
                thread.stopForever();
                thread = null;
            }

            thread = new MonitoringThread(holder_hdr, "monitoring", machineItems.get(position).getMcIotMac(), position + "");
            air_line_position = position;
            thread.start();
        }
    }

    void start_thread(int i, int k, MonitoringServiceHandler holder_hdr, ArrayItem_<CompanyData> data) {

        if (air_line_position != i || air_line_position == -1) {
            if (thread != null) {
                thread.stopForever();
                thread = null;
            }

            //전체 탭에서 위로 스크롤 했을 경우
            if (before_i >= 0 && before_i > i) {

                for (int n = 0; n < MyApplication.serviceThreads.size(); n++) {
                    int thread_position = MyApplication.serviceThreads.get(n).getPosition();

                    if (k < thread_position) {
                        MyApplication.serviceThreads.get(n).stopForever();
                        machineData.getArrayitem().getMachineAll().get(thread_position).setRunning(false);
                        machineData.getArrayitem().getMachineAll().get(thread_position).setMonitoring(null);
                        ioTProdRecyclerAdapter.notifyItemChanged(thread_position, null);
                    }
                }

                for (int h = i; h < before_i; h++) {
                    MonitoringThread thread = new MonitoringThread(holder_hdr, "monitoring", data.getArrayitem().getMachineAll().get(h).getMcIotMac(), (h) + "");
                    MyApplication.serviceThreads.add(thread);
                    thread.start();
                }

                //전체탭에서 아래로 스크롤 했을 경우
            } else if (before_i >= 0 && before_i < i) {

                for (int n = 0; n < MyApplication.serviceThreads.size(); n++) {
                    int thread_position = MyApplication.serviceThreads.get(n).getPosition();

                    if (i > thread_position) {
                        MyApplication.serviceThreads.get(n).stopForever();
                        machineData.getArrayitem().getMachineAll().get(thread_position).setRunning(false);
                        machineData.getArrayitem().getMachineAll().get(thread_position).setMonitoring(null);
                        ioTProdRecyclerAdapter.notifyItemChanged(thread_position, null);
                    }
                }

                for (int h = before_k + 1; h <= k; h++) {
                    MonitoringThread thread = new MonitoringThread(holder_hdr, "monitoring", data.getArrayitem().getMachineAll().get(h).getMcIotMac(), (h) + "");
                    MyApplication.serviceThreads.add(thread);
                    thread.start();
                }

            } else {
                //메인화면 전체탭에 처음 들어왔을 경우
                for (int h = i; h <= k; h++) {
                    MonitoringThread thread = new MonitoringThread(holder_hdr, "monitoring", data.getArrayitem().getMachineAll().get(h).getMcIotMac(), (h) + "");
                    MyApplication.serviceThreads.add(thread);
                    thread.start();
                }
            }

            before_i = i;
            before_k = k;

            air_line_position = i;
        }
    }

    class MonitoringServiceHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {

            String msg_data = msg.obj.toString();
            String get_mac = msg_data.substring(0, msg_data.indexOf("i"));
            String i = "";
            String k = "";

            HashMap<String, String> data = new HashMap<>();
            data.put("mac", get_mac);

            if (!msg_data.contains("k")) {
                i = msg_data.substring(msg_data.indexOf("i") + 1);
            } else {
                i = msg_data.substring(msg_data.indexOf("i") + 1, msg_data.indexOf("k"));
                k = msg_data.substring(msg_data.indexOf("k") + 1);
                data.put("k", k);
                data.put("type", "A");
            }

            data.put("i", i);
            new ApiClient(data, "proc_monitoring", hdr);
        }
    }
    public void init_Hdr() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                String url = msg.getData().getString("url");

                if (url.equals("proc_monitoring")) {
                    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());

                    String position = result_item.get("resultItem").getAsJsonObject().get("message").toString();
                    int position_i = -1;
                    int position_k = -1;

                    if (position.contains("i") && position.contains("k")) {
                        position_i = Integer.parseInt(position.substring(position.indexOf("i") + 1, position.indexOf("k")));
                        position_k = Integer.parseInt(position.substring(position.indexOf("k") + 1, position.length() - 1));

                    } else {
                        position_i = Integer.parseInt(result_item.get("resultItem").getAsJsonObject().get("message").getAsString());
                    }

                    //모니터링 데이터를 정상적으로 가져왔을 때
                    if (monitoringArray.isSuccess() && monitoringArray.getArrayitem() != null) {
                        if (is_tap_first_item && position_i > -1 && ioTProdRecyclerAdapter != null) {
                            machineData.getArrayitem().getMachineAll().get(position_i).setMonitoring(monitoringArray);
                            ioTProdRecyclerAdapter.notifyItemChanged(position_i);

                        } else if (!is_tap_first_item && position_i > -1 && contentAdapter != null) {
                            if (!MyApplication.doing_toggle) {
                                machineItems.get(position_i).setRunning(true);
                                machineItems.get(position_i).setMonitoring(monitoringArray);
                                contentAdapter.notifyItemChanged(position_i, null);
                            }
                            MyApplication.stop_ui_change = false;
                        }
                    }
                    //모니터링 데이터를 가져오는 것을 실패했을 때
                    else {
                        if (is_tap_first_item && position_i > -1 && ioTProdRecyclerAdapter != null) {
                            machineData.getArrayitem().getMachineAll().get(position_i).setMonitoring(null);
                            ioTProdRecyclerAdapter.notifyItemChanged(position_i);

                        } else if (!is_tap_first_item && position_i > -1 && contentAdapter != null) {
                            if (!MyApplication.doing_toggle) {
                                if (air_line_position < 0) air_line_position = 0;
                                machineItems.get(air_line_position).setRunning(true);
                                machineItems.get(air_line_position).setMonitoring(null);
                                if (contentAdapter != null) {
                                    contentAdapter.notifyItemChanged(air_line_position, null);
                                } else {
                                    ioTProdRecyclerAdapter.notifyItemChanged(air_line_position, null);
                                }
                            }
                            MyApplication.stop_ui_change = false;
                        }
                    }
                }
            }
        };
    }

    void Get_Partner() {

        if (userItem == null || userItem.getArrayitem() == null) {
            Intent i = context.getPackageManager().
                    getLaunchIntentForPackage(context.getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", userItem.getArrayitem().getAgIdx());
        data.put("pt_idx", userItem.getArrayitem().getPtIdx());
        data.put("type", "COMPANY");
        data.put("session_id", Common.getInstance().getPref(context, "session_id"));
        data.put("mb_id", userItem.getArrayitem().getMbId());
        new ApiClient(data, "proc_admin_partner_view2", handler);
    }

    public void Get_Company() {

        before_i = -1;
        before_k = -1;

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", companyData.getAgIdx());
        data.put("cp_idx", companyData.getCpIdx());
        new ApiClient(data, "proc_admin_company_view3", handler);
    }

    @Override
    protected void init_Listener() {

        //하단 메뉴 > 마이페이지 클릭리스너
        main_my_pageLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "마이페이지");
                intent.putExtra("type", "main_menu");
                intent.putExtra("value1", "1");
                intent.putExtra("value2", companyData);
                startActivity(intent);
            }
        });

        //하단 메뉴 > 기계 보안 클릭리스너 //2021.04.05 수정
        main_lock_settingLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "기계보안");
                intent.putExtra("type", "password_setting");
                intent.putExtra("value1", userItem.getArrayitem().getPartner().getPtMachinePw());
                startActivity(intent);
            }
        });

        //하단 메뉴 > 서비스 센터 클릭리스너
        main_service_centerLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "고객센터");
                intent.putExtra("type", "main_menu");
                intent.putExtra("value1", "2");
                startActivity(intent);
            }
        });

        //메인 메뉴 > 장소추가 클릭리스너
        main_add_placeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "장소 정보 수정");
                intent.putExtra("type", "place_adjust");
                intent.putExtra("value1", companyData);
                startActivity(intent);

            }
        });

        //하단 메뉴 > 머신 등록 클릭리스너
        main_add_machineLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "머신 등록");
                intent.putExtra("type", "add_machine");
                intent.putExtra("value1", companyData.getAgIdx());
                intent.putExtra("value2", companyData.getPtIdx());
                startActivity(intent);
            }
        });

        //하단 메뉴 > 지점 관리 클릭리스너
        main_company_managementLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                companyItems = null;

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "지점 관리");
                intent.putExtra("type", "company_management");
                startActivity(intent);
            }
        });


        //상단 회사정보 클릭리스너
        main_pt_info_toggleIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (main_pt_infoLL.getVisibility() == View.VISIBLE) {
                    main_pt_infoLL.setVisibility(View.GONE);
                    main_pt_info_toggleIV.setImageResource(R.drawable.arrow_down);
                    main_pt_info_topLL.setBackgroundResource(R.drawable.bg_round_dark_purple);

                } else {
                    main_pt_infoLL.setVisibility(View.VISIBLE);
                    main_pt_info_toggleIV.setImageResource(R.drawable.arrow_up);
                    main_pt_info_topLL.setBackgroundResource(R.drawable.bg_round_dark_purple_top);
                }
            }
        });

        //메인 메뉴 > 서비스 접수현황
        main_service_listTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "테스트");
                intent.putExtra("type", "test");
                startActivity(intent);
                finish();
            }
        });

        //최상단, 최하단에서 스와이프 했을 경우 갱신
        mainSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                mainSRL.setRefreshing(false);
                mainPB.setVisibility(View.VISIBLE);

                int position = -1;

                for (int i = 0; i < companyItems.size(); i++) {
                    if (companyItems.get(i).isSelected()) {
                        position = i;
                        break;
                    }
                }

                if (position == 0) {

                    is_tap_first_item = true;
                    if (ioTProdRecyclerAdapter != null) ioTProdRecyclerAdapter.clearItem();
                    companyData = companyItems.get(1);

                } else {
                    is_tap_first_item = false;
                    if (contentAdapter != null) contentAdapter.clearItem();
                    companyData = companyItems.get(position);
                }

                main_tap_contentRV.clearOnScrollListeners();

                if (thread != null) {
                    thread.stopForever();
                    thread = null;
                }

                if (MyApplication.serviceThreads.size() > 0) {

                    for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                        MyApplication.serviceThreads.get(i).stopForever();
                    }
                    MyApplication.serviceThreads = new ArrayList<>();
                }

                Get_Company();

            }
        });

        //하단메뉴 > 기계 알람 클릭 리스너
        main_alarmLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "기계 알림 내역");
                intent.putExtra("type", "machine_management");
                intent.putExtra("value1", companyData.getAgIdx());
                intent.putExtra("value2", companyData.getPtIdx());
                startActivity(intent);

            }
        });

        //하단메뉴 > 서비스 현황 클릭 리스너
        main_serviceLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "서비스 현황");
                intent.putExtra("type", "service_list");
                intent.putExtra("value1", companyData);
                startActivity(intent);
            }
        });

        //슬라이드 방향 클릭리스너
        main_slide_modeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is_horizontal = !is_horizontal;

                if (thread != null) {
                    thread.stopForever();
                    thread = null;
                }

                if (MyApplication.serviceThreads.size() > 0) {

                    for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                        MyApplication.serviceThreads.get(i).stopForever();
                    }
                    MyApplication.serviceThreads = new ArrayList<>();
                }

                Set_Machine();
            }
        });
    }

    @Override
    protected void getMessage(Message msg) {

        String url = msg.getData().getString("url");

        if (msg.what == 1) {

            if (url.equals("proc_admin_partner_view2")) {

                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                companyItems = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                }.getType());

                if (companyItems.isSuccess()) {

                    CompanyData all_company_data = new CompanyData();
                    all_company_data.setCpName("전체");
                    companyData = companyItems.get(0);
                    companyItems.addPosition(0, all_company_data);
                    companyItems.getArrayitem().get(0).setSelected(true);
                    Get_Company();

                } else {

                    Toast.makeText(context, msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                    main_tap_contentRV.setVisibility(View.GONE);
                    main_no_dataTV.setVisibility(View.VISIBLE);
                    mainPB.setVisibility(View.GONE);
                }

                Set_TapList();


            }

            else if (url.equals("proc_admin_company_view3"))
            {

                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                machineData = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                }.getType());

                Set_Contents();

                if (machineData.isSuccess()) {
                    //교번 연동 운전 23.08.05
                    /*
                    if (machineData.getArrayitem().getInterlockChange() != null)
                    {
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                        dialogBuilder.setTitle("콤프케어 작업자");
                        dialogBuilder.setMessage("교번운전이 실행되었습니다.");
                        dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                dialog.dismiss();
                            }
                        });
                        dialogBuilder.show();
                    }
                    */

                    //끝

                    if (Integer.parseInt(machineData.getArrayitem().getAlarmCount()) > 0) {
                        alarm_countTV.setVisibility(View.VISIBLE);
                        alarm_countTV.setText(machineData.getArrayitem().getAlarmCount());

                    } else {
                        alarm_countTV.setVisibility(View.GONE);
                    }

                    if (Integer.parseInt(machineData.getArrayitem().getServiceCount()) > 0) {
                        service_countTV.setVisibility(View.VISIBLE);
                        service_countTV.setText(machineData.getArrayitem().getServiceCount());

                    } else {
                        service_countTV.setVisibility(View.GONE);
                    }

                    Set_Machine();

                } else {

                    main_slide_modeIV.setVisibility(View.GONE);

                    if (machineData.getMessage().equals("999")) {
                        main_no_dataTV.setText("등록된 에어라인이 없습니다.");

                    } else if (machineData.getMessage().equals("000")) {
                        main_no_dataTV.setText("등록된 머신 데이터가 없습니다.");

                    } else {
                        main_no_dataTV.setText("등록된 본사정보가 없습니다.");
                    }
                    main_no_dataTV.setVisibility(View.VISIBLE);
                    main_tap_contentRV.setVisibility(View.GONE);
                }
                mainPB.setVisibility(View.GONE);

            } else if (url.equals("proc_mqtt_machine_onoff")) {

                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();

            } else if (url.equals("proc_mqtt_machine_care_value")) {
                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(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                }
            } else if (url.equals("proc_get_partner_machines")) {

                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 (report_machine_data == null) {
                    Common.getInstance().toastShow(context, "데이터가 올바르지 않습니다.");
                    return;
                }

                MonitoringReportDialog dialog = new MonitoringReportDialog(context, handler, report_machine_data, companyData.getCpName(), machineItem);
                dialog.show();
                mainPB.setVisibility(View.GONE);

            } else if (url.equals("proc_ble_machine_option_save")) {

                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                ArrayItem<MachineItem> machineItem222 = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                }.getType());

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

                    machineItems.get(finalPosition).setMcInitializationYn(machineItem222.get(0).getMcInitializationYn());
                    machineItems.get(finalPosition).setMcCurrent1Max(machineItem222.get(0).getMcCurrent1Max());
                    machineItems.get(finalPosition).setMcCurrent2Max(machineItem222.get(0).getMcCurrent2Max());
                    machineItems.get(finalPosition).setMcCurrent3Max(machineItem222.get(0).getMcCurrent3Max());
                    machineItems.get(finalPosition).setMcCurrent1Up(machineItem222.get(0).getMcCurrent1Up());
                    machineItems.get(finalPosition).setMcCurrent2Up(machineItem222.get(0).getMcCurrent2Up());
                    machineItems.get(finalPosition).setMcCurrent3Up(machineItem222.get(0).getMcCurrent3Up());

                    machineItems.get(finalPosition).setMcTempNtcDown(machineItem222.get(0).getMcTempNtcDown());
                    machineItems.get(finalPosition).setMcTempNtc2Down(machineItem222.get(0).getMcTempNtc2Down());
                    machineItems.get(finalPosition).setMcTempPtDown(machineItem222.get(0).getMcTempPtDown());
                    machineItems.get(finalPosition).setMcTempNtcUp(machineItem222.get(0).getMcTempNtcUp());
                    machineItems.get(finalPosition).setMcTempNtc2Up(machineItem222.get(0).getMcTempNtc2Up());
                    machineItems.get(finalPosition).setMcTempPtUp(machineItem222.get(0).getMcTempPtUp());
                    machineItems.get(finalPosition).setMcTempNtcMax(machineItem222.get(0).getMcTempNtcMax());
                    machineItems.get(finalPosition).setMcTempNtc2Max(machineItem222.get(0).getMcTempNtc2Max());
                    machineItems.get(finalPosition).setMcTempPtMax(machineItem222.get(0).getMcTempPtMax());

                    machineItems.get(finalPosition).setMcPressure1Up(machineItem222.get(0).getMcPressure1Up());
                    machineItems.get(finalPosition).setMcPressure2Up(machineItem222.get(0).getMcPressure2Up());
                    machineItems.get(finalPosition).setMcPressure3Up(machineItem222.get(0).getMcPressure3Up());
                    machineItems.get(finalPosition).setMcPressure1Max(machineItem222.get(0).getMcPressure1Max());
                    machineItems.get(finalPosition).setMcPressure2Max(machineItem222.get(0).getMcPressure2Max());
                    machineItems.get(finalPosition).setMcPressure3Max(machineItem222.get(0).getMcPressure3Max());

                    contentAdapter.notifyItemChanged(finalPosition);

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

                MyApplication.stop_ui_change = false;
                mainPB.setVisibility(View.GONE);

            } else if(url.equals("proc_get_exchange_log")){
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                Log.d("가져왔다요@@@@@", result_item.toString());
                ArrayItem<ExchangeData> log_data = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ExchangeData>>() {
                }.getType());

                if (log_data.isSuccess()) {

                    ExchangeLogDialog dialog = new ExchangeLogDialog(context, log_data);
                    dialog.show();

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

        } else if (msg.what == 2) {

            Toast.makeText(context, "다른 기기에서 접속하여 연결이 끊겼습니다.\n이용을 원하시면 재접속 해주세요.", Toast.LENGTH_LONG).show();

            Common.getInstance().delPref(context, "id");
            Common.getInstance().delPref(context, "pw");

            Intent i = this.getBaseContext().getPackageManager().
                    getLaunchIntentForPackage(this.getBaseContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);

        } else {

            Toast.makeText(context, msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
            main_no_dataTV.setVisibility(View.VISIBLE);
            main_tap_contentRV.setVisibility(View.GONE);
            mainPB.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_main, "메인화면");
        MyApplication.myActivity = this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void init_Handler() {
        super.init_Handler();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("메인@@@@", "onResume!!!!");
        mainPB.setVisibility(View.VISIBLE);
        MyApplication.myActivity = this;
        MyFirebaseMessagingService.activity = this;
        air_line_position = -1;
        relay_setting = false;
        relay = -1;
        pressed_emergency = false;
        mc_idx = "";
        pressed_option = false;
        mqtt_connect();

        if (companyItems != null) {

            mainPB.setVisibility(View.VISIBLE);

            int position = -1;

            for (int i = 0; i < companyItems.size(); i++) {
                if (companyItems.get(i).isSelected()) {
                    position = i;
                    break;
                }
            }

            main_tap_contentRV.clearOnScrollListeners();

            if (position == 0) {

                is_tap_first_item = true;

                if (ioTProdRecyclerAdapter != null)
                    ioTProdRecyclerAdapter.clearItem();
                companyData = companyItems.get(1);

                before_i = -1;
                before_k = -1;

            } else {
                is_tap_first_item = false;

                if (contentAdapter != null)
                    contentAdapter.clearItem();
                companyData = companyItems.get(position);
            }

            if (thread != null) {
                thread.stopForever();
                thread = null;
            }

            Get_Company();

        } else {

            is_tap_first_item = true;
            main_tap_contentRV.clearOnScrollListeners();

            if (thread != null) {
                thread.stopForever();
                thread = null;
            }

            Get_Partner();
        }

        Intent intent = getIntent();
        if (intent.getStringExtra("report_type") != null)
            get_report_publish(intent.getStringExtra("report_type"));

    }

    void get_report_publish(String report_type) {

        Intent intent = new Intent(context, FragmentActivity.class);
        intent.putExtra("type", "report_publish");

        switch (report_type) {
            case "":
                if (Common.getInstance().getPref(context, "month_report", true)) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("확인하지 않은 월간 레포트가 있습니다.\n확인하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            intent.putExtra("title", "소비전력 월간레포트");
                            intent.putExtra("value1", "month");
                            Common.getInstance().delPref(context, "month_report");
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.setNegativeButton("확인 안함", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            Common.getInstance().delPref(context, "month_report");
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();

                } else if (Common.getInstance().getPref(context, "week_report", true)) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("확인하지 않은 주간레포트가 있습니다.\n확인하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            intent.putExtra("title", "소비전력 주간레포트");
                            intent.putExtra("value1", "week");
                            Common.getInstance().delPref(context, "week_report");
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.setNegativeButton("확인 안함", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            Common.getInstance().delPref(context, "week_report");
                            dialog.dismiss();
                        }
                    });

                    dialogBuilder.show();
                }
                break;

            case "month":
                intent.putExtra("title", "소비전력 월간레포트");
                intent.putExtra("value1", "month");
                Common.getInstance().setPref(context, "month_report", false);
                startActivity(intent);
                break;

            case "week":
                intent.putExtra("title", "소비전력 주간레포트");
                intent.putExtra("value1", "week");
                Common.getInstance().setPref(context, "week_report", false);
                startActivity(intent);
                break;
        }

        getIntent().putExtra("report_type", "");
    }

    void delay_thread(String mac, String relay1) {

        Common.getInstance().toastShow(context, "원격제어에 성공했습니다.");
        MyApplication.stop_ui_change = false;
        relay_setting = false;
        start_thread(finalPosition);
        relay_dialog.dismiss();

        String del_flag = "MM";
        if (relay == 0) del_flag = "STOP";

        HashMap<String, String> data = new HashMap<>();
        data.put("mac", mac);
        data.put("mc_idx", machineItems.get(finalPosition).getMcIdx());
        data.put("del_flag", del_flag);
        data.put("pt_idx", machineItems.get(finalPosition).getPtIdx());
        data.put("cp_idx", machineItems.get(finalPosition).getCpIdx());
        data.put("mb_idx", userItem.getArrayitem().getMbIdx());

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

    void mqtt_connect() {

        if (mqttAndroidClient == null) {
            mqttAndroidClient = Common.getInstance().mqtt_connect(context, mqttAndroidClient);
        }

        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                Log.d("mesasge@@@", "메인 connectionLost");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = (JsonObject) parser.parse(new String(message.getPayload()));
                MonitoringData monitoringData = new Gson().fromJson(jsonObject, new TypeToken<MonitoringData>() {
                }.getType());

                Log.d("mesasge@@@", message.toString());
                if (topic.contains("check")) {

                    Common.getInstance().unSubscribeTopic(topic, mqttAndroidClient);

                    if (pressed_emergency) {
                        MyApplication.stop_ui_change = false;
                        relay_setting = false;
                        pressed_emergency = false;
                        Common.getInstance().toastShow(context, "비상정지 버튼이 눌렸습니다.");
                        relay_dialog.dismiss();
                    }

                    if (relay == Integer.parseInt(monitoringData.getRelay1Val()) && relay_setting) {
                        if (timer_thread != null) {
                            timer_thread.interrupt();
                            timer_thread = null;
                        }
                        String mac = topic.substring(topic.indexOf("/") + 1);
                        delay_thread(mac, relay + "");
                    }

                } else if (topic.contains("sensors") && pressed_option) {

                    Common.getInstance().unSubscribeTopic(topic, mqttAndroidClient);

                    if (timer_thread != null) {
                        timer_thread.interrupt();
                        timer_thread = null;
                    }

                    pressed_option = false;

                    if (monitoringData == null) {
                        Toast.makeText(getApplicationContext(), "IoT의 인터넷 연결상태를 확인해주세요.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Intent intent = new Intent(context, FragmentActivity.class);
                    intent.putExtra("title", "기계 옵션설정");
                    intent.putExtra("type", "machine_option");
                    intent.putExtra("value1", mc_idx);
                    intent.putExtra("value2", (ArrayList<String>) machineData.getArrayitem().getCpAirlineArr());
                    startActivity(intent);

                } else if (topic.contains("get_val")) {

                    if (monitoringData == null) {
                        return;
                    }

                    if (timer_thread != null) {
                        timer_thread.interrupt();
                        timer_thread = null;
                    }

                    Common.getInstance().unSubscribeTopic(topic, mqttAndroidClient);
                    machine_initial(topic.substring(8), monitoringData);
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
    }

    void machine_initial(String mc_iot_mac, MonitoringData monitoringData) {

        MyApplication.stop_ui_change = true;

        HashMap<String, String> data = new HashMap<>();
        data.put("mc_iot_mac", mc_iot_mac);

        data.put("mc_current1_up", Common.getInstance().isNullToZero(monitoringData.getMcCurrent1Up()));
        data.put("mc_current2_up", Common.getInstance().isNullToZero(monitoringData.getMcCurrent2Up()));
        data.put("mc_current3_up", Common.getInstance().isNullToZero(monitoringData.getMcCurrent3Up()));
        data.put("mc_current1_max", Common.getInstance().isNullToZero(monitoringData.getCurrent1Max()));
        data.put("mc_current2_max", Common.getInstance().isNullToZero(monitoringData.getCurrent2Max()));
        data.put("mc_current3_max", Common.getInstance().isNullToZero(monitoringData.getCurrent3Max()));

        data.put("mc_pressure1_up", Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure1Up()));
        data.put("mc_pressure2_up", Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure2Up()));
        data.put("mc_pressure3_up", Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure3Up()));
        data.put("mc_pressure1_max", Common.getInstance().isNullToZeroFloat(monitoringData.getPressure1Max()));
        data.put("mc_pressure2_max", Common.getInstance().isNullToZeroFloat(monitoringData.getPressure2Max()));
        data.put("mc_pressure3_max", Common.getInstance().isNullToZeroFloat(monitoringData.getPressure3Max()));

        data.put("mc_temp_ntc_down", Common.getInstance().isNullToZero(monitoringData.getMcTempNtcDown()));
        data.put("mc_temp_ntc_up", Common.getInstance().isNullToZero(monitoringData.getMcTempNtcUp()));
        data.put("mc_temp_ntc_2_down", Common.getInstance().isNullToZero(monitoringData.getMcTempNtc2Down()));
        data.put("mc_temp_ntc_2_up", Common.getInstance().isNullToZero(monitoringData.getMcTempNtc2Up()));
        data.put("mc_temp_pt_down", Common.getInstance().isNullToZero(monitoringData.getMcTempPtDown()));
        data.put("mc_temp_pt_up", Common.getInstance().isNullToZero(monitoringData.getMcTempPtUp()));
        data.put("mc_temp_ntc_max", Common.getInstance().isNullToZero(monitoringData.getTempNtcMax()));
        data.put("mc_temp_ntc_2_max", Common.getInstance().isNullToZero(monitoringData.getTempNtc2Max()));
        data.put("mc_temp_pt_max", Common.getInstance().isNullToZero(monitoringData.getTempPt100Max()));

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

    @Override
    public void onStop() {
        super.onStop();
        Log.d("메인@@@@", "onStop!!!!");
        MyFirebaseMessagingService.activity = null;

        if (thread != null) {
            thread.stopForever();
            thread = null;
        }

        if (MyApplication.serviceThreads.size() > 0) {

            for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                MyApplication.serviceThreads.get(i).stopForever();
            }
            MyApplication.serviceThreads = new ArrayList<>();
        }

        if (mqttAndroidClient != null) {
            mqttAndroidClient = Common.getInstance().mqtt_disconnect(mqttAndroidClient);
        }
    }

    @Override
    public void onBackPressed() {
        backPressCloseHandler.onBackPressed();
    }

    //지점 탭 클릭시 동작
    @Override
    public void onClick(Bundle value) {

        mainPB.setVisibility(View.VISIBLE);
        tap_list_adapter.clearItem();

        int position = Integer.parseInt(value.getString("item_position"));

        for (int i = 0; i < companyItems.size(); i++) {
            if (i == position) {
                companyItems.getArrayitem().get(i).setSelected(true);

            } else {
                companyItems.getArrayitem().get(i).setSelected(false);
            }
        }

        tap_list_adapter.addItems(companyItems.getArrayitem());
        main_tap_contentRV.clearOnScrollListeners();

        if (position == 0) {

            is_tap_first_item = true;

            before_k = -1;
            before_i = -1;

            if (ioTProdRecyclerAdapter != null)
                ioTProdRecyclerAdapter.clearItem();
            companyData = companyItems.get(1);

        } else {
            is_tap_first_item = false;

            if (contentAdapter != null)
                contentAdapter.clearItem();
            companyData = companyItems.get(position);
        }

        if (thread != null) {
            thread.stopForever();
            thread = null;
        }

        if (MyApplication.serviceThreads.size() > 0) {

            for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                MyApplication.serviceThreads.get(i).stopForever();
            }
            MyApplication.serviceThreads = new ArrayList<>();
        }

        Get_Company();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult result = FragmentIntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result.getContents() != null && !result.getContents().equals("")) {

            String pt_idx = iot_bundle.getString("pt_idx");
            String cp_idx = iot_bundle.getString("cp_idx");
            String mc_idx = iot_bundle.getString("mc_idx");
            String mc_airline = iot_bundle.getString("mc_airline");

            AddIotDialog dialog = new AddIotDialog(context, hdr, companyData.getAgIdx(), pt_idx, cp_idx, mc_idx, mc_airline, result.getContents(), new AddIotDialog.clickListener() {
                @Override
                public void clickBtn(String mac) {

                    if (mqttAndroidClient == null) {
                        Common.getInstance().toastShow(context, "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
                        mqtt_connect();
                        return;
                    }

                    String msg = "{'opt' : 9, 'qr_value' :5}";
                    JsonParser send_parser = new JsonParser();
                    Object obj = send_parser.parse(msg);
                    Common.getInstance().publishMessage("check/" + mac, obj.toString(), mqttAndroidClient);

                }
            });
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (thread != null) {
                        thread.stopForever();
                        thread = null;
                    }

                    if (MyApplication.serviceThreads.size() > 0) {

                        for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                            MyApplication.serviceThreads.get(i).stopForever();
                        }
                        MyApplication.serviceThreads = new ArrayList<>();
                    }

                    MyApplication.my_thread.clear();
                    is_show_dlg = false;
                    Get_Company();
                }
            });
            dialog.show();
        }
    }
}
