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

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
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.DatePicker;
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.LinearLayoutManager;
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.FileDatum;
import kr.co.compcareworker.Data.ServiceList.ServiceImageData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ServiceImageRecylerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.CustomView.MyPickerDialog2;

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

    Handler handler, hdr;
    FragmentActivity fa;
    String ag_idx, pt_idx;
    TextView search_service_dateTV, show_service_countTV, service_noneTV;
    private DatePickerDialog.OnDateSetListener callbackMethod;
    EditText search_service_orderET;
    ImageView search_serviceIV;
    RecyclerView service_imgRV;
    RecyclerView.LayoutManager layoutManager;
    String search_date, search_keyword;
    ProgressBar search_img_progress;

    ServiceImageData data;
    ArrayItem<FileDatum> imgArrayItem;
    ArrayItem<ServiceImageData> items;
    ServiceImageRecylerAdapter adapter;
    int set_num;
    int size;

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

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

    @SuppressLint("ValidFragment")
    public Service_Image_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_service_image, container, false);

        search_service_dateTV = v.findViewById(R.id.search_service_dateTV);
        search_service_orderET = v.findViewById(R.id.search_service_orderET);
        search_serviceIV = v.findViewById(R.id.search_serviceIV);
        service_imgRV = v.findViewById(R.id.service_imgRV);
        service_noneTV = v.findViewById(R.id.service_noneTV);
        search_img_progress = v.findViewById(R.id.search_img_progress);

        init_Handler();
        init_Listener();

        search_img_progress.setVisibility(View.VISIBLE);
        Get_Service_Img();

        return v;
    }

    void Get_Service_Img() {

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

    private void Get_Service_Images(String wo_idx, String wr_idx) {

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("file_type", "after");
        data.put("wo_idx", wo_idx);
        data.put("wr_idx", wr_idx);
        new ApiClient(data, "proc_worker_file", hdr);

    }

    private void init_Listener() {

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

                MyPickerDialog2 dialog = new MyPickerDialog2();
                dialog.setListener(callbackMethod);
                dialog.show(getFragmentManager(), "MyPickerDialog");
            }
        });

        callbackMethod = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                if (monthOfYear < 10) {

                    search_date = year + "-0" + monthOfYear;
                } else {

                    search_date = year + "-" + monthOfYear;
                }

                search_service_dateTV.setText(year + "년 " + monthOfYear + "월");
            }
        };

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

                search_img_progress.setVisibility(View.VISIBLE);

                search_keyword = search_service_orderET.getText().toString();

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);

                if (!TextUtils.isEmpty(search_date)) {

                    data.put("search_date", search_date);
                }

                if (!TextUtils.isEmpty(search_keyword)) {

                    data.put("search_keyword", search_keyword);
                }

                new ApiClient(data, "proc_search_service_img", hdr);

                search_date = null;
                search_keyword = null;
                search_service_dateTV.setText("날짜 선택");
                search_service_orderET.getText().clear();
                search_service_orderET.clearFocus();

            }
        });

    }

    void Set_Contents() {

        adapter = new ServiceImageRecylerAdapter(getContext());
        layoutManager = new LinearLayoutManager(getContext());
        service_imgRV.setLayoutManager(layoutManager);

        adapter.addItem(items.getArrayitem());
        service_imgRV.setAdapter(adapter);
        search_img_progress.setVisibility(View.GONE);
    }

    public 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_service_img_view")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ServiceImageData>>() {
                        }.getType());

                        if (items.isSuccess()) {

                            set_num = 0;
                            size = items.getArrayitem().size();

                            for (int i = 0; i < items.getArrayitem().size(); i++) {
                                data = null;
                                data = items.getArrayitem().get(i);
                                Log.d("보자??@@@@", "wo : " + data.getWoIdx() + " wr : " + data.getWrIdx());
                                Get_Service_Images(data.getWoIdx(), data.getWrIdx());
                            }

                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                            service_noneTV.setVisibility(View.VISIBLE);
                            service_imgRV.setVisibility(View.GONE);
                            search_img_progress.setVisibility(View.GONE);
                        }

                    } else if (url.equals("proc_worker_file")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        imgArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<FileDatum>>() {
                        }.getType());

                        if (imgArrayItem.isSuccess()) {
                            for (int i = 0; i < items.getArrayitem().size(); i++) {
                                for (int j = 0; j < imgArrayItem.getArrayitem().size(); j++) {
                                    if (items.getArrayitem().get(i).getWoIdx().equals(imgArrayItem.getArrayitem().get(j).getPostId())) {
                                        items.getArrayitem().get(i).setFileDatum(imgArrayItem.getArrayitem());
                                    }
                                }
                            }

                            set_num++;

                            if (size == set_num) Set_Contents();

                        } else {

                            Toast.makeText(getContext(), imgArrayItem.getMessage(), Toast.LENGTH_SHORT).show();
                            search_img_progress.setVisibility(View.GONE);
                        }
                    } else if (url.equals("proc_search_service_img")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<ServiceImageData>>() {
                        }.getType());

                        if (items.isSuccess()) {
                            service_noneTV.setVisibility(View.GONE);
                            service_imgRV.setVisibility(View.VISIBLE);
                            set_num = 0;
                            size = items.getArrayitem().size();

                            for (int i = 0; i < items.getArrayitem().size(); i++) {
                                data = null;
                                data = items.getArrayitem().get(i);
                                Get_Service_Images(data.getWoIdx(), data.getWrIdx());
                            }

                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                            service_noneTV.setVisibility(View.VISIBLE);
                            service_imgRV.setVisibility(View.GONE);
                            search_img_progress.setVisibility(View.GONE);

                        }
                    }

                } else if (msg.what == -1) {

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

            }
        };
    }
}
