package com.cpm.lorealbaMabeline.consumeractivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaMabeline.gsonGetterSetter.ProductMaster;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


import static com.cpm.lorealbaMabeline.constant.CommonFunctions.removeFirstChar;
import static com.cpm.lorealbaMabeline.dailyactivity.ConsumerReturnActivity.replace_productList;


public class ConsumerReturnReplaceProductActivity extends AppCompatActivity implements View.OnClickListener {
    ArrayAdapter<CharSequence> dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter;
    TextView txt_product_name, txt_return_qty, txt_product_mrp;
    EditText edt_scan_code;
    Button btn_scan, btn_enter_code, btn_sku_list;
    RecyclerView drawer_layout_recycle_store;
    MultiPurposeDialog multiPurposeDialog;
    InvoiceGetterSetter object, selected_product_mrpObject;
    int minteger = 0;

    String counterID, username, visit_date, dialog_brand_Id = "", dialog_sub_brand_Id = "",
            dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0", product_scan_code = "",
            bill_no, mobile_no, consumer_name;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor = null;
    TextView qrcode_text, sku_name, stock_text_value, actual_qty_dialog;
    boolean clicked_flag = false, flag_for_filter = false, flag_filter_by_edt = false;
    public ArrayList<ProductMaster> dialog_product_list = new ArrayList<>();
    public ArrayList<ProductMaster> dialog_product_using_searchlist = new ArrayList<>();
    FloatingActionButton save_fab;
    LinearLayout rl_actual_qty;
    Lorealba_Database db;
    Context context;
    int current_total = 0;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consumer_return_replace_product);
        context = this;
        ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();
        setTitle("Replace Product - " + username);

        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counterID);
    }

    @SuppressLint("SetTextI18n")
    private void iduserinterface() {
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counterID = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        txt_product_name = (TextView) findViewById(R.id.txt_product_name);
        txt_return_qty = (TextView) findViewById(R.id.txt_return_qty);
        txt_product_mrp = (TextView) findViewById(R.id.txt_product_mrp);
        save_fab = (FloatingActionButton) findViewById(R.id.save_fab);

        btn_scan = (Button) findViewById(R.id.btn_scan);
        btn_enter_code = (Button) findViewById(R.id.btn_enter_code);
        btn_sku_list = (Button) findViewById(R.id.btn_sku_list);
        drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store);
        db.open();
        btn_scan.setOnClickListener(this);
        btn_enter_code.setOnClickListener(this);
        btn_sku_list.setOnClickListener(this);
        save_fab.setOnClickListener(this);
        db.open();
        dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, counterID, null);
        selected_product_mrpObject = (InvoiceGetterSetter) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        if (selected_product_mrpObject != null && selected_product_mrpObject.getTotal_replace_product_value() != 0) {
            txt_return_qty.setText("Return Total Rs. : " + selected_product_mrpObject.getTotal_replace_product_value());
            txt_product_mrp.setText("Current Total Rs. : 0");
        }


        if (!replace_productList.isEmpty()) {
            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList));
            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
            txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList));
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        (dialog, id12) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            ConsumerReturnReplaceProductActivity.this.finish();
                        }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ConsumerReturnReplaceProductActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                    (dialog, id) -> {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        ConsumerReturnReplaceProductActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ConsumerReturnReplaceProductActivity.this.finish();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.btn_scan) {
            ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            show_proforma_dialog(context, true);

        } else if (view.getId() == R.id.btn_enter_code) {
            ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            show_proforma_dialog(context, false);

        } else if (view.getId() == R.id.btn_sku_list) {
            ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            show_dialog_forsku_categorywise(context);

        } else if (view.getId() == R.id.save_fab) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ConsumerReturnReplaceProductActivity.this.finish();
        }

    }


    @SuppressLint("SetTextI18n")
    private void show_proforma_dialog(final Context context, final boolean flag_for_rl) {
        minteger = 0;
        final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_bar_code_dialog);
        multiPurposeDialog.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);

//for actual Quantity form Tstock_Summery
        rl_actual_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actual_qty);
        actual_qty_dialog = (TextView) multiPurposeDialog.findViewById(R.id.actual_qty_dialog);

        LinearLayout rl_bar_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_bar_code);
        LinearLayout RL_scan_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.RL_scan_code);
        Button check_exist_sku = (Button) multiPurposeDialog.findViewById(R.id.check_exist_sku);
        TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code);
        TextView txt_enterbar_code = multiPurposeDialog.findViewById(R.id.txt_enterbar_code);
        LinearLayout rl_quantity = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_quantity);
        final RecyclerView recycl_mutliennter_qty = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_mutliennter_qty);
        recycl_mutliennter_qty.setVisibility(View.GONE);
        rl_quantity.setVisibility(View.VISIBLE);

        sku_name = multiPurposeDialog.findViewById(R.id.sku_name);
        if (flag_for_rl) {
            RL_scan_code.setVisibility(View.GONE);
            rl_bar_code.setVisibility(View.VISIBLE);
            txt_bar_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.GONE);
        } else {
            rl_bar_code.setVisibility(View.GONE);
            txt_bar_code.setVisibility(View.GONE);
            RL_scan_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.VISIBLE);
        }

        qrcode_text = (TextView) multiPurposeDialog.findViewById(R.id.qrcode_text);
        edt_scan_code = (EditText) multiPurposeDialog.findViewById(R.id.edt_scan_code);
        final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus);
        Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus);
        stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value);

        ImageView img_bar_code = (ImageView) multiPurposeDialog.findViewById(R.id.img_bar_code);
        ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add);
        btn_add.setVisibility(View.VISIBLE);

        stock_img_plus.setOnClickListener(v -> {
            if (!product_Id.equals("0")) {
                db.open();
                if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() == 0) {
                    AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                } else {
                    minteger = minteger + 1;
                    db.open();
                    if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() != 0 && minteger > db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock()) {
                        minteger = minteger - 1;
                        AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                    } else {
                        int val = calculate_total() + (minteger * (Integer.parseInt(product_mrp)));
                        stock_text_value.setText("" + minteger);
                    }
                }
            }
        });

        stock_img_minus.setOnClickListener(v -> {
            if (minteger == 0) {
                AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
            } else {
                minteger = minteger - 1;
                stock_text_value.setText("" + minteger);
            }
        });

        cancet_btn.setOnClickListener(v -> {
            multiPurposeDialog.dismiss();
            sku_name.setText("");
            stock_text_value.setText("");
            qrcode_text.setText("");
            product_scan_code = "";
            product_name = "";
            product_mrp = "";
            product_Id = "0";
            sku_name.setVisibility(View.GONE);
        });

        check_exist_sku.setOnClickListener(v -> {
            if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bar Code");
            } else {
                db.open();
                if (db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, counterID, null).isEmpty()) {
                    edt_scan_code.setText("");
                    AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again");
                } else {
                    db.open();
                    show_dialog_forsku(context, db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, counterID, null), rl_actual_qty, actual_qty_dialog);
                }
            }
        });


        btn_add.setOnClickListener(v -> {
            db.open();
            if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() == 0) {
                AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                multiPurposeDialog.cancel();
                stock_text_value.setText("");
                qrcode_text.setText("");
                edt_scan_code.setText("");
                product_scan_code = "";
                product_name = "";
                product_mrp = "";
                product_Id = "0";
                sku_name.setText("");
                sku_name.setVisibility(View.GONE);

            } else {
                if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Scan Bar Code");
                } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Bar Code ");
                } else if (stock_text_value.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity ");
                } else {
                    object = new InvoiceGetterSetter();
                    if (checkduplicate_entry()) {
                        if (!flag_for_rl) {
                            product_scan_code = edt_scan_code.getText().toString();
                            db.open();
                            if (db.getsku_fromproductusing_eancode(product_scan_code, true, visit_date, counterID, null).isEmpty()) {
                                AlertandMessages.showToastMsg(context, "Product not found ");
                            } else {
                                minteger = 0;
                                multiPurposeDialog.cancel();

                                // get selected radio button from radioGroup
                                object = new InvoiceGetterSetter();
                                object.setCustomer_name(consumer_name);
                                object.setConsumer_return_bill_no(bill_no);
                                object.setMobile_no(mobile_no);
                                object.setProduct_rate(product_mrp);
                                object.setProduct(product_name);
                                object.setProduct_Id(product_Id);
                                object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                                object.setQuantity(stock_text_value.getText().toString());
                                replace_productList.add(object);
                                txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList));

                                stock_text_value.setText("");
                                qrcode_text.setText("");
                                edt_scan_code.setText("");
                                product_scan_code = "";
                                product_name = "";
                                product_mrp = "";
                                product_Id = "0";
                                sku_name.setText("");
                                sku_name.setVisibility(View.GONE);
                                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList));
                                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                            }
                        } else {
                            multiPurposeDialog.cancel();
                            minteger = 0;
                            // get selected radio button from radioGroup
                            object = new InvoiceGetterSetter();
                            object.setCustomer_name(consumer_name);
                            object.setConsumer_return_bill_no(bill_no);
                            object.setMobile_no(mobile_no);
                            object.setProduct_rate(product_mrp);
                            object.setProduct(product_name);
                            object.setProduct_Id(product_Id);
                            object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                            object.setQuantity(stock_text_value.getText().toString());
                            replace_productList.add(object);
                            txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList));
                            sku_name.setText("");
                            stock_text_value.setText("");
                            qrcode_text.setText("");
                            product_scan_code = "";
                            product_name = "";
                            product_mrp = "";
                            product_Id = "0";
                            sku_name.setVisibility(View.GONE);
                            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList));
                            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                        }
                    }
                }
            }
        });

        img_bar_code.setOnClickListener(v -> openScanner());
        multiPurposeDialog.show();
    }

    public class MultiPurposeDialog extends Dialog {
        public MultiPurposeDialog(Context context) {
            super(context);
            // DIALOG USER_INTERFACE TEMPLATE
            WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes();
            wmLayoutParams.gravity = Gravity.CENTER;
            getWindow().setAttributes(wmLayoutParams);
            setTitle(null);
            setCancelable(false);
            setOnCancelListener(null);
            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
        }
    }

    private int calculate_total_consume(ArrayList<InvoiceGetterSetter> invoice_List) {
        int total_INR_value = 0;
        if (!invoice_List.isEmpty()) {
            for (int k = 0; k < invoice_List.size(); k++) {
                int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate()));
                amount = amount * quantity;
                invoice_List.get(k).setTotal_amount("" + amount);
                total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount());

            }
        }

        return total_INR_value;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                //test("ScanActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
            } else {

                db.open();
                ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancode(result.getContents(), true, visit_date, counterID, null);

                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), true, visit_date, counterID, null);
                }

                if (!productList.isEmpty()) {
                    show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog);
                    sku_name.setText(productList.get(0).getProductName());
                    sku_name.setVisibility(View.VISIBLE);
                    stock_text_value.setText("0");
                    minteger = 0;
                } else {
                    minteger = 0;
                    product_name = "";
                    product_scan_code = "";
                    qrcode_text.setText("");
                    AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again.");
                }
            }

        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    private void openScanner() {
        IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context);
        intentIntegrator.setBeepEnabled(true);
        intentIntegrator.setOrientationLocked(false);
        intentIntegrator.setPrompt("Scan the barcode or QR code to get the data");
        intentIntegrator.initiateScan();
    }

    @SuppressLint("SetTextI18n")
    private void show_dialog_forsku_categorywise(final Context context) {
        minteger = 0;
        multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_list_with_category);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(multiPurposeDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);

        final Spinner dialog_brand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_brand_spin);
        final Spinner dialog_subbrand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_subbrand_spin);
        final Spinner dialog_reference_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_reference_spin);
        final Spinner dialog_product_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_product_spin);
        final EditText et_search = (EditText) multiPurposeDialog.findViewById(R.id.et_search);
        final TextView stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value);

        final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus);
        Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus);

        ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add);
//for actual Quantity form Tstock_Summery
        rl_actual_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actual_qty);
        actual_qty_dialog = (TextView) multiPurposeDialog.findViewById(R.id.actual_qty_dialog);
        TextView txt_current_invoice_type = (TextView) multiPurposeDialog.findViewById(R.id.txt_current_invoice_type);

        et_search.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) {
                String text = s.toString();
                setSearchFilter(dialog_product_list, text, dialog_product_spin);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
            }
        });


        db.open();
        validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin,
                db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, counterID, null),
                db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, counterID, null),
                db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, counterID, null),
                db.getbrand_wise_sku_fromproduct(null, null, visit_date, counterID, null), stock_text_value, actual_qty_dialog, txt_current_invoice_type);


        cancet_btn.setOnClickListener(v -> multiPurposeDialog.dismiss());


        stock_img_minus.setOnClickListener(v -> {
            if (minteger == 0) {
                AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
            } else {
                minteger = minteger - 1;
                stock_text_value.setText("" + minteger);
            }
        });


        stock_img_plus.setOnClickListener(v -> {
            if (!product_Id.equals("0")) {
                db.open();
                if (!product_Id.equals("0")) {
                    rl_actual_qty.setVisibility(View.VISIBLE);
                    db.open();
                    if (db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock() == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else {
                        minteger = minteger + 1;
                        db.open();
                        if (db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock() != 0 && minteger > db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock()) {
                            minteger = minteger - 1;
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else {
                            int val = (calculate_total() + (minteger * (Integer.parseInt(product_mrp))));
                            stock_text_value.setText("" + minteger);
                        }
                    }
                }
            }
        });


        btn_add.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                if (dialog_product_spin.getSelectedItemId() == 0) {
                    AlertandMessages.showToastMsg(context, "Please Select Product");
                } else if (stock_text_value.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity ");
                } else {
                    // get selected radio button from radioGroup
                    object = new InvoiceGetterSetter();
                    object.setCustomer_name(consumer_name);
                    object.setConsumer_return_bill_no(bill_no);
                    object.setMobile_no(mobile_no);
                    object.setProduct_rate(product_mrp);
                    object.setProduct(product_name);
                    object.setProduct_Id(product_Id);
                    object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                    object.setQuantity(stock_text_value.getText().toString());
                    replace_productList.add(object);
                    txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList));
                    minteger = 0;
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    dialog_brand_Id = "";
                    dialog_sub_brand_Id = "";
                    dialog_reference_Id = "";
                    product_name = "";
                    product_Id = "0";
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    multiPurposeDialog.dismiss();

                }
            }
        });

        multiPurposeDialog.show();
    }


    public void setSearchFilter(ArrayList<ProductMaster> originalList, String text, Spinner dialog_product_spin) {
        flag_filter_by_edt = true;
        dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        dialog_sku_adapter.add("- Select Product -");
        dialog_product_using_searchlist = new ArrayList<>();
        dialog_product_using_searchlist = filterListForProduct_edt(originalList, text);

        if (filterListForProduct_edt(originalList, text).isEmpty()) {
            dialog_product_using_searchlist = originalList;
        }

        for (int i = 0; i < dialog_product_using_searchlist.size(); i++) {
            dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")");
        }
        dialog_product_spin.setAdapter(dialog_sku_adapter);
        dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        dialog_product_spin.invalidate();
    }


    public ArrayList<ProductMaster> filterListForProduct_edt(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getProductName().toLowerCase().contains(text.toLowerCase())) {
                filterList.add(object);
            } else {
                continue;
            }
        }

        return filterList;
    }

    private void
    validate_spin_ui_data(final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin,
                          final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, final ArrayList<ProductMaster> brandList, final ArrayList<ProductMaster> subbrandList,
                          final ArrayList<ProductMaster> referenceList,
                          final ArrayList<ProductMaster> productList, final TextView stock_text_value, final TextView actual_qty_dialog, final TextView txt_current_invoice_type) {

        dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_brand_adapter.add("- Select Brand -");

        for (int i = 0; i < brandList.size(); i++) {
            dialog_brand_adapter.add(brandList.get(i).getBrandName());
        }

        dialog_brand_spin.setAdapter(dialog_brand_adapter);

        dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);

        setReferenceSpinnerData(referenceList, dialog_franchise_spin);

        setProductSpinnerData(productList, dialog_product_spin);

        dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    dialog_brand_Id = adapterView.getSelectedItem().toString();
                    setFilter(FILTER_FOR_BRAND, dialog_product_spin);

                    setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", null, visit_date, counterID, true, null), dialog_sub_brand_spin);
                    setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", null, visit_date, counterID, true, null), dialog_franchise_spin);
                } else {
                    dialog_brand_Id = "";
                    if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 ||
                            dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }


            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    dialog_sub_brand_Id = adapterView.getSelectedItem().toString();
                    setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin);
                    setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, counterID, true, null), dialog_franchise_spin);
                } else {
                    dialog_sub_brand_Id = "";
                    if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 ||
                            dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    dialog_reference_Id = adapterView.getSelectedItem().toString();
                    setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin);

                } else {
                    dialog_reference_Id = "";
                    if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 ||
                            dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    if (flag_filter_by_edt) {
                        product_name = dialog_product_using_searchlist.get(position - 1).getProductName();
                        product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString();
                        product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString();
                        product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode();
                        stock_text_value.setText("0");

                        stock_text_value.setText("0");
                        if (!product_Id.equals("0")) {
                            rl_actual_qty.setVisibility(View.VISIBLE);
                            db.open();
                            txt_current_invoice_type.setText(R.string.current_stock_saleable);
                            actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock());
                        }

                        minteger = 0;
                    } else if (flag_for_filter) {
                        product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName();
                        product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString();
                        product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString();
                        product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode();
                        stock_text_value.setText("0");
                        if (!product_Id.equals("0")) {
                            rl_actual_qty.setVisibility(View.VISIBLE);
                            db.open();
                            txt_current_invoice_type.setText(R.string.current_stock_saleable);
                            actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock());
                        }
                        minteger = 0;
                    } else {
                        product_name = productList.get(position - 1).getProductName();
                        product_Id = productList.get(position - 1).getProductId().toString();
                        product_mrp = productList.get(position - 1).getMrp().toString();
                        product_scan_code = productList.get(position - 1).getEanCode();
                        stock_text_value.setText("0");
                        if (!product_Id.equals("0")) {
                            rl_actual_qty.setVisibility(View.VISIBLE);
                            db.open();
                            txt_current_invoice_type.setText(R.string.current_stock_saleable);
                            actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock());
                        }
                        minteger = 0;
                    }

                } else {
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    product_mrp = "0";
                    product_name = "";
                    product_Id = "0";
                    minteger = 0;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


    private void setSubBrandSpinnerData(ArrayList<ProductMaster> axeList, Spinner dialog_sub_brand_spin) {
        dialog_sub_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_sub_brand_adapter.add("- Select Sub Brand -");

        for (int i = 0; i < axeList.size(); i++) {
            dialog_sub_brand_adapter.add(axeList.get(i).getBrandName());
        }

        dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter);
        dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }


    private void setReferenceSpinnerData(ArrayList<ProductMaster> referenceList, Spinner dialog_franchise_spin) {
        dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_frenchise_adapter.add("- Select Franchise -");

        for (int i = 0; i < referenceList.size(); i++) {
            dialog_frenchise_adapter.add(referenceList.get(i).getBrandName());
        }

        dialog_franchise_spin.setAdapter(dialog_frenchise_adapter);
        dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
    }

    private void setProductSpinnerData(ArrayList<ProductMaster> productList, Spinner dialog_product_spin) {
        dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_sku_adapter.add("- Select Product -");

        for (int i = 0; i < productList.size(); i++) {
            dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")");
        }

        dialog_product_spin.setAdapter(dialog_sku_adapter);
        dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
    }


    public void setFilter(int filterType, Spinner dialog_spin) {
        if (filterType == FILTER_FOR_BRAND) {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");

            for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")");
            }

            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        } else if (filterType == FILTER_FOR_SUB_BRAND) {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");

            for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" +
                        filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")");
            }
            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } else if (filterType == FILTER_FOR_REFERENCE_NAME) {

            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");

            for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getProductName() +
                        " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getMrp().toString() + ")");
            }

            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        } else {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");

            for (int i = 0; i < dialog_product_list.size(); i++) {
                dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")");
            }

            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        }

        dialog_spin.invalidate();
    }

    final int CLEAR_FILTER = 0;
    final int FILTER_FOR_BRAND = 1;
    final int FILTER_FOR_SUB_BRAND = 2;
    final int FILTER_FOR_REFERENCE_NAME = 3;

    public ArrayList<ProductMaster> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getBrandName().equalsIgnoreCase(text)) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubBrand(List<ProductMaster> originalList, String sub_brand_name_id, String brand_Id) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (sub_brand_name_id.isEmpty() && object.getBrandName().equalsIgnoreCase(brand_Id)) {
                filterList.add(object);
            } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brand_Id))) {
                filterList.add(object);
            } else {
                continue;
            }
        }

        return filterList;
    }


    public ArrayList<ProductMaster> filterListForReferencename(List<ProductMaster> originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (sub_brand_name_Id.isEmpty() && object.getBrandName().equalsIgnoreCase(brandName_Id)) {
                filterList.add(object);
            } else if (franchise_Id.isEmpty() && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) {
                filterList.add(object);
            } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.isEmpty() || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) {
                filterList.add(object);
            } else {
                continue;
            }
        }

        return filterList;
    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<InvoiceGetterSetter> data;


        public ValueAdapter(Context context, List<InvoiceGetterSetter> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

        @NonNull
        @Override
        public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_adapter_return_consumer, parent, false);
            return new ValueAdapter.MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final InvoiceGetterSetter current = data.get(position);

            holder.select_promo_productRl.setVisibility(View.GONE);
            holder.select_promo_productRl.setId(position);

            holder.select_productRl.setVisibility(View.VISIBLE);
            holder.select_productRl.setId(position);

            if (current.getDiscount() == 0.0 || current.getDiscount() == 0) {
                holder.text_item.setText(current.getProduct());
                holder.text_item.setId(position);
            } else {
                String string = current.getDiscount().toString();
                //test("last character: " + string.substring(string.length() - 1));
                holder.text_item.setText(current.getProduct() + "  Discount : " + string.substring(string.length() - 1) + "0%");
                holder.text_item.setId(position);
            }

            holder.text_qty.setText(current.getQuantity());
            holder.text_qty.setId(position);

            holder.text_actualqty.setText(current.getActualQty());
            holder.text_actualqty.setId(position);

            holder.txt_amount.setText(current.getProduct_rate());
            holder.txt_amount.setId(position);

            holder.delete_added_product.setOnClickListener(v -> {
                @SuppressLint("NotifyDataSetChanged") AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false)
                        .setPositiveButton("Yes",
                                (dialog, id) -> {
                                    data.remove(position);
                                    notifyDataSetChanged();
                                    if (!data.isEmpty()) {
                                        ValueAdapter adapter = new ValueAdapter(context, data);
                                        drawer_layout_recycle_store.setAdapter(adapter);
                                        adapter.notifyDataSetChanged();
                                    }

                                    txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList));
                                    notifyDataSetChanged();
                                })
                        .setNegativeButton("No",
                                (dialog, id) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            });

        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            LinearLayout select_productRl, select_promo_productRl;
            TextView text_item, text_qty, txt_amount, text_actualqty;
            ImageView delete_added_product;

            public MyViewHolder(View itemView) {
                super(itemView);
                text_item = (TextView) itemView.findViewById(R.id.text_item);
                text_qty = (TextView) itemView.findViewById(R.id.text_qty);
                txt_amount = (TextView) itemView.findViewById(R.id.txt_amount);
                text_actualqty = (TextView) itemView.findViewById(R.id.text_actualqty);
                delete_added_product = (ImageView) itemView.findViewById(R.id.delete_added_product);
                select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl);
                select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl);
            }
        }
    }

    ////sku scannnnnnnnnnnn
    private void show_dialog_forsku(final Context context, ArrayList<ProductMaster> skuList_with_eancode,
                                    LinearLayout rl_actual_qty, TextView actual_qty_dialog) {
        multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);
        TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName());
        RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku);

        recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0", rl_actual_qty, actual_qty_dialog));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));
        ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(v -> multiPurposeDialog.dismiss());

        multiPurposeDialog.show();
    }


    private class AdapterforSku extends RecyclerView.Adapter<AdapterforSku.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;
        String show_dialog;
        MultiPurposeDialog multiPurposeDialog;
        LinearLayout rl_actual_qty;
        TextView actual_qty_dialog;

        public AdapterforSku(Context context, List<ProductMaster> data, MultiPurposeDialog multiPurposeDialog, String show_dialog
                , LinearLayout rl_actual_qty, TextView actual_qty_dialog) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.show_dialog = show_dialog;
            this.multiPurposeDialog = multiPurposeDialog;

            this.actual_qty_dialog = actual_qty_dialog;
            this.rl_actual_qty = rl_actual_qty;
        }

        @Override
        public AdapterforSku.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.adapter_custom, parent, false);
            return new AdapterforSku.MyViewHolder(view);
        }


        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final AdapterforSku.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);
            if (show_dialog.equals("1")) {
                holder.sale_card.setVisibility(View.VISIBLE);
                holder.sale_card.setId(position);
                holder.sale_trcking_name.setText("Date : " + current.getVisit_date());
                holder.sale_trcking_name.setId(position);
                holder.consumer_recycle.setVisibility(View.VISIBLE);
                holder.consumer_recycle.setId(position);

            } else {
                holder.sale_card.setVisibility(View.VISIBLE);
                holder.sale_card.setId(position);
                holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")");
                holder.sale_trcking_name.setId(position);

                holder.consumer_recycle.setVisibility(View.GONE);
                holder.consumer_recycle.setId(position);

                holder.sale_card.setOnClickListener(new View.OnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onClick(View v) {
                        qrcode_text.setVisibility(View.VISIBLE);
                        qrcode_text.setText(current.getEanCode());
                        product_name = current.getProductName();
                        product_Id = current.getProductId().toString();
                        product_scan_code = current.getEanCode();
                        product_mrp = current.getMrp().toString();
                        sku_name.setText(product_name + " Mrp - " + product_mrp);
                        sku_name.setVisibility(View.VISIBLE);
                        multiPurposeDialog.dismiss();
                        if (!product_Id.equals("0")) {
                            db.open();
                            actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock());
                            rl_actual_qty.setVisibility(View.VISIBLE);
                        }

                    }
                });
            }
        }


        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView sale_trcking_name;
            CardView sale_card;
            RecyclerView consumer_recycle;


            public MyViewHolder(View itemView) {
                super(itemView);
                sale_card = (CardView) itemView.findViewById(R.id.sale_card);
                sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name);
                ////for consumer product
                consumer_recycle = (RecyclerView) itemView.findViewById(R.id.consumer_recycle);
            }
        }
    }

    private boolean checkduplicate_entry() {
        boolean status = true;
        if (replace_productList != null && !replace_productList.isEmpty()) {
            for (int k = 0; k < replace_productList.size(); k++) {
                if (replace_productList.get(k).getProduct_Id().equals(product_Id) && replace_productList.get(k).getProduct_rate().equals(product_mrp)) {
                    AlertandMessages.showToastMsg(context, "This product already added ");
                    status = false;
                    break;
                }
            }
        }
        return status;
    }

    private int calculate_total() {
        current_total = 0;
        if (!replace_productList.isEmpty()) {
            for (int k = 0; k < replace_productList.size(); k++) {
                current_total = current_total + (Integer.parseInt(replace_productList.get(k).getQuantity()) * Integer.parseInt(replace_productList.get(k).getProduct_rate()));
            }
        }

        return current_total;
    }

}
