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

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
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.Data.ArrayItem;
import kr.co.compcareworker.Data.ImageList.ImageListData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ImageCheckListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

import static android.content.Context.INPUT_METHOD_SERVICE;

@SuppressLint("ValidFragment")
public class ImageCheck_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;

    ArrayItem<ImageListData> items;

    /**
     * 상단 컨텐츠
     */
    //TextView tv_act_deal_list_name, tv_act_deal_list_office, tv_act_deal_list_line;
    //LinearLayout ll_act_deal_list_content;
    TextView sort;
    ImageView find;
    EditText findText;
    String sortType = "ins_dt";

    /**
     * 거래명세서 목록
     */
    RecyclerView list;
    TextView noneList;
    ImageCheckListRecyclerAdapter adapter;
    boolean imgList = false;

    /**
     * 프로그래스바
     */
    ProgressBar progress;

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

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

    @SuppressLint("ValidFragment")
    public ImageCheck_Fragment(Handler handler) {
        this.handler = handler;
    }

    public ImageCheck_Fragment() {
    }

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

        /** 상단 컨텐츠*/
        /*tv_act_deal_list_name = v.findViewById(R.id.tv_act_deal_list_name);
        tv_act_deal_list_office = v.findViewById(R.id.tv_act_deal_list_office);
        tv_act_deal_list_line = v.findViewById(R.id.tv_act_deal_list_line);
        ll_act_deal_list_content = v.findViewById(R.id.ll_act_deal_list_content);*/

        sort = v.findViewById(R.id.sort);
        find = v.findViewById(R.id.find);
        findText = v.findViewById(R.id.findText);

        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(findText.getWindowToken(), 0);

        /** 거래명세서 목록*/
        list = v.findViewById(R.id.list);
        noneList = v.findViewById(R.id.noneList);
        adapter = new ImageCheckListRecyclerAdapter(getContext(), hdr);
        list.setAdapter(adapter);

        /** 프로그래스바*/
        progress = v.findViewById(R.id.progress);

        init_Handler();
        init_Listener();

        Get_Contents();

        return v;
    }

    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", fa.enterpriseItem.getArrayitem().getCpIdx());
        data.put("sfield", sortType);
        data.put("skeyword", findText.getText().toString());
        new ApiClient(data, "proc_checkup_list", hdr);
    }

    void Set_Contents() {
        /** 사진점검 리스트*/
        if (imgList) {
            adapter.addItem(items.getArrayitem());
        }

        progress.setVisibility(View.GONE);
    }

    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");
                    if (url.equals("proc_checkup_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ImageListData>>() {
                        }.getType());

                        if (items.isSuccess()) {
                            imgList = true;
                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                            list.setVisibility(View.GONE);
                            noneList.setVisibility(View.VISIBLE);
                        }

                        Set_Contents();
                    }
                }
            }
        };
    }

    private void init_Listener() {
        sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] arr_str = new String[]{"등록일", "AIRLINE"};
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                alertDialogBuilder.setSingleChoiceItems(arr_str, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        sort.setText(arr_str[which] + " ▼");
                        if (which == 0) {
                            sortType = "ins_dt";
                            findText.setText("");
                            //findText.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
                            findText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
                            findText.setHint("ex)2019-01-01");
                        } else {
                            sortType = "cp_airline";
                            findText.setText("");
                            //findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setHint("AIRLINE 을 입력하세요.");
                        }
                        dialog.dismiss();
                    }
                });
                alertDialogBuilder.show();
            }
        });

        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Get_Contents();
            }
        });
    }
}
