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

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
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.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
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.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.CompanyData;
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;


@SuppressLint("ValidFragment")
public class Place_Adjust_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;
//    EditText adress;

    private String pt_gu, Spinner_data, pt_idx, cp_idx, type, wo_idx, sido, sigungu;
    private Button btn_modify;
    private RadioGroup ra_group;
    private RadioButton radio_ALL, radio_A, radio_B;
    private Spinner pt_type_spinner;
    private String map_x, map_y;
    private RelativeLayout mapViewRL;
//    private MapView mapView;

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

    ArrayItem_<MemoData> items;

    @SuppressLint("ValidFragment")
    public Place_Adjust_Fragment(Handler handler, String pt_idx, String cp_idx, String type) {

        this.handler = handler;
        this.pt_idx = pt_idx;
        this.cp_idx = cp_idx;
        this.type = type;
    }

    @SuppressLint("ValidFragment")
    public Place_Adjust_Fragment(Handler handler) {

        this.handler = handler;
        this.pt_idx = fa.enterpriseItem.getArrayitem().getPtIdx();
    }

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

        this.handler = handler;
        this.type = type;
        this.wo_idx = wo_idx;
        this.pt_idx = fa.enterpriseItem.getArrayitem().getPtIdx();
    }

    @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_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);
        search_addr_copyTV = v.findViewById(R.id.search_addr_copyTV);

        /**지도*/
        mapViewRL = v.findViewById(R.id.mapViewRL);
        mapViewRL.setVisibility(View.VISIBLE);

//        mapView = new MapView(getContext());
//        mapView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });
//        ViewGroup mapViewContainer = v.findViewById(R.id.mapViewRL);
//        mapViewContainer.addView(mapView);
//        mapView.removeAllPOIItems();

        init_Handler();

        if (TextUtils.isEmpty(type) || type.equals("navi")) {

            Get_Contents();

        } else {

            Get_Company();
        }

        return v;
    }


    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("pt_idx", pt_idx);
        Log.d("보자요111@@@", data.toString());
        new ApiClient(data, "proc_partner_view", hdr);
    }

    void Get_Company() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        Log.d("보자요222 @@@", data.toString());
        new ApiClient(data, "proc_company_view", hdr);
    }

    void Set_Marker() {

//        mapView.removeAllPOIItems();
//
//        MapPOIItem marker = new MapPOIItem();
//        marker.setItemName("Default Marker");
//        marker.setTag(0);
//        MapPoint p = MapPoint.mapPointWithGeoCoord(Double.parseDouble(map_x), Double.parseDouble(map_y));
//        marker.setMapPoint(p);
//        marker.setMarkerType(MapPOIItem.MarkerType.BluePin); // 기본으로 제공하는 BluePin 마커 모양.
//        marker.setSelectedMarkerType(MapPOIItem.MarkerType.RedPin); // 마커를 클릭했을때, 기본으로 제공하는 RedPin 마커 모양.
//
//        mapView.addPOIItem(marker);
//        mapView.setMapCenterPoint(p, true);

    }

    void Set_Contents() {

        place.clearFocus();

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

        if (items.getArrayitem().getPtType().equals("COMP")) {
            /**법인*/
            pt_type_spinner.setSelection(1);
        } else {
            /**개인*/
            pt_type_spinner.setSelection(0);
        }

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

        //공장이 본사가 아니면 파트너 테이블 수정 불가
        if (!fa.enterpriseItem.getArrayitem().getCpName().equals("본사")) {

            company_name.setEnabled(false);
            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);
            place.requestFocus();
        }


        /**컴퍼니 테이블*/
        place.setText(fa.enterpriseItem.getArrayitem().getCpName());
        adress.setText(fa.enterpriseItem.getArrayitem().getCpAddr());
        adress_detail.setText(fa.enterpriseItem.getArrayitem().getCpAddrSub());
        zipcode.setText(fa.enterpriseItem.getArrayitem().getCpZip());
        company_tel.setText(fa.enterpriseItem.getArrayitem().getCpTel());
        company_fax.setText(fa.enterpriseItem.getArrayitem().getCpFax());
        company_email.setText(fa.enterpriseItem.getArrayitem().getCpEmail());

        map_x = fa.enterpriseItem.getArrayitem().getCpMapx();
        map_y = fa.enterpriseItem.getArrayitem().getCpMapy();

        if (!TextUtils.isEmpty(map_x) && !TextUtils.isEmpty(map_y)) {
            Set_Marker();
        }

        btn_modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> data = new HashMap<>();

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

                if (pt_type_spinner.getSelectedItem().equals("법인")) {

                    Spinner_data = "COMP";

                } else {

                    Spinner_data = "PER";
                }

                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("pt_idx", fa.enterpriseItem.getArrayitem().getPtIdx());
                data.put("cp_idx", fa.enterpriseItem.getArrayitem().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);
                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);

                if (!TextUtils.isEmpty(wo_idx)) {

                    data.put("wo_idx", wo_idx);
                }
                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"));
                        map_x = data.get("lnt");
                        map_y = data.get("lot");
                        sido = data.get("sido");
                        sigungu = data.get("sigungu");

                        Log.d("주소뭔데@@@@", data.toString());
                        adress_detail.requestFocus();

                        if (!TextUtils.isEmpty(map_x) && !TextUtils.isEmpty(map_y)) {
                            Set_Marker();
                        }
                    }
                });
                dialog.show();
            }
        });

        search_addr_copyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("copy_addr", adress.getText());
                clipboard.setPrimaryClip(clipData);
                Toast.makeText(getContext(), "주소가 복사되었습니다.", Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    }

    @Override
    public void onPause() {
        super.onPause();
//        mapViewRL.removeView(mapView);
    }

    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_partner_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        Log.e("element==", element.toString());
                        if (!element.isJsonNull()) {
                            JsonObject result_item = element.getAsJsonObject();
                            items = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MemoData>>() {
                            }.getType());
                            if (items.isSuccess()) {
                                Set_Contents();
                            }
                        }
                    } else 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()) {
                            fa.Set_Text();
                            Toast.makeText(getContext(), res_item.getMessage(), Toast.LENGTH_SHORT).show();

                            if (TextUtils.isEmpty(type)) {
                                getActivity().finish();

                            } else if (type.equals("enterprise")) {

//                                mapViewRL.removeView(mapView);
                                startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                getActivity().finish();

                            } else if (type.equals("navi")) {

                                Common.getInstance().getLocation(getContext(), place.getText().toString(), adress.getText().toString());
                                getActivity().finish();
                            } else {

//                                mapViewRL.removeView(mapView);
                                startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                getActivity().finish();
                            }
//                        Get_Contents();
                        } else {
                            Toast.makeText(getContext(), "수정 작업에 실패하였습니다.", Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_company_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        fa.enterpriseItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                        }.getType());

                        if (fa.enterpriseItem.isSuccess()) {
                            cp_idx = fa.enterpriseItem.getArrayitem().getCpIdx();
                            Get_Contents();
                        } else {
                            Toast.makeText(getContext(), fa.enterpriseItem.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }
}
