package com.cpm.lorealbaautomation.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;

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

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

import android.os.Bundle;

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

import android.text.Editable;
import android.text.TextWatcher;
import android.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.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.gson.Gson;
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.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.consumeractivity.ConsumerReturnReplaceProductActivity;
import com.cpm.lorealbaautomation.consumeractivity.ConsumerReturnsHistoryActivity;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerSalesHistory;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterReturnReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
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 okhttp3.ResponseBody;
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 ConsumerReturnActivity extends AppCompatActivity implements View.OnClickListener {
    ArrayAdapter<CharSequence> dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter, return_reason_adapter;
    public ArrayList<InvoiceGetterSetter> selected_list = new ArrayList<>();
    public static ArrayList<InvoiceGetterSetter> replace_productList = new ArrayList<>();
    public ArrayList<ProductMaster> dialog_product_list = new ArrayList<>();
    public ArrayList<MasterReturnReason> returnReasonList = new ArrayList<>();
    public ArrayList<ProductMaster> dialog_product_using_searchlist = new ArrayList<>();
    String counterID, username, visit_date, dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0", product_scan_code = "", otp_code = "", return_reason_Id = "0", return_reason_name = "", TransId = "", str_return_bill_img = "", _pathforcheck = "", _path = "";
    private SharedPreferences preferences;
    Button btn_scan, btn_enter_code, btn_sku_list, btn_send_otp;
    EditText edt_customer, edt_bill_no, edt_mobile_no, edt_scan_code, edt_otp;
    RecyclerView drawer_layout_recycle_store;
    TextView qrcode_text, sku_name, stock_text_value, txt_history;
    FloatingActionButton save_fab, add_product_fab;
    boolean clicked_flag = false, flag_for_filter = false, flag_filter_by_edt = false, flag_click_history = false;
    Lorealba_Database db;
    Context context;
    MultiPurposeDialog multiPurposeDialog;
    InvoiceGetterSetter object;
    int minteger = 0;
    ProgressDialog loading;
    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    ArrayList<InvoiceGetterSetter> returnheaderList;
    HashMap<InvoiceGetterSetter, List<InvoiceGetterSetter>> listDataChild;
    JourneyPlan storeDataObject = new JourneyPlan();
    List<ConsumerSalesHistory> previusHistoryList = new ArrayList<>();
    InvoiceGetterSetter calculateReplace_product = new InvoiceGetterSetter();
    LinearLayout rl_bill_return_img, rl_send_otp;
    ImageView img_bill;
    EditText edt_email_address;

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


        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();
        TransId = CommonFunctions.getUUID(context);
        setTitle("Consumer Returns -" + username);
        getstatusof_termcondition();

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


    @SuppressLint("RestrictedApi")
    private void iduserinterface() {
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = preferences.edit();
        counterID = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        txt_history = (TextView) findViewById(R.id.txt_history);
        btn_send_otp = (Button) findViewById(R.id.btn_send_otp);
        btn_scan = (Button) findViewById(R.id.btn_scan);
        btn_enter_code = (Button) findViewById(R.id.btn_enter_code);
        btn_sku_list = (Button) findViewById(R.id.btn_sku_list);
        save_fab = (FloatingActionButton) findViewById(R.id.save_fab);
        edt_customer = (EditText) findViewById(R.id.edt_customer);
        edt_bill_no = (EditText) findViewById(R.id.edt_bill_no);
        edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no);
        edt_otp = (EditText) findViewById(R.id.edt_otp);
        radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp);
        add_product_fab = (FloatingActionButton) findViewById(R.id.btn_select_sku);

        drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store);
        ///////new changes
        rl_bill_return_img = (LinearLayout) findViewById(R.id.rl_bill_return_img);
        rl_send_otp = (LinearLayout) findViewById(R.id.rl_send_otp);
        img_bill = (ImageView) findViewById(R.id.img_bill);
        edt_email_address = (EditText) findViewById(R.id.edt_email_address);

        db.open();
        storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, counterID, username);
        btn_scan.setOnClickListener(this);
        btn_enter_code.setOnClickListener(this);
        btn_sku_list.setOnClickListener(this);
        save_fab.setOnClickListener(this);
        btn_send_otp.setOnClickListener(this);
        txt_history.setOnClickListener(this);
        img_bill.setOnClickListener(this);
        add_product_fab.setOnClickListener(this);

        db.open();
        dialog_product_list = db.getproduct_masterlist(null, visit_date, counterID, null);
        returnReasonList = db.getreturn_reasonList();
        setDataToListView();
        add_product_fab.hide();
        save_fab.show();
    }


    public void setDataToListView() {
        try {
            db.open();
            selected_list = db.getconsumerReturndataformDb(counterID, visit_date, username);
            if (!selected_list.isEmpty()) {
                Collections.reverse(selected_list);
                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
            }

        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(e);
            //test("Exception when fetching", e.toString());
        }
    }


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

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.img_bill) {
            _pathforcheck = counterID + "_invoiceimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
        } else if (id == R.id.txt_history) {
            if (edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (edt_bill_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bill Number ");
            } else if (edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (checkindex()) {
                if (CommonFunctions.checkNetIsAvailable(context)) {
                    try {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("Downloadtype", "Consumer_SalesHistory");
                        jsonObject1.put("Username", username);
                        jsonObject1.put("Param2", edt_email_address.getText().toString());
                        jsonObject1.put("Param1", edt_mobile_no.getText().toString());
                        loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
                        getpreviousHistory_from_mobile_no(context, loading, jsonObject1.toString());
                        flag_click_history = true;
                    } catch (JSONException e) {
                        e.fillInStackTrace();
                    }
                } else {
                    AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated");
                }
            }

        } else if (id == R.id.btn_send_otp) {
            try {
                ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                if (edt_mobile_no.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
                } else if (edt_mobile_no.getText().toString().length() < 10) {
                    AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
                } else {
                    if (checkindex()) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("MobileNumber", edt_mobile_no.getText().toString());
                        getotp_from_mobile_no(jsonObject.toString());
                    } else {
                        AlertandMessages.showToastMsg(context, "Invalid Mobile Number. Please Enter Correct Mobile Number");
                    }
                }
            } catch (JSONException e) {
                e.fillInStackTrace();
            }

        } else if (id == R.id.btn_scan) {
            clicked_flag = true;
            ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (edt_bill_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bill Number");
            } else if (edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (!flag_click_history) {
                AlertandMessages.showToastMsg(context, "Please Click Show History");
            } else {
                show_proforma_dialog(context, true);
            }

        } else if (id == R.id.btn_enter_code) {
            clicked_flag = true;
            ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (edt_bill_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bill Number ");
            } else if (edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (!flag_click_history) {
                AlertandMessages.showToastMsg(context, "Please Click Show History");
            } else {
                show_proforma_dialog(context, false);
            }

        } else if (id == R.id.btn_select_sku) {
            prepareListData();
            if (calculateReplace_product != null && calculateReplace_product.getTotal_replace_product_value() != 0) {
                startActivity(new Intent(context, ConsumerReturnReplaceProductActivity.class).putExtra(CommonString.TAG_OBJECT, calculateReplace_product));
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }

        } else if (id == R.id.save_fab) {
            if (selected_list.size() > 0) {
                if (previusHistoryList.size() == 0 && edt_otp.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter OTP");
                } else if (previusHistoryList.size() == 0 && !otp_code.equals(edt_otp.getText().toString().trim())) {
                    AlertandMessages.showToastMsg(context, "Please Enter Correct OTP");
                } else if (str_return_bill_img.equals("")) {
                    AlertandMessages.showToastMsg(context, "Please Capture Bill Image");
                } else {
                    prepareListData();
                    if (calculateReplace_product != null && calculateReplace_product.getTotal_replace_product_value() != 0 && replace_productList.size() == 0) {
                        startActivity(new Intent(context, ConsumerReturnReplaceProductActivity.class).putExtra(CommonString.TAG_OBJECT, calculateReplace_product));
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    } else {
                        show_selected_invoice(context);
                    }
                }
            } else {
                AlertandMessages.showToastMsg(context, "Please Add first ");
            }

        } else if (id == R.id.btn_sku_list) {
            clicked_flag = true;
            ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (edt_bill_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bill Number ");
            } else if (edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (!flag_click_history) {
                AlertandMessages.showToastMsg(context, "Please Click Show History");
            } else {
                show_dialog_forsku_categorywise(context);
            }
        }
    }


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

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

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

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

        ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add);

        final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason);
        final Spinner return_reason_spin = (Spinner) multiPurposeDialog.findViewById(R.id.return_reason_spin);

        rl_return_reason.setVisibility(View.VISIBLE);
        rl_actualreaturn_qty.setVisibility(View.GONE);

        setReturnReasonSpinnerData(returnReasonList, return_reason_spin);

        return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    return_reason_name = returnReasonList.get(pos - 1).getReason();
                    return_reason_Id = returnReasonList.get(pos - 1).getReasonId().toString();
                } else {
                    return_reason_name = "";
                    return_reason_Id = "0";
                }
            }

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

            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = s.toString();
                setSearchFilter(dialog_product_list, text, dialog_product_spin);
            }

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


        db.open();
        validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin, db.getproductdata_dialogfor_return("BrandName", "BrandId", false, ""), db.getproductdata_dialogfor_return("SubBrandName", "SubBrandId", false, ""), db.getproductdata_dialogfor_return("ReferenceName", "ReferenceId", false, ""), db.getbrand_wise_sku_fromproductfor_return(), stock_text_value);


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

        stock_img_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                if (!product_Id.equals("0")) {
                    try {
                        minteger = minteger + 1;
                        stock_text_value.setText("" + minteger);
                       /* if (minteger > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) {
                            minteger = minteger - 1;
                            stock_text_value.setText("" + minteger);
                            AlertandMessages.showToastMsg(context, "Product quantity should not be Greater than Invoice Actual Quantity ");
                        } else {
                            stock_text_value.setText("" + minteger);
                        }*/
                    } catch (NumberFormatException e) {
                        e.fillInStackTrace();
                    }
                } else {
                    AlertandMessages.showToastMsg(context, "First Select Product");
                }
                // } else {
                // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                // }
            }
        });

        stock_img_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                if (minteger == 0) {
                    AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero ");
                } else {
                    minteger = minteger - 1;
                    stock_text_value.setText("" + minteger);
                }
                //  } else {
                // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                //  }
            }
        });


        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                if (dialog_product_spin.getSelectedItemId() == 0) {
                    AlertandMessages.showToastMsg(context, "Please Select Product");
                }/* else if (edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                } else if (edt_actual_qty_reaturn.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please Enter atleast One Invoice Actual Quantity");
                }*/ else if (stock_text_value.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity ");
                } else if (return_reason_spin.getSelectedItemId() == 0) {
                    AlertandMessages.showToastMsg(context, "Please Select Return Reason ");
                }/* else if (Integer.parseInt(stock_text_value.getText().toString()) > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) {
                    AlertandMessages.showToastMsg(context, "Product Quantity Should be Less Than OR equal to Invoice Actual Quantity");
                }*/ else {
                    // get selected radio button from radioGroup
                    int selectedId = radioSexGroup.getCheckedRadioButtonId();
                    // find the radiobutton by returned id
                    radioSexButton = (RadioButton) findViewById(selectedId);
                    object = new InvoiceGetterSetter();
                    object.setStore_name(storeDataObject.getCounterName());
                    object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
                    object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
                    object.setMobile_no(edt_mobile_no.getText().toString());
                    object.setConsumer_email_Id(edt_email_address.getText().toString());

                    object.setConsumer_return_bill_no(edt_bill_no.getText().toString());
                    object.setProduct_rate(product_mrp);
                    object.setProduct(product_name);
                    object.setProduct_Id(product_Id);
                    object.setCustomer_gender(radioSexButton.getText().toString());
                    object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                    object.setQuantity(stock_text_value.getText().toString());
                    // object.setActualQty(edt_actual_qty_reaturn.getText().toString());
                    object.setActualQty("0");
                    object.setCon_return_reason(return_reason_name);
                    object.setCon_return_reason_Id(return_reason_Id);
                    object.setReturn_bill_img(str_return_bill_img);
                    selected_list.add(object);

                    /////for return to product
                    if (calcualtereturntoprodcutList(selected_list)) {
                        save_fab.hide();
                        add_product_fab.show();
                    } else {
                        save_fab.show();
                        add_product_fab.hide();
                    }

                    minteger = 0;
                    //edt_actual_qty_reaturn.setText("0");
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    dialog_brand_Id = "";
                    dialog_sub_brand_Id = "";
                    dialog_reference_Id = "";
                    product_name = "";
                    product_Id = "0";
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    multiPurposeDialog.dismiss();

                }
            }
        });

        multiPurposeDialog.show();
    }


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

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

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

        dialog_brand_spin.setAdapter(dialog_brand_adapter);

        dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);

        setReferenceSpinnerData(referenceList, dialog_franchise_spin);

        setProductSpinnerData(productList, dialog_product_spin);

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

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


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

            }
        });

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

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

            }
        });

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

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

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

            }
        });


        dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    if (flag_filter_by_edt) {
                        product_name = dialog_product_using_searchlist.get(position - 1).getProductName();
                        product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString();
                        product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString();
                        product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode();
                        stock_text_value.setText("0");
                        minteger = 0;
                    } else if (flag_for_filter) {
                        product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName();
                        product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString();
                        product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString();
                        product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode();
                        stock_text_value.setText("0");
                        minteger = 0;
                    } else {
                        product_name = productList.get(position - 1).getProductName();
                        product_Id = productList.get(position - 1).getProductId().toString();
                        product_mrp = productList.get(position - 1).getMrp().toString();
                        product_scan_code = productList.get(position - 1).getEanCode();
                        stock_text_value.setText("0");
                        minteger = 0;
                    }

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

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

            }
        });

    }


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

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

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

    }


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

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

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

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

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

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


    public void setFilter(int filterType, Spinner dialog_spin) {
        List<ProductMaster> filteredList = new ArrayList<>();
        switch (filterType) {
            case FILTER_FOR_BRAND:
                filteredList = filterListForBrand(dialog_product_list, dialog_brand_Id);
                break;
            case FILTER_FOR_SUB_BRAND:
                filteredList = filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id);
                break;
            case FILTER_FOR_REFERENCE_NAME:
                filteredList = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id);
                break;
            default:
                filteredList = dialog_product_list;
                break;
        }
        // Prepare display strings
        List<String> displayList = new ArrayList<>();
        displayList.add("- Select Product -"); // default item
        for (ProductMaster product : filteredList) {
            displayList.add(product.getProductName() + " - (MRP-" + product.getMrp() + ")");
        }
        // Set adapter
        dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        dialog_sku_adapter.addAll(displayList);
        dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        dialog_spin.setAdapter(dialog_sku_adapter);
    }
    /*public void setFilter(int filterType, Spinner dialog_spin) {
        if (filterType == FILTER_FOR_BRAND) {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");
            for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")");
            }
            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } else if (filterType == FILTER_FOR_SUB_BRAND) {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");

            for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")");
            }
            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } else if (filterType == FILTER_FOR_REFERENCE_NAME) {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");
            for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).size(); i++) {
                dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getMrp().toString() + ")");
            }
            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } else {
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");
            for (int i = 0; i < dialog_product_list.size(); i++) {
                dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")");
            }
            dialog_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        }
        dialog_spin.invalidate();
    }*/

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

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

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

        return filterList;
    }


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

        return filterList;
    }


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


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

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

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

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

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


            int quantity = Integer.parseInt(current.getQuantity());
            double amount = Double.parseDouble(current.getProduct_rate());
            amount = amount * quantity;
            double cCom = ((amount) * current.getDiscount());

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

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

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

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

            holder.delete_added_product.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            data.remove(position);
                            notifyDataSetChanged();
                            if (data.size() > 0) {
                                ValueAdapter adapter = new ValueAdapter(context, data);
                                drawer_layout_recycle_store.setAdapter(adapter);
                                adapter.notifyDataSetChanged();
                            }

                            /////for return to product
                            if (calcualtereturntoprodcutList((ArrayList<InvoiceGetterSetter>) data)) {
                                save_fab.hide();
                                add_product_fab.show();
                            } else {
                                save_fab.show();
                                add_product_fab.hide();
                            }

                            notifyDataSetChanged();
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            });

        }

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

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

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


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


        LinearLayout rl_actualreaturn_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actualreaturn_qty);
        final EditText edt_actual_qty_reaturn = (EditText) multiPurposeDialog.findViewById(R.id.edt_actual_qty_reaturn);

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

        if (flag_for_rl) {
            RL_scan_code.setVisibility(View.GONE);
            rl_bar_code.setVisibility(View.VISIBLE);
            txt_bar_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.GONE);
        } else {
            rl_bar_code.setVisibility(View.GONE);
            txt_bar_code.setVisibility(View.GONE);
            RL_scan_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.VISIBLE);
        }


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

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

        final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason);
        final Spinner return_reason_spin = (Spinner) multiPurposeDialog.findViewById(R.id.return_reason_spin);
        btn_add.setVisibility(View.VISIBLE);
        rl_return_reason.setVisibility(View.VISIBLE);

        setReturnReasonSpinnerData(returnReasonList, return_reason_spin);

        return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    return_reason_name = returnReasonList.get(pos - 1).getReason();
                    return_reason_Id = returnReasonList.get(pos - 1).getReasonId().toString();
                } else {
                    return_reason_name = "";
                    return_reason_Id = "0";
                }

            }

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

            }
        });

        stock_img_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                if (!product_Id.equals("0")) {
                    minteger = minteger + 1;
                    stock_text_value.setText("" + minteger);

//                        if (minteger > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) {
//                            minteger = minteger - 1;
//                            stock_text_value.setText("" + minteger);
//                            AlertandMessages.showToastMsg(context, "Product quantity should not be Greater than Invoice Actual Quantity ");
//                        }
//                        else {
//                            stock_text_value.setText("" + minteger);
//                        }
                } else {
                    AlertandMessages.showToastMsg(context, "First Select Product");
                }
                // } else {
                // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                // }
            }
        });

        stock_img_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                if (minteger == 0) {
                    AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero ");
                } else {
                    minteger = minteger - 1;
                    stock_text_value.setText("" + minteger);
                }
                //  } else {
                // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                //  }
            }
        });

        cancet_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiPurposeDialog.dismiss();
                sku_name.setText("");
                stock_text_value.setText("");
                qrcode_text.setText("");
                product_scan_code = "";
                product_name = "";
                product_mrp = "";
                product_Id = "0";
                sku_name.setVisibility(View.GONE);
            }
        });

        check_exist_sku.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Bar Code ");
                } else {

                    db.open();
                    ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancodefor_return(edt_scan_code.getText().toString());
                    if (productList.size() == 0) {
                        db.open();
                        productList = db.getsku_fromproductusing_eancodefor_return(removeFirstChar(edt_scan_code.getText().toString()));
                    }

                    if (productList.size() == 0) {
                        edt_scan_code.setText("");
                        AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again ");
                    } else {
                        show_dialog_forsku(context, productList);
                    }
                }
            }
        });


        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Scan Bar Code ");
                } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Bar Code ");
                }

               /* else if (edt_actual_qty_reaturn.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity");
                } else if (edt_actual_qty_reaturn.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please Enter atleast One Invoice Actual Quantity");
                } */

                else if (stock_text_value.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity ");
                } else if (return_reason_spin.getSelectedItemId() == 0) {
                    AlertandMessages.showToastMsg(context, "Please Select Return Reason ");
                } else if (product_Id.equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please Click On Get Buttton ");
                }/* else if (Integer.parseInt(stock_text_value.getText().toString()) > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) {
                    AlertandMessages.showToastMsg(context, "Product Quantity Should be Less Than OR equal to Invoice Actual Quantity");
                }*/ else {
                    object = new InvoiceGetterSetter();
                    if (checkduplicate_entry()) {
                        if (!flag_for_rl) {
                            db.open();
                            product_scan_code = edt_scan_code.getText().toString();
                            if (db.getsku_fromproductusing_eancodefor_return(product_scan_code).size() == 0) {
                                AlertandMessages.showToastMsg(context, "Product not found ");
                            } else {
                                minteger = 0;
                                multiPurposeDialog.cancel();
                                // get selected radio button from radioGroup
                                int selectedId = radioSexGroup.getCheckedRadioButtonId();
                                // find the radiobutton by returned id
                                radioSexButton = (RadioButton) findViewById(selectedId);

                                object = new InvoiceGetterSetter();
                                object.setStore_name(storeDataObject.getCounterName());
                                object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
                                object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
                                object.setConsumer_return_bill_no(edt_bill_no.getText().toString());
                                object.setMobile_no(edt_mobile_no.getText().toString());
                                object.setConsumer_email_Id(edt_email_address.getText().toString());

                                object.setProduct_rate(product_mrp);
                                object.setProduct(product_name);
                                object.setProduct_Id(product_Id);

                                object.setCustomer_gender(radioSexButton.getText().toString());
                                object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                                object.setQuantity(stock_text_value.getText().toString());
                                // object.setActualQty(edt_actual_qty_reaturn.getText().toString());
                                object.setActualQty("0");
                                object.setCon_return_reason(return_reason_name);
                                object.setCon_return_reason_Id(return_reason_Id);
                                object.setReturn_bill_img(str_return_bill_img);
                                selected_list.add(object);

                                /////for return to product
                                if (calcualtereturntoprodcutList(selected_list)) {
                                    save_fab.hide();
                                    add_product_fab.show();
                                } else {
                                    save_fab.show();
                                    add_product_fab.hide();
                                }

                                //edt_actual_qty_reaturn.setText("");
                                stock_text_value.setText("");
                                qrcode_text.setText("");
                                edt_scan_code.setText("");
                                product_scan_code = "";
                                product_name = "";
                                product_mrp = "";
                                product_Id = "0";
                                sku_name.setText("");
                                sku_name.setVisibility(View.GONE);
                                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                            }
                        } else {
                            multiPurposeDialog.cancel();
                            minteger = 0;
                            // get selected radio button from radioGroup
                            int selectedId = radioSexGroup.getCheckedRadioButtonId();
                            // find the radiobutton by returned id
                            radioSexButton = (RadioButton) findViewById(selectedId);
                            object = new InvoiceGetterSetter();
                            object.setStore_name(storeDataObject.getCounterName());
                            object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
                            object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
                            object.setConsumer_email_Id(edt_email_address.getText().toString());
                            object.setConsumer_return_bill_no(edt_bill_no.getText().toString());
                            object.setMobile_no(edt_mobile_no.getText().toString());
                            object.setProduct_rate(product_mrp);
                            object.setProduct(product_name);
                            object.setProduct_Id(product_Id);
                            object.setCustomer_gender(radioSexButton.getText().toString());
                            object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                            object.setQuantity(stock_text_value.getText().toString());
                            // object.setActualQty(edt_actual_qty_reaturn.getText().toString());
                            object.setActualQty("0");

                            object.setCon_return_reason(return_reason_name);
                            object.setCon_return_reason_Id(return_reason_Id);
                            object.setReturn_bill_img(str_return_bill_img);
                            selected_list.add(object);

                            /////for return to product
                            if (calcualtereturntoprodcutList(selected_list)) {
                                save_fab.hide();
                                add_product_fab.show();
                            } else {
                                save_fab.show();
                                add_product_fab.hide();
                            }


                            stock_text_value.setText("");
                            //  edt_actual_qty_reaturn.setText("");
                            qrcode_text.setText("");
                            edt_scan_code.setText("");
                            product_scan_code = "";
                            product_name = "";
                            product_mrp = "";
                            product_Id = "0";
                            sku_name.setText("");
                            sku_name.setVisibility(View.GONE);
                            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));

                        }
                    }
                }
            }
        });

        img_bar_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openScanner();
            }
        });
        multiPurposeDialog.show();
    }

    private void show_dialog_forsku(final Context context, ArrayList<ProductMaster> skuList_with_eancode) {
        multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(multiPurposeDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);

        TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName());
        RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku);
        recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0"));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));
        ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiPurposeDialog.dismiss();
            }
        });

        multiPurposeDialog.show();
    }

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

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

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


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

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

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

                holder.sale_card.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        qrcode_text.setText(current.getEanCode());
                        product_name = current.getProductName();
                        product_Id = current.getProductId().toString();
                        product_scan_code = current.getEanCode();
                        product_mrp = current.getMrp().toString();
                        sku_name.setText(product_name + " Mrp - " + product_mrp);
                        sku_name.setVisibility(View.VISIBLE);
                        multiPurposeDialog.dismiss();
                    }
                });
            }
        }


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

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


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

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

    private boolean checkduplicate_entrymultiple(String product_Id, String product_mrp) {
        boolean status = true;
        if (selected_list != null && selected_list.size() > 0) {
            for (int k = 0; k < selected_list.size(); k++) {
                if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) {
                    status = false;
                }
            }
        }
        return status;
    }

    private boolean checkindex() {
        boolean status = false;
        String str = edt_mobile_no.getText().toString();
        String strArray[] = str.split(" ");
        //print elements of String array
        for (int i = 0; i < strArray.length; i++) {
            if (strArray[i].contains("1") || strArray[i].contains("2") || strArray[i].contains("3") || strArray[i].contains("4") || strArray[i].contains("5") || strArray[i].contains("6") || strArray[i].contains("7") || strArray[i].contains("9") || strArray[i].contains("8")) {
                status = true;
                break;
            }
        }
        return status;
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result == null) {
            switch (resultCode) {
                case 0:
                    Log.i("MakeMachine", "User cancelled");
                    break;
                case -1:
                    if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                        try {
                            if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                                convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                                img_bill.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                str_return_bill_img = _pathforcheck;
                                _pathforcheck = "";

                            }
                        } catch (Resources.NotFoundException e) {
                            e.fillInStackTrace();
                        }
                    }

                    break;
            }

        } else if (result != null) {
            if (result.getContents() == null) {
                //test("ScanActivity", "Cancelled scan");
                AlertandMessages.showToastMsg(context, "Cancelled ");
            } else {
                db.open();

                db.open();
                ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancodefor_return(result.getContents());

                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancodefor_return(removeFirstChar(result.getContents()));
                }

                if (!productList.isEmpty()) {
                    show_dialog_forsku(context, productList);
                    stock_text_value.setText("0");
                    minteger = 0;
                } else {
                    product_name = "";
                    product_scan_code = "";
                    qrcode_text.setText("");
                    minteger = 0;
                    AlertandMessages.showToastMsg(context, "Unable to Scan Correct data. Please try again ");
                }
            }
        } else super.onActivityResult(requestCode, resultCode, data);
    }

    public void getotp_from_mobile_no(String jsondata) {
        try {
            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true);
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<ResponseBody> call = api.getOTPMethod(jsonData);
            call.enqueue(new retrofit2.Callback<ResponseBody>() {
                @Override
                public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {

                            loading.dismiss();
                            data = response.body().string();
                            JSONObject jObject = new JSONObject(data);
                            otp_code = jObject.getString("SendOTPResult");

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }

                    } else {
                        loading.dismiss();
                        AlertandMessages.showToastMsg(context, "Server Not Responding . Please Try Again ");
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });

        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }


    private ArrayList<InvoiceGetterSetter> calculate_invoice_added_data(ArrayList<InvoiceGetterSetter> invoice_List) {
        try {
            for (int k = 0; k < invoice_List.size(); k++) {

                int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate());
                amount = amount * quantity;
                invoice_List.get(k).setTotal_amount("" + amount);
            }

        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }

        return invoice_List;
    }

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

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

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

        dialog_product_spin.invalidate();
    }


    private void setReturnReasonSpinnerData(ArrayList<MasterReturnReason> productList, Spinner return_reason_spin) {
        return_reason_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        return_reason_adapter.add("- Select Reason -");

        for (int i = 0; i < productList.size(); i++) {
            return_reason_adapter.add(productList.get(i).getReason());
        }
        return_reason_spin.setAdapter(return_reason_adapter);
        return_reason_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
    }

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

        return filterList;
    }

    private void prepareListData() {
        returnheaderList = new ArrayList<>();
        listDataChild = new HashMap<>();
        returnheaderList.add(selected_list.get(0));
        if (returnheaderList.size() > 0) {
            // Adding child data
            for (int i = 0; i < returnheaderList.size(); i++) {
                listDataChild.put(returnheaderList.get(i), selected_list); // Header, Child data
            }
        }

        int total_replace_product_mrp = 0, total_replace_product_qty = 0;
        if (selected_list.size() > 0) {
            try {
                for (int k = 0; k < selected_list.size(); k++) {
                    if (selected_list.get(k).getCon_return_reason_Id().equals("3")) {
                        total_replace_product_mrp = total_replace_product_mrp + (Integer.parseInt(selected_list.get(k).getQuantity()) * Integer.parseInt(selected_list.get(k).getProduct_rate()));
                        total_replace_product_qty = total_replace_product_qty + (Integer.parseInt(selected_list.get(k).getQuantity()));
                    }
                }

                calculateReplace_product = new InvoiceGetterSetter();
                calculateReplace_product.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
                calculateReplace_product.setMobile_no(edt_mobile_no.getText().toString());
                calculateReplace_product.setConsumer_email_Id(edt_email_address.getText().toString());
                calculateReplace_product.setConsumer_return_bill_no(edt_bill_no.getText().toString());
                calculateReplace_product.setTotal_replace_product_value(total_replace_product_mrp);
                calculateReplace_product.setTotal_replace_product_qty(total_replace_product_qty);
            } catch (NumberFormatException e) {
                e.fillInStackTrace();
            }
        }

    }

    private boolean calcualtereturntoprodcutList(ArrayList<InvoiceGetterSetter> selected_list) {
        boolean status = false;
        if (selected_list.size() > 0) {
            for (int k = 0; k < selected_list.size(); k++) {
                if (selected_list.get(k).getCon_return_reason_Id().equals("3")) {
                    status = true;
                    break;
                }
            }
        }
        return status;
    }


    public void getpreviousHistory_from_mobile_no(final Context context, final ProgressDialog loading, String jsondata) {
        try {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<String> call = api.getDownloadAll(jsonData);

            call.enqueue(new retrofit2.Callback<String>() {
                @Override
                public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                    String responseBody = response.body();
                    String data_for = null;
                    loading.dismiss();
                    if (responseBody != null && response.isSuccessful()) {
                        data_for = response.body();
                        if (data_for.equals("")) {
                            loading.dismiss();
                            Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show();
                            txt_history.setEnabled(false);
                            txt_history.setTextColor(getResources().getColor(R.color.gray));
                        } else {
                            loading.dismiss();
                            if (!data_for.contains("No Data")) {
                                loading.dismiss();
                                edt_mobile_no.setEnabled(false);
                                MasterBAProfileGetterSetter masterPromoOfferObject = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class);
                                if (masterPromoOfferObject != null) {
                                    previusHistoryList = masterPromoOfferObject.getConsumerSalesHistory();
                                    if (previusHistoryList.size() > 0) {
                                        rl_send_otp.setVisibility(View.GONE);
                                        show_consumer_previous_histry(context, previusHistoryList);
                                    }
                                } else {
                                    rl_send_otp.setVisibility(View.VISIBLE);
                                    edt_mobile_no.setEnabled(true);
                                    loading.dismiss();
                                    previusHistoryList.clear();
                                }
                            } else {
                                txt_history.setEnabled(false);
                                edt_mobile_no.setEnabled(true);
                                rl_send_otp.setVisibility(View.VISIBLE);
                                txt_history.setTextColor(getResources().getColor(R.color.gray));
                                previusHistoryList.clear();
                                loading.dismiss();
                                Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else {
                        loading.dismiss();
                        previusHistoryList.clear();
                        txt_history.setEnabled(false);
                        edt_mobile_no.setEnabled(true);
                        rl_send_otp.setVisibility(View.VISIBLE);
                        txt_history.setTextColor(getResources().getColor(R.color.gray));
                        AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated");
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<String> call, Throwable t) {
                    loading.dismiss();
                    previusHistoryList.clear();
                    txt_history.setEnabled(false);
                    edt_mobile_no.setEnabled(true);
                    rl_send_otp.setVisibility(View.VISIBLE);
                    txt_history.setTextColor(getResources().getColor(R.color.gray));
                    AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated");
                }
            });
        } catch (Exception e) {
            txt_history.setTextColor(getResources().getColor(R.color.gray));
            rl_send_otp.setVisibility(View.VISIBLE);
            edt_mobile_no.setEnabled(true);
            txt_history.setEnabled(false);
            e.fillInStackTrace();
            loading.dismiss();
        }
    }

    private void show_consumer_previous_histry(final Context context, final List<ConsumerSalesHistory> previusHistoryList) {
        multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(multiPurposeDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);
        TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code);
        txt_bar_code.setText("Consumer Previous History");
        TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setVisibility(View.GONE);

        RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku);
        if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Male")) {
            //radioSexButton
            radioSexGroup.check(R.id.radioM);
        } else if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Female")) {
            //radioSexButton
            radioSexGroup.check(R.id.radioF);
        } else {
            radioSexGroup.check(R.id.radio_other);
        }


        recycl_sku.setAdapter(new AdapterforHistry(context, previusHistoryList, multiPurposeDialog));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));
        ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiPurposeDialog.dismiss();

/*
                if (previusHistoryList.size() > 0) {
                    if (checked_returnproduct(previusHistoryList)) {
                        for (int k = 0; k < previusHistoryList.size(); k++) {
                            if (previusHistoryList.get(k).isChecked_flag()
                                    && checkduplicate_entrymultiple(previusHistoryList.get(k).getProductId().toString(), previusHistoryList.get(k).getMrp().toString())) {
                                // get selected radio button from radioGroup
                                int selectedId = radioSexGroup.getCheckedRadioButtonId();
                                // find the radiobutton by returned id
                                radioSexButton = (RadioButton) findViewById(selectedId);
                                object = new InvoiceGetterSetter();
                                object.setStore_name(storeDataObject.getCounterName());
                                object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
                                object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
                                object.setConsumer_return_bill_no(edt_bill_no.getText().toString());
                                object.setMobile_no(edt_mobile_no.getText().toString());
                                object.setConsumer_email_Id(edt_email_address.getText().toString());

                                object.setProduct_rate(previusHistoryList.get(k).getMrp().toString());
                                object.setProduct(previusHistoryList.get(k).getProductName());
                                object.setProduct_Id(previusHistoryList.get(k).getProductId().toString());
                                object.setCustomer_gender(radioSexButton.getText().toString());
                                object.setScan_ean_code_or_enterd_ean_code(previusHistoryList.get(k).getEanCode());
                                object.setQuantity("" + previusHistoryList.get(k).getSelected_product_qty());
                                object.setActualQty("" + previusHistoryList.get(k).getQtySold());
                                object.setCon_return_reason(previusHistoryList.get(k).getSelected_reason());
                                object.setCon_return_reason_Id(previusHistoryList.get(k).getSelected_reason_Id());
                                object.setReturn_bill_img(str_return_bill_img);
                                selected_list.add(object);
                            }
                        }

                        drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                        drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));

                    }
                }
*/
            }
        });

        multiPurposeDialog.show();
    }

/*
    protected boolean checked_returnproduct(final List<ConsumerSalesHistory> previusHistoryList) {
        boolean status = true;
        if (previusHistoryList.size() > 0) {
            for (int k = 0; k < previusHistoryList.size(); k++) {
                if (previusHistoryList.get(k).isChecked_flag()) {
                    if (previusHistoryList.get(k).getSelected_product_qty() == 0) {
                        AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity ");
                        status = false;
                        break;
                    } else if (previusHistoryList.get(k).getSelected_reason_Id().equals("0")) {
                        AlertandMessages.showToastMsg(context, "Please Select Selected Product Return Reason");
                        status = false;
                        break;
                    }
                }
            }
        }

        return status;
    }
*/

/*
    public class AdapterforHistry extends RecyclerView.Adapter<AdapterforHistry.MyViewHolder> {
        private LayoutInflater inflator;
        List<ConsumerSalesHistory> data;
        MultiPurposeDialog multiPurposeDialog;

        public AdapterforHistry(Context context, List<ConsumerSalesHistory> data, MultiPurposeDialog multiPurposeDialog) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.multiPurposeDialog = multiPurposeDialog;
        }

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


        @Override
        public void onBindViewHolder(final AdapterforHistry.MyViewHolder holder, final int position) {
            final ConsumerSalesHistory current = data.get(position);

            holder.txt_product_name.setText("Date : " + current.getVisitDate());
            holder.txt_product_name.setId(position);

            holder.txt_product_mrp.setText("Product Name : " + current.getProductName());
            holder.txt_product_mrp.setId(position);

            holder.txt_product_qty.setText("MRP : " + current.getMrp().toString());
            holder.txt_product_qty.setId(position);

            holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString());
            holder.qty_sold_txt.setId(position);

            holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString());
            holder.total_amount_txt.setId(position);

            if (position != 0) {
                if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) {
                    holder.rl_visit_date.setVisibility(View.GONE);
                    holder.rl_visit_date.setId(position);
                } else {
                    holder.rl_visit_date.setVisibility(View.VISIBLE);
                    holder.rl_visit_date.setId(position);
                }
            }

            holder.check_return_product.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (holder.check_return_product.isChecked()) {
                        current.setChecked_flag(true);
                    } else {
                        current.setChecked_flag(false);
                    }
                }
            });

            holder.stock_img_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (current.isChecked_flag()) {
                        try {
                            int minteger = current.getSelected_product_qty();
                            if (minteger == 0) {
                                AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
                            } else {
                                minteger = minteger - 1;
                                holder.stock_text_value.setText("" + minteger);
                                current.setSelected_product_qty(minteger);
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    } else {
                        AlertandMessages.showToastMsg(context, "First Tick check");
                    }

                }
            });

            holder.stock_img_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (current.isChecked_flag()) {
                        try {
                            int minteger = current.getSelected_product_qty();
                            minteger = minteger + 1;
                            if (minteger > current.getQtySold()) {
                                minteger = minteger - 1;
                                AlertandMessages.showToastMsg(context, "Product Quantity should not be Greater Than Actual Product Quantity");
                            }

                            holder.stock_text_value.setText("" + minteger);
                            current.setSelected_product_qty(minteger);
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    } else {
                        AlertandMessages.showToastMsg(context, "First Tick check");
                    }
                }
            });

            setReturnReasonSpinnerData(returnReasonList, holder.return_reason_spin);

            holder.return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                    if (pos != 0) {
                        current.setSelected_reason(returnReasonList.get(pos - 1).getReason());
                        current.setSelected_reason_Id(returnReasonList.get(pos - 1).getReasonId().toString());
                    } else {
                        current.setSelected_reason("");
                        current.setSelected_reason_Id("0");
                    }
                }

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

                }
            });


            if (returnReasonList.size() > 0) {
                for (int k = 0; k < returnReasonList.size(); k++) {
                    if (current.getSelected_reason_Id().equals(returnReasonList.get(k).getReasonId().toString())) {
                        holder.return_reason_spin.setSelection(k + 1);
                        break;
                    }
                }
            }

            if (current.isChecked_flag()) {
                holder.check_return_product.setChecked(true);
                holder.check_return_product.setId(position);

                holder.stock_text_value.setText("" + current.getSelected_product_qty());
                holder.stock_text_value.setId(position);
            } else {
                holder.check_return_product.setChecked(false);
                holder.check_return_product.setId(position);

                holder.stock_text_value.setText("" + 0);
                holder.stock_text_value.setId(position);

                holder.return_reason_spin.setSelection(0);
                holder.return_reason_spin.setId(position);

                current.setSelected_reason("");
                current.setSelected_reason_Id("0");
            }
        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_product_mrp, txt_product_qty, txt_product_name, qty_sold_txt, total_amount_txt, stock_text_value;
            Button stock_img_minus, stock_img_plus;

            LinearLayout rl_visit_date;
            CheckBox check_return_product;
            Spinner return_reason_spin;

            public MyViewHolder(View itemView) {
                super(itemView);
                rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date);
                txt_product_qty = (TextView) itemView.findViewById(R.id.txt_product_qty);
                txt_product_mrp = (TextView) itemView.findViewById(R.id.txt_product_mrp);
                txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name);
                qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt);
                total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt);
                stock_text_value = (TextView) itemView.findViewById(R.id.stock_text_value);
                check_return_product = (CheckBox) itemView.findViewById(R.id.check_return_product);
                return_reason_spin = (Spinner) itemView.findViewById(R.id.return_reason_spin);
                stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus);
                stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus);
            }
        }
    }
*/

    public class AdapterforHistry extends RecyclerView.Adapter<AdapterforHistry.MyViewHolder> {
        private LayoutInflater inflator;
        List<ConsumerSalesHistory> data;
        MultiPurposeDialog multiPurposeDialog;

        public AdapterforHistry(Context context, List<ConsumerSalesHistory> data, MultiPurposeDialog multiPurposeDialog) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.multiPurposeDialog = multiPurposeDialog;
        }

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

        }


        @Override
        public void onBindViewHolder(final AdapterforHistry.MyViewHolder holder, final int position) {
            final ConsumerSalesHistory current = data.get(position);

            holder.text_visit_date.setText("Date : " + current.getVisitDate());
            holder.text_visit_date.setId(position);

            holder.consume_product.setText("Product Name : " + current.getProductName());
            holder.consume_product.setId(position);

            holder.consume_product_qty_with_date.setText("MRP : " + current.getMrp().toString());
            holder.consume_product_qty_with_date.setId(position);

            holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString());
            holder.qty_sold_txt.setId(position);

            holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString());
            holder.total_amount_txt.setId(position);


            if (position != 0) {
                if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) {
                    holder.rl_visit_date.setVisibility(View.GONE);
                    holder.rl_visit_date.setId(position);
                } else {
                    holder.rl_visit_date.setVisibility(View.VISIBLE);
                    holder.rl_visit_date.setId(position);
                }
            }
        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView consume_product, consume_product_qty_with_date, text_visit_date, qty_sold_txt, total_amount_txt;
            LinearLayout rl_visit_date;

            public MyViewHolder(View itemView) {
                super(itemView);
                rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date);
                consume_product_qty_with_date = (TextView) itemView.findViewById(R.id.consume_product_qty_with_date);
                consume_product = (TextView) itemView.findViewById(R.id.consume_product);
                text_visit_date = (TextView) itemView.findViewById(R.id.text_visit_date);
                qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt);
                total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt);
            }
        }
    }


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


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_return_history) {
            //for Return history list with replace product..............
            db.open();
            if (db.getsaleReturnHeaderData(visit_date, counterID, username, false, false, null).size() > 0) {
                startActivity(new Intent(context, ConsumerReturnsHistoryActivity.class));
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            } else {
                AlertandMessages.showToastMsg(context, "Records Not Found");
            }

        } else if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> {
                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    ConsumerReturnActivity.this.finish();
                }).setNegativeButton("Cancel", (dialog, id2) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ConsumerReturnActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        /////for return to product
        if (calcualtereturntoprodcutList(selected_list) && replace_productList.size() >= 0) {
            save_fab.show();
            add_product_fab.show();
        } else {
            save_fab.show();
            add_product_fab.hide();
        }
    }

    private void getstatusof_termcondition() {
        edt_mobile_no.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().equals("") && editable.toString().length() == 10) {

                } else {
                    edt_mobile_no.setEnabled(true);
                    txt_history.setEnabled(true);
                    previusHistoryList.clear();
                    txt_history.setTextColor(getResources().getColor(R.color.blue));
                    rl_send_otp.setVisibility(View.GONE);
                }
            }
        });
    }


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

        RecyclerView recycl_return_product = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_return_product);
        RecyclerView recycl_replace_product = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_replace_product);
        ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_submit = (ImageView) multiPurposeDialog.findViewById(R.id.btn_submit);

        TextView total_qty_returnProduct = (TextView) multiPurposeDialog.findViewById(R.id.total_qty_returnProduct);
        TextView total_amount_return_product = (TextView) multiPurposeDialog.findViewById(R.id.total_amount_return_product);

        TextView total_qty_replace_Product = (TextView) multiPurposeDialog.findViewById(R.id.total_qty_replace_Product);
        TextView total_amount_replace_product = (TextView) multiPurposeDialog.findViewById(R.id.total_amount_replace_product);

        LinearLayout rl_replaceProduct = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_replaceProduct);

        ////////set adapter of return products
        if (selected_list.size() > 0) {
            recycl_return_product.setAdapter(new CustomAdapter(context, selected_list));
            recycl_return_product.setLayoutManager(new LinearLayoutManager(context));

            int return_total_qty = 0, return_total_amount = 0;

            for (int k = 0; k < selected_list.size(); k++) {
                return_total_qty = return_total_qty + Integer.parseInt(selected_list.get(k).getQuantity());
                return_total_amount = return_total_amount + (Integer.parseInt(selected_list.get(k).getQuantity()) * Integer.parseInt(selected_list.get(k).getProduct_rate()));
            }

            total_qty_returnProduct.setText("Total QTY : " + return_total_qty);
            total_amount_return_product.setText("Total Amount : " + return_total_amount);
        }

        ////////set adapter of replace products
        if (replace_productList.size() > 0) {
            rl_replaceProduct.setVisibility(View.VISIBLE);

            recycl_replace_product.setAdapter(new CustomAdapter(context, replace_productList));
            recycl_replace_product.setLayoutManager(new LinearLayoutManager(context));

            int replace_product_total_qty = 0, replacep_total_amount = 0;

            for (int k = 0; k < replace_productList.size(); k++) {
                replace_product_total_qty = replace_product_total_qty + Integer.parseInt(replace_productList.get(k).getQuantity());
                replacep_total_amount = replacep_total_amount + (Integer.parseInt(replace_productList.get(k).getQuantity()) * Integer.parseInt(replace_productList.get(k).getProduct_rate()));
            }

            total_qty_replace_Product.setText("Total QTY : " + replace_product_total_qty);
            total_amount_replace_product.setText("Total Amount : " + replacep_total_amount);
        }

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

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        db.open();
                        db.insert_consumer_return_headerchild_data(username, visit_date, counterID, TransId, listDataChild, returnheaderList, str_return_bill_img, replace_productList);
                        // Intent intent = new Intent(context, Downloader.class);
                        if (calculate_invoice_added_data(selected_list).size() > 0) {
                            // intent.putExtra(CommonString.KEY_Consumer_Return, returnheaderList);
                            // Downloader.enqueueWork(context, intent);
                        }

                        replace_productList.clear();
                        multiPurposeDialog.cancel();
                        dialogInterface.cancel();
                        CommonFunctions.call_upload(context);
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        ConsumerReturnActivity.this.finish();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });

                builder.show();
            }
        });

        multiPurposeDialog.show();
    }

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


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

        }

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

        }


        @Override
        public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {
            final InvoiceGetterSetter current = data.get(position);

            holder.txt_product_name.setText("Product : " + current.getProduct());
            holder.txt_product_name.setId(position);

            holder.txt_product_mrp.setText("QTY : " + current.getQuantity());
            holder.txt_product_mrp.setId(position);

            holder.txt_product_qty.setText("MRP : " + current.getProduct_rate());
            holder.txt_product_qty.setId(position);

        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_product_mrp, txt_product_qty, txt_product_name;

            public MyViewHolder(View itemView) {
                super(itemView);
                txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name);
                txt_product_qty = (TextView) itemView.findViewById(R.id.txt_product_qty);
                txt_product_mrp = (TextView) itemView.findViewById(R.id.txt_product_mrp);
            }
        }
    }


}
