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.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.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
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.Product.MachineItem;
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;

public class Option_Machine_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView option_pd_nameTV, option_pd_specTV, option_macTV, option_set_dateTV, option_make_dateTV, option_qrTV, option_qr_use_dateTV,
            option_mc_delTV, option_saveTV, option_alarm_settingTV, option_add_qrTV, option_guaranteeTV, option_interlock_settingTV;
    private Spinner option_airlineSN, option_horsepowerSN;
    private EditText option_cycle_timeET, option_cycle_yearET, option_mc_lotET, option_power_maxET;
    private RadioGroup option_remoteRG, option_internetRG;
    private LinearLayout option_set_dateLL, option_make_dateLL, option_mc_delLL, option_photo_addLL, option_photoLL;
    private RecyclerView option_photoRV;
    private String mc_idx, mc_airline, remote_yn, mac, air_line, qr_code, mc_internet, mc_horsepower, air_leak_yn;
    private String[] air_line_array;
    private ArrayList<String> ori_photo_array, del_photo_array;
    private ArrayAdapter<String> air_line_adapter;
    private ArrayItem_<MachineItem> machine_item;
    private Context context;

    private ReportImageAdapter photo_adapter;
    private ArrayList<String> arr = new ArrayList<>();
    private DatePickerDialog.OnDateSetListener make_callbackMethod, del_callbackMethod, set_callbackMethod;

    private ProgressBar optionPB;

    //22-12-27 에어리크 기능추가
    private RadioGroup option_air_leakRG;
    private EditText option_air_leak_stdET, option_air_leak_timeET, option_air_leak_rangeET;

    @SuppressLint("ValidFragment")
    public Option_Machine_Fragment(Handler handler, String mc_idx, String air_line_array) {
        this.handler = handler;
        this.mc_idx = mc_idx;
        this.air_line = air_line_array;
    }

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

        option_airlineSN = v.findViewById(R.id.option_airlineSN);
        option_pd_nameTV = v.findViewById(R.id.option_pd_nameTV);
        option_pd_specTV = v.findViewById(R.id.option_pd_specTV);
        option_cycle_timeET = v.findViewById(R.id.option_cycle_timeET);
        option_cycle_yearET = v.findViewById(R.id.option_cycle_yearET);
        option_macTV = v.findViewById(R.id.option_macTV);
        option_remoteRG = v.findViewById(R.id.option_remoteRG);
        option_set_dateLL = v.findViewById(R.id.option_set_dateLL);
        option_set_dateTV = v.findViewById(R.id.option_set_dateTV);
        option_mc_lotET = v.findViewById(R.id.option_mc_lotET);
        option_make_dateLL = v.findViewById(R.id.option_make_dateLL);
        option_make_dateTV = v.findViewById(R.id.option_make_dateTV);
        option_qrTV = v.findViewById(R.id.option_qrTV);
        option_mc_delLL = v.findViewById(R.id.option_mc_delLL);
        option_qr_use_dateTV = v.findViewById(R.id.option_qr_use_dateTV);
        option_mc_delTV = v.findViewById(R.id.option_mc_delTV);
        option_saveTV = v.findViewById(R.id.option_saveTV);
        option_photoRV = v.findViewById(R.id.option_photoRV);
        option_photo_addLL = v.findViewById(R.id.option_photo_addLL);
        option_photoLL = v.findViewById(R.id.option_photoLL);
        optionPB = v.findViewById(R.id.optionPB);
        option_alarm_settingTV = v.findViewById(R.id.option_alarm_settingTV);
        option_add_qrTV = v.findViewById(R.id.option_add_qrTV);
        option_internetRG = v.findViewById(R.id.option_internetRG);
        option_horsepowerSN = v.findViewById(R.id.option_horsepowerSN);

        option_air_leakRG = v.findViewById(R.id.option_air_leakRG);
        option_air_leak_stdET = v.findViewById(R.id.option_air_leak_stdET);
        option_air_leak_timeET = v.findViewById(R.id.option_air_leak_timeET);
        option_air_leak_rangeET = v.findViewById(R.id.option_air_leak_rangeET);

        option_guaranteeTV = v.findViewById(R.id.option_guaranteeTV);

        option_interlock_settingTV = v.findViewById(R.id.option_interlock_settingTV);
        option_power_maxET = v.findViewById(R.id.option_power_maxET);

        context = getActivity().getBaseContext();

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

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

        air_line_adapter = new ArrayAdapter<>(getContext(), R.layout.custom_spinner_item_black_txt_15);
        air_line_array = air_line.split(",");
        air_line_adapter.addAll(air_line_array);
        option_airlineSN.setAdapter(air_line_adapter);

        ArrayAdapter<CharSequence> horsepower_adapter = ArrayAdapter.createFromResource(getContext(), R.array.horsepower, R.layout.custom_spinner_item_black_txt_15);
        option_horsepowerSN.setAdapter(horsepower_adapter);

        init_Handler();
        Get_Machine();
        init_Listener();

        return v;
    }

    void Get_Machine() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mc_idx", mc_idx);
        new ApiClient(data, "proc_admin_get_machine", handler);
    }

    void Set_Content() throws ParseException {

        option_pd_nameTV.setText(machine_item.getArrayitem().getProductData().getPdName());
        option_pd_specTV.setText(machine_item.getArrayitem().getProductData().getPdSpec());
        option_cycle_timeET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcCycle()));
        option_cycle_yearET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcCycleYear()));
        option_power_maxET.setText(machine_item.getArrayitem().getMcPowerConsumptionMax());

        if (machine_item.getArrayitem().getMcRemoteYn() != null && machine_item.getArrayitem().getMcRemoteYn().equals("Y")) {
            option_remoteRG.check(R.id.option_remote_yRBtn);
            remote_yn = "Y";
        } else {
            option_remoteRG.check(R.id.option_remote_nRBtn);
            remote_yn = "N";
        }

        if (machine_item.getArrayitem().getMcAirLeakYn() != null && machine_item.getArrayitem().getMcAirLeakYn().equals("Y")) {
            option_air_leakRG.check(R.id.option_air_leak_yRBtn);
            option_air_leak_stdET.setEnabled(true);
            option_air_leak_timeET.setEnabled(true);
            option_air_leak_rangeET.setEnabled(true);
            air_leak_yn = "Y";
        } else {
            option_air_leakRG.check(R.id.option_air_leak_nRBtn);
            option_air_leak_stdET.setEnabled(false);
            option_air_leak_timeET.setEnabled(false);
            option_air_leak_rangeET.setEnabled(false);
            air_leak_yn = "N";
        }

        if (machine_item.getArrayitem().getQrCode() == null || machine_item.getArrayitem().getQrCode().toString().contains("NO QR")) {
            option_add_qrTV.setVisibility(View.VISIBLE);

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

        if (machine_item.getArrayitem().getMcHorsepower() != null) {
            String[] androidStrings = getResources().getStringArray(R.array.horsepower);
            for (int i = 0; i < androidStrings.length; i++) {
                if (androidStrings[i].equals(machine_item.getArrayitem().getMcHorsepower())) {
                    option_horsepowerSN.setSelection(i);
                }
            }
        }

        if (machine_item.getArrayitem().getMcInternet() != null && machine_item.getArrayitem().getMcInternet().equals("LAN")) {
            option_internetRG.check(R.id.option_internet_lanRBtn);
            mc_internet = "LAN";

        } else if (machine_item.getArrayitem().getMcInternet() != null && machine_item.getArrayitem().getMcInternet().equals("LTE")) {
            option_internetRG.check(R.id.option_internet_lteRBtn);
            mc_internet = "LTE";
        }

        option_set_dateTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcSetdt()).toString());
        option_make_dateTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcMakedt()).toString());
        option_qrTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getQrCode()).toString());
        option_qr_use_dateTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getQrUseDt()).toString());
        option_mc_delTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcDeldt()).toString());
        option_mc_lotET.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcLot()).toString());

        if (!TextUtils.isEmpty(machine_item.getArrayitem().getMcAirLeakStd()))
            option_air_leak_stdET.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcAirLeakStd()).toString());
        if (!TextUtils.isEmpty(machine_item.getArrayitem().getMcAirLeakTime()))
            option_air_leak_timeET.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcAirLeakTime()).toString());
        if (!TextUtils.isEmpty(machine_item.getArrayitem().getMcAirLeakRange()))
            option_air_leak_rangeET.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcAirLeakRange()).toString());

        //에어라인 초기화
        for (int i = 0; i < air_line_array.length; i++) {
            if (air_line_array[i].equals(machine_item.getArrayitem().getMcAirline())) {
                option_airlineSN.setSelection(i);
                break;
            }
        }

        SimpleDateFormat sdfYMD = new SimpleDateFormat("yyyy-MM-dd");
        String qr_dt = machine_item.getArrayitem().getQrUseDt();

        if (!TextUtils.isEmpty(qr_dt)) {

            Date date = sdfYMD.parse(qr_dt);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            switch (machine_item.getArrayitem().getMcPaymentMethod()) {
                case "A":
                    cal.add(Calendar.MONTH, 12);
                    break;
                case "B":
                    cal.add(Calendar.MONTH, 24);
                    break;
                case "C":
                    cal.add(Calendar.MONTH, 36);
                    break;
                case "D":
                    cal.add(Calendar.MONTH, 48);
                    break;
            }

            Date today = new Date(System.currentTimeMillis());
            Date format2 = cal.getTime();
            long result = format2.getTime() - today.getTime();
            if (result > 0) {
                option_guaranteeTV.setText(sdfYMD.format(format2)+" ( 잔여 "+result / (24 * 60 * 60 * 1000) + "일 )");
            } else {
                option_guaranteeTV.setText(sdfYMD.format(format2)+" ( 보증기간 종료 )");
            }

        }


        //사진 초기화
        ori_photo_array = new ArrayList<>();
        del_photo_array = new ArrayList<>();
        if (machine_item.getArrayitem().getMachinePhoto() != null) {
            String manager_uri = "https://www.compcare.co.kr/uploads/machine/";
            arr.clear();
            for (int i = 0; i < machine_item.getArrayitem().getMachinePhoto().size(); i++) {
                arr.add(manager_uri + machine_item.getArrayitem().getMachinePhoto().get(i).getPfiFilename());
                ori_photo_array.add(machine_item.getArrayitem().getMachinePhoto().get(i).getPfiFilename());
            }
            option_photoLL.setVisibility(View.VISIBLE);
            photo_adapter.addItem(arr);
        }

        option_macTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getMcIotMac()).toString());
        mac = option_macTV.getText().toString();

        if (TextUtils.isEmpty(mac) || mac.equals("")) {
            option_cycle_timeET.setEnabled(false);
            option_cycle_yearET.setEnabled(false);
            option_remoteRG.findViewById(R.id.option_remote_yRBtn).setEnabled(false);
            option_remoteRG.findViewById(R.id.option_remote_nRBtn).setEnabled(false);
        }
    }

    void init_Listener() {

        //IoT 설정 클릭 리스너
        option_alarm_settingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(mac) || mac.equals("")) {
                    Common.getInstance().toastShow(context, "해당 메뉴는 IoT를 설치한 뒤 이용하실 수 있습니다.");
                    return;
                }

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("title", "기계 옵션설정");
                intent.putExtra("type", "option_iot");
                intent.putExtra("value1", machine_item.getArrayitem().getMcIdx());
                intent.putExtra("value2", machine_item.getArrayitem().getCpIdx());
                intent.putExtra("value3", machine_item.getArrayitem().getMcIotMac());
                intent.putExtra("value4", air_line);
                fa.finish();
                startActivity(intent);

            }
        });

        //연동제어 설정 클릭리스너
        option_interlock_settingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mac) || mac.equals("")) {
                    Common.getInstance().toastShow(context, "해당 메뉴는 IoT를 설치한 뒤 이용하실 수 있습니다.");
                    return;
                }

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("title", "기계 옵션설정");
                intent.putExtra("type", "option_interlock");
                intent.putExtra("value1", machine_item.getArrayitem().getCpIdx());
                intent.putExtra("value2", machine_item.getArrayitem().getMcIdx());
                intent.putExtra("value3", air_line);
                fa.finish();
                startActivity(intent);
            }
        });

        //에어라인 클릭 리스너
        option_airlineSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mc_airline = option_airlineSN.getSelectedItem().toString();
            }

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

            }
        });

        //원격 조종 클릭 리스너
        option_remoteRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Button button = group.findViewById(checkedId);
                switch (button.getText().toString()) {
                    case "사용":
                        remote_yn = "Y";
                        break;
                    case "사용안함":
                        remote_yn = "N";
                        break;
                }
            }
        });

        //인터넷 연결 클릭 리스너
        option_internetRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Button button = group.findViewById(checkedId);
                switch (button.getText().toString()) {
                    case "LAN":
                        mc_internet = "LAN";
                        break;
                    case "LTE":
                        mc_internet = "LTE";
                        break;
                    default:
                        mc_internet = null;
                        break;
                }
            }
        });

        //기계 마력 리스너
        option_horsepowerSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    mc_horsepower = option_horsepowerSN.getSelectedItem().toString();
                } else {
                    mc_horsepower = null;
                }
            }

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

            }
        });

        //제조일 클릭 리스너
        option_make_dateLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getContext(), make_callbackMethod, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
                dialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
                dialog.show();
            }
        });

        make_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;
                }
                option_make_dateTV.setText(year + "-" + con_month + "-" + con_day);
            }
        };

        //설치/관리일 클릭 리스너
        option_set_dateLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getContext(), set_callbackMethod, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
                dialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
                dialog.show();
            }
        });

        set_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;
                }
                option_set_dateTV.setText(year + "-" + con_month + "-" + con_day);
            }
        };

        //폐기일자 클릭 리스너
        option_mc_delLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getContext(), del_callbackMethod, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
                dialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
                dialog.show();
            }
        });

        del_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;
                }
                option_mc_delTV.setText(year + "-" + con_month + "-" + con_day);
            }
        };

        //사진 추가 리스너
        option_photo_addLL.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);
                                option_photoLL.setVisibility(View.VISIBLE);
                            });
//                    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);
//                                    option_photoLL.setVisibility(View.VISIBLE);
//                                }
//                            })
//                            .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();
                }
            }
        });

        //사진삭제버튼 클릭리스너
        photo_adapter.setOnItemClickListener(new ReportImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                photo_adapter.removeItem(position);

                if (machine_item.getArrayitem().getMachinePhoto() != null && ori_photo_array.size() > 0) {
                    for (int i = 0; i < machine_item.getArrayitem().getMachinePhoto().size(); i++) {
                        if (machine_item.getArrayitem().getMachinePhoto().get(i).getPfiFilename().contains(ori_photo_array.get(position))) {
                            del_photo_array.add(machine_item.getArrayitem().getMachinePhoto().get(i).getPfiIdx());
                            break;
                        }
                    }
                }
                ori_photo_array.remove(position);
                arr.remove(position);

                if (photo_adapter.getItemCount() < 1) {
                    option_photoLL.setVisibility(View.GONE);
                }
            }
        });

        //에어리크 활성화
        option_air_leakRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Button button = group.findViewById(checkedId);
                switch (button.getText().toString()) {
                    case "비활성화":
                        air_leak_yn = "N";
                        option_air_leak_stdET.setEnabled(false);
                        option_air_leak_timeET.setEnabled(false);
                        option_air_leak_rangeET.setEnabled(false);
                        break;
                    case "활성화":
                        air_leak_yn = "Y";
                        option_air_leak_stdET.setEnabled(true);
                        option_air_leak_timeET.setEnabled(true);
                        option_air_leak_rangeET.setEnabled(true);
                        break;
                }
            }
        });

        //저장버튼 클릭 리스너
        option_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                option_saveTV.setEnabled(false);
                optionPB.setVisibility(View.VISIBLE);
                save_option();

            }
        });

        //QR 등록 클릭 리스너
        option_add_qrTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentIntentIntegrator integrator = new FragmentIntentIntegrator(Option_Machine_Fragment.this);
                integrator.setCaptureActivity(QRCodeActivity.class);
                integrator.setBarcodeImageEnabled(true);
                integrator.setOrientationLocked(false);
                integrator.initiateScan();
            }
        });

    }

    void save_option() {

        if (qr_code != null && !TextUtils.isEmpty(qr_code) && !qr_code.contains("Q")) {
            Common.getInstance().toastShow(context, "QR 코드의 형식이 올바르지 않습니다. QR 코드를 다시 입력해주세요.");
        }

        String mc_cycle = Common.getInstance().isNullToZero(option_cycle_timeET.getText().toString());
        String mc_cycle_year = Common.getInstance().isNullToZero(option_cycle_yearET.getText().toString());

        String mc_setdt = Common.getInstance().isNullText(option_set_dateTV.getText().toString());
        String mc_lot = Common.getInstance().isNullText(option_mc_lotET.getText().toString());
        String mc_makedt = Common.getInstance().isNullText(option_make_dateTV.getText().toString());
        String mc_deldt = Common.getInstance().isNullText(option_mc_delTV.getText().toString());

        String mc_air_leak_std = Common.getInstance().isNullToZeroFloat(option_air_leak_stdET.getText().toString());
        String mc_air_leak_time = Common.getInstance().isNullToZero(option_air_leak_timeET.getText().toString());
        String mc_air_leak_range = Common.getInstance().isNullToZeroFloat(option_air_leak_rangeET.getText().toString());

        HashMap<String, String> data = new HashMap<>();
        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
        data.put("mb_token", Common.getInstance().getPref(context, "token"));
        data.put("mc_idx", mc_idx);
        data.put("ag_idx", machine_item.getArrayitem().getAgIdx());
        data.put("pt_idx", machine_item.getArrayitem().getPtIdx());
        data.put("cp_idx", machine_item.getArrayitem().getCpIdx());
        data.put("mc_power_consumption_max", Common.getInstance().isNullToZero(option_power_maxET.getText().toString()));

        if (!TextUtils.isEmpty(mac)) data.put("mac", mac);

        data.put("mc_airline", mc_airline);
        data.put("mc_remote_yn", remote_yn);
        data.put("mc_air_leak_yn", air_leak_yn);

        if (air_leak_yn.equals("Y")) {
            data.put("mc_air_leak_std", mc_air_leak_std);
            data.put("mc_air_leak_time", mc_air_leak_time);
            data.put("mc_air_leak_range", mc_air_leak_range);
        }

        if (option_macTV.getText() != null || !option_macTV.getText().equals("")) {
            data.put("mc_cycle", mc_cycle);
            data.put("mc_cycle_year", mc_cycle_year);
        }

        if (!mc_setdt.equals("")) {
            data.put("mc_setdt", mc_setdt);
        }

        if (!mc_lot.equals("")) {
            data.put("mc_lot", mc_lot);
        }

        if (!mc_makedt.equals("")) {
            data.put("mc_makedt", mc_makedt);
        }

        if (!mc_deldt.equals("")) {
            data.put("mc_deldt", mc_deldt);
        }

        if (!TextUtils.isEmpty(mc_horsepower)) {
            data.put("mc_horsepower", mc_horsepower);
        }

        if (!TextUtils.isEmpty(mc_internet)) {
            data.put("mc_internet", mc_internet);
        }

        if (qr_code != null && !TextUtils.isEmpty(qr_code))
            data.put("qr_code", qr_code);

        if (del_photo_array.size() > 0) {
            String del_photo = del_photo_array.toString();
            del_photo = del_photo.replace("[", "");
            del_photo = del_photo.replace("]", "");
            data.put("del_photo_array", del_photo);
        }

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

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

        } else {
            new ApiClient(data, "proc_admin_machine_option2", 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) {
            qr_code = result.getContents();
            option_qrTV.setText(qr_code);
        }

    }

    void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {

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

                        if (machine_item.isSuccess()) {
                            try {
                                Set_Content();
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }

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

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

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

                            Toast.makeText(context, "머신 기계정보를 수정했습니다.", Toast.LENGTH_SHORT).show();
                            getActivity().finish();

                        } else {
                            Toast.makeText(getContext(), "데이터 저장에 실패했습니다.", Toast.LENGTH_SHORT).show();
                        }
                        option_saveTV.setEnabled(true);

                    }

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

