package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
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.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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.ArrayList;
import java.util.HashMap;
import java.util.List;

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.FileDatum;
import kr.co.compcarecompany.Data.Product.AlarmReportData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ReportImageAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

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

    Handler handler;
    FragmentActivity fa;
    EditText report_man_nameET, report_contentET;
    TextView report_saveTV;
    RecyclerView report_photoRV;
    List<String> idx_list;
    String type;
    LinearLayout photo_addLL;
    ReportImageAdapter photo_adapter;
    ArrayList<String> arr = new ArrayList<>();
    ArrayItem<AlarmReportData> alarm_report;
    ArrayItem<FileDatum> alarm_photo;

    @SuppressLint("ValidFragment")
    public Alarm_Report_Fragment(Handler handler, List<String> idx_list, String type) {
        this.handler = handler;
        this.idx_list = idx_list;
        this.type = type;
    }

    @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_alarm_report, container, false);

        report_man_nameET = v.findViewById(R.id.report_man_nameET);
        report_contentET = v.findViewById(R.id.report_contentET);
        report_photoRV = v.findViewById(R.id.report_photoRV);
        report_saveTV = v.findViewById(R.id.report_saveTV);
        photo_addLL = v.findViewById(R.id.photo_addLL);

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) - (report_photoRV.getPaddingLeft() + report_photoRV.getPaddingRight() - px * 6) / 5;
        report_photoRV.setLayoutManager(new GridLayoutManager(getContext(), 5));
        photo_adapter = new ReportImageAdapter(getContext(), itemHeight);
        report_photoRV.setAdapter(photo_adapter);

        init_Listener();
        init_Handler();

        if (type.equals("modify")) {
            Get_Report();
        }

        return v;
    }

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

        photo_adapter.setOnItemClickListener(new ReportImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                photo_adapter.removeItem(position);
                arr.remove(position);
            }
        });
    }

    void Get_Report() {

        HashMap<String, String> data = new HashMap<>();
        data.put("ar_idx", idx_list.get(0));
        new ApiClient(data, "proc_get_alarm_report", handler);
    }

    void Get_photo() {
        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        data.put("ar_idx", idx_list.get(0));
        new ApiClient(data, "proc_get_alarm_image", handler);
    }

    void Set_Contents() {
        report_man_nameET.setText(alarm_report.getArrayitem().get(0).getArWorker());
        report_contentET.setText(alarm_report.getArrayitem().get(0).getArContent());
    }

    void init_Listener() {

        //사진추가 버튼 클릭리스너
        photo_addLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectSize = photo_adapter.getItemCount();
                if (selectSize < 15) {
                    TedImagePicker.with(requireContext())
                            .startMultiImage(uriList -> {
                                for (int i = 0; i < uriList.size(); i++) {
                                    arr.add(uriList.get(i).toString());
                                }
                                photo_adapter.addItem(arr);
                                report_photoRV.setAdapter(photo_adapter);
                            });
//                    TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(getContext()).setImageProvider(new TedBottomPicker.ImageProvider() {
//                        @Override
//                        public void onProvideImage(ImageView imageView, Uri imageUri) {
//                            Glide.with(getContext()).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                        }
//                    }).setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
//                        @Override
//                        public void onImagesSelected(ArrayList<Uri> uriList) {
//
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//                            photo_adapter.addItem(arr);
//                            report_photoRV.setAdapter(photo_adapter);
//                        }
//                    })
//                            .setCompleteButtonText("저장")
//                            .setPeekHeight(2400)
//                            .setPreviewMaxCount(1000).setSelectMaxCount(15 - selectSize).create();
//                    tedBottomPicker.show(getActivity().getSupportFragmentManager());
                } else {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사진은 최대 15장까지 등록가능합니다.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }
            }
        });

        //저장버튼 클릭리스너
        report_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = report_man_nameET.getText().toString();
                String content = report_contentET.getText().toString();

                if (TextUtils.isEmpty(name)) {
                    Common.getInstance().toastShow(getContext(), "작업자 이름을 입력해주세요.");
                    return;
                }

                if (TextUtils.isEmpty(content)) {
                    Common.getInstance().toastShow(getContext(), "작업 내용을 입력해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ar_worker", name);
                data.put("ar_content", content);
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());

                ArrayList<Uri> photo_uri = new ArrayList<>();
                for (int i = 0; i < arr.size(); i++) {
                    photo_uri.add(Uri.parse(arr.get(i)));
                }

                if (type.equals("modify")) {
                    data.put("ar_idx", alarm_report.getArrayitem().get(0).getArIdx());
                    data.put("ar_modify_id", fa.userItem.getArrayitem().getMbId());

                    new ApiClient(data, "proc_alarm_report_modify", photo_uri, handler);

                } else {

                    String mcl_idx = idx_list.toString();
                    mcl_idx = mcl_idx.substring(mcl_idx.indexOf("[")+1, mcl_idx.indexOf("]"));

                    data.put("mcl_idx", mcl_idx);
                    data.put("mem_id", fa.userItem.getArrayitem().getMbId());

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

                    new ApiClient(data, "proc_alarm_report_write", photo_uri, handler);
                }
            }
        });
    }

    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_alarm_report_write")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        getActivity().finish();

                    } else if (url.equals("proc_get_alarm_report")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        alarm_report = new Gson().fromJson(result_item, new TypeToken<ArrayItem<AlarmReportData>>() {
                        }.getType());

                        if (alarm_report.isSuccess()) {
                            Get_photo();

                        } else {
                            Common.getInstance().toastShow(getContext(), "작업일지 가져오기를 실패했습니다.");
                        }
                    } else if (url.equals("proc_get_alarm_image")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        alarm_photo = new Gson().fromJson(result_item, new TypeToken<ArrayItem<FileDatum>>() {
                        }.getType());

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

                            String manager_uri = "https://www.compcare.co.kr/uploads/alarm_report/";
                            ArrayList<String> photo_uri = new ArrayList<>();

                            for (int i = 0; i < alarm_photo.size(); i++) {
                                photo_uri.add(manager_uri + alarm_photo.get(i).getPfiFilename());
                            }
                            photo_adapter.addItem(photo_uri);
                        }
                        Set_Contents();

                    } else if (url.equals("proc_alarm_report_modify")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

//                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        Common.getInstance().toastShow(getContext(), "작업일지를 수정했습니다.");
                        getActivity().finish();

                    }

                } else {
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };

    }

}
