package com.cpm.lorealbaautomation.makeupexpert;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.util.Log;
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.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
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.gson.JsonObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;
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.download.Downloader;
import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;

import com.cpm.lorealbaautomation.retrofit.PostApi;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class SalesActivity extends AppCompatActivity implements View.OnClickListener {
    Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin;
    ArrayList<ProductMaster> brandList = new ArrayList<>();
    ArrayList<ProductMaster> subBrandList = new ArrayList<>();
    ArrayList<ProductMaster> referenceList = new ArrayList<>();
    ArrayList<ProductMaster> signatureList = new ArrayList<>();
    ExpandableListView lvExp_stock_check;
    FloatingActionButton fab_save, fab_draft;
    Lorealba_Database db;
    Context context;
    private SharedPreferences preferences;
    String counter_id, visit_date, username, _pathforcheck, _path;
    ArrayList<ProductMaster> listDataHeader = new ArrayList<>();
    ArrayList<ProductMaster> childStockList = new ArrayList<>();
    HashMap<ProductMaster, List<ProductMaster>> listDataChild;
    boolean checkflag = true, changes_flg = false;
    ArrayList<Integer> checkHeaderArray = new ArrayList<>();
    ExpandableListAdapter listAdapter;
    String brandName = "";
    String axeName = "";
    String subAxeName = "";
    int groupPositionGlobal = -1;
    ProductMaster globalHeaderObject = new ProductMaster();
    EditText et_search;
    boolean regularStockFlag = false, check_flag = true;
    View sheetView;
    ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference;

    ImageView img_scan, img_clear_subaxe, img_unfilled;
    boolean flagScan = true;
    String counterGroupId;
    RecyclerView recSubAxe;
    String selectedSubAxe = "";
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sales);
        context = this;
        ((SalesActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();
        validateUIData();

        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);
        new LoadAsync().execute();

        lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lvExp_stock_check.invalidate();
                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);
                }
            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
                lvExp_stock_check.invalidateViews();
            }
        });
    }

    JourneyPlan jcp;

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

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("ME_Sales - " + visit_date);
        sku_spin = (Spinner) findViewById(R.id.sku_spin);
        brand_spin = (Spinner) findViewById(R.id.stock_brand_spin);
        sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin);
        axe_spin = (Spinner) findViewById(R.id.axe_spin);
        lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check);
        fab_save = (FloatingActionButton) findViewById(R.id.save_fab);
        fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab);
        et_search = (EditText) findViewById(R.id.et_search);
        img_scan = (ImageView) findViewById(R.id.img_scan);
        img_unfilled = (ImageView) findViewById(R.id.img_unfilled);
        img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe);
        ImageView img_filter = (ImageView) findViewById(R.id.img_filter);
        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        fab_save.setOnClickListener(this);
        fab_draft.setOnClickListener(this);
        db.open();

        img_filter.setOnClickListener(v -> sheetView = showFilterBottomSheet());

        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();
                if (text.isEmpty()) {
                    if (lvExp_stock_check != null && listAdapter != null) {
                        lvExp_stock_check.setAdapter(listAdapter);
                        listAdapter.notifyDataSetChanged();
                    }
                } else {
                    lvExp_stock_check.invalidate();
                    setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild());
                }
            }

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

        img_scan.setOnClickListener(this);
        ///changes icon
        img_unfilled.setOnClickListener(this);
        img_clear_subaxe.setOnClickListener(this);
        db.open();
        String status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id);

        /*db.open();
        String status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id);
        //if regular stock need to be captured after First stock capture
        if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) {
            fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.save_icon));
            regularStockFlag = true;
            fab_draft.hide();
        }*/
    }

    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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.cancel();
            }
        });

        tv_clear_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFilters();
                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));
                ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter();
                String type = adapter.getType();
                ArrayList<ProductMaster> list = new ArrayList<>();
                switch (type) {
                    case CommonString.Signature:
                        list = signatureList;
                        break;
                    case CommonString.Brand:
                        list = brandList;
                        break;
                    case CommonString.SubBrand:
                        list = subBrandList;
                        break;
                    case CommonString.Reference:
                        list = referenceList;
                        break;
                }
                recBrand.setLayoutManager(new LinearLayoutManager(SalesActivity.this, LinearLayoutManager.VERTICAL, true));
                recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature));
                recBrand.getAdapter().notifyDataSetChanged();
            }
        });

        mBottomSheetDialog.show();
        return sheetView;
    }

    private void prepareListData() {
        db.open();
        jcp = db.getJCP();
        if (jcp != null) {
            db.open();
            listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true);
        } else {
            db.open();
            listSubAxe = db.getSubAxe("1", true);
        }

        //inserted data
        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();
        db.open();
        jcp = db.getJCP();
        if (jcp != null) {
            db.open();
            listDataHeader = db.getFunctionMEHeader(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, CommonString.ME_SALE, counter_id, visit_date);
            //  listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, CommonString.KEY_SaleableBalance, counter_id, visit_date);
        } else {
            db.open();
            listDataHeader = db.getMESaleSignatureBrandSubBrandReference("1", false, regularStockFlag, CommonString.ME_SALE);
        }
        jcp = db.getJCP();
        if (jcp != null) {
            db.open();
            brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe);
            db.open();
            subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
            db.open();
            referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
            db.open();
            signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
        } else {
            db.open();
            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);
        }

        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                JourneyPlan jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    childStockList = db.getInsertedMEChildData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, visit_date, counter_id);
                    // //test("childsize", String.valueOf(childStockList.size()));
                    if (childStockList.size() == 0) {
                        db.open();
                        childStockList = db.getDefaultMESaleFunctionData(listDataHeader.get(i).getNuanceName(),
                                CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date);
                    } else {
                        if (childStockList.get(0).getUploadStatus().equalsIgnoreCase("Y")) {
                            fab_draft.hide();
                        } else {
                            fab_draft.show();
                        }
                    }
                } else {
                    db.open();
                    childStockList = db.getInsertedMEChildData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, visit_date, counter_id);
                    //test("childsize", String.valueOf(childStockList.size()));
                    if (childStockList.size() == 0) {
                        db.open();
                        childStockList = db.getDefaultMESaleFunctionData(listDataHeader.get(i).getNuanceName(),
                                CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date);
                    } else {
                        if (childStockList.get(0).getUploadStatus().equalsIgnoreCase("Y")) {
                            fab_draft.hide();
                        } else {
                            fab_draft.show();
                        }
                    }
                }
                listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data
            }
        }
    }

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

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.save_fab) {
            ////for final submit stock using regular stock flag
            lvExp_stock_check.clearFocus();
            lvExp_stock_check.invalidateViews();
            if (regularStockFlag) {
                if (validate_regular_stock()) {
                    if (validateData(listDataChild, listDataHeader)) {
                        dialogFinalSubmit();
                    }
                }
            } else {
                if (validateData(listDataChild, listDataHeader)) {
                    dialogFinalSubmit();
                }
            }
        } else if (view.getId() == R.id.draft_fab) {
            ///save draft stock....
            lvExp_stock_check.clearFocus();
            lvExp_stock_check.invalidateViews();
            if (validateData(listDataChild, listDataHeader)) {
                new InsertAsync().execute(false);
            }

        } 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));
            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_scan) {

            if (flagScan) {
                openScanner();
            } else {
                img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon));
                flagScan = true;
                et_search.setText("");
            }

        } else if (view.getId() == R.id.img_unfilled) {
            setUnFilledFilter(listAdapter.get_listDataHeader(), listAdapter.get_listDataChild());
        } 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();
            brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe);
            db.open();
            subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe);
            db.open();
            referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe);
            db.open();
            signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe);
        }
    }

    private boolean validateData(HashMap<ProductMaster, List<ProductMaster>> listDataChild, ArrayList<ProductMaster> listDataHeader) {
        checkflag = true;
        int sum = 0;
        String uploadStatus = "";
        for (int j = 0; j < listDataHeader.size(); j++) {
            List<ProductMaster> data = listDataChild.get(listDataHeader.get(j));
            for (int i = 0; i < data.size(); i++) {
                sum = sum + data.get(i).getStock();
                uploadStatus = data.get(i).getUploadStatus();
            }
        }

        if (sum == 0) {
            AlertandMessages.showToastMsg(context, "Sale qty should be greater than zero");
            checkflag = false;
        } else if (uploadStatus.equalsIgnoreCase(CommonString.KEY_Y)) {
            AlertandMessages.showToastMsg(context, "Sale Data Already Uploaded");
            checkflag = false;
        } else {
            checkflag = true;
        }
        return checkflag;
    }

    public void uploadData(boolean finalFlag) {
        //download service
        // Intent intent =\ new Intent(context, Downloader.class);
        SaleableGetterSetter stock = new SaleableGetterSetter();
        ArrayList<ProductMaster> data = new ArrayList<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
            for (int j = 0; j < list.size(); j++) {
                //for final - complete data upload
                if (finalFlag) {
                    list.get(j).setImagePath(listDataHeader.get(i).getImagePath());
                    data.add(list.get(j));
                } else {
                    if (list.get(j).isSelected()) {
                        list.get(j).setImagePath(listDataHeader.get(i).getImagePath());
                        data.add(list.get(j));
                    }
                }
            }
        }

        if (data.size() > 0) {
            stock.setProductList(data);
            String uuid = CommonFunctions.getUUID(context);
            stock.setTransactionId(uuid);
            db.open();
            ////changes by jeevan insert transaction for future use and handle master transaction
            if (regularStockFlag) {
                db.open();
                db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "Regular_Stock");
            } else {
                if (finalFlag) {
                    db.open();
                    db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "FirstTime_Stock_Comp");
                } else {
                    db.open();
                    db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "FirstTime_Stock_Draft");
                }
            }

            dialog.cancel();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            SalesActivity.this.finish();
            CommonFunctions.call_upload(context);
        }
    }


    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);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {

            if (object.getBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    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);
            } else {
                continue;
            }
        }
        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);
            } 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 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;
        }

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

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

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

        @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);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_stock_layout, null);
                holder = new ViewHolder();
                holder.cardView = convertView.findViewById(R.id.card_view);
                holder.ed_Stock = convertView.findViewById(R.id.ed_Stock);
                holder.mrp = convertView.findViewById(R.id.mrp);
                holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus);
                holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus);
                holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner);
                holder.reasonLayout = convertView.findViewById(R.id.reason_layout);
                holder.et_stock = convertView.findViewById(R.id.et_stock);
                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
            }
            //test("productIdtag",childText.getBrandName() + ","+childText.getSignatureName());
            TextView txtListChild = convertView.findViewById(R.id.lblListItem);
            txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")");
            final ViewHolder finalHolder = holder;
            holder.stock_img_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    if (!regularStockFlag) {
                        String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", "");
                        if (!stot.equals("")) {
                            int st = Integer.parseInt(stot);
                            childText.setStock(st);
                        }
                    }

                    int stock = childText.getStock();
                    int receivedStock = childText.getStock_receive();
                    ++stock;
                    childText.setStock(stock);

                    /*if (regularStockFlag) {
                        if (receivedStock >= stock) {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                            if (receivedStock == stock) {
                                finalHolder.reasonLayout.setVisibility(View.GONE);
                                finalHolder.reasonSpinner.setSelection(0);
                                childText.setReasonId(0);
                            }
                        } else {
                            AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock");
                        }
                    } else {
                        if (receivedStock == -1) {
                            childText.setStock_receive(0);
                        }
                        childText.setStock(stock);
                        isDataAdded = true;
                        childText.setSelected(true);
                    }*/
                }
            });

            holder.stock_img_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    if (!regularStockFlag) {
                        String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", "");
                        if (!stot.equals("")) {
                            int st = Integer.parseInt(stot);
                            childText.setStock(st);
                        }
                    }

                    int stock = childText.getStock();
                    int receivedStock = childText.getStock_receive();
                    --stock;

                    if (stock >= 0) {
                        childText.setStock(stock);
                        isDataAdded = true;
                        childText.setSelected(true);

                    } else {
                        AlertandMessages.showToastMsg(context, "Sale cannot be less than 0");
                    }

                }
            });

            holder.et_stock.setOnFocusChangeListener((v, hasFocus) -> {
                final EditText caption = (EditText) v;
                String stock = caption.getText().toString().replaceFirst("^0+(?!$)", "");
                if (!stock.equals("")) {
                    childText.setStock(Integer.parseInt(stock));
                    isDataAdded = true;
                    childText.setSelected(true);
                } else {
                    childText.setStock(0);
                }
            });

            ArrayList<MasterNonStockReason> reasonList;
            db.open();
            reasonList = db.getReasonData(true);
            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) {

                }
            });


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


            int stock = childText.getStock();
            if (!childText.isSelected() && childText.getStock() == 0) {
                stock = childText.getStock_receive();
                childText.setStock(stock);
            }

            if (childText.getStock() < childText.getStock_receive()) {
                if (regularStockFlag) {
                    finalHolder.reasonLayout.setVisibility(View.VISIBLE);
                    finalHolder.reasonLayout.setId(childPosition);
                }
            } else {
                finalHolder.reasonLayout.setVisibility(View.GONE);
                finalHolder.reasonLayout.setId(childPosition);
            }


            if (regularStockFlag) {
                holder.ed_Stock.setText(String.valueOf(stock));
                holder.ed_Stock.setId(childPosition);

                holder.et_stock.setVisibility(View.GONE);
                holder.ed_Stock.setVisibility(View.VISIBLE);
            } else {
                if (stock == -1) {
                    holder.et_stock.setText("");
                } else {
                    holder.et_stock.setText(String.valueOf(stock));
                }

                holder.et_stock.setId(childPosition);

                holder.ed_Stock.setVisibility(View.GONE);
                holder.et_stock.setVisibility(View.VISIBLE);
            }

            holder.mrp.setText(" MRP = " + childText.getMrp());
            holder.mrp.setId(childPosition);

            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({"InflateParams", "UseCompatLoadingForDrawables"})
        @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_me_sale_stock_entry, null);
            }
            TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
            ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam);

            stock_cam.setOnClickListener(v -> {
                groupPositionGlobal = groupPosition;
                globalHeaderObject = headerTitle;
                _pathforcheck = counter_id + "_stock_check_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(SalesActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR);
            });

            if (headerTitle.getImagePath().equals("")) {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera));
            } else {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick));
            }

            lblListHeader.setText(headerTitle.getNuanceName());
            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.red));
                } else {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red));
                }

            } else {
                lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red));
            }

            return convertView;
        }

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

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

    class ViewHolder {
        TextView ed_Stock, mrp;
        Button stock_img_plus, stock_img_minus;
        CardView cardView;
        Spinner reasonSpinner;
        LinearLayout reasonLayout;
        EditText et_stock;
    }


    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, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild);
        }

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

    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;

    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()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) {
                    listFilterChild.add(listChild.get(j));
                } else {
                    continue;
                }
            }

            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 isDataAdded = false;

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

    void isChanged() {
        if (isDataAdded) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SalesActivity.this);
            builder.setTitle(R.string.parinaam);
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> {

                    });
            android.app.AlertDialog alert = builder.create();
            alert.show();
        } else {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    void dialogFinalSubmit() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SalesActivity.this);
        builder.setTitle(R.string.parinaam);
        builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false)
                .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                    show_dialog_for_final_submit(context);
                    dialog.dismiss();
                }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());

        android.app.AlertDialog alert = builder.create();
        alert.show();
    }

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

        btn_okay.setOnClickListener(v -> {
            if (txt_hint_yes.getText().toString().equals("")) {
                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();
    }

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


    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("MakeMachine", "resultCode: " + resultCode);
        if (requestCode == 131) {
            switch (resultCode) {
                case 0:
                    Log.i("MakeMachine", "User cancelled");
                    break;

                case -1:
                    if (_pathforcheck != null && !_pathforcheck.equals("")) {
                        if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                            convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);

                            isDataAdded = true;
                            globalHeaderObject.setImagePath(_pathforcheck);
                            groupPositionGlobal = -1;
                            _pathforcheck = "";
                            listAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
            }
        } else {
            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);
                    }

                    //test("Ean Code", result.getContents());
                    if (!productList.isEmpty()) {
                        flagScan = false;
                        img_scan.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);
    }


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

        public String getType() {
            return type;
        }

        public ValueAdapter(Context context, List<ProductMaster> data, String type) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.type = 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);
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @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 (type) {

                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.card.setOnClickListener(v -> {

                et_search.setText("");

                switch (type) {
                    case CommonString.Signature:
                        selectedSignature = current;
                        filterId[0] = R.id.img_filter_signature;
                        //clear other sub filters--
                        selectedBrand = null;
                        selectedSubBrand = null;
                        selectedReference = null;

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

                        setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature);
                        db.open();
                        brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                        db.open();
                        subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                        db.open();
                        referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe);

                        break;
                    case CommonString.Brand:
                        selectedBrand = current;
                        filterId[0] = R.id.img_filter_brand;

                        //clear other sub filters--
                        selectedSubBrand = null;
                        selectedReference = null;

                        (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
                        (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
                        //--

                        setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand);
                        //setFilter(FILTER_FOR_BRAND);
                        db.open();
                        subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe);
                        db.open();
                        referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe);

                        break;
                    case CommonString.SubBrand:
                        selectedSubBrand = current;
                        filterId[0] = R.id.img_filter_sub_brand;

                        //clear other sub filters--
                        selectedReference = null;

                        (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
                        //--
                        setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand);
                        //setFilter(FILTER_FOR_SUB_BRAND);
                        db.open();
                        referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe);
                        break;
                    case CommonString.Reference:
                        selectedReference = current;
                        filterId[0] = R.id.img_filter_reference;
                        setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference);
                        //setFilter(FILTER_FOR_REFERENCE);
                        break;
                }

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

            if (selected[0]) {
                holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach));
            } else {
                holder.card.setCardBackgroundColor(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);

            }
        }
    }

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

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

    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.setCaptureActivity(CaptureActivity.class);
        intentIntegrator.initiateScan();
    }


    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));
                } else {
                    continue;
                }
            }

            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(counterGroupId, "BrandName", false, selectedSubAxe);
        db.open();
        subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe);
        db.open();
        referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe);
        db.open();
        signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe);
    }

    private Dialog dialog;
    ProgressBar pb;

    class LoadAsync extends AsyncTask<Void, Void, Void> {
        @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(Void... voids) {
            prepareListData();
            //validate_spin_ui_data();

            return null;
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.cancel();
            recSubAxe.setLayoutManager(new GridLayoutManager(SalesActivity.this, 3));
            subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature);
            recSubAxe.setAdapter(subAxeValueAdapter);
            recSubAxe.getAdapter().notifyDataSetChanged();

            //validate_spin_ui_data();
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
            lvExp_stock_check.setAdapter(listAdapter);
            db.open();
            JourneyPlan jcp = db.getJCP();
            if (jcp != null) {
                counterGroupId = jcp.getCounterGroupId().toString();
            } else {
                counterGroupId = "1";
            }

            super.onPostExecute(aVoid);
        }
    }


    private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) {
        try {
            JSONArray topUpArray = new JSONArray();
            String key = "SaleableData";
            int mid = 0;
            if (stock != null) {
                if (jcp != null) {
                    mid = jcp.getMID();
                }
                for (int j = startIndex; j < endIndex; j++) {
                    JSONObject obj = new JSONObject();
                    obj.put("ProductId", stock.getProductList().get(j).getProductId());
                    obj.put("MID", mid);
                    obj.put("REASON_ID", stock.getProductList().get(j).getReasonId());
                    obj.put("TranId", stock.getTransactionId());
                    obj.put("UserId", username);
                    obj.put("CounterId", counter_id);
                    //header image
                    String img = stock.getProductList().get(j).getImagePath();
                    if (img == null) {
                        img = "";
                    }
                    obj.put("Image", img);
                    ////for uploaded first time data if status is not null
                    if (status != null) {
                        int stk = stock.getProductList().get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }
                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        //different key for first time data
                        key = "SaleableFData";
                    } else {
                        obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock());
                    }
                    topUpArray.put(obj);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", mid);
            jsonObject.put("Keys", key);
            jsonObject.put("JsonData", topUpArray.toString());
            jsonObject.put("UserId", username);
            String jsonString = jsonObject.toString();
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    assert stock != null;
                                    if (endIndex < stock.getProductList().size()) {
                                        int startIndex1 = endIndex;
                                        int endIndex1 = 0;
                                        if (startIndex1 + 200 < stock.getProductList().size()) {
                                            endIndex1 = startIndex1 + 200;
                                        } else {
                                            endIndex1 = stock.getProductList().size();
                                        }
                                        UploadStockRecursive(status, startIndex1, endIndex1, stock);
                                    } else {
                                        db.open();
                                        db.updateStockTransactionDataStatus(stock.getTransactionId());
                                        db.updateMasterTransactionDataStatus(stock.getTransactionId());
                                        dialog.cancel();
                                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                        SalesActivity.this.finish();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            db.open();
                            dialog.cancel();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again");
                        }
                    } else {
                        dialog.cancel();
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    dialog.cancel();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again");
                }
            });
        } catch (JSONException e) {
            e.fillInStackTrace();
            dialog.cancel();
            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again");
        }
    }

    @Override
    public void onDestroy() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        super.onDestroy();
    }

    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")
        @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);
                    db.open();
                    subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
                    db.open();
                    referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
                    db.open();
                    signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
                } else {
                    db.open();
                    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);
                }
            });

            //if (current.isSelected()) {
            if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) {
                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 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 void setBottomFilter(List<ProductMaster> originalList, String text, HashMap<ProductMaster,
            List<ProductMaster>> listDataChild, String type) {

        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++) {

                switch (type) {
                    case CommonString.Signature:
                        if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                    case CommonString.Brand:
                        if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }

                        break;
                    case CommonString.SubBrand:
                        if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                    case CommonString.Reference:
                        if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                }

            }

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

            }

        }

        ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter1);
        listAdapter1.notifyDataSetChanged();
    }

    class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        boolean flag = false;

        @Override
        protected void onPreExecute() {
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            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) {
            flag = bool[0];
            // db.open();
            // db.insertMESaleCapturedData(visit_date, listDataChild, listDataHeader, flag, counter_id);
            // db.insertStockCapturedData(visit_date, listDataChild, listDataHeader, flag, counter_id);
            // uploadData(flag);
            //validate_spin_ui_data();
            db.open();
            db.insertMESaleCapturedData(visit_date, listDataChild, listDataHeader, "N", counter_id, CommonFunctions.getUUID(context), username);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.cancel();

            if (flag) {
                Intent intent = new Intent(context, Downloader.class);
                intent.putExtra(CommonString.ME_SALE, listDataHeader);
                Downloader.enqueueWork(context, intent);

                AlertandMessages.showToastMsg(context, "Data Uploaded Successfully");
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                SalesActivity.this.finish();
            } else {
                AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                SalesActivity.this.finish();
            }

            /*dialog.dismiss();
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);*/
        }
    }

    public void setUnFilledFilter(List<ProductMaster> originalList, 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).getStock() == -1) {
                    listFilterChild.add(listChild.get(j));
                } else {
                    continue;
                }
            }

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

    private boolean validate_regular_stock() {
        check_flag = true;
        if (listDataHeader.size() > 0) {
            for (int k = 0; k < listDataHeader.size(); k++) {
                List<ProductMaster> child_list = listDataChild.get(listDataHeader.get(k));
                /*for (int i = 0; i < child_list.size(); i++) {
                    if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) {
                        if (child_list.get(i).getReasonId() == 0) {
                            check_flag = false;
                            AlertandMessages.showToastMsg(context, "Please Select Reason");
                            break;
                        }
                    }

                }*/

                if (!check_flag) {
                    break;
                }
            }
        }

        return check_flag;

    }


}