package kr.co.compcareworker.Fragment.Machine;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
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.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
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.Company.Machine.Product.ProductData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.FileUploadHelper;

public class Code_Management_Fragment extends Fragment {

    private Handler handler, hdr;
    FragmentActivity fa;
    TextView code_code_nameTV, code_product_nameTV, code_product_specTV, code_photo_dellTV,
            code_inventory_cntTV, code_inventory_priceTV, code_inventory_sell_priceTV;
    EditText code_product_memoET, code_inventory_marginET;
    RadioGroup code_inventoryRG;
    RadioButton code_inventory_yesRB, code_inventory_noRB;
    LinearLayout code_photo_addLL, code_saveLL, code_inventory_adminLL;
    ImageView code_photoIV;
    String pd_idx, pd_code, pd_name, pd_spec, pd_memo, pd_inven, pd_photo;
    RelativeLayout code_photoRL;
    ProductData productData;

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

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

    @SuppressLint("ValidFragment")
    public Code_Management_Fragment(Handler handler, ProductData productData) {
        this.handler = handler;
        this.pd_idx = productData.getPdIdx();
        this.pd_code = productData.getPdCode();
        this.pd_name = productData.getPdName();
        this.pd_spec = productData.getPdSpec();
        this.pd_memo = productData.getPdMemo();
        this.pd_inven = productData.getInvenYn();
        this.pd_photo = productData.getPhoto1();
        this.productData = productData;
    }

    public Code_Management_Fragment() {
    }

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

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        code_code_nameTV = v.findViewById(R.id.code_code_nameTV);
        code_product_nameTV = v.findViewById(R.id.code_product_nameTV);
        code_product_specTV = v.findViewById(R.id.code_product_specTV);
        code_product_memoET = v.findViewById(R.id.code_product_memoET);
        code_inventoryRG = v.findViewById(R.id.code_inventoryRG);
        code_inventory_yesRB = v.findViewById(R.id.code_inventory_yesRB);
        code_inventory_noRB = v.findViewById(R.id.code_inventory_noRB);
        code_photoRL = v.findViewById(R.id.code_photoRL);
        code_photo_addLL = v.findViewById(R.id.code_photo_addLL);

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

        code_photo_dellTV = v.findViewById(R.id.code_photo_dellTV);
        code_saveLL = v.findViewById(R.id.code_saveLL);

        code_inventory_cntTV = v.findViewById(R.id.code_inventory_cntTV);
        code_inventory_priceTV = v.findViewById(R.id.code_inventory_priceTV);
        code_inventory_marginET = v.findViewById(R.id.code_inventory_marginET);
        code_inventory_sell_priceTV = v.findViewById(R.id.code_inventory_sell_priceTV);
        code_inventory_adminLL = v.findViewById(R.id.code_inventory_adminLL);

        init_Handler();
        init_Listener();
        Set_Contents();

        return v;

    }

    void Set_Contents() {

        code_code_nameTV.setText(pd_code);
        code_product_nameTV.setText(pd_name);
        code_product_specTV.setText(pd_spec);

        if (!TextUtils.isEmpty(pd_memo)) {

            code_product_memoET.setText(pd_memo);
        }

        if (!TextUtils.isEmpty(pd_inven) && pd_inven.equals("Y")) {

            code_inventory_yesRB.setChecked(true);
            code_inventory_noRB.setChecked(false);
            pd_inven = "Y";

        } else {

            code_inventory_yesRB.setChecked(false);
            code_inventory_noRB.setChecked(true);
            pd_inven = "N";

        }

        if (!TextUtils.isEmpty(pd_photo)) {

            String uri = "https://www.compcare.co.kr/uploads/product/";
            Glide.with(requireContext()).load(Uri.parse(uri + pd_photo)).into(code_photoIV);
            code_photoRL.setVisibility(View.VISIBLE);
        }

        if (!fa.userItem.getArrayitem().getMbType2().isEmpty() && fa.userItem.getArrayitem().getMbType2().equals("adm")) {

            code_inventory_adminLL.setVisibility(View.VISIBLE);
        }

        String margin = null;
        String pd_price = null;

        if (productData.getInvenCnt() != null && !productData.getInvenCnt().isEmpty()) {
            code_inventory_cntTV.setText(productData.getInvenCnt());

        } else {
            code_inventory_cntTV.setText("0");
        }

        if (productData.getPdMargin() != null && !productData.getPdMargin().isEmpty()) {
            margin = Common.getInstance().valueConvert(productData.getPdMargin());
            code_inventory_marginET.setText(margin);

        } else {
            code_inventory_marginET.setText("0");
        }

        if (productData.getPrice() != null && !productData.getPrice().isEmpty()) {
            pd_price = Common.getInstance().moneyFormatToWon(Integer.parseInt(productData.getPrice()));
            code_inventory_priceTV.setText(pd_price);

        } else {
            code_inventory_priceTV.setText("0");
        }

        if (productData.getPdMargin() != null && productData.getPrice() != null && !productData.getPdMargin().isEmpty() && !productData.getPrice().isEmpty()) {
            double cal_price = Integer.parseInt(productData.getPrice()) * Double.parseDouble(margin);
            if (cal_price > 0) {
                String sell_price = Common.getInstance().valueConvert2(cal_price + "");
                sell_price = Common.getInstance().moneyFormatToWon(Integer.parseInt(sell_price));
                code_inventory_sell_priceTV.setText(sell_price);
            } else {
                code_inventory_sell_priceTV.setText("0");
            }

        } else {
            code_inventory_sell_priceTV.setText("0");
        }
    }

    void init_Listener() {

        code_inventoryRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == R.id.code_inventory_yesRB) {

                    pd_inven = "Y";

                } else if (checkedId == R.id.code_inventory_noRB) {

                    pd_inven = "N";
                }
            }
        });

        code_photo_addLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TedImagePicker.with(requireContext())
                        .start(uri -> {
                            Glide.with(getContext()).load(uri).into(code_photoIV);
                            pd_photo = uri.toString();
                            code_photoRL.setVisibility(View.VISIBLE);
                        });
//                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(code_photoIV);
//                        pd_photo = uri.toString();
//                        code_photoRL.setVisibility(View.VISIBLE);
//                    }
//                })
//                        .setCompleteButtonText("저장")
//                        .setPeekHeight(2400)
//                        .setPreviewMaxCount(1000).setSelectMaxCount(1).create();
//
//                cardImgPicker.show(getActivity().getSupportFragmentManager());

            }
        });

        code_photoIV.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 (!TextUtils.isEmpty(pd_photo) && pd_photo.contains("file")) {

                    String path = getRealPathFromURI(Uri.parse(pd_photo));
                    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);

                } else {

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

                }

                progress.setVisibility(View.GONE);
                dig.show();

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


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

                Glide.with(getContext()).load("").into(code_photoIV);
                code_photoRL.setVisibility(View.GONE);
                pd_photo = null;
            }
        });

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

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("pd_idx", pd_idx);
                data.put("pd_memo", code_product_memoET.getText().toString());
                data.put("pd_inven", pd_inven);

                String margin = code_inventory_marginET.getText().toString();
                if (!TextUtils.isEmpty(margin)) {
                    data.put("pd_margin", margin);
                }

                if (!TextUtils.isEmpty(pd_photo)) {

                    data.put("photo1", pd_photo);

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

                        new ApiClient(data, "proc_product_code", Uri.parse(pd_photo), hdr);

                    } else {

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

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

        code_inventory_marginET.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 (code_inventory_marginET.length() > 0) {

                    if (productData.getPrice() != null) {
                        String cvt_margin = Common.getInstance().valueConvert(code_inventory_marginET.getText().toString());
                        double cal_price = Integer.parseInt(productData.getPrice()) * Double.parseDouble(cvt_margin);
                        if (cal_price > 0) {
                            String sell_price = Common.getInstance().valueConvert2(cal_price + "");
                            sell_price = Common.getInstance().moneyFormatToWon(Integer.parseInt(sell_price));
                            code_inventory_sell_priceTV.setText(sell_price);
                        } else {
                            code_inventory_sell_priceTV.setText("0");
                        }
                    }
                } else if (code_inventory_marginET.length() == 0) {
                    code_inventory_sell_priceTV.setText("0");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

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

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

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

                        } else {

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

                    }
                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).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;
    }
}
