package kr.co.compcareworker.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
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 com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.kakao.vectormap.KakaoMap;
import com.kakao.vectormap.KakaoMapReadyCallback;
import com.kakao.vectormap.LatLng;
import com.kakao.vectormap.MapLifeCycleCallback;
import com.kakao.vectormap.MapType;
import com.kakao.vectormap.MapView;
import com.kakao.vectormap.MapViewInfo;
import com.kakao.vectormap.camera.CameraUpdate;
import com.kakao.vectormap.camera.CameraUpdateFactory;
import com.kakao.vectormap.label.Label;
import com.kakao.vectormap.label.LabelLayer;
import com.kakao.vectormap.label.LabelLayerOptions;
import com.kakao.vectormap.label.LabelManager;
import com.kakao.vectormap.label.LabelOptions;

import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.Machine.AlarmData;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.Data.List.DefaultData;
import kr.co.compcareworker.Data.MainViewList.IotProdData;
import kr.co.compcareworker.Data.MainViewList.OldProdData;
import kr.co.compcareworker.Data.MainViewList.SubProdData;
import kr.co.compcareworker.Data.MainViewList.WorkerListData;
import kr.co.compcareworker.Data.Search.SearchData;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.IoTProdRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.OldProdRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.SubProdRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.WorkerListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.BackPressCloseHandler;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.MemberCallListDialog;
import kr.co.compcareworker.Util.CustomView.MonitoringReportDialog;
import kr.co.compcareworker.Util.CustomView.ProductSearchDialog;
import kr.co.compcareworker.Util.CustomView.RunningTimeResetDialog;
import kr.co.compcareworker.Util.Firebase.MyFirebaseMessagingService;
import kr.co.compcareworker.Util.MonitoringThread;
import kr.co.compcareworker.Util.ViewToBitmap;

public class MainActivity extends ActivityBasic {
    private BackPressCloseHandler backPressCloseHandler;

    /**
     * 지도관련
     */
    ImageView iv_act_main_location;
    MapView mapView;
    KakaoMap kakaoMap;
    LocationManager lm;
    String provider; //위치정보
    double longitude; //위도
    double latitude; //경도
    double altitude; //고도
    LatLng currentMapPoint; //현재 위치
    LatLng mp;
    boolean firstCurrentPoint = true;

    public Criteria criteria;
    public String bestProvider;

    AlertDialog alertDialog;

    /**
     * 탭 관련
     */
    TextView tv_act_main_basic, tv_act_main_consumables, tv_act_main_old, tv_act_main_iot;
    TextView[] tv_act_main;
    String mode = "default";
    TextView typeText;

    /**
     * 리사이클러뷰
     */
    SwipeRefreshLayout swipe;
    RecyclerView list;
    TextView tv_act_main_schedule_refresh;

    /**
     * API데이터
     */
    ArrayItem<DefaultData> defaultDataArrayItem;
    ArrayItem<WorkerListData> workerListDataArrayItem;
    ArrayItem<SubProdData> subProdDataArrayItem;
    ArrayItem<OldProdData> oldProdDataArrayItem;
    ArrayItem_<SearchData> searchDataItem;
    ArrayItem<IotProdData> iotProdDataArrayItem;

    /**
     * 리스트컨텐츠 공통
     */
    int lastIndex = 0, limitCount = 10, count = 0;
    TextView tv_act_main_content;

    /**
     * 서비스일정
     */
    ArrayList<WorkerListData> workerListData;
    WorkerListRecyclerAdapter workerListRecyclerAdapter;
    String[] arr_str = new String[]{"전체", "접수", "완료", "취소"};
    String sortText = "접수";
    String[] sortType = new String[]{"", "A", "D", "F"};
    String sort = "A";

    /**
     * 소모품만료
     */
    ArrayList<SubProdData> subProdData;
    SubProdRecyclerAdapter subProdRecyclerAdapter;
    LinearLayout exchange_cntLL;
    TextView exchange_cntTV;

    /**
     * 노후장비
     */
    ArrayList<OldProdData> oldProdData;
    OldProdRecyclerAdapter oldProdRecyclerAdapter;

    /**
     * 프로그래스바
     */
    ProgressBar mapProgress, workerProgress;

    /**
     * 검색
     */
    TextView search;
    String cp_idx;

    /**
     * 하단메뉴
     */
    LinearLayout tv_act_main_qr_cognition, menu1, menu2, addFrame, camera, main_code_managementLL;

    /**
     * 서비스일정 업체검색
     **/
    EditText find_companyET;
    ImageView find_companyIV;
    LinearLayout find_companyLL;

    /**
     * 마커
     */
    int[] m_off;
    int[] m_on;

    /**
     * IoT
     **/
    ArrayList<IotProdData> iotProdData;
    IoTProdRecyclerAdapter iotProdRecyclerAdapter;

    /**
     * iot 검색
     ***/
    EditText find_iotET;
    ImageView find_iotIV;
    LinearLayout find_iotLL;
    String[] iot_str = new String[]{"전체", "기동중", "기동정지", "트립", "소모품만료"};
    String[] iot_sortType = new String[]{"", "A", "B", "C", "D"};


    /**
     * 소모품
     **/
    TextView mc_typeText;
    LinearLayout find_subprodLL, sub_regionLL;
    EditText find_subprodET;
    ImageView find_subprodIV;
    String[] sub_str = new String[]{"전체 기종", "IoT 기종", "소모품 만료"};
    String[] sub_sort = new String[]{"", "A", "B"};
    String[] sub_type_str = new String[]{"타입 전체", "COMP", "TANK", "COOLER", "FILTER", "SUCTION", "ETC"};
    String sub_type = "타입 전체";
    Spinner sub_sidoSN, sub_sigunguSN;
    String cp_sido, cp_sigungu, sub_search = "";

    /**
     * 보유기종 등록
     **/
    LinearLayout tv_act_main_mc_registration;

    //알림
    TextView alarm_countTV;

    MainActivity.MonitoringServiceHandler holder_hdr;
    int air_line_position = -1;
    ArrayList<IotProdData> scroll_iot_data = new ArrayList<>();
    static Handler monitoring_hdr;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d("onNewIntent", "123124");
        setIntent(intent);
    }

    @Override
    protected void init() {
        /** 지도관련*/
        mapView = findViewById(R.id.mapView);
        mapView.start(new MapLifeCycleCallback() {
            @Override
            public void onMapDestroy() {
                kakaoMap = null;
            }

            @Override
            public void onMapError(Exception e) {
            }
        }, new KakaoMapReadyCallback() {
            @NonNull
            @Override
            public int getZoomLevel() {
                return 18;
            }

            @NonNull
            @Override
            public LatLng getPosition() {
                return LatLng.from(37.394760, 127.111192);
            }

            @Override
            public void onMapReady(@NonNull KakaoMap kakaoMap) {
                kakaoMap.changeMapViewInfo(MapViewInfo.from("openmap", MapType.NORMAL));
                MainActivity.this.kakaoMap = kakaoMap;
                Set_Map(kakaoMap);
            }
        });
        iv_act_main_location = findViewById(R.id.iv_act_main_location);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /** 탭 관련*/
        tv_act_main_basic = findViewById(R.id.tv_act_main_basic);
        tv_act_main_consumables = findViewById(R.id.tv_act_main_consumables);
        tv_act_main_old = findViewById(R.id.tv_act_main_old);
        tv_act_main_iot = findViewById(R.id.tv_act_main_iot);
        tv_act_main = new TextView[]{tv_act_main_basic, tv_act_main_consumables, tv_act_main_old, tv_act_main_iot};
        typeText = findViewById(R.id.typeText);

        exchange_cntLL = findViewById(R.id.exchange_cntLL);
        exchange_cntTV = findViewById(R.id.exchange_cntTV);

        /** 검색관련*/
        search = findViewById(R.id.search);

        /** 탭별 결과 리스트 관련*/
        tv_act_main_schedule_refresh = findViewById(R.id.tv_act_main_schedule_refresh);
        swipe = findViewById(R.id.swipe);
        tv_act_main_content = findViewById(R.id.tv_act_main_content);
        list = findViewById(R.id.list);

        /** 서비스일정 어댑터*/
        workerListRecyclerAdapter = new WorkerListRecyclerAdapter(this, handler, workerListOnLoadMoreListener, "main");
        list.setAdapter(workerListRecyclerAdapter);

        /** 소모품 어댑터*/
        subProdRecyclerAdapter = new SubProdRecyclerAdapter(this, handler, subProdOnLoadMoreListener, subProdOnClickListener, subProdResetListener, enterpriseListener);

        /** 노후장비 어댑터*/
        oldProdRecyclerAdapter = new OldProdRecyclerAdapter(this, handler, oldProdOnLoadMoreListener, oldProdOnClickListener);

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

        /** 프로그레스바*/
        mapProgress = findViewById(R.id.mapProgress);
        workerProgress = findViewById(R.id.workerProgress);

        /** 하단메뉴*/
        tv_act_main_qr_cognition = findViewById(R.id.tv_act_main_qr_cognition);
        menu1 = findViewById(R.id.menu1);
        menu2 = findViewById(R.id.menu2);
        main_code_managementLL = findViewById(R.id.main_code_managementLL);

        /**장소추가*/
        addFrame = findViewById(R.id.addFrame);

        /**문자인식*/
        camera = findViewById(R.id.camera);

        backPressCloseHandler = new BackPressCloseHandler(this);

        m_off = new int[]{R.drawable.marker_00, R.drawable.marker_01, R.drawable.marker_02, R.drawable.marker_03, R.drawable.marker_04, R.drawable.marker_05, R.drawable.marker_06, R.drawable.marker_07, R.drawable.marker_08};
        m_on = new int[]{R.drawable.marker_00_on, R.drawable.marker_01_on, R.drawable.marker_02_on, R.drawable.marker_03_on, R.drawable.marker_04_on, R.drawable.marker_05_on, R.drawable.marker_06_on, R.drawable.marker_07_on, R.drawable.marker_08_on};

        /**서비스일정 업체검색**/
        find_companyET = findViewById(R.id.find_companyET);
        find_companyIV = findViewById(R.id.find_companyIV);
        find_companyLL = findViewById(R.id.find_companyLL);

        /**iot 검색**/
        find_iotLL = findViewById(R.id.find_iotLL);
        find_iotET = findViewById(R.id.find_iotET);
        find_iotIV = findViewById(R.id.find_iotIV);

        /**소모품**/
        find_subprodLL = findViewById(R.id.find_subprodLL);
        find_subprodET = findViewById(R.id.find_subprodET);
        find_subprodIV = findViewById(R.id.find_subprodIV);
        mc_typeText = findViewById(R.id.mc_typeText);
        sub_regionLL = findViewById(R.id.sub_regionLL);
        sub_sidoSN = findViewById(R.id.sub_sidoSN);
        sub_sigunguSN = findViewById(R.id.sub_sigunguSN);

        /**보유기종 등록**/
        tv_act_main_mc_registration = findViewById(R.id.tv_act_main_mc_registration);

        alarm_countTV = findViewById(R.id.alarm_countTV);

        init_Hdr();
    }

    //GPS 설정 체크
    private boolean chkGpsService() {
        return !lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void setGpsService() {
        // GPS OFF 일때 Dialog 표시
        AlertDialog.Builder gsDialog = new AlertDialog.Builder(context);
        gsDialog.setTitle("위치 서비스 설정");
        gsDialog.setMessage("GPS 사용을 체크하셔야 사용 가능합니다.\n위치 서비스 기능을 설정하시겠습니까?");
        gsDialog.setCancelable(false);
        gsDialog.setPositiveButton("설정", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // GPS설정 화면으로 이동
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("종료", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        return;
                    }
                });

        alertDialog = gsDialog.create();
        alertDialog.show();
    }

    @Override
    protected void init_Listener() {

        for (int i = 0; i < tv_act_main.length; i++) {
            tv_act_main[i].setOnClickListener(tv_act_main_click);
        }

        iv_act_main_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cp_idx = null;
//                mapView.setMapCenterPoint(currentMapPoint, true);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(currentMapPoint);
                kakaoMap.moveCamera(cameraUpdate);
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "업체 검색");
                intent.putExtra("type", "search");
                startActivityForResult(intent, 100);
            }
        });

        tv_act_main_schedule_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lastIndex = 0;
                count = 0;
                Get_Worker_List();
            }
        });

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

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "QR코드 등록");
                intent.putExtra("type", "quick");
                intent.putExtra("value1", cp_idx);
                context.startActivity(intent);
            }
        });

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

                stop_thread();

                if (mode.equals("default")) {

                    int sortWhich = 0;

                    for (int i = 0; i < arr_str.length; i++)

                        if (sortText.equals(arr_str[i]))
                            sortWhich = i;

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    alertDialogBuilder.setSingleChoiceItems(arr_str, sortWhich, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, final int which) {
                            typeText.setText("서비스일정(" + arr_str[which] + ")▼");
                            sortText = arr_str[which];
                            sort = sortType[which];
                            lastIndex = 0;
                            count = 0;
                            Get_Worker_List();
                            dialog.dismiss();
                        }
                    });

                    alertDialog = alertDialogBuilder.create();
                    alertDialog.show();

                } else if (mode.equals("iot")) {

                    int sortWhich = 0;
                    for (int i = 0; i < iot_str.length; i++)
                        if (sortText.equals(iot_str[i]))
                            sortWhich = i;

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    alertDialogBuilder.setSingleChoiceItems(iot_str, sortWhich, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, final int which) {

                            air_line_position = -1;
                            scroll_iot_data = new ArrayList<>();
                            typeText.setText("IoT 기동현황 (" + iot_str[which] + ")▼");
                            sortText = iot_str[which];
                            sort = iot_sortType[which];
                            lastIndex = 0;
                            count = 0;
                            list.removeOnScrollListener(scrollListener);
                            Common.getInstance().toastShow(context, "현재 인터넷이 연결된 기기내에서 검색됩니다.");

                            Get_Worker_List();
                            dialog.dismiss();
                        }
                    });

                    alertDialog = alertDialogBuilder.create();
                    alertDialog.show();

                } else if (mode.equals("exchange")) {

                    int sortWhich = 0;
                    for (int i = 0; i < sub_str.length; i++)
                        if (sortText.equals(sub_str[i]))
                            sortWhich = i;

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                    alertDialogBuilder.setSingleChoiceItems(sub_str, sortWhich, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, final int which) {

                            typeText.setText(sub_str[which] + " ▼");
                            sortText = sub_str[which];
                            sort = sub_sort[which];
                            lastIndex = 0;
                            count = 0;
                            Get_Worker_List();
                            dialog.dismiss();
                        }
                    });

                    alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
        });

        /**소모품 mahcine type**/
        mc_typeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int sortWhich = 0;
                for (int i = 0; i < sub_type_str.length; i++)
                    if (sub_type.equals(sub_type_str[i]))
                        sortWhich = i;

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                alertDialogBuilder.setSingleChoiceItems(sub_type_str, sortWhich, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {

                        mc_typeText.setText(sub_type_str[which]);
                        sub_type = sub_type_str[which];
                        lastIndex = 0;
                        count = 0;
                        Get_list();
                        Get_Worker_List();
                        dialog.dismiss();
                    }
                });
                alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });

        menu1.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");
                startActivity(intent);
            }
        });

        menu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "알림내역");
                intent.putExtra("type", "alarm_list");
                startActivity(intent);
            }
        });

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

                ProductSearchDialog dialog = new ProductSearchDialog(context, "main", userItem.getArrayitem().getAgIdx());
                dialog.show();
            }
        });

        /**보유기종 등록**/
        tv_act_main_mc_registration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "보유기종 등록");
                intent.putExtra("type", "add_machine2");
                intent.putExtra("value1", userItem.getArrayitem().getAgIdx());
                context.startActivity(intent);
            }
        });

        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                lastIndex = 0;
                count = 0;
                Get_Worker_List();
            }
        });

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionCheck();
            }
        });

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

                int[] selectedItem = {0};
                String[] items = new String[]{"본사", "자회사"};

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("추가 할 회사유형 선택");
                dialogBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        selectedItem[0] = which;

                    }
                });
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String type = items[selectedItem[0]];

                        Intent intent = new Intent(context, FragmentActivity.class);
                        if (type.equals("본사")) {

                            intent.putExtra("title", "본사 추가");

                        } else {

                            intent.putExtra("title", "자회사 추가");
                        }
                        intent.putExtra("type", "place_registration");
                        intent.putExtra("value1", type);
                        startActivity(intent);

                    }
                });
                dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                });

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

        /**서비스일정 업체검색**/
        find_companyIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mapProgress.setVisibility(View.VISIBLE);

                String find_company = find_companyET.getText().toString();

                lastIndex = 0;
                count = 0;

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", userItem.getArrayitem().getAgIdx());
                data.put("per_page", limitCount + "");
                data.put("offset", lastIndex + "");
                data.put("company_name", find_company);
                data.put("wr_status", sort);

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

                find_companyET.getText().clear();
                mapProgress.setVisibility(View.GONE);
            }
        });

//        /**보유기종 검색**/
//        find_subprodIV.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow( find_subprodET.getWindowToken(), 0);    //hide keyboard
//                lastIndex = 0;
//                count = 0;
//                Get_list();
//                Get_Worker_List();
//                find_subprodET.clearFocus();
//                find_subprodET.getText().clear();
//            }
//        });

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

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (find_subprodET.length() > 1) {
                    lastIndex = 0;
                    count = 0;
                    Get_Worker_List();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        /**보유기종 검색_ 키보드 엔터**/
        find_subprodET.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(find_subprodET.getWindowToken(), 0);    //hide keyboard
                    air_line_position = -1;
                    lastIndex = 0;
                    count = 0;
                    Get_Worker_List();
                    find_subprodET.getText().clear();
                    find_subprodET.clearFocus();
                    return true;
                }
                return false;
            }
        });

        /**보유기종 지역 스피너**/
        sub_sidoSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                lastIndex = 0;
                count = 0;

                switch (i) {
                    case 0:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_sigungu);
                        break;
                    case 1:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_seoul);
                        break;
                    case 2:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_busan);
                        break;
                    case 3:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_daegu);
                        break;
                    case 4:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_incheon);
                        break;
                    case 5:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_gwangju);
                        break;
                    case 6:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_daejeon);
                        break;
                    case 7:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_ulsan);
                        break;
                    case 8:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_sejong);
                        break;
                    case 9:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_gyeonggi);
                        break;
                    case 10:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_gangwon);
                        break;
                    case 11:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_chung_buk);
                        break;
                    case 12:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_chung_nam);
                        break;
                    case 13:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_jeon_buk);
                        break;
                    case 14:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_jeon_nam);
                        break;
                    case 15:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_gyeong_buk);
                        break;
                    case 16:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_gyeong_nam);
                        break;
                    case 17:
                        setSigunguSpinnerAdapterItem(R.array.spinner_region_jeju);
                        break;
                }
                if (i > 0) {
                    Get_list();
                    Get_Worker_List();
                }

            }

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

            }
        });

        sub_sigunguSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                lastIndex = 0;
                count = 0;

                if (i > 0) {
                    Get_list();
                    Get_Worker_List();
                }
            }

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

            }
        });

        /**iot 검색**/
        find_iotIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mapProgress.setVisibility(View.VISIBLE);

                String find_iot = find_iotET.getText().toString();

                lastIndex = 0;
                count = 0;
                air_line_position = -1;
                list.removeOnScrollListener(scrollListener);

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", userItem.getArrayitem().getAgIdx());
                data.put("per_page", limitCount + "");
                data.put("offset", lastIndex + "");
                data.put("search", find_iot);

                stop_thread();
                scroll_iot_data.clear();
                new ApiClient(data, "proc_iotprod_list", handler);

                find_iotET.getText().clear();
                mapProgress.setVisibility(View.GONE);
            }
        });
    }

    TextView.OnClickListener tv_act_main_click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mapProgress.getVisibility() == View.VISIBLE) {
                Toast.makeText(context, "지도를 불러오는 중입니다. 잠시후 다시 시도해 주세요.", Toast.LENGTH_LONG).show();
                return;
            }

            stop_thread();
            mapProgress.setVisibility(View.VISIBLE);

            if (v == tv_act_main_basic) {
                mode = "default";
                list.setAdapter(workerListRecyclerAdapter);
                swipe.setEnabled(true);
                iotProdRecyclerAdapter = null;
                Get_list();

            } else if (v == tv_act_main_consumables) {
                mode = "exchange";
                list.setAdapter(subProdRecyclerAdapter);
                swipe.setEnabled(false);
                iotProdRecyclerAdapter = null;
                Get_list();

            } else if (v == tv_act_main_old) {
                mode = "old";
                list.setAdapter(oldProdRecyclerAdapter);
                swipe.setEnabled(true);
                iotProdRecyclerAdapter = null;

            } else if (v == tv_act_main_iot) {

                air_line_position = -1;
                mode = "iot";

                /**IoT 어탭터**/
                iotProdRecyclerAdapter = new IoTProdRecyclerAdapter(MainActivity.this, handler, iotProdOnLoadMoreListener, iotProdOnClickListener);
                list.setAdapter(iotProdRecyclerAdapter);
                holder_hdr = new MonitoringServiceHandler(MainActivity.this);
                swipe.setEnabled(false);
            }

            lastIndex = 0;
            count = 0;

            Set_Layout();
            Get_Worker_List();

            mapProgress.setVisibility(View.GONE);
        }
    };

    RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (iotProdRecyclerAdapter != null) {

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

                        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        assert layoutManager != null;
                        int firstVisible = layoutManager.findFirstVisibleItemPosition();
                        int lastVisible = layoutManager.findLastVisibleItemPosition();
                        if (firstVisible < 0) firstVisible = 0;
                        if (lastVisible < 0) lastVisible = 0;
                        else if (lastVisible > scroll_iot_data.size())
                            lastVisible = scroll_iot_data.size();
                        start_thread(firstVisible, lastVisible, holder_hdr, scroll_iot_data);
                    }
                });
            }
        }
    };

    private void setSigunguSpinnerAdapterItem(int array_resource) {
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this, array_resource, R.layout.custom_spinner_list);
        adapter.setDropDownViewResource(R.layout.custom_spinner);
        sub_sigunguSN.setAdapter(adapter);
    }

    public void PermissionCheck() {
        /**
         * 6.0 마시멜로우 이상일 경우에는 권한 체크후 권한을 요청한다.
         */
        if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED &&
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED &&
                checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            // 권한 없음
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        } else {
            // 권한 있음
            Intent intent = new Intent(context, FragmentActivity.class);
            intent.putExtra("title", "문자인식");
            intent.putExtra("type", "tesseract");
            startActivity(intent);
        }
    }

    void Set_Layout() {

        Log.d("1234", "Set_Layout");
        cp_idx = "";

        if (mode.equals("default")) {
            sort = "A";
            sortText = "접수";
            find_iotET.getText().clear();
            find_iotET.clearFocus();
            find_subprodET.getText().clear();
            find_subprodET.clearFocus();
            tv_act_main_basic.setBackgroundResource(R.drawable.bg_round_purple);
            tv_act_main_consumables.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_old.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_iot.setBackgroundResource(R.drawable.btn_select_on);
            find_companyLL.setVisibility(View.VISIBLE);
            find_subprodLL.setVisibility(View.GONE);
            typeText.setText("서비스일정 (" + sortText + ")▼");
            exchange_cntLL.setVisibility(View.GONE);
            find_iotLL.setVisibility(View.GONE);
            mc_typeText.setVisibility(View.GONE);
            sub_regionLL.setVisibility(View.GONE);

        } else if (mode.equals("exchange")) {
            sort = "";
            sortText = "전체 기종";
            sub_type = "타입 전체";
            find_companyET.getText().clear();
            find_companyET.clearFocus();
            find_iotET.getText().clear();
            find_iotET.clearFocus();

            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_region, R.layout.custom_spinner_list);
            adapter.setDropDownViewResource(R.layout.custom_spinner);
            sub_sidoSN.setAdapter(adapter);
            sub_sidoSN.setSelection(0);
            setSigunguSpinnerAdapterItem(R.array.spinner_region_sigungu);
            mc_typeText.setText("타입 전체");
            tv_act_main_basic.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_consumables.setBackgroundResource(R.drawable.bg_round_purple);
            tv_act_main_old.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_iot.setBackgroundResource(R.drawable.btn_select_on);
            find_companyLL.setVisibility(View.GONE);
            find_subprodLL.setVisibility(View.VISIBLE);
            typeText.setText(sortText + " ▼");
            exchange_cntLL.setVisibility(View.VISIBLE);
            find_iotLL.setVisibility(View.GONE);
            sub_regionLL.setVisibility(View.VISIBLE);
            mc_typeText.setVisibility(View.VISIBLE);

        } else if (mode.equals("old")) {
            tv_act_main_basic.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_consumables.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_old.setBackgroundResource(R.drawable.bg_round_purple);
            tv_act_main_iot.setBackgroundResource(R.drawable.btn_select_on);
            find_companyLL.setVisibility(View.GONE);
            find_subprodLL.setVisibility(View.GONE);
            typeText.setText(getString(R.string.main_old));
            exchange_cntLL.setVisibility(View.GONE);
            find_iotLL.setVisibility(View.GONE);

        } else if (mode.equals("iot")) {
            sort = "";
            sortText = "전체";
            scroll_iot_data = new ArrayList<>();
            find_companyET.getText().clear();
            find_companyET.clearFocus();
            find_subprodET.getText().clear();
            find_subprodET.clearFocus();
            tv_act_main_basic.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_consumables.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_old.setBackgroundResource(R.drawable.btn_select_on);
            tv_act_main_iot.setBackgroundResource(R.drawable.bg_round_purple);
            find_companyLL.setVisibility(View.GONE);
            typeText.setText("IoT 현황 (" + sortText + ")▼");
            find_subprodLL.setVisibility(View.GONE);
            exchange_cntLL.setVisibility(View.GONE);
            find_iotLL.setVisibility(View.VISIBLE);
            mc_typeText.setVisibility(View.GONE);
            sub_regionLL.setVisibility(View.GONE);
        }
    }

    public void init_Hdr() {
        monitoring_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 = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                    }.getType());

                    Log.d("모니터링@@@@", result_item.toString());

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

                    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 if (position.contains("i") && !position.contains("k")) {
                        position_i = Integer.parseInt(result_item.get("resultItem").getAsJsonObject().get("message").getAsString());
                    }

                    //모니터링 데이터를 정상적으로 가져왔을 때
                    if (monitoringArray.isSuccess() && monitoringArray.getArrayitem() != null && iotProdRecyclerAdapter != null) {
//                        if (scroll_iot_data.size() > 0) {
//                            scroll_iot_data.get(position_i).getMachineItems().get(position_k).setMonitoring(monitoringArray);
//                            iotProdRecyclerAdapter.notifyItemChanged(position_i);
//                        }
                        scroll_iot_data.get(position_i).getMachineItems().get(position_k).setMonitoring(monitoringArray);
                        iotProdRecyclerAdapter.notifyItemChanged(position_i);
                    }
                    //모니터링 데이터를 가져오는 것을 실패했을 때
                    else if (iotProdRecyclerAdapter != null) {
                        if (scroll_iot_data.size() > 0) {
                            scroll_iot_data.get(position_i).getMachineItems().get(position_k).setMonitoring(null);
                            iotProdRecyclerAdapter.notifyItemChanged(position_i);
                        }
//                        scroll_iot_data.get(position_i).getMachineItems().get(position_k).setMonitoring(null);
//                        iotProdRecyclerAdapter.notifyItemChanged(position_i);
                    }
                }
            }
        };
    }


    @Override
    protected void getMessage(Message msg) {
        Log.d("1234", "getMessage");
        String url = msg.getData().getString("url");

        if (msg.what == 1) {
            if (url.equals("proc_map_list")) {
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                defaultDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<DefaultData>>() {
                }.getType());

                if (defaultDataArrayItem.isSuccess()) {
                    Set_Marker();

                } else {
                    Toast.makeText(context, "마커 불러오기에 실패했습니다.", Toast.LENGTH_SHORT).show();
                    mapProgress.setVisibility(View.GONE);
                }
            } else if (url.equals("proc_worker_list") || url.equals("proc_worker_list_with_company")) {
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                workerListDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<WorkerListData>>() {
                }.getType());

                if (workerListDataArrayItem.isSuccess()) {

                    list.setVisibility(View.VISIBLE);
                    tv_act_main_content.setVisibility(View.GONE);

                    workerListData = new ArrayList<>();
                    workerListData.addAll(workerListDataArrayItem.getArrayitem());
                    count = workerListData.size();
                    if (lastIndex != 0) {
                        workerListRecyclerAdapter.addItemMore(workerListData);
                    } else {
                        workerListRecyclerAdapter.addAll(workerListData);
                    }
                    workerListRecyclerAdapter.itemClick = itemClickListener;
                    workerListRecyclerAdapter.callListClick = callListClickListener;
                } else {
                    if (lastIndex == 0) {
                        list.setVisibility(View.GONE);
                        tv_act_main_content.setVisibility(View.VISIBLE);
                        workerListRecyclerAdapter.clearItem();
                    }
                }

                workerProgress.setVisibility(View.GONE);
                swipe.setRefreshing(false);

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

                if (subProdDataArrayItem.isSuccess()) {
                    list.setVisibility(View.VISIBLE);
                    tv_act_main_content.setVisibility(View.GONE);

                    subProdData = new ArrayList<>();
                    subProdData.addAll(subProdDataArrayItem.getArrayitem());
                    count = subProdData.size();

                    if (lastIndex != 0) {
                        subProdRecyclerAdapter.addItemMore(subProdData);
                    } else {
                        subProdRecyclerAdapter.addAll(subProdData);
                    }

                } else {
                    if (lastIndex == 0) {
                        list.setVisibility(View.GONE);
                        tv_act_main_content.setVisibility(View.VISIBLE);
                        subProdRecyclerAdapter.clearItem();
                    }
                }

                workerProgress.setVisibility(View.GONE);
                swipe.setRefreshing(false);

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

                if (oldProdDataArrayItem.isSuccess()) {
                    list.setVisibility(View.VISIBLE);
                    tv_act_main_content.setVisibility(View.GONE);

                    oldProdData = new ArrayList<>();
                    oldProdData.addAll(oldProdDataArrayItem.getArrayitem());
                    count = oldProdData.size();
                    if (lastIndex != 0) {
                        oldProdRecyclerAdapter.addItemMore(oldProdData);
                    } else {
                        oldProdRecyclerAdapter.addAll(oldProdData);
                    }

                } else {
                    if (lastIndex == 0) {
                        list.setVisibility(View.GONE);
                        tv_act_main_content.setVisibility(View.VISIBLE);
                        oldProdRecyclerAdapter.clearItem();
                    }
                }

                workerProgress.setVisibility(View.GONE);
                swipe.setRefreshing(false);

            } else if (url.equals("proc_qr_code_view")) {
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                searchDataItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<SearchData>>() {
                }.getType());

                if (searchDataItem.isSuccess()) {
                    Intent intent = new Intent(context, FragmentActivity.class);
                    intent.putExtra("title", "설치장소 정보");
                    intent.putExtra("type", "enterprise");
                    intent.putExtra("value1", searchDataItem.getArrayitem().getCpIdx());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "QR코드 데이터가 잘못되었습니다.", Toast.LENGTH_LONG).show();
                }

                mapProgress.setVisibility(View.GONE);

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

                if (iotProdDataArrayItem.isSuccess()) {

                    list.setVisibility(View.VISIBLE);
                    list.addOnScrollListener(scrollListener);
                    tv_act_main_content.setVisibility(View.GONE);

                    iotProdData = new ArrayList<>();
                    iotProdData.addAll(iotProdDataArrayItem.getArrayitem());

                    if (count + iotProdData.size() > scroll_iot_data.size()) {
                        scroll_iot_data.addAll(iotProdDataArrayItem.getArrayitem());
                        count = iotProdData.size();

                        if (lastIndex != 0) {
                            iotProdRecyclerAdapter.addItemMore(iotProdData);

                        } else {
                            iotProdRecyclerAdapter.addAll(iotProdData);
                            list.scrollToPosition(0);
                        }
                    }

                    if (!TextUtils.isEmpty(search.getText())) {
                        if (scroll_iot_data.size() > 3) {
                            start_thread(0, 3, holder_hdr, scroll_iot_data);
                        } else {
                            start_thread(0, scroll_iot_data.size() - 1, holder_hdr, scroll_iot_data);
                        }
                    }

                } else {
                    if (lastIndex == 0) {
                        list.setVisibility(View.GONE);
                        tv_act_main_content.setVisibility(View.VISIBLE);
                        iotProdRecyclerAdapter.clearItem();
                        scroll_iot_data.clear();
                    }
                }

                workerProgress.setVisibility(View.GONE);
                swipe.setRefreshing(false);

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

                if (subProdDataArrayItem.isSuccess()) {
                    list.setVisibility(View.VISIBLE);
                    tv_act_main_content.setVisibility(View.GONE);

                    subProdData = new ArrayList<>();
                    subProdData.addAll(subProdDataArrayItem.getArrayitem());
                    count = subProdData.size();

                    if (lastIndex != 0) {
                        subProdRecyclerAdapter.addItemMore(subProdData);
                    } else {
                        subProdRecyclerAdapter.addAll(subProdData);
                    }

                } else {
                    if (lastIndex == 0) {
                        list.setVisibility(View.GONE);
                        tv_act_main_content.setVisibility(View.VISIBLE);
                        subProdRecyclerAdapter.clearItem();
                    }
                }

                workerProgress.setVisibility(View.GONE);
                swipe.setRefreshing(false);

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

                if (items.isSuccess()) {
                    String not_read_cnt = result_item.get("resultItem").getAsJsonObject().get("message").getAsString();
                    not_read_cnt = not_read_cnt.substring(0, not_read_cnt.indexOf("+"));
                    int cnt = Integer.parseInt(not_read_cnt);

                    if (cnt > 0) {
                        alarm_countTV.setVisibility(View.VISIBLE);
                    } else {
                        if (MyApplication.alarm_thread != null) {
                            MyApplication.alarm_thread.stopForever();
                            MyApplication.alarm_thread = null;
                        }

                        if (MyApplication.notify_manager != null) {
                            MyApplication.notify_manager.cancelAll();
                        }
                        alarm_countTV.setVisibility(View.GONE);
                    }
                }
            } 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());

                MonitoringReportDialog dialog = new MonitoringReportDialog(context, handler, machineItem.get(0).getOriData(), machineItem.get(0).getOriData().getCpName(), machineItem);
                dialog.show();
            }

        } else {
            Common.getInstance().toastShow(context, msg.obj.toString());

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

            Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    }

    void start_thread(int i, int k, MonitoringServiceHandler holder_hdr, ArrayList<IotProdData> data) {

        if (air_line_position != i || air_line_position == -1) {

            if (MyApplication.monitoringThread.size() > 0) {
                for (int n = MyApplication.monitoringThread.size() - 1; n >= 0; n--) {
                    int i_position = MyApplication.monitoringThread.get(n).getPosition();
                    int k_position = MyApplication.monitoringThread.get(n).getPosition_k();

                    MyApplication.monitoringThread.get(n).stopForever();
                    data.get(i_position).getMachineItems().get(k_position).setRunning(false);
                    data.get(i_position).getMachineItems().get(k_position).setMonitoring(null);
                    iotProdRecyclerAdapter.notifyItemChanged(i_position, null);
                }
                MyApplication.monitoringThread = new ArrayList<>();
            }

            for (int h = i; h <= k; h++) {
                for (int m = 0; m < data.get(h).getMachineItems().size(); m++) {
                    MonitoringThread thread = new MonitoringThread(holder_hdr, "monitoring", data.get(h).getMachineItems().get(m).getMcIotMac(), h + "", m + "");
                    MyApplication.monitoringThread.add(thread);
                    thread.start();
                }
            }

            air_line_position = i;
        }
    }

    private static class MonitoringServiceHandler extends Handler {

        public MonitoringServiceHandler(MainActivity activity) {
            WeakReference<MainActivity> weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(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("i", i);
            data.put("type", "A");

            new ApiClient(data, "proc_monitoring", monitoring_hdr);
        }
    }

    View.OnClickListener callListClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String pt_idx = (String) v.getTag();
            MemberCallListDialog dialog = new MemberCallListDialog(context, handler, pt_idx);
            dialog.show();
        }
    };

    View.OnClickListener itemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String wr_idx = (String) v.getTag();
            if (TextUtils.isEmpty(wr_idx)) {
                Common.getInstance().toastShow(context, "상세보기를 불러올 수 없습니다. 잠시후 다시 시도해주세요.");
                return;
            }
            Intent intent = new Intent(context, FragmentActivity.class);
            intent.putExtra("title", "서비스일정 상세");
            intent.putExtra("type", "plan_detail");
            intent.putExtra("value1", wr_idx);
            startActivity(intent);
            finish();
        }
    };

    void Get_Location() {
        if (kakaoMap == null) {
            return;
        }
        Log.d("1234", "Get_Location");
        mapProgress.setVisibility(View.VISIBLE);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    0);
        } else {

            criteria = new Criteria();
            //정확도
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            //전원 소비량
            criteria.setPowerRequirement(Criteria.POWER_LOW);

            bestProvider = String.valueOf(lm.getBestProvider(criteria, true));

            Location location = lm.getLastKnownLocation(bestProvider);

            if (location != null) {
                Log.e("TAG", "GPS is on");
                latitude = location.getLatitude();
                longitude = location.getLongitude();

//                currentMapPoint = MapPoint.mapPointWithGeoCoord(latitude, longitude);
                currentMapPoint = LatLng.from(latitude, longitude);

                MyApplication app = (MyApplication) getApplication();
                if (firstCurrentPoint) {
                    if (app.lastMapPoint != null) {
                        mp = app.lastMapPoint;
//                        mapView.setMapCenterPoint(app.lastMapPoint, true);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(mp);
                        kakaoMap.moveCamera(cameraUpdate);
                        firstCurrentPoint = false;
                    } else {
                        mp = currentMapPoint;
//                        mapView.setMapCenterPoint(currentMapPoint, true);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(mp);
                        kakaoMap.moveCamera(cameraUpdate);

                        firstCurrentPoint = false;
                    }
                }

                mapProgress.setVisibility(View.GONE);
            }


            boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            boolean isNETWORKEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (isGPSEnabled) {

                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        1000,
                        1,
                        gpsLocationListener);

            } else if (isNETWORKEnabled) {

                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        1000,
                        1,
                        gpsLocationListener);

            }
        }
    }


    LocationListener gpsLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            provider = location.getProvider();
            longitude = location.getLongitude();
            latitude = location.getLatitude();
            altitude = location.getAltitude();

            currentMapPoint = LatLng.from(37.48367333991361, 126.75444108906184); //위치 잡기
            //currentMapPoint = MapPoint.mapPointWithGeoCoord(37.48367333991361, 126.75444108906184); //위치 잡기

            MyApplication app = (MyApplication) getApplication();
            if (firstCurrentPoint) {
                if (app.lastMapPoint != null) {
                    mp = app.lastMapPoint;
//                    mapView.setMapCenterPoint(app.lastMapPoint, true);
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(mp);
                    kakaoMap.moveCamera(cameraUpdate);
                    firstCurrentPoint = false;
                } else {
                    mp = currentMapPoint;
//                    mapView.setMapCenterPoint(currentMapPoint, true);
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(mp);
                    kakaoMap.moveCamera(cameraUpdate);
                    firstCurrentPoint = false;
                }
            } else {

                mp = currentMapPoint;
            }
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    private Label prevBalloonLabel;

    void Set_Map(KakaoMap kMap) {
        Log.d("1234", "Set_Map");
//        mapFrame.removeAllViews();
//        mapView.onSurfaceDestroyed();
//        mapView.setDaumMapApiKey(getString(R.string.kakao_key));
//        mapView.setMapViewEventListener(mapViewListener);
//        mapView.setPOIItemEventListener(markerListener);
//        mapFrame.addView(mapView);

        kMap.setOnCameraMoveEndListener((kakaoMap, cameraPosition, gestureType) -> {
            mp = cameraPosition.getPosition();
            Get_list();
        });

        kMap.setOnLabelClickListener((kakaoMap, labelLayer, label) -> {
            String labelId = label.getLabelId();
            if (labelId.endsWith("_balloon")) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "설치장소 정보");
                intent.putExtra("type", "enterprise");
                intent.putExtra("value1", label.getTag() + "");
                startActivity(intent);
            } else {
                Label balloonLabel = labelLayer.getLabel(labelId + "_balloon");
                if (prevBalloonLabel != null) {
                    if (prevBalloonLabel != balloonLabel) {
                        prevBalloonLabel.changeRank(0);
                        prevBalloonLabel.hide();
                    }
                }
                prevBalloonLabel = balloonLabel;
                if (balloonLabel != null) {
                    if (balloonLabel.isShow()) {
                        balloonLabel.changeRank(0);
                        balloonLabel.hide();
                    } else {
                        balloonLabel.changeRank(100);
                        balloonLabel.show();
                    }
                }
            }
            return true;
        });

        Get_Location();
    }

    void Get_Alarms() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", userItem.getArrayitem().getAgIdx());
        data.put("per_page", "30");
        data.put("offset", "0");
        new ApiClient(data, "proc_get_alarm_list2", handler);
    }

    void Get_list() {
        Log.d("1234", "Get_list");
        mapProgress.setVisibility(View.VISIBLE);
//        mapView.removeAllPOIItems();

        double lat = mp.latitude;
        double lng = mp.longitude;

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", userItem.getArrayitem().getAgIdx());
        if (mode.equals("iot")) {
            data.put("mode", "default");
        } else {
            data.put("mode", mode);
        }
        data.put("lat", lat + "");
        data.put("lng", lng + "");
        new ApiClient(data, "proc_map_list", handler);
    }

    void Get_Worker_List() {
        Log.d("1234", "Get_Worker_List");
        if (lastIndex == 0) workerProgress.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", userItem.getArrayitem().getAgIdx());
        data.put("per_page", limitCount + "");
        data.put("offset", lastIndex + "");
        String method = "";
        if (mode.equals("default")) {
            data.put("wr_status", sort);
            method = "proc_worker_list";
        } else if (mode.equals("exchange")) {
            data.put("sort", sort);
            sub_search = find_subprodET.getText().toString();
            cp_sido = sub_sidoSN.getSelectedItem().toString();
            cp_sigungu = sub_sigunguSN.getSelectedItem().toString();

            if (!sub_type.equals("타입 전체")) data.put("type", sub_type);
            if (!TextUtils.isEmpty(sub_search)) data.put("search", sub_search);
            if (!TextUtils.isEmpty(cp_sido) && !cp_sido.contains("전지역"))
                data.put("cp_sido", cp_sido);
            if (!TextUtils.isEmpty(cp_sigungu) && !cp_sigungu.contains("시/군/구") && !cp_sigungu.contains("선택"))
                data.put("cp_sigungu", cp_sigungu);

            method = "proc_subprod_list2";
        } else if (mode.equals("old")) method = "proc_oldprod_list";
        else if (mode.equals("iot")) {
            if (!sortText.equals("전체"))
                data.put("iot_state", sort);
            method = "proc_iotprod_list";
        }

        new ApiClient(data, method, handler);
    }

    public Label createBalloonLabel(LabelLayer labelLayer, LatLng latLng, String id, String text) {
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.layout_callout_balloon, null);
        TextView tv = viewGroup.findViewById(R.id.tv_callout_balloon);
        tv.setText(text);
        Bitmap bitmap = ViewToBitmap.createBitmap(viewGroup);
        Label label = labelLayer.addLabel(
                LabelOptions.from(id + "_balloon", latLng).setStyles(bitmap).setVisible(false)
        );
        label.setTag(id);
        label.changePixelOffset(0, -80);
        return label;
    }

    void Set_Marker() {
        if (kakaoMap == null) {
            return;
        }

        LabelManager labelManager = kakaoMap.getLabelManager();
        if (labelManager == null) {
            return;
        }
        labelManager.removeAllLabelLayer();
        LabelLayer labelLayer = labelManager.addLayer(LabelLayerOptions.from());
        if (labelLayer == null) {
            return;
        }

        ArrayList<LabelOptions> labelOptionsList = new ArrayList<>();
        for (int i = 0; i < defaultDataArrayItem.getArrayitem().size(); i++) {
            double x = Double.parseDouble(defaultDataArrayItem.getArrayitem().get(i).getCpMapx());
            double y = Double.parseDouble(defaultDataArrayItem.getArrayitem().get(i).getCpMapy());
            String name = defaultDataArrayItem.getArrayitem().get(i).getPtName() + " - " + defaultDataArrayItem.getArrayitem().get(i).getCpName();
            String tagString = defaultDataArrayItem.getArrayitem().get(i).getCpIdx();
            int tag = Integer.parseInt(tagString);
            LatLng latLng = LatLng.from(x, y);
            LabelOptions labelOptions = LabelOptions.from(tagString, latLng);
            labelOptions.setTag(tag);
            labelOptions.setClickable(true);

            if (!defaultDataArrayItem.getArrayitem().get(i).getServiceCnt().equals("0")) { //서비스접수(빨간색)
                labelOptions.setStyles(R.drawable.marker_service);
            } else if (!defaultDataArrayItem.getArrayitem().get(i).getWorkCnt().equals("0")) { //작업자배정(초록색)
                labelOptions.setStyles(R.drawable.marker_a_s);
            } else if (!defaultDataArrayItem.getArrayitem().get(i).getExchangeCnt().equals("0")) { //소모품완료(노란색)
                labelOptions.setStyles(R.drawable.marker_consump);
            } else if (!defaultDataArrayItem.getArrayitem().get(i).getOldCnt().equals("0")) { //노후장비(검은색)
                labelOptions.setStyles(R.drawable.marker_end);
            } else {
                labelOptions.setStyles(R.drawable.marker_blue);
            }
            labelOptionsList.add(labelOptions);
            Label label = labelLayer.addLabel(labelOptions);
            Label balloonLabel = createBalloonLabel(labelLayer, latLng, tagString, name);
            label.addShareTransform(balloonLabel);
        }

//        mapView.removeAllPOIItems();
//
//        for (int i = 0; i < defaultDataArrayItem.getArrayitem().size(); i++) {
//
//            MapPOIItem marker = new MapPOIItem();
//            marker.setItemName(defaultDataArrayItem.getArrayitem().get(i).getPtName() + " - " + defaultDataArrayItem.getArrayitem().get(i).getCpName());
//            marker.setTag(Integer.parseInt(defaultDataArrayItem.getArrayitem().get(i).getCpIdx()));
//            MapPoint p = MapPoint.mapPointWithGeoCoord(Double.parseDouble(defaultDataArrayItem.getArrayitem().get(i).getCpMapx()), Double.parseDouble(defaultDataArrayItem.getArrayitem().get(i).getCpMapy()));
//            marker.setMapPoint(p);
//            marker.setSelectedMarkerType(MapPOIItem.MarkerType.CustomImage);
//
//            if (!defaultDataArrayItem.getArrayitem().get(i).getServiceCnt().equals("0")) { //서비스접수(빨간색)
//                marker.setMarkerType(MapPOIItem.MarkerType.CustomImage);
//                marker.setCustomImageResourceId(R.drawable.marker_service);
//                marker.setCustomSelectedImageResourceId(R.drawable.marker_service);
//
//            } else if (!defaultDataArrayItem.getArrayitem().get(i).getWorkCnt().equals("0")) { //작업자배정(초록색)
//                marker.setMarkerType(MapPOIItem.MarkerType.CustomImage);
//                marker.setCustomImageResourceId(R.drawable.marker_a_s);
//                marker.setCustomSelectedImageResourceId(R.drawable.marker_a_s);
//
//            } else if (!defaultDataArrayItem.getArrayitem().get(i).getExchangeCnt().equals("0")) { //소모품완료(노란색)
//                marker.setMarkerType(MapPOIItem.MarkerType.CustomImage);
//                marker.setCustomImageResourceId(R.drawable.marker_consump);
//                marker.setCustomSelectedImageResourceId(R.drawable.marker_consump);
//
//            } else if (!defaultDataArrayItem.getArrayitem().get(i).getOldCnt().equals("0")) { //노후장비(검은색)
//                marker.setMarkerType(MapPOIItem.MarkerType.CustomImage);
//                marker.setCustomImageResourceId(R.drawable.marker_end);
//                marker.setCustomSelectedImageResourceId(R.drawable.marker_end);
//            } else {
//
//                marker.setMarkerType(MapPOIItem.MarkerType.BluePin);
//                marker.setSelectedMarkerType(MapPOIItem.MarkerType.RedPin);
//            }
//            mapView.addPOIItem(marker);
//        }
//
//        //업체 검색 후 보라색으로 표시
//        if (cp_idx != null && !TextUtils.isEmpty(cp_idx)) {
//
//            MapPOIItem marker = mapView.findPOIItemByTag(Integer.parseInt(cp_idx));
//            if (marker != null) {
//                mapView.selectPOIItem(marker, true);
//            }
//        }

        mapProgress.setVisibility(View.GONE);
    }

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

    @Override
    protected void onResume() {
        super.onResume();
        mapView.resume();
        MyFirebaseMessagingService.activity = this;
        air_line_position = -1;
        lastIndex = 0;
        count = 0;
        if (scroll_iot_data != null) scroll_iot_data.clear();

        if (chkGpsService()) {
            firstCurrentPoint = true;
            setGpsService();
        } else {
            try {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Get_Alarms();
                        Get_Location();
                        Get_Worker_List();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
//                startActivity(new Intent(context, Intro.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                finish();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.pause();
        MyFirebaseMessagingService.activity = null;
    }

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

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

    SubProdRecyclerAdapter.OnClickListener subProdOnClickListener = new SubProdRecyclerAdapter.OnClickListener() {
        @Override
        public void onClick(String x, String y, String get_cp_idx, String get_pt_idx, String cp_zip) {

            if (cp_zip != null && x != null && y != null) {
                cp_idx = get_cp_idx;
//                MapPoint mapPoint = MapPoint.mapPointWithGeoCoord(Double.parseDouble(x), Double.parseDouble(y));
//                mapView.setMapCenterPoint(mapPoint, true);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(
                        LatLng.from(Double.parseDouble(x), Double.parseDouble(y))
                );
                kakaoMap.moveCamera(cameraUpdate);
                Get_list();
                Set_Marker();
            } else {

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("우편번호 혹은 주소가 잘못되어 마커 표시가 불가합니다.\n주소를 수정해주세요.");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(context, FragmentActivity.class);
                        intent.putExtra("title", "장소정보 수정");
                        intent.putExtra("type", "place_adjust2");
                        intent.putExtra("value1", get_pt_idx);
                        intent.putExtra("value2", get_cp_idx);
                        intent.putExtra("value3", "main");
                        startActivity(intent);
                    }
                });
                dialogBuilder.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();

            }
        }
    };

    SubProdRecyclerAdapter.resetListener subProdResetListener = new SubProdRecyclerAdapter.resetListener() {
        @Override
        public void onClick(MachineItem data) {
            RunningTimeResetDialog dialog = new RunningTimeResetDialog(context, handler, data);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {

                    mode = "exchange";
                    list.setAdapter(subProdRecyclerAdapter);
                    swipe.setEnabled(false);
                    lastIndex = 0;
                    count = 0;
                    Set_Layout();
                    Get_list();
                    Get_Worker_List();
                }
            });
            dialog.show();
        }
    };

    SubProdRecyclerAdapter.enterpriseListener enterpriseListener = new SubProdRecyclerAdapter.enterpriseListener() {
        @Override
        public void onClick(SubProdData data) {
            String incodeUrl = URLEncoder.encode("https://" + userItem.getArrayitem().getAgency().getMbId() +
                    ".compcare.co.kr/sell/invoice/invoice_total_item/?ag_idx=" + data.getAgIdx() + "&cp_idx=" + data.getCpIdx() + "&pt_idx=" + data.getPtIdx());
            Intent intent = new Intent(context, WebviewAct.class);
            intent.putExtra("title", "매출 내역");
            intent.putExtra("url", "https://" + userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
            startActivity(intent);
        }
    };

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

    OldProdRecyclerAdapter.OnClickListener oldProdOnClickListener = new OldProdRecyclerAdapter.OnClickListener() {
        @Override
        public void onClick(String x, String y) {
//            MapPoint mapPoint = MapPoint.mapPointWithGeoCoord(Double.parseDouble(x), Double.parseDouble(y));
//            mapView.setMapCenterPoint(mapPoint, true);
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(
                    LatLng.from(Double.parseDouble(x), Double.parseDouble(y))
            );
            kakaoMap.moveCamera(cameraUpdate);
        }
    };

    IoTProdRecyclerAdapter.OnLoadMoreListener iotProdOnLoadMoreListener = new IoTProdRecyclerAdapter.OnLoadMoreListener() {
        @Override
        public void onLoadMore(int position) {

            if (count == limitCount) {
                lastIndex += limitCount;
                Get_Worker_List();
            }
        }
    };

    IoTProdRecyclerAdapter.OnClickListener iotProdOnClickListener = new IoTProdRecyclerAdapter.OnClickListener() {
        @Override
        public void onClick(String x, String y, String get_cp_idx, String get_pt_idx) {

            if (get_cp_idx != null && x != null && y != null) {
                cp_idx = get_cp_idx;
//                MapPoint mapPoint = MapPoint.mapPointWithGeoCoord(Double.parseDouble(x), Double.parseDouble(y));
//                mapView.setMapCenterPoint(mapPoint, true);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(
                        LatLng.from(Double.parseDouble(x), Double.parseDouble(y))
                );
                kakaoMap.moveCamera(cameraUpdate);
                Get_list();
                Set_Marker();

            } else {

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("우편번호 혹은 주소가 잘못되어 마커 표시가 불가합니다.\n주소를 수정해주세요.");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(context, FragmentActivity.class);
                        intent.putExtra("title", "장소정보 수정");
                        intent.putExtra("type", "place_adjust2");
                        intent.putExtra("value1", get_pt_idx);
                        intent.putExtra("value2", get_cp_idx);
                        intent.putExtra("value3", "main");
                        startActivity(intent);
                    }
                });
                dialogBuilder.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        }

        @Override
        public void onReportClick(Bundle bundle) {
            HashMap<String, String> data = new HashMap<>();
            data.put("ag_idx", bundle.getString("ag_idx"));
            data.put("pt_idx", bundle.getString("pt_idx"));
            data.put("mc_idx", bundle.getString("mc_idx"));
            new ApiClient(data, "proc_get_partner_machines", handler);
        }

        @Override
        public void onInitialization(MachineItem items) {

            RunningTimeResetDialog dialog = new RunningTimeResetDialog(context, handler, items);
            dialog.show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                mapProgress.setVisibility(View.VISIBLE);
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
//                        MapPoint point = MapPoint.mapPointWithGeoCoord(Double.parseDouble(data.getStringExtra("lat")), Double.parseDouble(data.getStringExtra("lng")));
//                        cp_idx = data.getStringExtra("cp_idx");
//                        mapView.setZoomLevel(1, true);
//                        mapView.setMapCenterPoint(point, true);

                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCenterPosition(
                                LatLng.from(Double.parseDouble(data.getStringExtra("lat")), Double.parseDouble(data.getStringExtra("lng")))
                        );
                        kakaoMap.moveCamera(cameraUpdate);
                    }
                }.start();
            }
        } else {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result.getContents() != null && !result.getContents().equals("")) {
                //Log.d("1234", result.getContents());
                mapProgress.setVisibility(View.VISIBLE);
                HashMap<String, String> dt = new HashMap<>();
                dt.put("qr_code", result.getContents());
                new ApiClient(dt, "proc_qr_code_view", handler);
            } else {
                Toast.makeText(context, "qr코드가 정상적으로 인식되지 않았습니다.", Toast.LENGTH_LONG).show();
            }
        }
    }

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

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication app = (MyApplication) getApplication();
        app.lastMapPoint = mp;
//        mapView.onSurfaceDestroyed();

        stop_thread();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication app = (MyApplication) getApplication();
        app.lastMapPoint = mp;
//        mapView.onSurfaceDestroyed();

        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }

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

    public void refresh() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mode = "default";
                list.setAdapter(workerListRecyclerAdapter);
                lastIndex = 0;
                count = 0;

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Get_Alarms();
                        Set_Layout();
                        Get_list();
                        Get_Worker_List();
                    }
                });
            }
        });
    }
}
