package kr.co.compcarecompany.Fragment.Menu;

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.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
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.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Memo.MemoData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.CustomView.SearchAddressDialog;

@SuppressLint("ValidFragment")

public class Place_Modify_Fragment extends Fragment {

    Handler handler, hdr;
    FragmentActivity fa;

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

    TextView adress;
    String pt_gu, Spinner_data, pt_idx, wo_idx;
    Button btn_modify;
    RadioGroup ra_group;
    RadioButton radio_ALL, radio_A, radio_B;
    Spinner pt_type_spinner;
    String map_x, map_y, type;
    RelativeLayout mapViewRL;

    LinearLayout company_nameLL;
    CompanyData companyData;

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

    ArrayItem_<MemoData> items;

    @SuppressLint("ValidFragment")
    public Place_Modify_Fragment(Handler handler, CompanyData companyData) {

        this.handler = handler;
        this.companyData = companyData;
    }

    @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_modify, 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_modify = v.findViewById(R.id.btn_modify);
        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);
        company_nameLL = v.findViewById(R.id.company_nameLL);

        init_Handler();
        init_Listener();
        Set_Contents();

        return v;
    }

    void Set_Contents(){

        pt_idx = companyData.getPtIdx();

        if(companyData.getCpName().equals("본사")){
            place.setEnabled(false);

        } else {

            pt_field.setEnabled(false);
            pt_condition.setEnabled(false);
            ceo_name.setEnabled(false);
            company_number.setEnabled(false);
            company_name.setEnabled(false);
            ra_group.setEnabled(false);
            pt_type_spinner.setEnabled(false);
            radio_ALL.setEnabled(false);
            radio_A.setEnabled(false);
            radio_B.setEnabled(false);

        }

        pt_field.setText(companyData.getPtField());
        pt_condition.setText(companyData.getPtCondition());
        ceo_name.setText(companyData.getPtCeo());
        company_number.setText(companyData.getPtCode());
        company_name.setText(companyData.getPtName());

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

        if (companyData.getPtType().equals("COMP")) {
            /**법인*/
            pt_type_spinner.setSelection(1);

        } else {
            /**개인*/
            pt_type_spinner.setSelection(0);
        }

        place.setText(companyData.getCpName());
        company_tel.setText(companyData.getCpTel());
        company_fax.setText(companyData.getCpFax());
        company_email.setText(companyData.getCpEmail());
        zipcode.setText(companyData.getCpZip());
        adress.setText(companyData.getCpAddr());
        adress_detail.setText(companyData.getCpAddrSub());
        map_x = companyData.getCpMapx();
        map_y = companyData.getCpMapy();

    }

    void init_Listener() {

        btn_modify.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 (pt_type_spinner.getSelectedItem().equals("법인")) {

                    Spinner_data = "COMP";

                } else {

                    Spinner_data = "PER";
                }

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

                data.put("ag_idx", companyData.getAgIdx());
                data.put("pt_idx", companyData.getPtIdx());
                data.put("cp_idx", companyData.getCpIdx());
                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);

                if(companyData.getCpAirline() != null){
                    data.put("company_cp_airline", companyData.getCpAirline().toString());

                } else {
                    data.put("company_cp_airline", "기본값");
                }

                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);

                Log.d("데이터확인@@@@", data.toString());
                new ApiClient(data, "proc_place_modify", 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");
                        adress_detail.requestFocus();
                    }
                });
                dialog.show();
            }
        });
    }

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

                String url = msg.getData().getString("url");
                Log.e("plce_url==", url.toString());

                if (url.equals("proc_place_modify")) {
                    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()) {
                        Toast.makeText(getContext(), res_item.getMessage(), Toast.LENGTH_SHORT).show();
                        getActivity().finish();

                    } else if(res_item.getMessage().equals("저장된 서비스가 없습니다.")) {

                        Toast.makeText(getContext(), "장소 수정이 완료되었습니다.", Toast.LENGTH_SHORT).show();
                        getActivity().finish();

                    }else {

                        Toast.makeText(getContext(), "장소 수정에 실패하였습니다.", Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                    }
                }
            }
        };
    }
}
