package kr.co.compcarecompany.Fragment.Join;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
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.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

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

    private Handler handler, hdr;
    EditText join_2nd_idET, join_2nd_pwET, join_2nd_pw_checkET, join_2nd_nameET, join_2nd_telET, join_2nd_emailET;
    TextView join_2nd_id_checkTV, join_2nd_joinTV, join_2nd_id_warnTV, join_2nd_pw_check_warnTV;
    ImageView join_2nd_pw_clearIV, join_2nd_pw_check_clearIV;
    FragmentActivity fa;
    String ag_idx, pt_idx;
    boolean id_check = false;
    boolean pw_check = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @SuppressLint("ValidFragment")
    public Join_Step_Second_Fragment(Handler handler, String ag_idx, String pt_idx) {
        this.handler = handler;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_join_step_second, container, false);

        join_2nd_idET = v.findViewById(R.id.join_2nd_idET);
        join_2nd_pwET = v.findViewById(R.id.join_2nd_pwET);
        join_2nd_pw_checkET = v.findViewById(R.id.join_2nd_pw_checkET);
        join_2nd_nameET = v.findViewById(R.id.join_2nd_nameET);
        join_2nd_telET = v.findViewById(R.id.join_2nd_telET);
        join_2nd_emailET = v.findViewById(R.id.join_2nd_emailET);
        join_2nd_id_checkTV = v.findViewById(R.id.join_2nd_id_checkTV);
        join_2nd_id_warnTV = v.findViewById(R.id.join_2nd_id_warnTV);
        join_2nd_pw_check_warnTV = v.findViewById(R.id.join_2nd_pw_check_warnTV);
        join_2nd_joinTV = v.findViewById(R.id.join_2nd_joinTV);
        join_2nd_pw_clearIV = v.findViewById(R.id.join_2nd_pw_clearIV);
        join_2nd_pw_check_clearIV = v.findViewById(R.id.join_2nd_pw_check_clearIV);

        init_Handler();
        init_Listener();

        return v;
    }

    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_join_company")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

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

                            if (result_item.get("resultItem").getAsJsonObject().get("message").getAsString().equals("999")) {

                                join_2nd_idET.getText().clear();
                                join_2nd_id_warnTV.setTextColor(Color.parseColor("#dd3333"));
                                join_2nd_id_warnTV.setText("!중복되는 아이디 입니다.");
                                id_check = false;

                            } else if (result_item.get("resultItem").getAsJsonObject().get("message").getAsString().equals("777")) {

                                join_2nd_id_warnTV.setTextColor(Color.parseColor("#22a03f"));
                                join_2nd_id_warnTV.setText("*사용가능한 아이디 입니다.");
                                id_check = true;

                            } else {

                                Toast.makeText(getContext(), "가입이 완료되었습니다.\n로그인 해주세요.", Toast.LENGTH_SHORT).show();
                                getActivity().finish();

                            }

                        } else {

                            Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                            join_2nd_joinTV.setEnabled(true);
                        }
                    }
                } else {

                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                    join_2nd_joinTV.setEnabled(true);
                }
            }
        };
    }

    void init_Listener() {

        join_2nd_telET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        join_2nd_pw_checkET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //입력란에 변화가 있을 경우
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //입력이 끝났을 경우
                if (!s.toString().equals("") && !join_2nd_pw_checkET.getText().toString().equals("")) {

                    String pw = join_2nd_pwET.getText().toString();
                    String pw_confirm = join_2nd_pw_checkET.getText().toString();

                    if (pw_confirm.equals(pw)) {

                        join_2nd_pw_check_warnTV.setText("*비밀번호가 일치합니다.");
                        join_2nd_pw_check_warnTV.setTextColor(Color.parseColor("#22a03f"));
                        pw_check = true;

                    } else {

                        join_2nd_pw_check_warnTV.setTextColor(Color.parseColor("#dd3333"));
                        join_2nd_pw_check_warnTV.setText("!비밀번호가 일치하지 않습니다.");
                        pw_check = false;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //입력 하기 전
            }
        });

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

                join_2nd_pwET.getText().clear();
            }
        });


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

                join_2nd_pw_checkET.getText().clear();
            }
        });

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

                HashMap<String, String> data = new HashMap<>();
                data.put("mb_id", join_2nd_idET.getText().toString());
                new ApiClient(data, "proc_join_company", handler);
            }
        });


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

                String mb_id = join_2nd_idET.getText().toString();
                String mb_password = join_2nd_pwET.getText().toString();
                String mb_password_check = join_2nd_pw_checkET.getText().toString();
                String mb_name = join_2nd_nameET.getText().toString();
                String mb_phone = join_2nd_telET.getText().toString();
                String mb_email = join_2nd_emailET.getText().toString();
                boolean is_email = Common.getInstance().isValidEmail(mb_email);

                if (TextUtils.isEmpty(mb_id) && TextUtils.isEmpty(mb_password) && TextUtils.isEmpty(mb_password_check) && TextUtils.isEmpty(mb_name) && TextUtils.isEmpty(mb_phone) && TextUtils.isEmpty(mb_email)) {
                    Toast.makeText(getContext(), "전체 항목을 입력해 주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (!id_check) {
                    Toast.makeText(getContext(), "아이디 중복확인을 해주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(mb_password)) {
                    Toast.makeText(getContext(), "비밀번호를 입력해 주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(mb_password_check)) {
                    Toast.makeText(getContext(), "비밀번호 확인을 해주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(mb_name)) {
                    Toast.makeText(getContext(), "이름을 입력해 주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(mb_phone)) {
                    Toast.makeText(getContext(), "연락처를 입력해 주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(mb_email)) {
                    Toast.makeText(getContext(), "이메일을 입력해 주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (!pw_check) {
                    Toast.makeText(getContext(), "비밀번호가 일치하지 않습니다.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (!is_email) {
                    Toast.makeText(getContext(), "이메일 형식이 올바르지 않습니다.", Toast.LENGTH_SHORT).show();
                    return;
                }

                join_2nd_joinTV.setEnabled(false);

                HashMap<String, String> data = new HashMap<>();
                data.put("mb_id", mb_id);
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);
                data.put("mb_type", "COMPANY");
                data.put("mb_password", mb_password);
                data.put("mb_name", mb_name);
                data.put("mb_phone", mb_phone);
                data.put("mb_email", mb_email);
                data.put("mb_fcm_key", Common.getInstance().getPref(getContext(), "token"));

                Log.d("데이터확인@@@@", data.toString());
                new ApiClient(data, "proc_join_company", handler);


//                Intent intent = new Intent(getContext(), FragmentActivity.class);
//                intent.putExtra("title", "회원가입");
//                intent.putExtra("type", "join_step_second");
//                startActivity(intent);
//                startActivity(new Intent(getContext(), Intro.class));
//                getActivity().finish();
            }
        });
    }

}
