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

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

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 com.ortiz.touchview.TouchImageView;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Objects;

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.WebviewAct;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.ManagerList.ManagerData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ManagerListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.FileUploadHelper;
import kr.co.compcareworker.Util.MyOnItemClick;

@SuppressLint("ValidFragment")
public class BusinessCard_Fragment extends Fragment implements MyOnItemClick {

    Handler handler, hdr;
    FragmentActivity fa;
    String cp_idx, cardImg_uri, ptm_idx;
    ManagerData data;

    /**
     * 상단 업체명
     */
    TextView enterprise_nameTV;

    /**
     * 업체 담당자 목록
     */
    RecyclerView managerRV;
    Button manager_modify;
    ImageView manager_callIV;

    /**
     * 업체 담당자 관리
     */
    EditText manager_departmentET, manager_positionET, manager_nameET, manager_telET, manager_emailET;

    /**
     * 명함사진
     */
    LinearLayout add_business_cardLL;
    RelativeLayout business_cardRL;
    ImageView business_cardIV;
    TextView business_card_delBtn;

    /**
     * 저장 및 삭제버튼
     */
    Button manager_saveBtn, manager_delBtn;

    /**
     * 새로고침
     */
    SwipeRefreshLayout swipe;

    ArrayItem<ManagerData> items;
    ManagerListRecyclerAdapter adapter;
    RecyclerView.LayoutManager layoutManager;

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

    @SuppressLint("ValidFragment")
    public BusinessCard_Fragment() {
    }

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

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_business_card, container, false);

        /**새로고침*/
        swipe = v.findViewById(R.id.swipe);

        /**상단 업체명*/
        enterprise_nameTV = v.findViewById(R.id.enterprise_nameTV);

        /**업체 담당자 목록*/
        managerRV = v.findViewById(R.id.managerRV);

        /**업체 담당자 관리*/
        manager_departmentET = v.findViewById(R.id.manager_departmentET);
        manager_positionET = v.findViewById(R.id.manager_positionET);
        manager_nameET = v.findViewById(R.id.manager_nameET);
        manager_telET = v.findViewById(R.id.manager_telET);
        manager_emailET = v.findViewById(R.id.manager_emailET);

        /**명함사진*/
        business_cardRL = v.findViewById(R.id.business_cardRL);
        add_business_cardLL = v.findViewById(R.id.add_business_cardLL);
        business_card_delBtn = v.findViewById(R.id.business_card_delBtn);

        GradientDrawable drawable = (GradientDrawable) getContext().getDrawable(R.drawable.border_white_round2);
        business_cardIV = v.findViewById(R.id.business_cardIV);
        business_cardIV.setBackground(drawable);
        business_cardIV.setClipToOutline(true);

        /**저장 및 삭제버튼*/
        manager_saveBtn = v.findViewById(R.id.manager_saveBtn);
        manager_delBtn = v.findViewById(R.id.manager_delBtn);

        adapter = new ManagerListRecyclerAdapter(getContext(), hdr, this::onClick);

        init_Handler();
        init_Listener();
        Get_Contents();

        return v;
    }

    void Get_Contents() {

        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", fa.enterpriseItem.getArrayitem().getPtIdx());
        new ApiClient(data, "proc_partner_men_view", hdr);
    }

    void Set_Contents() {

        /**상단 업체명*/
        enterprise_nameTV.setText(fa.enterpriseItem.getArrayitem().getPtName());

        /**업체 담당자 목록*/

        adapter = new ManagerListRecyclerAdapter(getContext(), hdr, this::onClick);
        layoutManager = new LinearLayoutManager(getContext());
        managerRV.setLayoutManager(layoutManager);
        adapter.addItem(items.getArrayitem());
        managerRV.setAdapter(adapter);

    }

    /**
     * 업체 담당자 목록 리스트에서 수정버튼 클릭시
     */
    @Override
    public void onClick(Bundle value) {

        ptm_idx = value.getString("ptm_idx");
        manager_departmentET.setText(value.getString("department"));
        manager_positionET.setText(value.getString("position"));
        manager_nameET.setText(value.getString("name"));
        manager_telET.setText(value.getString("phone"));
        manager_emailET.setText(value.getString("email"));

        String manager_uri = "https://www.compcare.co.kr/uploads/partner_men/";
        cardImg_uri = value.getString("photo");
        Glide.with(requireContext()).load(Uri.parse(manager_uri + cardImg_uri)).into(business_cardIV);

        if (!TextUtils.isEmpty(cardImg_uri)) {
            business_cardRL.setVisibility(View.VISIBLE);
        }
    }

    private void init_Listener() {

        //새로고침
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Get_Contents();
                swipe.setRefreshing(false);
            }
        });

        //연락처 입력시 자동으로 하이픈 추가
        manager_telET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        //명함사진 버튼
        add_business_cardLL.setOnClickListener(v -> {
            TedImagePicker.with(requireContext())
                    .start(uri -> {
                        Glide.with(requireContext()).load(uri).into(business_cardIV);
                        business_cardRL.setVisibility(View.VISIBLE);
                        cardImg_uri = uri.toString();
                    });

//                TedBottomPicker cardImgPicker = 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);
//                    }
//                }).setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
//                    @Override
//                    public void onImageSelected(Uri uri) {
//                        // uri 활용
//                        Glide.with(getContext()).load(uri).into(business_cardIV);
//                        business_cardRL.setVisibility(View.VISIBLE);
//                        cardImg_uri = uri.toString();
//
//                    }
//                })
//                        .setCompleteButtonText("저장")
//                        .setPeekHeight(2400)
//                        .setPreviewMaxCount(1000).setSelectMaxCount(1).create();
//
//                cardImgPicker.show(getActivity().getSupportFragmentManager());

        });

        //추가된 명함사진 삭제버튼 클릭
        business_card_delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Glide.with(getContext()).load("").into(business_cardIV);
                business_cardRL.setVisibility(View.GONE);
                cardImg_uri = null;
            }
        });


        //명함사진 클릭시 확대기능
        business_cardIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext(), R.style.Transparent);
                AlertDialog dig = dialogBuilder.create();
                View view = getLayoutInflater().inflate(R.layout.dlg_image, null);
                TouchImageView iv = view.findViewById(R.id.imageview);
                dig.setView(view);

                ProgressBar progress = view.findViewById(R.id.image_progress);
                progress.setVisibility(View.VISIBLE);

                if (cardImg_uri.contains("file")) {

                    String path = getRealPathFromURI(Uri.parse(cardImg_uri));
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 3;
                    Bitmap src = BitmapFactory.decodeFile(path, options);
                    Bitmap resized = Bitmap.createScaledBitmap(src, options.outWidth, options.outHeight, true);

                    iv.setImageBitmap(resized);
                    progress.setVisibility(View.GONE);

                } else {


                    String manager_uri = "https://www.compcare.co.kr/uploads/partner_men/";
                    new GetImageFromUrl(iv).execute(manager_uri + cardImg_uri);

                    Handler progress_hdr = new Handler();
                    progress_hdr.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            progress.setVisibility(View.GONE);
                        }
                    }, 850);
                }
                dig.show();

                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dig.dismiss();
                    }
                });
            }
        });

        //저장버튼
        manager_saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HashMap<String, String> data = new HashMap<>();

                data.put("mem_id", fa.userItem.getArrayitem().getMbId());
                data.put("ag_idx", fa.enterpriseItem.getArrayitem().getAgIdx());
                data.put("pt_idx", fa.enterpriseItem.getArrayitem().getPtIdx());
                data.put("ptm_department", manager_departmentET.getText().toString());
                data.put("ptm_position", manager_positionET.getText().toString());
                data.put("ptm_name", manager_nameET.getText().toString());
                data.put("ptm_phone", manager_telET.getText().toString());
                data.put("ptm_email", manager_emailET.getText().toString());
                if (ptm_idx != null) {
                    data.put("ptm_idx", ptm_idx);
                }

                if (!TextUtils.isEmpty(cardImg_uri)) {

                    data.put("photo1", cardImg_uri);

                    if (cardImg_uri.contains("file")) {

                        Log.d("데이터확인@@@@", data.toString());
                        new ApiClient(data, "proc_partner_men_write", Uri.parse(cardImg_uri), hdr);

                    } else {

                        new ApiClient(data, "proc_partner_men_write", hdr);
                    }
                } else {

                    new ApiClient(data, "proc_partner_men_write", hdr);
                }
            }
        });

        //삭제버튼
        manager_delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (adapter.getItemCount() == 0) {
                    Toast.makeText(getContext(), "삭제는 담당자 등록 후 가능합니다.", Toast.LENGTH_SHORT).show();
                    return;
                }

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("담당자 관리");
                dialogBuilder.setMessage("선택된 명함을 삭제하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {

                        HashMap<String, String> data = new HashMap<>();

                        data.put("ptm_idx", ptm_idx);
                        data.put("ptm_department", manager_departmentET.getText().toString());
                        data.put("ptm_position", manager_positionET.getText().toString());
                        data.put("ptm_name", manager_nameET.getText().toString());
                        data.put("ptm_phone", manager_telET.getText().toString());
                        data.put("type", "delete");

                        new ApiClient(data, "proc_partner_men_write", hdr);
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                dialogBuilder.show();
            }
        });
    }

    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) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    if (url.equals("proc_partner_men_view")) {

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

                        if (items.isSuccess()) {

                            if (items.size() > 0) {
                                data = items.getArrayitem().get(0);
                            }
                            Set_Contents();

                        } else {

                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                            Set_Contents();
                        }
                    } else if (url.equals("proc_partner_men_write")) {

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

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

                            Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");

                            ptm_idx = null;
                            manager_departmentET.getText().clear();
                            manager_positionET.getText().clear();
                            manager_nameET.getText().clear();
                            manager_telET.getText().clear();
                            manager_emailET.getText().clear();
                            manager_emailET.setCursorVisible(false);
                            business_cardRL.setVisibility(View.GONE);
                            cardImg_uri = null;

                            Toast.makeText(getContext(), "저장되었습니다.", Toast.LENGTH_SHORT).show();
                            Get_Contents();

                        } else {

                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        };
    }


    public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
        ImageView imageView;

        public GetImageFromUrl(ImageView img) {
            this.imageView = img;
        }

        @Override
        protected Bitmap doInBackground(String... url) {
            String stringUrl = url[0];
            Bitmap bitmap = null;
            InputStream inputStream;
            try {
                inputStream = new java.net.URL(stringUrl).openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }

    private String getRealPathFromURI(Uri contentURI) {

        String result;
        Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);

        if (cursor == null) { // Source is Dropbox or other similar local file path

            result = contentURI.getPath();

        } else {

            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }

        return result;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
    }
}
