package com.cpm.lorealbaautomation.dailyactivity;

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 android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

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

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary;

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

import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar;

public class InwardStockDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    TextView invoiceNumber, invoiceType;
    ArrayList<ProductMaster> brandList = new ArrayList<>();
    ExpandableListView lvExp_stock_check;
    FloatingActionButton fab_save;
    Lorealba_Database db;
    Context context;
    private SharedPreferences preferences;
    String counter_id, visit_date, username, invoiceNo, type;
    ArrayList<ProductMaster> listDataHeader = new ArrayList<>();
    ArrayList<ProductMaster> childStockList;
    HashMap<ProductMaster, List<ProductMaster>> listDataChild;
    ExpandableListAdapter listAdapter;
    String brandName = "";
    String axeName = "";
    String subAxeName = "", invDate = "", Error_Msg = "";
    TCounterInvoice tCounterInvoice;
    CheckBox confirmationCheckAll;
    boolean headerCheckedFlag = false;
    boolean headerTransactionFlag = false;
    boolean checkConfirmationAll = false;
    boolean checkflag = true;
    View sheetView;
    EditText et_search;
    ImageView bar_code_img, img_clear_subaxe;
    String msg = "";
    ArrayList<ProductMaster> signatureList = new ArrayList<>();
    ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference;
    ArrayList<ProductMaster> subBrandList = new ArrayList<>();
    ArrayList<ProductMaster> referenceList = new ArrayList<>();
    List<Integer> checkHeaderArray = new ArrayList<Integer>();
    boolean flagScan = true;
    final int FILTER_FOR_SIGNATURE = 4;
    final int FILTER_FOR_SUB_BRAND = 5;
    final int FILTER_FOR_REFERENCE = 6;
    final int FILTER_FOR_BRAND = 1;
    final int FILTER_FOR_AXE = 2;
    final int FILTER_FOR_SUBAXE = 3;
    final int CLEAR_FILTER = 0;
    ////jp added sub axe
    RecyclerView recSubAxe;
    String selectedSubAxe = "";
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;
    JourneyPlan jcp;
    TextView txt_invoice_qty, txt_actual_qty;

    @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inward_stock_details);
        context = this;
        ((InwardStockDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();

        if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) {
            tCounterInvoice = (TCounterInvoice) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
            assert tCounterInvoice != null;
            invoiceNo = tCounterInvoice.getInvoiceNo();
            type = tCounterInvoice.getInvoiceType();
            invDate = tCounterInvoice.getInvoiceDate();
        }


        validateUIData();
        prepareListData();
        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 - " + counter_id);
        //validate_spin_ui_data();
        listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        lvExp_stock_check.setAdapter(listAdapter);
        ////added sub axe
        recSubAxe.setLayoutManager(new GridLayoutManager(InwardStockDetailsActivity.this, 3));
        subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature);
        recSubAxe.setAdapter(subAxeValueAdapter);
        Objects.requireNonNull(recSubAxe.getAdapter()).notifyDataSetChanged();
        lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int lastItem = firstVisibleItem + visibleItemCount;
                if (firstVisibleItem == 0) {
                    fab_save.show();//.setVisibility(View.VISIBLE);
                } else if (lastItem == totalItemCount) {
                    fab_save.hide();//setVisibility(View.INVISIBLE);
                } else {
                    fab_save.show();//setVisibility(View.VISIBLE);
                }
            }
        });

        db.open();
        checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild);
        if (checkConfirmationAll) {
            confirmationCheckAll.setChecked(true);
            confirmationCheckAll.setEnabled(false);
            fab_save.setEnabled(false);
            bar_code_img.setEnabled(false);
            confirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706")));
        }

        txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty());
        txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty());
    }


    @SuppressLint("UseCompatLoadingForDrawables")
    private void validateUIData() {
        preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");

        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);
        setTitle("DMS Stock - " + visit_date);
        invoiceNumber = (TextView) findViewById(R.id.invoice_number);
        invoiceType = (TextView) findViewById(R.id.invoice_type);
        lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check);
        confirmationCheckAll = (CheckBox) findViewById(R.id.confirmation_check_all);
        fab_save = (FloatingActionButton) findViewById(R.id.save_fab);
        bar_code_img = (ImageView) findViewById(R.id.img_scan);
        img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe);
        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        ///added actual and invoice qty
        txt_invoice_qty = (TextView) findViewById(R.id.txt_invoice_qty);
        txt_actual_qty = (TextView) findViewById(R.id.txt_actual_qty);

        invoiceNumber.setText(invoiceNo);
        invoiceType.setText(type);
        fab_save.setOnClickListener(this);
        img_clear_subaxe.setOnClickListener(this);
        et_search = (EditText) findViewById(R.id.et_search);


        bar_code_img.setOnClickListener(view -> {
            if (flagScan) {
                openScanner();
            } else {
                bar_code_img.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon));
                flagScan = true;
                et_search.setText("");
            }

        });

        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(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild());
            }

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


        confirmationCheckAll.setOnCheckedChangeListener((compoundButton, b) -> {
            if (compoundButton.isPressed()) {
                setConfirmCheckedAllDataValidation(listDataHeader, listDataChild, compoundButton.isChecked());
            }
        });


        loadingValueForFilter();
        db.open();

    }


    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();
    }


    private void loadingValueForFilter() {
        db.open();
        brandList = db.get_inward_sub_brand_name("BrandName", invoiceNo, type);
        subBrandList = db.get_inward_sub_brand_name("SubBrandName", invoiceNo, type);
        signatureList = db.get_inward_sub_brand_name("SignatureName", invoiceNo, type);
        referenceList = db.get_inward_sub_brand_name("ReferenceName", invoiceNo, type);
    }


    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0:

                break;

            case -1:
                db.open();
                ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null);

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

                if (!productList.isEmpty()) {
                    flagScan = false;
                    bar_code_img.setImageDrawable(getResources().getDrawable(R.mipmap.ok));
                    clearFilters();
                    setScanFilter(productList);
                } else {
                    AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again.");

                }

                break;
        }


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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.filter_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    View showFilterBottomSheet() {
        final CardView cardSignature, cardBrand, cardSubBrand, cardReference;
        final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null);
        mBottomSheetDialog.setContentView(sheetView);
        View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet);
        if (bottomSheet != null) {
            bottomSheet.setBackgroundResource(android.R.color.transparent);
        }
        mBottomSheetDialog.setCancelable(false);
        final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand);
        ImageView img_cancel = sheetView.findViewById(R.id.img_cancel);
        TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter);
        recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature));
        recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
        cardSignature = sheetView.findViewById(R.id.card_signature);
        cardBrand = sheetView.findViewById(R.id.card_brand);
        cardSubBrand = sheetView.findViewById(R.id.card_sub_brand);
        cardReference = sheetView.findViewById(R.id.card_reference);
        cardSignature.setOnClickListener(this);
        cardBrand.setOnClickListener(this);
        cardSubBrand.setOnClickListener(this);
        cardReference.setOnClickListener(this);
        cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
        if (selectedSignature != null) {
            (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE);
        }
        if (selectedBrand != null) {
            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE);
        }
        if (selectedSubBrand != null) {
            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE);
        }
        if (selectedReference != null) {
            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE);
        }

        img_cancel.setOnClickListener(v -> mBottomSheetDialog.cancel());


        tv_clear_filter.setOnClickListener(v -> {
            setFilter(CLEAR_FILTER);
            selectedSignature = null;
            selectedBrand = null;
            selectedSubBrand = null;
            selectedReference = null;

            cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
            cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
            cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
            cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));

            (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);

            loadingValueForFilter();
            recBrand.getAdapter().notifyDataSetChanged();
        });


        mBottomSheetDialog.show();
        return sheetView;
    }


    private void setConfirmCheckedAllDataValidation(ArrayList<ProductMaster> listDataHeader, HashMap<ProductMaster, List<ProductMaster>> listDataChild, boolean checkFlag) {
        if (!listDataHeader.isEmpty()) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                if (checkFlag) {
                    listDataHeader.get(i).setInvoice_Status("1");
                } else {
                    listDataHeader.get(i).setInvoice_Status("0");
                }
                for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) {
                    if (checkFlag) {
                        listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(true);
                    } else {
                        if (listDataChild.get(listDataHeader.get(i)).get(j).getTransaction_Id().isEmpty()) {
                            listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(false);
                        } else {
                            listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(true);
                        }
                    }
                }
            }
        }
        listAdapter.notifyDataSetChanged();
    }

    private void prepareListData() {
        db.open();
        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();
        listDataHeader = db.get_inwrad_stock_header_data(invoiceNo, type, counter_id);
        db.open();
        jcp = db.getJCP();
        if (jcp != null) {
            listSubAxe = db.getSubAxeforinward(jcp.getCounterGroupId().toString());
        } else {
            listSubAxe = db.getSubAxeforinward("1");
        }

        if (!listDataHeader.isEmpty()) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                childStockList = new ArrayList<>();
                db.open();
                childStockList = db.get_inward_stock_child_product_data(listDataHeader.get(i).getReferenceName(), listDataHeader.get(i).getBrandName(),
                        listDataHeader.get(i).getSubBrandName(), listDataHeader.get(i).getSignatureName(), invoiceNo, type, counter_id);
                listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data
            }
        }

    }


    @SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged"})
    @Override
    public void onClick(final View view) {

        if (view.getId() == R.id.save_fab) {
            if (ValidationData(listDataHeader, listDataChild)) {
                androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context);
                builder.setCancelable(false);
                builder.setMessage(R.string.save_data_msg_new).setCancelable(false)
                        .setPositiveButton("OK", (dialog, id1) -> {
                            show_dialog_for_final_submit(context);
                            dialog.dismiss();
                        }).setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
                androidx.appcompat.app.AlertDialog alert = builder.create();
                alert.show();
            } else {
                AlertandMessages.showToastMsg(context, Error_Msg);
            }

        } else if (view.getId() == R.id.card_signature) {
            RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand);
            recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature));
            recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Signature);
        } else if (view.getId() == R.id.card_brand) {
            RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand);
            recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand));
            recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Brand);
        } else if (view.getId() == R.id.card_sub_brand) {
            RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand);
            recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand));
            recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged();
            setFilterSelected(sheetView, CommonString.SubBrand);
        } else if (view.getId() == R.id.card_reference) {
            RecyclerView recReference = sheetView.findViewById(R.id.rec_brand);
            recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference));
            recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Reference);
        } else if (view.getId() == R.id.img_clear_subaxe) {
            et_search.setText("");
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
            lvExp_stock_check.setAdapter(listAdapter);
            listAdapter.notifyDataSetChanged();
            selectedSubAxe = "";
            subAxeValueAdapter.notifyDataSetChanged();
            //clear filters also
            selectedSignature = null;
            selectedBrand = null;
            selectedSubBrand = null;
            selectedReference = null;
            db.open();
            jcp = db.getJCP();
            if (jcp != null) {
                db.open();
                brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe);
                subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
                referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
                signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
            } else {
                brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe);
                subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe);
                referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe);
                signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe);
            }

        }
    }


    private void show_dialog_for_final_submit(final Context context) {
        final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context);
        final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        final_save_dialog.setContentView(R.layout.custom_dialog_final_save);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        final_save_dialog.getWindow().setAttributes(lp);
        final_save_dialog.setCancelable(false);

        final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes);
        Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel);
        Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay);

        TextView final_text = (TextView) final_save_dialog.findViewById(R.id.final_text);
        final_text.setText(getString(R.string.want_to_final_save));
        btn_okay.setOnClickListener(v -> {
            if (txt_hint_yes.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Text");
            } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) {
                AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text");
            } else {
                final_save_dialog.dismiss();
                new InsertAsync().execute(true);

            }
        });

        btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss());
        final_save_dialog.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);
        }
    }

    void setFilterSelected(View sheetView, String type) {
        CardView cardSignature, cardBrand, cardSubBrand, cardReference;
        cardSignature = sheetView.findViewById(R.id.card_signature);
        cardBrand = sheetView.findViewById(R.id.card_brand);
        cardSubBrand = sheetView.findViewById(R.id.card_sub_brand);
        cardReference = sheetView.findViewById(R.id.card_reference);

        cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));

        switch (type) {
            case CommonString.Signature:
                cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.Brand:
                cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.SubBrand:
                cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.Reference:
                cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
        }
    }

    private boolean ValidationData(ArrayList<ProductMaster> listDataHeader, HashMap<ProductMaster, List<ProductMaster>> listDataChild) {
        checkflag = true;
        boolean flag_for_availability = false;
        for (int i = 0; i < listDataHeader.size(); i++) {
            for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) {
                if (listDataChild.get(listDataHeader.get(i)).get(j).isConfirmChecked()) {
                    flag_for_availability = true;
                    if (Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getActualQty()) < Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getConsumer_qty())) {
                        if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() == 0) {
                            msg = getResources().getString(R.string.error_reason);
                            Error_Msg = msg;
                            checkflag = false;
                            break;
                        }
                    }
                } else if (Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getActualQty()) < Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getConsumer_qty())) {
                    if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() == 0) {
                        msg = getResources().getString(R.string.error_reason);
                        Error_Msg = msg;
                        checkflag = false;
                        break;
                    } else if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() != 0) {
                        msg = getResources().getString(R.string.selected_item_checked_msg);
                        Error_Msg = msg;
                        checkflag = false;
                        break;
                    }
                }
            }
            if (!checkflag) {
                if (!checkHeaderArray.contains(i)) {
                    checkHeaderArray.add(i);
                }
                break;
            }
        }

        if (checkflag) {
            Error_Msg = "";
            if (!flag_for_availability) {
                msg = getResources().getString(R.string.error_confirmation);
                Error_Msg = msg;
                checkflag = false;
            }
        }

        listAdapter.notifyDataSetChanged();
        return checkflag;
    }

    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> filterListForAxe(List<ProductMaster> originalList, String text, String brandName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubAxe(List<ProductMaster> originalList, String text, String brandName, String axeName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

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

        return filterList;
    }

    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        Context _context;
        List<ProductMaster> _listDataHeader;
        HashMap<ProductMaster, List<ProductMaster>> _listDataChild;

        public ExpandableListAdapter(Context context, List<ProductMaster> listDataHeader, HashMap<ProductMaster, List<ProductMaster>> listChildData) {
            this._context = context;
            this._listDataHeader = listDataHeader;
            this._listDataChild = listChildData;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
        }


        public HashMap<ProductMaster, List<ProductMaster>> get_listDataChild() {
            return _listDataChild;
        }

        public List<ProductMaster> get_listDataHeader() {
            return _listDataHeader;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition);
            final ProductMaster headerData = (ProductMaster) getGroup(groupPosition);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_item_inward_stock, null);
                holder = new ViewHolder();
                holder.cardView = convertView.findViewById(R.id.card_view);
                holder.actual_qty = convertView.findViewById(R.id.actual_qty);
                holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus);
                holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus);
                holder.confirmationCheck = convertView.findViewById(R.id.confirmation_check);
                holder.invoice_qty = convertView.findViewById(R.id.invoice_qty);
                holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner);
                holder.reasonLayout = convertView.findViewById(R.id.reason_layout);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            TextView txtListChild = convertView.findViewById(R.id.brand_name);
            txtListChild.setText(childText.getProductName() + "( MRP - ₹ " + childText.getMrp() + ")");
            final ViewHolder finalHolder = holder;

            holder.stock_img_plus.setOnClickListener(v -> {
                ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                int minteger = Integer.parseInt(childText.getActualQty());
                ++minteger;

                if (minteger < Integer.parseInt(childText.getConsumer_qty())) {
                    childText.setActualQty(String.valueOf(minteger));
                    isDataAdded = true;
                } else if (minteger == Integer.parseInt(childText.getConsumer_qty())) {
                    childText.setActualQty(String.valueOf(minteger));
                    finalHolder.reasonSpinner.setSelection(0);
                    childText.setReasonId(0);
                    finalHolder.reasonLayout.setVisibility(View.GONE);
                    isDataAdded = true;
                } else {
                    AlertandMessages.showToastMsg(context, "Actual quantity cannot be greater than invoice quantity");
                }
            });

            ArrayList<MasterNonStockReason> reasonList = new ArrayList<>();
            db.open();
            reasonList = db.getReasonData(false);
            holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList));
            final ArrayList<MasterNonStockReason> finalReasonList = reasonList;
            holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                    if (pos != 0) {
                        MasterNonStockReason obj = finalReasonList.get(pos);
                        childText.setReasonId(obj.getReasonId());
                    } else {
                        childText.setReasonId(0);
                    }
                }

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

                }
            });


            if (!finalReasonList.isEmpty()) {
                for (int i = 0; i < finalReasonList.size(); i++) {
                    if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) {
                        holder.reasonSpinner.setSelection(i);
                        break;
                    }
                }
            }

            if (Integer.parseInt(childText.getActualQty()) < Integer.parseInt(childText.getConsumer_qty())) {
                finalHolder.reasonLayout.setVisibility(View.VISIBLE);
            } else {
                finalHolder.reasonLayout.setVisibility(View.GONE);
            }


            holder.stock_img_minus.setOnClickListener(v -> {
                ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                int minteger = Integer.parseInt(childText.getActualQty());
                --minteger;

                if (minteger >= 0) {
                    finalHolder.reasonLayout.setVisibility(View.VISIBLE);
                    childText.setActualQty(String.valueOf(minteger));
                    isDataAdded = true;
                } else {
                    AlertandMessages.showToastMsg(context, "Actual quantity cannot be less than 0");
                }
            });


            holder.confirmationCheck.setOnCheckedChangeListener((compoundButton, b) -> {
                if (compoundButton.isPressed()) {
                    headerData.setInvoice_Status("0");
                    if (compoundButton.isChecked()) {
                        childText.setConfirmChecked(true);
                        childCheckConfirmationDataValidation(childText);
                        checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild);
                        if (checkConfirmationAll) {
                            confirmationCheckAll.setChecked(true);
                        } else {
                            confirmationCheckAll.setChecked(false);
                        }
                    } else {
                        childText.setConfirmChecked(false);
                        childCheckConfirmationDataValidation(childText);

                    }
                }
            });


            if (!childText.getTransaction_Id().equals("")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.confirmationCheck.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706")));
                }

                holder.confirmationCheck.setEnabled(false);
                holder.stock_img_minus.setEnabled(false);
                holder.stock_img_plus.setEnabled(false);
                holder.reasonSpinner.setEnabled(false);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.confirmationCheck.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000")));
                }

                holder.confirmationCheck.setEnabled(true);
                holder.stock_img_minus.setEnabled(true);
                holder.stock_img_plus.setEnabled(true);
                holder.reasonSpinner.setEnabled(true);
            }

            if (childText.isConfirmChecked()) {
                holder.confirmationCheck.setChecked(true);
            } else {
                holder.confirmationCheck.setChecked(false);
            }

            if (Integer.parseInt(childText.getActualQty()) < Integer.parseInt(childText.getConsumer_qty())) {
                holder.actual_qty.setTextColor(Color.RED);
            } else {
                holder.actual_qty.setTextColor(Color.BLACK);
            }

            holder.actual_qty.setText("" + childText.getActualQty());
            holder.actual_qty.setId(childPosition);

            holder.invoice_qty.setText("" + childText.getConsumer_qty());
            holder.invoice_qty.setId(childPosition);


            if ((!childText.isConfirmChecked() && childText.getReasonId() == 0) || (childText.isConfirmChecked() && childText.getReasonId() == 0)) {
                if (checkHeaderArray.contains(groupPosition)) {
                    if (!checkflag) {
                        holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.light_red));
                    } else
                        holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                } else
                    holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
            }


            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return this._listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this._listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @SuppressLint({"RestrictedApi", "SetTextI18n"})
        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition);
            if (convertView == null) {

                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group_inward_stock, null);
            }


            TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
            final CheckBox headerConfirmationCheckAll = (CheckBox) convertView.findViewById(R.id.header_confirmation_check_all);
            lblListHeader.setText(headerTitle.getBrandName() + " - " + headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName());

            headerConfirmationCheckAll.setOnCheckedChangeListener((compoundButton, b) -> {
                if (compoundButton.isPressed()) {
                    if (compoundButton.isChecked()) {
                        headerCheckConfirmationDataValidation(headerTitle, true);
                        checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild);
                        if (checkConfirmationAll) {
                            confirmationCheckAll.setChecked(true);
                            setInvoiceStatus(listDataHeader, "1");
                        } else {
                            setInvoiceStatus(listDataHeader, "0");
                            confirmationCheckAll.setChecked(false);
                        }
                    } else {
                        confirmationCheckAll.setChecked(false);
                        headerCheckConfirmationDataValidation(headerTitle, false);
                        setInvoiceStatus(listDataHeader, "0");
                    }
                }
            });


            headerCheckedFlag = childConfirmationCheckDataValidation(headerTitle);

            if (headerCheckedFlag) {
                headerTransactionFlag = childTransactionCheckDataValidation(headerTitle);
                if (headerTransactionFlag) {
                    headerConfirmationCheckAll.setEnabled(false);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706")));
                    }
                } else {
                    headerConfirmationCheckAll.setEnabled(true);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000")));
                    }
                }
                headerConfirmationCheckAll.setChecked(true);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000")));
                }
                headerConfirmationCheckAll.setChecked(false);
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    private boolean childTransactionCheckDataValidation(ProductMaster headerTitle) {
        boolean flag = true;
        for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) {
            if (listDataChild.get(headerTitle).get(i).getTransaction_Id().equals("")) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    private boolean checkHeaderConfirmationValidation(ArrayList<ProductMaster> listDataHeader, HashMap<ProductMaster, List<ProductMaster>> listDataChild) {
        boolean flag = true;
        for (int i = 0; i < listDataHeader.size(); i++) {
            for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) {
                if (!listDataChild.get(listDataHeader.get(i)).get(j).isConfirmChecked()) {
                    flag = false;
                    break;
                } else {
                    if (listDataChild.get(listDataHeader.get(i)).get(j).getTransaction_Id().equals("")) {
                        flag = true;
                    }
                }
            }
            if (!flag) {
                break;
            }
        }
        listAdapter.notifyDataSetChanged();
        return flag;
    }


    private boolean setInvoiceStatus(ArrayList<ProductMaster> listDataHeader, String invoice_status) {
        boolean flag = true;
        for (int i = 0; i < listDataHeader.size(); i++) {
            listDataHeader.get(i).setInvoice_Status(invoice_status);
        }
        listAdapter.notifyDataSetChanged();
        return flag;
    }

    private boolean childConfirmationCheckDataValidation(ProductMaster headerTitle) {
        boolean flag = true;
        for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) {
            if (!listDataChild.get(headerTitle).get(i).isConfirmChecked()) {
                flag = false;
                break;
            }
        }
        return flag;
    }


    private void childCheckConfirmationDataValidation(ProductMaster childText) {
        if (!childText.isConfirmChecked()) {
            confirmationCheckAll.setChecked(false);
        }
        listAdapter.notifyDataSetChanged();
    }

    private void headerCheckConfirmationDataValidation(ProductMaster headerTitle, boolean flag) {
        for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) {
            if (flag) {
                listDataChild.get(headerTitle).get(i).setConfirmChecked(true);
            } else {
                if (listDataChild.get(headerTitle).get(i).getTransaction_Id().equals("")) {
                    listDataChild.get(headerTitle).get(i).setConfirmChecked(false);
                } else {
                    listDataChild.get(headerTitle).get(i).setConfirmChecked(true);
                }
            }
        }
        listAdapter.notifyDataSetChanged();
    }


    public class ViewHolder {
        TextView actual_qty, invoice_qty;
        Button stock_img_plus, stock_img_minus;
        CardView cardView;
        CheckBox confirmationCheck;
        Spinner reasonSpinner;
        LinearLayout reasonLayout;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;
        String type1;

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

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

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);
            final boolean[] selected = {false};
            final int[] filterId = {0};
            switch (type1) {
                case CommonString.Signature:
                    if (selectedSignature != null && selectedSignature == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.Brand:
                    if (selectedBrand != null && selectedBrand == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.SubBrand:
                    if (selectedSubBrand != null && selectedSubBrand == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.Reference:
                    if (selectedReference != null && selectedReference == current) {
                        selected[0] = true;
                    }

                    break;
            }

            holder.tv_item.setText(current.getBrandName());

            holder.tv_item.setOnClickListener(v -> {
                switch (type1) {
                    case CommonString.Signature:
                        selectedSignature = current;
                        filterId[0] = R.id.img_filter_signature;
                        setFilter(FILTER_FOR_SIGNATURE);
                        db.open();
                        brandList = db.getInwardSubBrandOrReference("BrandName", current.getBrandName(), null, null, invoiceNo, type);
                        subBrandList = db.getInwardSubBrandOrReference("SubBrandName", current.getBrandName(), null, null, invoiceNo, type);
                        referenceList = db.getInwardSubBrandOrReference("ReferenceName", current.getBrandName(), null, null, invoiceNo, type);

                        break;
                    case CommonString.Brand:
                        db.open();
                        selectedBrand = current;
                        filterId[0] = R.id.img_filter_brand;
                        setFilter(FILTER_FOR_BRAND);
                        subBrandList = db.getInwardSubBrandOrReference("SubBrandName", "", current.getBrandName(), null, invoiceNo, type);
                        referenceList = db.getInwardSubBrandOrReference("ReferenceName", "", current.getBrandName(), null, invoiceNo, type);
                        break;
                    case CommonString.SubBrand:
                        db.open();
                        selectedSubBrand = current;
                        filterId[0] = R.id.img_filter_sub_brand;
                        setFilter(FILTER_FOR_SUB_BRAND);
                        referenceList = db.getInwardSubBrandOrReference("ReferenceName", "", null, current.getBrandName(), invoiceNo, type);
                        break;
                    case CommonString.Reference:
                        selectedReference = current;
                        filterId[0] = R.id.img_filter_reference;

                        setFilter(FILTER_FOR_REFERENCE);
                        break;
                }

                RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand);
                Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged();
                //show filter_menu icon on filter_menu selected
                (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE);
            });

            if (selected[0]) {
                holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
            } else {
                holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_item;
            CardView card;

            public MyViewHolder(View itemView) {
                super(itemView);
                tv_item = (TextView) itemView.findViewById(R.id.tv_item);
                card = (CardView) itemView.findViewById(R.id.item_card);

            }
        }
    }

    public void setSearchFilter(List<ProductMaster> originalList, String text, HashMap<ProductMaster, List<ProductMaster>> listDataChild) {
        HashMap<ProductMaster, List<ProductMaster>> filterChildHashMap = new HashMap<>();
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (int i = 0; i < originalList.size(); i++) {
            ProductMaster parent = originalList.get(i);
            List<ProductMaster> listChild = listDataChild.get(parent);
            List<ProductMaster> listFilterChild = new ArrayList<>();
            for (int j = 0; j < listChild.size(); j++) {
                if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase())) {
                    listFilterChild.add(listChild.get(j));
                }
            }

            if (listFilterChild.size() > 0) {
                filterList.add(parent);
                filterChildHashMap.put(parent, listFilterChild);

            }

        }

        ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
        for (int i = 0; i < listAdapter.getGroupCount(); i++) {
            lvExp_stock_check.expandGroup(i);
        }

    }

    public void setFilter(int filterType) {
        if (filterType == FILTER_FOR_SIGNATURE) {
            listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_BRAND) {
            listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_SUB_BRAND) {
            listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_REFERENCE) {
            listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_AXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild);
        } else if (filterType == FILTER_FOR_SUBAXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild);
        } else {
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        }

        lvExp_stock_check.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
    }


    public ArrayList<ProductMaster> filterListForSubBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) {
                filterList.add(object);
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForReference(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))
                    && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) {
                filterList.add(object);
            }
        }
        return filterList;
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            isChanged();

        } else if (id == R.id.filter_data) {
            sheetView = showFilterBottomSheet();
        }


        return super.onOptionsItemSelected(item);
    }

    boolean isDataAdded = false;

    @Override
    public void onBackPressed() {
        isChanged();
    }

    void isChanged() {
        if (isDataAdded) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam));
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), (dialog, id) -> {

                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        InwardStockDetailsActivity.this.finish();
                    }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            InwardStockDetailsActivity.this.finish();
        }
    }


    public void setScanFilter(List<ProductMaster> scanList) {

        HashMap<ProductMaster, List<ProductMaster>> filterChildHashMap = new HashMap<>();

        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            ProductMaster parent = listDataHeader.get(i);
            List<ProductMaster> listChild = listDataChild.get(parent);
            List<ProductMaster> listFilterChild = new ArrayList<>();
            for (int j = 0; j < listChild.size(); j++) {
                if (containsProduct(scanList, listChild.get(j))) {
                    listFilterChild.add(listChild.get(j));
                }
            }

            if (listFilterChild.size() > 0) {
                filterList.add(parent);
                filterChildHashMap.put(parent, listFilterChild);

            }

        }

        ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter1);
        for (int i = 0; i < listAdapter1.getGroupCount(); i++) {
            lvExp_stock_check.expandGroup(i);
        }
        listAdapter1.notifyDataSetChanged();

    }


    boolean containsProduct(List<ProductMaster> scanList, ProductMaster obj) {
        boolean contains = false;
        for (int i = 0; i < scanList.size(); i++) {
            if (scanList.get(i).getProductId().equals(obj.getProductId())) {
                contains = true;
                break;
            }
        }

        return contains;
    }


    void clearFilters() {
        et_search.setText("");

        setFilter(CLEAR_FILTER);
        selectedSignature = null;
        selectedBrand = null;
        selectedSubBrand = null;
        selectedReference = null;

        if (sheetView != null) {
            (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
        }
        db.open();
        brandList = db.getsub_brand_name("1", "BrandName", false);
        subBrandList = db.getsub_brand_name("1", "SubBrandName", false);
        referenceList = db.getsub_brand_name("1", "ReferenceName", false);
        signatureList = db.getsub_brand_name("1", "SignatureName", false);
    }

    public class SubAxeValueAdapter extends RecyclerView.Adapter<SubAxeValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;
        String type;

        public String getType() {
            return type;
        }

        public SubAxeValueAdapter(Context context, List<ProductMaster> data, String type) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.type = type;
        }

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

        @SuppressLint("NotifyDataSetChanged")
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);
            holder.tv_item.setText(current.getSubAxeName());
            holder.tv_item.setOnClickListener(v -> {
                et_search.setText("");
                listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild);
                lvExp_stock_check.setAdapter(listAdapter);
                listAdapter.notifyDataSetChanged();

                current.setSelected(true);
                selectedSubAxe = current.getSubAxeName();
                subAxeValueAdapter.notifyDataSetChanged();
                db.open();
                jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe);
                    subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
                    referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
                    signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
                } else {
                    brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe);
                    subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe);
                    referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe);
                    signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe);
                }
            });

            try {
                if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) {
                    holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach));
                } else {
                    holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background));
                }
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_item;
            CardView card;

            public MyViewHolder(View itemView) {
                super(itemView);
                tv_item = (TextView) itemView.findViewById(R.id.tv_item);
                card = (CardView) itemView.findViewById(R.id.item_card);

            }
        }
    }

    private int calculate_invoice_qty() {
        int total_invoice_qty = 0;
        if (!listDataHeader.isEmpty()) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getConsumer_qty() != null && !list.get(j).getConsumer_qty().equals("")) {
                        total_invoice_qty = total_invoice_qty + Integer.parseInt(list.get(j).getConsumer_qty());
                    }
                }
            }
        }

        return total_invoice_qty;
    }

    private int calculate_actual_qty() {
        int total_actual_qty = 0;
        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getActualQty() != null && !list.get(j).getActualQty().equals("")) {
                        total_actual_qty = total_actual_qty + Integer.parseInt(list.get(j).getActualQty());
                    }
                }
            }
        }

        return total_actual_qty;
    }


    class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        Dialog dialog = null;
        ProgressBar pb = null;

        @Override
        protected void onPreExecute() {
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.circular_progress_bar);
            pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
            dialog.setCancelable(false);
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Boolean... bool) {
            ////final submit
            String TransactionId = CommonFunctions.getUUID(context);
            db.open();
            boolean fornew_productchecked = newinwardproduct_Checked(listDataChild, listDataHeader);
            ///Insert for New Inward Product
            long val = db.insertNewInwardProductStockData(visit_date, listDataChild, listDataHeader, invoiceNo, type, invDate, counter_id, username,
                    "DMS", TransactionId, fornew_productchecked);
            boolean checked_checkbox_flag = inwardproduct_Checked(listDataChild, listDataHeader);
            ////Insert for Exist in T_Stock Summery Inward Product
            TransactionId = CommonFunctions.getUUID(context);
            long val2 = db.insertInwardStockData(visit_date, listDataChild, listDataHeader, invoiceNo, type, invDate,
                    counter_id, username, "DMS", TransactionId, checked_checkbox_flag);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.cancel();
            if (CommonFunctions.checkNetIsAvailable(context)) {
                CommonFunctions.call_upload(context);
            }
            AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            InwardStockDetailsActivity.this.finish();
        }
    }

    private boolean newinwardproduct_Checked(HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader) {
        boolean status = false;
        if (save_listDataHeader.size() > 0) {
            for (int k = 0; k < save_listDataHeader.size(); k++) {
                List<ProductMaster> child = data.get(save_listDataHeader.get(k));
                if (child != null && child.size() > 0) {
                    for (int j = 0; j < child.size(); j++) {
                        if (child.get(j).isConfirmChecked()) {
                            db.open();
                            ProductMaster transactionList = db.getInwardStockCheckTransactionData(child.get(j).getProductId(), child.get(j).getInvId(), invoiceNo);
                            db.open();
                            TStockSummary stockObj = db.getTStockSummaryProductDetails(child.get(j).getProductId());
                            if (transactionList == null && stockObj == null) {
                                status = true;
                                break;
                            }
                        }
                    }
                }
                if (status) {
                    break;
                }
            }
        }
        return status;
    }


    private boolean inwardproduct_Checked(HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader) {
        boolean status = false;
        if (save_listDataHeader.size() > 0) {
            for (int k = 0; k < save_listDataHeader.size(); k++) {
                List<ProductMaster> child = data.get(save_listDataHeader.get(k));
                if (child != null && child.size() > 0) {
                    for (int j = 0; j < child.size(); j++) {
                        if (child.get(j).isConfirmChecked()) {
                            db.open();
                            ProductMaster transactionList = db.getInwardStockCheckTransactionData(child.get(j).getProductId(), child.get(j).getInvId(), invoiceNo);
                            TStockSummary stockObj = db.getTStockSummaryProductDetails(child.get(j).getProductId());
                            if (transactionList == null && stockObj != null && stockObj.getProductId() != null) {
                                status = true;
                                break;
                            }
                        }
                    }
                }

                if (status) {
                    break;
                }
            }
        }

        return status;
    }

}
