package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
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.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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.IntentResult;

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

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Activity.QRCodeActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.Data.Product.ProductData;
import kr.co.compcarecompany.Fragment.FragmentIntentIntegrator;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ReportImageAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AddAirLineDialog;
import kr.co.compcarecompany.Util.CustomView.AddPlaceDialog;
import kr.co.compcarecompany.Util.CustomView.AddProductDialog;
import kr.co.compcarecompany.Util.CustomView.SearchMachineDialog;

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

    Handler handler;
    FragmentActivity fa;

    TextView add_machine_pt_nameTV, add_machine_pt_ceoTV, add_machine_pt_codeTV, add_machine_add_companyTV, add_machine_cp_addrTV, add_machine_cp_addr_subTV,
            add_machine_add_lineTV, add_machine_add_productTV, add_machine_product_codeTV, add_machine_product_nameTV,
            add_machine_product_specTV, add_machine_make_dateTV, add_machine_qrTV, add_machine_saveTV, add_machine_product_typeTV;
    Spinner add_machine_select_companySN, add_machine_select_lineSN, add_machine_product_typeSN, add_machine_macSN;
    ImageView add_machine_search_productIV;
    EditText add_machine_product_serialET, add_machine_running_totalET, add_machine_remain_timeET, add_machine_search_productET;
    LinearLayout add_machine_add_photoLL, add_machine_iotLL, add_machine_add_iotLL;
    RecyclerView add_machine_photoRV;
    String ag_idx, pt_idx, place_str, air_line_str, product_str, airline, qr_code, mac, mc_ttype, pd_idx;
    String[] air_line_array, product_array;
    ArrayAdapter<String> place_adapter, air_line_adapter, product_adapter, mac_adapter;
    ArrayItem<CompanyData> companyItems;
    ArrayItem<MonitoringData> mac_items;
    ProductData productData;
    int select_position = 0;
    int air_position = 0;
    boolean add_iot = false;
    boolean mac_is_correct = true;
    ArrayItem<ProductData> product_items;
    String product;
    RadioButton add_machine_qr_yBtn, add_machine_qr_nBtn;

    ReportImageAdapter photo_adapter;
    private ArrayList<String> arr = new ArrayList<>();
    private DatePickerDialog.OnDateSetListener callbackMethod;

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

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

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

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

        add_machine_pt_nameTV = v.findViewById(R.id.add_machine_pt_nameTV);
        add_machine_pt_ceoTV = v.findViewById(R.id.add_machine_pt_ceoTV);
        add_machine_pt_codeTV = v.findViewById(R.id.add_machine_pt_codeTV);
        add_machine_add_companyTV = v.findViewById(R.id.add_machine_add_companyTV);
        add_machine_select_companySN = v.findViewById(R.id.add_machine_select_companySN);
        add_machine_cp_addrTV = v.findViewById(R.id.add_machine_cp_addrTV);
        add_machine_cp_addr_subTV = v.findViewById(R.id.add_machine_cp_addr_subTV);
        add_machine_add_lineTV = v.findViewById(R.id.add_machine_add_lineTV);
        add_machine_select_lineSN = v.findViewById(R.id.add_machine_select_lineSN);
        add_machine_add_productTV = v.findViewById(R.id.add_machine_add_productTV);
        add_machine_search_productET = v.findViewById(R.id.add_machine_search_productET);
        add_machine_search_productIV = v.findViewById(R.id.add_machine_search_productIV);
        add_machine_product_typeSN = v.findViewById(R.id.add_machine_product_typeSN);
        add_machine_product_codeTV = v.findViewById(R.id.add_machine_product_codeTV);
        add_machine_product_nameTV = v.findViewById(R.id.add_machine_product_nameTV);
        add_machine_product_specTV = v.findViewById(R.id.add_machine_product_specTV);
        add_machine_running_totalET = v.findViewById(R.id.add_machine_running_totalET);
        add_machine_remain_timeET = v.findViewById(R.id.add_machine_remain_timeET);
        add_machine_add_photoLL = v.findViewById(R.id.add_machine_add_photoLL);
        add_machine_photoRV = v.findViewById(R.id.add_machine_photoRV);
        add_machine_iotLL = v.findViewById(R.id.add_machine_iotLL);
        add_machine_qrTV = v.findViewById(R.id.add_machine_qrTV);
        add_machine_macSN = v.findViewById(R.id.add_machine_macSN);
        add_machine_saveTV = v.findViewById(R.id.add_machine_saveTV);
        add_machine_product_typeTV = v.findViewById(R.id.add_machine_product_typeTV);
        add_machine_add_iotLL = v.findViewById(R.id.add_machine_add_iotLL);
        add_machine_qr_yBtn = v.findViewById(R.id.add_machine_qr_yBtn);
        add_machine_qr_nBtn = v.findViewById(R.id.add_machine_qr_nBtn);

        qr_code = "NO QR CODE";
        add_machine_qrTV.setText(qr_code);

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, getContext().getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) - (add_machine_photoRV.getPaddingLeft() + add_machine_photoRV.getPaddingRight() - px * 2) / 3;

        add_machine_photoRV.setLayoutManager(new GridLayoutManager(getContext(), 3));
        photo_adapter = new ReportImageAdapter(getContext(), itemHeight);
        add_machine_photoRV.setAdapter(photo_adapter);

        //mac 주소 검색 21.10.20
//        search_macIV = v.findViewById(R.id.search_macIV);
//        search_macET = v.findViewById(R.id.search_macET);
//        search_macRL = v.findViewById(R.id.search_macRL);

        init_Listener();
        init_Handler();
        Get_partner();

        return v;
    }

    void Get_partner() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("pt_idx", pt_idx);
        data.put("type", "COMPANY");
        new ApiClient(data, "proc_admin_partner_view", handler);
    }

    void Set_Content() {

        add_machine_pt_nameTV.setText(companyItems.get(0).getPtName());
        add_machine_pt_ceoTV.setText(companyItems.get(0).getPtCeo());
        add_machine_pt_codeTV.setText(companyItems.get(0).getPtCode());

        //설치장소 스피너 초기화
        place_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

        for (int i = 0; i < companyItems.size(); i++) {
            place_adapter.add(companyItems.get(i).getCpName());
        }
        add_machine_select_companySN.setAdapter(place_adapter);
        add_machine_select_companySN.setSelection(select_position);
        add_machine_cp_addrTV.setText(companyItems.get(select_position).getCpAddr());
        add_machine_cp_addr_subTV.setText(companyItems.get(select_position).getCpAddrSub());

        //에어라인 스피너 초기화
        air_line_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

        if (companyItems.getArrayitem().get(select_position).getCpAirline() == null) {
            air_line_str = "기본값";

        } else {
            air_line_str = companyItems.get(select_position).getCpAirline().toString();
        }

        air_line_array = air_line_str.split(",");
        for (String s : air_line_array) {
            if (!s.equals("임시 에어라인"))
            air_line_adapter.add(s);
        }
        add_machine_select_lineSN.setAdapter(air_line_adapter);
        add_machine_select_lineSN.setSelection(air_position);

        //기종추가 스피너 초기화
        product_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

        product_array = new String[]{"Compressor", "Tank", "After Cooler", "Dryer", "Filter", "흡착식", "OIL MIST SEPERATOR", "AUTO TRAP"};
        for (String s : product_array) {
            product_adapter.add(s);
        }
        add_machine_product_typeSN.setAdapter(product_adapter);

    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        photo_adapter.setOnItemClickListener(new ReportImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                photo_adapter.removeItem(position);
                arr.remove(position);
            }
        });
    }

    void init_Listener() {

        //선택한 place
        add_machine_select_companySN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                add_machine_cp_addrTV.setText(companyItems.get(position).getCpAddr());
                add_machine_cp_addr_subTV.setText(companyItems.get(position).getCpAddrSub());

                air_line_adapter.clear();
                air_line_array = null;
                air_line_str = null;

                if (companyItems.getArrayitem().get(position).getCpAirline() == null) {
                    air_line_str = "기본값";

                } else {
                    air_line_str = companyItems.get(position).getCpAirline().toString();
                }

                air_line_array = air_line_str.split(",");
                for (String s : air_line_array) {
                    if (!s.equals("임시 에어라인"))
                    air_line_adapter.add(s);
                }

                airline = add_machine_select_lineSN.getItemAtPosition(0).toString();
                select_position = position;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        //선택한 Air_Line
        add_machine_select_lineSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                airline = add_machine_select_lineSN.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

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

                AddPlaceDialog dialog = new AddPlaceDialog(getContext(), handler, ag_idx, pt_idx);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        Get_partner();
                    }
                });
                dialog.show();
            }
        });

        //라인추가 클릭 리스너
        add_machine_add_lineTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddAirLineDialog dialog = new AddAirLineDialog(getContext(), handler, companyItems.get(select_position).getCpIdx(), air_line_array, new AddAirLineDialog.clickListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> data) {
                        air_position = Integer.parseInt(data.get("air_position"));
                        Get_partner();
                    }
                });
                dialog.show();
            }
        });

        //기종검색 클릭 리스너
        add_machine_search_productIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                product = add_machine_search_productET.getText().toString();

                if (TextUtils.isEmpty(product)) {
                    Common.getInstance().toastShow(getContext(), "찾는 기종명을 입력해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pd_name", product);
                data.put("type", "COMPANY");
                new ApiClient(data, "proc_admin_search_machine", handler);

            }
        });

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

                int month = monthOfYear + 1;
                String con_month = month + "";
                if (month < 10) {
                    con_month = "0" + con_month;
                }

                String con_day = dayOfMonth + "";
                if (dayOfMonth < 10) {
                    con_day = "0" + con_day;
                }
                add_machine_make_dateTV.setText(year + "-" + con_month + "-" + con_day);
            }
        };

        //기종추가 클릭 리스너
        add_machine_add_productTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddProductDialog dialog = new AddProductDialog(getContext(), handler, ag_idx, pt_idx, new AddProductDialog.clickListener() {
                    @Override
                    public void clickBtn(HashMap<String, ProductData> data) {
                        ProductData productData = data.get("product_data");

                        add_machine_product_typeSN.setVisibility(View.GONE);
                        add_machine_product_typeTV.setVisibility(View.VISIBLE);

                        switch (productData.getPdTtype()) {
                            case "COMP":
                                mc_ttype = "COMP";
                                add_machine_product_typeTV.setText("Compressor");
                                break;
                            case "TANK":
                                mc_ttype = "TANK";
                                add_machine_product_typeTV.setText("Tank");
                                break;
                            case "COOLER":
                                mc_ttype = "COOLER";
                                add_machine_product_typeTV.setText("After Cooler");
                                break;
                            case "DRYER":
                                mc_ttype = "DRYER";
                                add_machine_product_typeTV.setText("Dryer");
                                break;
                            case "FILTER":
                                mc_ttype = "FILTER";
                                add_machine_product_typeTV.setText("Filter");
                                break;
                            case "SUCTION":
                                mc_ttype = "SUCTION";
                                add_machine_product_typeTV.setText("흡착식");
                                break;
                            case "MIST":
                                mc_ttype = "MIST";
                                add_machine_product_typeTV.setText("OIL MIST SEPERATOR");
                                break;
                            case "TRAP":
                                mc_ttype = "TRAP";
                                add_machine_product_typeTV.setText("AUTO TRAP");
                                break;
                            default:
                                mc_ttype = null;
                                add_machine_product_typeSN.setVisibility(View.VISIBLE);
                                add_machine_product_typeTV.setVisibility(View.GONE);
                        }
                        pd_idx = productData.getPdIdx();
                        add_machine_product_codeTV.setText(productData.getPdCode());
                        add_machine_product_nameTV.setText(productData.getPdShortName());
                        add_machine_product_specTV.setText(productData.getPdSpec());

                    }
                });
                dialog.show();
            }
        });

        //기종사진 추가 클릭 리스너
        add_machine_add_photoLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectSize = photo_adapter.getItemCount();
                if (selectSize < 3) {
                    TedImagePicker.with(requireContext())
                            .startMultiImage(uriList -> {
                                for (int i = 0; i < uriList.size(); i++) {
                                    arr.add(uriList.get(i).toString());
                                }
                                photo_adapter.addItem(arr);
                            });
//                    TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(getContext()).setImageProvider(new TedBottomPicker.ImageProvider() {
//                        @Override
//                        public void onProvideImage(ImageView imageView, Uri imageUri) {
//                            Glide.with(getContext()).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                        }
//                    }).setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
//                        @Override
//                        public void onImagesSelected(ArrayList<Uri> uriList) {
//
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//                            photo_adapter.addItem(arr);
//                        }
//                    })
//                            .setCompleteButtonText("저장")
//                            .setPeekHeight(2400)
//                            .setPreviewMaxCount(1000).setSelectMaxCount(3 - selectSize).create();
//                    tedBottomPicker.show(getActivity().getSupportFragmentManager());
                } else {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사진은 최대 3장까지 등록가능합니다.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }

            }
        });

        //선택한 제품 구분
        add_machine_product_typeSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (add_machine_product_typeSN.getSelectedItem().toString()) {
                    case "Compressor":
                        mc_ttype = "COMP";
                        break;
                    case "Tank":
                        mc_ttype = "TANK";
                        break;
                    case "After Cooler":
                        mc_ttype = "COOLER";
                        break;
                    case "Dryer":
                        mc_ttype = "DRYER";
                        break;
                    case "Filter":
                        mc_ttype = "FILTER";
                        break;
                    case "흡착식":
                        mc_ttype = "SUCTION";
                        break;
                    case "OIL MIST SEPERATOR":
                        mc_ttype = "MIST";
                        break;
                    case "AUTO TRAP":
                        mc_ttype = "TRAP";
                        break;
                }
            }

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

            }
        });

        //iot 추가 클릭 리스너
        add_machine_add_iotLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> get_data = new HashMap<>();
                qr_code = "NO QR CODE";
                add_machine_qrTV.setText(qr_code);
                add_iot = true;
                new ApiClient(get_data, "proc_influx_mac_get", handler);
            }
        });

        //qr 코드 등록여부
        add_machine_qr_nBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    qr_code = "NO QR CODE";
                    add_machine_qrTV.setText(qr_code);
                    add_iot = true;
                    add_machine_qr_yBtn.setChecked(false);
                    HashMap<String, String> get_data = new HashMap<>();
                    new ApiClient(get_data, "proc_influx_mac_get", handler);
                }
            }
        });

        //qr 코드 등록여부
        add_machine_qr_yBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    FragmentIntentIntegrator integrator = new FragmentIntentIntegrator(Add_Machine_Fragment.this);
                    integrator.setCaptureActivity(QRCodeActivity.class);
                    integrator.setBarcodeImageEnabled(true);
                    integrator.setOrientationLocked(false);
                    integrator.initiateScan();
                    add_machine_qr_nBtn.setChecked(false);
                }
            }
        });

        //선택한 mac
        add_machine_macSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mac = add_machine_macSN.getSelectedItem().toString();
            }

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

            }
        });

        //저장버튼 클릭 리스너
        add_machine_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mc_runningtime_total = add_machine_running_totalET.getText().toString();
                String mc_cycle = add_machine_remain_timeET.getText().toString();
                String product_name = add_machine_product_nameTV.getText().toString();

                if (TextUtils.isEmpty(product_name)) {
                    Common.getInstance().toastShow(getContext(), "등록할 기종을 검색 또는 추가해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);
                data.put("cp_idx", companyItems.get(select_position).getCpIdx());
                data.put("pd_idx", pd_idx);
                data.put("mc_airline", airline);
                data.put("mc_ttype", mc_ttype);
                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                data.put("mb_token", Common.getInstance().getPref(getContext(), "token"));
                Log.d("머신토큰@@@@", Common.getInstance().getPref(getContext(), "token"));
//                data.put("mb_token", FirebaseInstanceId.getInstance().getToken());

                if (add_iot) {

                    if (!mac_is_correct || TextUtils.isEmpty(mac)) {
                        Common.getInstance().toastShow(getContext(), "MAC 주소를 확인 해주세요.");
                        return;
                    }

                    if (TextUtils.isEmpty(mc_runningtime_total) || TextUtils.isEmpty(mc_cycle)) {
                        Common.getInstance().toastShow(getContext(), "IoT정보 전체 항목을 입력해주세요.");
                        return;
                    }

                    data.put("qr_code", qr_code);
                    data.put("mc_iot_mac", mac);
                    data.put("mc_runningtime_total", mc_runningtime_total);
                    data.put("mc_cycle", mc_cycle);
                }

                ArrayList<Uri> photo_uri = new ArrayList<>();
                for (int i = 0; i < arr.size(); i++) {
                    photo_uri.add(Uri.parse(arr.get(i)));
                }

                if (photo_uri.size() > 0) {
                    new ApiClient(data, "proc_machine_insert", photo_uri, handler);

                } else {
                    new ApiClient(data, "proc_machine_insert", handler);
                }
            }
        });
    }

    @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("")) {

            qr_code = result.getContents();
            add_machine_qrTV.setText(qr_code);
//            HashMap<String, String> get_data = new HashMap<>();
//            new ApiClient(get_data, "proc_influx_mac_get", handler);
            add_iot = true;

            HashMap<String, String> get_data = new HashMap<>();
            get_data.put("qr_code", qr_code.replace("Q", ""));
            Log.d("qr@@@", get_data.toString());

            new ApiClient(get_data, "proc_influx_mac_get", handler);


        } else {
            add_machine_qr_nBtn.setChecked(true);
            add_machine_qr_yBtn.setChecked(false);
        }
    }

    void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    if (url.equals("proc_admin_partner_view")) {
                        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()) {
                            Set_Content();

                        } else {
                            Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                        }

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

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

                        mac_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            add_machine_add_iotLL.setVisibility(View.GONE);

                            if (result_item.get("resultItem").getAsJsonObject().get("message").getAsString().equals("1")) {
                                ArrayItem_<MonitoringData> mac_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MonitoringData>>() {
                                }.getType());
                                mac_adapter.add(mac_items.getArrayitem().getMAC());

                            } else {
                                mac_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                                }.getType());

                                for (int i = 0; i < mac_items.size(); i++) {
                                    String str = mac_items.getArrayitem().get(i).getMAC();
                                    mac_adapter.add(str);
                                }
                            }
                            add_machine_macSN.setAdapter(mac_adapter);
                            add_machine_iotLL.setVisibility(View.VISIBLE);

                        } else {
                            add_machine_add_iotLL.setVisibility(View.VISIBLE);
                            add_machine_iotLL.setVisibility(View.GONE);
                            Toast.makeText(getContext(), "등록 가능한 MAC이 없습니다.", Toast.LENGTH_SHORT).show();
                            add_iot = false;
                        }

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();

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

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

                        if (product_items.isSuccess()) {

                            //ag_idx, pd_name
                            SearchMachineDialog dialog = new SearchMachineDialog(getContext(), handler, ag_idx, product, product_items, new SearchMachineDialog.clickListener() {
                                @Override
                                public void clickBtn(HashMap<String, ProductData> data) {
                                    productData = data.get("productData");
                                    add_machine_product_codeTV.setText(productData.getPdCode());
                                    add_machine_product_nameTV.setText(productData.getPdShortName());
                                    add_machine_product_specTV.setText(productData.getPdSpec());
                                    add_machine_search_productET.setText(productData.getPdShortName());
                                    pd_idx = productData.getPdIdx();

                                    if (productData.getPdTtype() == null) {
                                        add_machine_product_typeSN.setVisibility(View.VISIBLE);
                                        add_machine_product_typeTV.setVisibility(View.GONE);

                                    } else {
                                        add_machine_product_typeSN.setVisibility(View.GONE);
                                        add_machine_product_typeTV.setVisibility(View.VISIBLE);

                                        switch (productData.getPdTtype()) {
                                            case "COMP":
                                                mc_ttype = "COMP";
                                                add_machine_product_typeTV.setText("Compressor");
                                                break;
                                            case "TANK":
                                                mc_ttype = "TANK";
                                                add_machine_product_typeTV.setText("Tank");
                                                break;
                                            case "COOLER":
                                                mc_ttype = "COOLER";
                                                add_machine_product_typeTV.setText("After Cooler");
                                                break;
                                            case "DRYER":
                                                mc_ttype = "DRYER";
                                                add_machine_product_typeTV.setText("Dryer");
                                                break;
                                            case "FILTER":
                                                mc_ttype = "FILTER";
                                                add_machine_product_typeTV.setText("Filter");
                                                break;
                                            case "SUCTION":
                                                mc_ttype = "SUCTION";
                                                add_machine_product_typeTV.setText("흡착식");
                                                break;
                                            case "MIST":
                                                mc_ttype = "MIST";
                                                add_machine_product_typeTV.setText("OIL MIST SEPERATOR");
                                                break;
                                            case "TRAP":
                                                mc_ttype = "TRAP";
                                                add_machine_product_typeTV.setText("AUTO TRAP");
                                                break;
                                            default:
                                                mc_ttype = null;
                                                add_machine_product_typeSN.setVisibility(View.VISIBLE);
                                                add_machine_product_typeTV.setVisibility(View.GONE);
                                        }
                                    }
                                }
                            });
                            dialog.show();

                        } else {
                            Common.getInstance().toastShow(getContext(), "일치하는 기종이 없습니다.");
                        }
                    }

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