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

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

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.WebviewAct;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.EstimateList.EstimateListData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.EstimateRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

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

    private Handler hdr;
    FragmentActivity fa;
    TextView estimate_noneTV;
    EditText estimate_searchET;
    ImageView estimate_clearIV;
    LinearLayout estimate_listLL;
    RecyclerView estimate_listRV;
    String ag_idx, cp_idx;
    ArrayItem<EstimateListData> estimate_array;
    EstimateListData estimate_data;
    ProgressBar estimatePB;

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

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

    @SuppressLint("ValidFragment")
    public Estimate_Fragment(Handler handler, String ag_idx, String cp_idx) {
        this.hdr = handler;
        this.ag_idx = ag_idx;
        this.cp_idx = cp_idx;
    }

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

        estimate_noneTV = v.findViewById(R.id.estimate_noneTV);
        estimate_searchET = v.findViewById(R.id.estimate_searchET);
        estimate_listLL = v.findViewById(R.id.estimate_listLL);
        estimate_listRV = v.findViewById(R.id.estimate_listRV);
        estimatePB = v.findViewById(R.id.estimatePB);
        estimate_clearIV = v.findViewById(R.id.estimate_clearIV);

        estimatePB.setVisibility(View.VISIBLE);
        init_Handler();
        Get_Estimate();

        return v;
    }

    void Get_Estimate() {

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_estimate_list", hdr);
    }

    void Search_Estimate() {

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("cp_idx", cp_idx);
        data.put("word", estimate_searchET.getText().toString());
        new ApiClient(data, "proc_estimate_list", hdr);
    }

    void Set_Content() {

        EstimateRecyclerAdapter adapter = new EstimateRecyclerAdapter(getContext(), hdr, new EstimateRecyclerAdapter.EstimateListener() {
            @Override
            public void clickBtn(String es_idx) {

                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "견적서 상세보기");
                intent.putExtra("url", "https://agency.compcare.co.kr/sell/estimate/preview/" + es_idx + "?app_mode=Y");
                startActivity(intent);
            }
        });


        adapter.addItem(estimate_array.getArrayitem());
        estimate_listRV.setAdapter(adapter);

        estimate_searchET.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 (estimate_searchET.length() > 1) {

                    estimate_clearIV.setVisibility(View.VISIBLE);
                    estimatePB.setVisibility(View.VISIBLE);
                    Search_Estimate();

                } else if (estimate_searchET.length() == 0) {

                    estimate_clearIV.setVisibility(View.GONE);
                    estimatePB.setVisibility(View.VISIBLE);
                    Get_Estimate();

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

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

                estimate_searchET.getText().clear();
                estimate_clearIV.setVisibility(View.GONE);
            }
        });

        estimatePB.setVisibility(View.GONE);
    }

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

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

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

                        if (estimate_array.isSuccess()) {

                            estimate_listLL.setVisibility(View.VISIBLE);
                            estimate_noneTV.setVisibility(View.GONE);
                            Set_Content();

                        } else {

                            estimate_listLL.setVisibility(View.GONE);
                            estimate_noneTV.setVisibility(View.VISIBLE);
                            String message = result_item.get("resultItem").getAsJsonObject().get("message").toString();
                            message = message.replace("\"", "");
                            estimate_noneTV.setText(message);
                        }
                        estimatePB.setVisibility(View.GONE);
                    }
                } else if (msg.what == -1) {

                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                    estimatePB.setVisibility(View.GONE);
                }
            }
        };
    }

}
