package kr.co.compcareworker.Fragment.Enterprise.ServiceList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
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 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.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Memo.MemoData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.SearchAddressDialog;
import kr.co.compcareworker.Util.CustomView.SearchCompanyDialog;

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

    private Handler handler, hdr;
    private FragmentActivity fa;

    private EditText ceo_name, company_number, company_name,
            place,
            zipcode,
            company_fax,
            company_tel,
            adress_detail,
            company_email,
            pt_condition, pt_field;

    private TextView adress;
    private String pt_gu, Spinner_data, pt_idx, cp_airline, sido, sigungu;
    private Button btn_add;
    private RadioGroup ra_group;
    private RadioButton radio_ALL, radio_A, radio_B;
    private Spinner pt_type_spinner;
    private String map_x, map_y, type;

    private LinearLayout search_partnerLL, company_nameLL;
    private EditText search_partnerET;
    private ImageView search_partnerIV;

    /**
     * 주소검색
     */
    TextView search_addrTV;

    ArrayItem_<MemoData> items;

    @SuppressLint("ValidFragment")
    public Place_Registration_Fragment(Handler handler, String type) {

        this.handler = handler;
        this.type = type;
    }

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

        ceo_name = v.findViewById(R.id.ceo_name);
        company_number = v.findViewById(R.id.company_number);
        company_name = v.findViewById(R.id.company_name);
        place = v.findViewById(R.id.place);
        zipcode = v.findViewById(R.id.zipcode);
        adress = v.findViewById(R.id.adress);
        adress_detail = v.findViewById(R.id.adress_detail);
        company_tel = v.findViewById(R.id.company_tel);
        company_fax = v.findViewById(R.id.company_fax);
        company_email = v.findViewById(R.id.company_email);
        btn_add = v.findViewById(R.id.btn_modify);
        btn_add.setText("추가");
        ra_group = v.findViewById(R.id.ra_group);
        radio_ALL = v.findViewById(R.id.radio_ALL);
        radio_A = v.findViewById(R.id.radio_A);
        radio_B = v.findViewById(R.id.radio_B);
        pt_type_spinner = v.findViewById(R.id.pt_type_spinner);
        pt_condition = v.findViewById(R.id.pt_condition);
        pt_field = v.findViewById(R.id.pt_field);
        search_addrTV = v.findViewById(R.id.search_addrTV);

        search_partnerLL = v.findViewById(R.id.search_partnerLL);
        search_partnerET = v.findViewById(R.id.search_partnerET);
        search_partnerIV = v.findViewById(R.id.search_partnerIV);
        company_nameLL = v.findViewById(R.id.company_nameLL);

        if (type.equals("자회사")) {

            search_partnerLL.setVisibility(View.VISIBLE);
            company_nameLL.setVisibility(View.GONE);
            search_partnerET.requestFocus();

        } else {

            place.setText("본사");
            place.setEnabled(false);
            company_name.requestFocus();
        }


        init_Handler();

        Set_Contents();

        return v;
    }

    void Set_Contents() {


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

                String keyword = search_partnerET.getText().toString();

                SearchCompanyDialog dialog = new SearchCompanyDialog(getContext(), keyword, new SearchCompanyDialog.SearchCompanyDialogListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> get_data) {

                        pt_idx = get_data.get("pt_idx");
                        search_partnerET.setText(get_data.get("pt_name"));
                        company_name.setText(get_data.get("pt_name"));
                        company_number.setText(get_data.get("pt_code"));
                        ceo_name.setText(get_data.get("pt_ceo"));
                        pt_condition.setText(get_data.get("pt_condition"));
                        pt_field.setText(get_data.get("pt_field"));

                        /**파트너 테이블*/
                        if (get_data.get("pt_gu").equals("ALL")) {
                            /**공용*/
                            radio_ALL.setChecked(true);
                            pt_gu = "ALL";
                        } else if (get_data.get("pt_gu").equals("A")) {
                            /**매출처*/
                            radio_A.setChecked(true);
                            pt_gu = "A";
                        } else if (get_data.get("pt_gu").equals("B")) {
                            /**매입처*/
                            radio_B.setChecked(true);
                            pt_gu = "B";
                        } else {
                            radio_ALL.setChecked(true);
                            pt_gu = "ALL";
                        }

                        if (get_data.get("pt_type").equals("COMP")) {
                            /**법인*/
                            pt_type_spinner.setSelection(1);
                        } else {
                            pt_type_spinner.setSelection(0);
                        }

                        company_number.setEnabled(false);
                        ceo_name.setEnabled(false);
                        pt_condition.setEnabled(false);
                        pt_field.setEnabled(false);
                        radio_ALL.setEnabled(false);
                        radio_A.setEnabled(false);
                        radio_B.setEnabled(false);
                        pt_type_spinner.setEnabled(false);
                        search_partnerET.setFocusable(false);
                        place.requestFocus();

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


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

                if (TextUtils.isEmpty(company_name.getText())) {
                    Toast.makeText(getContext(), "거래처명을 입력해주세요", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(adress.getText())) {
                    Toast.makeText(getContext(), "주소를 입력해주세요", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(company_tel.getText())) {
                    Toast.makeText(getContext(), "연락처를 입력해주세요", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(sido) || TextUtils.isEmpty(sigungu)) {
                    Common.getInstance().toastShow(getContext(), "주소에 이상이 있습니다. 주소검색을 통해 주소를 다시 입력해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();

                if (pt_type_spinner.getSelectedItem().equals("법인")) {
                    Spinner_data = "COMP";
                } else {
                    Spinner_data = "PER";
                }

                if (!TextUtils.isEmpty(pt_idx)) {

                    data.put("pt_idx", pt_idx);
                }

                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("partner_pt_name", company_name.getText().toString());
                data.put("partner_pt_code", company_number.getText().toString());
                data.put("partner_pt_ceo", ceo_name.getText().toString());
                data.put("partner_pt_condition", pt_condition.getText().toString());
                data.put("partner_pt_field", pt_field.getText().toString());
                data.put("partner_pt_type", Spinner_data);
                data.put("partner_pt_gu", pt_gu);
                data.put("company_cp_name", place.getText().toString());
                data.put("company_cp_addr", adress.getText().toString());
                data.put("company_cp_addr_sub", adress_detail.getText().toString());
                data.put("company_cp_zip", zipcode.getText().toString());
                data.put("company_cp_tel", company_tel.getText().toString());
                data.put("company_cp_fax", company_fax.getText().toString());
                data.put("company_cp_email", company_email.getText().toString());
                data.put("company_cp_mapx", map_x);
                data.put("company_cp_mapy", map_y);
                data.put("cp_sido", sido);
                data.put("cp_sigungu", sigungu);

                Log.d("데이터 체크@@@@@", data.toString());
                new ApiClient(data, "proc_place_registration", hdr);
            }
        });

        ra_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_ALL) {
                    pt_gu = "ALL";
                } else if (checkedId == R.id.radio_A) {
                    pt_gu = "A";
                } else if (checkedId == R.id.radio_B) {
                    pt_gu = "B";
                }
            }
        });

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

                SearchAddressDialog dialog = new SearchAddressDialog(getContext(), new SearchAddressDialog.SearchAddressListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> data) {

                        zipcode.setText(data.get("zonecode"));
                        adress.setText(data.get("Address") + " " + data.get("buildingName"));
                        adress_detail.getText().clear();
                        map_x = data.get("lnt");
                        map_y = data.get("lot");
                        sido = data.get("sido");
                        sigungu = data.get("sigungu");
                        adress_detail.requestFocus();
                    }
                });
                dialog.show();
            }
        });
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    Log.e("plce_url==", url.toString());

                    if (url.equals("proc_place_registration")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        Log.e("result_item", result_item.toString());

                        ArrayItem<MemoData> res_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MemoData>>() {
                        }.getType());

                        if (res_item.isSuccess()) {
                            fa.Set_Text();
                            Toast.makeText(getContext(), res_item.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        } else {
                            Toast.makeText(getContext(), "장소 추가에 실패하였습니다.", Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }
}
