package kr.co.compcareworker.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
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 com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.Machine.Product.ProductData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

public class AddProductDialog extends Dialog {

    private Context context;
    private String ag_idx;
    private Handler hdr;
    private TextView dlg_product_saveTV;
    private EditText dlg_product_nameET, dlg_product_memoET, dlg_product_sizeET, dlg_product_weightET, dlg_product_inoutET;
    private Spinner dlg_product_typeSN, dlg_product_nameSN, dlg_product_pressureSN, dlg_product_voltageSN, dlg_product_frequencySN, dlg_product_coldSN, dlg_product_playSN;
    private RadioGroup dlg_product_guRG, dlg_product_oil_typeRG;
    private LinearLayout show_type_aLL, show_type_bLL, show_type_cLL, show_type_dLL;
    private ArrayAdapter<String> type_adapter, name_adapter, pressure_adapter, voltage_adapter, frequency_adapter, cold_adapter, play_adapter;
    private String[] type_array, pressure_array, voltage_array, frequency_array, cold_array, play_array;
    private String pd_gu, pd_cold, pd_play, pd_voltage, pd_frequency, pd_pressure, pd_type, pd_weight, pd_oil_type, pd_ttype, pd_short_name, pd_inout, pd_memo, pd_size;
    private int type = 0;
    private ArrayItem<ProductData> model_items;
    private ArrayItem_<ProductData> product_data;

    private AddProductDialog.clickListener clickListener;

    public interface clickListener {
        void clickBtn(HashMap<String, ProductData> data);
    }

    public AddProductDialog(@NonNull Context context, Handler hdr, String ag_idx, AddProductDialog.clickListener clickListener) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.clickListener = clickListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dlg_add_product);

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.90f);

        thisWindow.setLayout(x, y);

        dlg_product_typeSN = findViewById(R.id.dlg_product_typeSN);
        dlg_product_nameSN = findViewById(R.id.dlg_product_nameSN);
        dlg_product_nameET = findViewById(R.id.dlg_product_nameET);
        dlg_product_pressureSN = findViewById(R.id.dlg_product_pressureSN);
        dlg_product_voltageSN = findViewById(R.id.dlg_product_voltageSN);
        dlg_product_frequencySN = findViewById(R.id.dlg_product_frequencySN);
        dlg_product_coldSN = findViewById(R.id.dlg_product_coldSN);
        dlg_product_playSN = findViewById(R.id.dlg_product_playSN);
        dlg_product_memoET = findViewById(R.id.dlg_product_memoET);
        dlg_product_saveTV = findViewById(R.id.dlg_product_saveTV);
        dlg_product_sizeET = findViewById(R.id.dlg_product_sizeET);
        dlg_product_weightET = findViewById(R.id.dlg_product_weightET);
        dlg_product_inoutET = findViewById(R.id.dlg_product_inoutET);
        show_type_aLL = findViewById(R.id.show_type_aLL);
        show_type_bLL = findViewById(R.id.show_type_bLL);
        show_type_cLL = findViewById(R.id.show_type_cLL);
        show_type_dLL = findViewById(R.id.show_type_dLL);
        dlg_product_guRG = findViewById(R.id.dlg_product_guRG);
        dlg_product_oil_typeRG = findViewById(R.id.dlg_product_oil_typeRG);
        pd_gu = "PSOI";
        pd_cold = "A";
        pd_play = "A";
        pd_voltage = "A";
        pd_frequency = "A";
        pd_type = "MAIN";
        pd_ttype = "COMP";
        pd_oil_type = "INJEC";

        show_type_aLL.setVisibility(View.VISIBLE);
        show_type_bLL.setVisibility(View.GONE);
        show_type_cLL.setVisibility(View.GONE);
        show_type_dLL.setVisibility(View.VISIBLE);

        init_Handler();
        init_Listener();
        init_Spinners();
        Get_Product();
    }

    void Get_Product() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("pd_ttype", pd_ttype);
        new ApiClient(data, "proc_admin_product_list", hdr);
    }

    void init_Spinners() {

        type_array = new String[]{"Compressor", "Tank", "After Cooler", "Dryer", "Filter", "흡착식", "OIL MIST SEPERATOR", "AUTO TRAP"};
        type_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : type_array) {
            type_adapter.add(s);
        }
        dlg_product_typeSN.setAdapter(type_adapter);

        pressure_array = new String[]{"7k", "7.5k", "8k", "8.5k", "9k", "9.5k", "9.9k", "10k", "10.2k", "13k"};
        pressure_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : pressure_array) {
            pressure_adapter.add(s);
        }
        dlg_product_pressureSN.setAdapter(pressure_adapter);

        voltage_array = new String[]{"220V(단상)", "220V(삼상)", "380V(삼상)", "440V(삼상)", "2400V(삼상)", "3300V(삼상)", "6600V(삼상)"};
        voltage_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : voltage_array) {
            voltage_adapter.add(s);
        }
        dlg_product_voltageSN.setAdapter(voltage_adapter);

        frequency_array = new String[]{"50HZ", "60HZ"};
        frequency_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : frequency_array) {
            frequency_adapter.add(s);
        }
        dlg_product_frequencySN.setAdapter(frequency_adapter);

        cold_array = new String[]{"공냉식", "수냉식"};
        cold_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : cold_array) {
            cold_adapter.add(s);
        }
        dlg_product_coldSN.setAdapter(cold_adapter);

        play_array = new String[]{"직입", "Y-D", "인버터", "Y-D&인버터"};
        play_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        for (String s : play_array) {
            play_adapter.add(s);
        }
        dlg_product_playSN.setAdapter(play_adapter);

    }

    void init_Listener() {
        type_array = new String[]{"Compressor", "Tank", "After Cooler", "Dryer", "Filter", "흡착식", "OIL MIST SEPERATOR", "AUTO TRAP"};
        //제품 구분 선택
        dlg_product_typeSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0: {
                        type = 1;
                        pd_ttype = "COMP";
                    }
                    break;

                    case 1: {
                        type = 2;
                        pd_ttype = "TANK";
                    }
                    break;

                    case 2: {
                        type = 3;
                        pd_ttype = "COOLER";
                    }
                    break;

                    case 3: {
                        type = 3;
                        pd_ttype = "DRYER";
                    }
                    break;

                    case 4: {
                        type = 2;
                        pd_ttype = "FILTER";
                    }
                    break;

                    case 5: {
                        type = 3;
                        pd_ttype = "SUCTION";
                    }
                    break;

                    case 6: {
                        type = 2;
                        pd_ttype = "MIST";
                    }
                    break;

                    case 7: {
                        type = 2;
                        pd_ttype = "TRAP";
                    }
                    break;
                }

                if (type == 1) {
                    show_type_aLL.setVisibility(View.VISIBLE);
                    show_type_bLL.setVisibility(View.GONE);
                    show_type_cLL.setVisibility(View.GONE);
                    show_type_dLL.setVisibility(View.VISIBLE);

                } else if (type == 2) {
                    show_type_aLL.setVisibility(View.GONE);
                    show_type_bLL.setVisibility(View.VISIBLE);
                    show_type_cLL.setVisibility(View.VISIBLE);
                    show_type_dLL.setVisibility(View.GONE);

                } else if (type == 3) {
                    show_type_aLL.setVisibility(View.GONE);
                    show_type_bLL.setVisibility(View.GONE);
                    show_type_cLL.setVisibility(View.VISIBLE);
                    show_type_dLL.setVisibility(View.VISIBLE);
                }

                dlg_product_nameET.getText().clear();

                Get_Product();
            }

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

            }
        });


        //최대압력 선택
        dlg_product_pressureSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        pd_pressure = "A";
                        break;
                    case 1:
                        pd_pressure = "E";
                        break;
                    case 2:
                        pd_pressure = "F";
                        break;
                    case 3:
                        pd_pressure = "B";
                        break;
                    case 4:
                        pd_pressure = "C";
                        break;
                    case 5:
                        pd_pressure = "G";
                        break;
                    case 6:
                        pd_pressure = "D";
                        break;
                    case 7:
                        pd_pressure = "H";
                        break;
                    case 8:
                        pd_pressure = "I2";
                        break;
                    case 9:
                        pd_pressure = "I3";
                        break;
                }
            }

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

            }
        });

        //모델 구분 선택
        dlg_product_guRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton button = findViewById(checkedId);
                String select = button.getText().toString();
                switch (select) {
                    case "PISTON":
                        pd_gu = "PSOI";
                        break;
                    case "SCROLL":
                        pd_gu = "SCOI";
                        break;
                    case "SCREW":
                        pd_gu = "SWOI";
                        break;
                }
            }
        });

        // OIL TYPE 선택
        dlg_product_oil_typeRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton button = findViewById(checkedId);
                String select = button.getText().toString();
                switch (select) {
                    case "INJECTION":
                        pd_oil_type = "INJEC";
                        break;
                    case "FREE":
                        pd_oil_type = "FREE";
                        break;
                }
            }
        });


        //냉각방식 선택
        dlg_product_coldSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        pd_cold = "A";
                        break;
                    case 1:
                        pd_cold = "B";
                        break;
                }
            }

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

            }
        });

        //기동방식 선택
        dlg_product_playSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        pd_play = "A";
                        break;
                    case 1:
                        pd_play = "B";
                        break;
                    case 2:
                        pd_play = "C";
                        break;
                    case 3:
                        pd_play = "D";
                        break;
                }
            }

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

            }
        });

        //전압 선택
        dlg_product_voltageSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        pd_voltage = "A";
                        break;
                    case 1:
                        pd_voltage = "B";
                        break;
                    case 2:
                        pd_voltage = "C";
                        break;
                    case 3:
                        pd_voltage = "D";
                        break;
                    case 4:
                        pd_voltage = "A3";
                        break;
                    case 5:
                        pd_voltage = "F";
                        break;
                    case 6:
                        pd_voltage = "G";
                        break;
                }
            }

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

            }
        });

        //주파수 선택
        dlg_product_frequencySN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        pd_frequency = "A";
                        break;
                    case 1:
                        pd_frequency = "B";
                        break;
                }
            }

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

            }
        });

        //모델명 선택
        dlg_product_nameSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    pd_short_name = "";

                } else {
                    dlg_product_nameET.setText(dlg_product_nameSN.getSelectedItem().toString());
                    pd_short_name = dlg_product_nameSN.getSelectedItem().toString();
                }
            }

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

            }
        });

        //저장버튼 클릭 리스너
        dlg_product_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                pd_weight = dlg_product_weightET.getText().toString();
                pd_inout = dlg_product_inoutET.getText().toString();
                pd_memo = dlg_product_memoET.getText().toString();
                pd_size = dlg_product_sizeET.getText().toString();
                if (TextUtils.isEmpty(pd_short_name)) {
                    pd_short_name = dlg_product_nameET.getText().toString();
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pd_ttype", pd_ttype);
                data.put("pd_type", pd_type);
                data.put("pd_short_name", pd_short_name);

                if (type == 1) {
                    if (TextUtils.isEmpty(pd_gu) || TextUtils.isEmpty(pd_oil_type) || TextUtils.isEmpty(pd_pressure) || TextUtils.isEmpty(pd_cold) || TextUtils.isEmpty(pd_play) || TextUtils.isEmpty(pd_voltage) || TextUtils.isEmpty(pd_frequency)) {
                        Common.getInstance().toastShow(getContext(), "비고란을 제외한 전체 항목을 입력해주세요.");
                        return;
                    }
                    data.put("pd_gu", pd_gu);
                    data.put("pd_oil_type", pd_oil_type);
                    data.put("pd_pressure", pd_pressure);
                    data.put("pd_cold", pd_cold);
                    data.put("pd_play", pd_play);
                    data.put("pd_voltage", pd_voltage);
                    data.put("pd_frequency", pd_frequency);

                } else if (type == 2) {
                    if (TextUtils.isEmpty(pd_size) || TextUtils.isEmpty(pd_weight) || TextUtils.isEmpty(pd_inout)) {
                        Common.getInstance().toastShow(getContext(), "비고란을 제외한 전체 항목을 입력해주세요.");
                        return;
                    }
                    data.put("pd_size", pd_size);
                    data.put("pd_weight", pd_weight);
                    data.put("pd_inout", pd_inout);

                } else if (type == 3) {
                    if (TextUtils.isEmpty(pd_weight) || TextUtils.isEmpty(pd_inout) || TextUtils.isEmpty(pd_voltage) || TextUtils.isEmpty(pd_frequency)) {
                        Common.getInstance().toastShow(getContext(), "비고란을 제외한 전체 항목을 입력해주세요.");
                        return;
                    }
                    data.put("pd_weight", pd_weight);
                    data.put("pd_inout", pd_inout);
                    data.put("pd_voltage", pd_voltage);
                    data.put("pd_frequency", pd_frequency);
                }

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

                new ApiClient(data, "proc_machine_product_add", hdr);
            }
        });

    }

    void init_Handler() {

        hdr = 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_product_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        model_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ProductData>>() {
                        }.getType());

                        if (model_items.isSuccess()) {
                            name_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
                            name_adapter.add("(직접입력)");

                            for (int i = 0; i < model_items.size(); i++) {
                                name_adapter.add(model_items.get(i).getPdShortName());
                            }
                            dlg_product_nameSN.setAdapter(name_adapter);

                        } else {
                            name_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
                            name_adapter.add("(직접입력)");
                            dlg_product_nameSN.setAdapter(name_adapter);
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_machine_product_add")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        product_data = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<ProductData>>() {
                        }.getType());

                        if (product_data.isSuccess()) {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            HashMap<String, ProductData> data = new HashMap<>();
                            data.put("product_data", product_data.getArrayitem());
                            clickListener.clickBtn(data);
                            dismiss();

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

                } else if (msg.what == -1){
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }
}

