package com.cpm.lorealbaautomation.consumeractivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

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.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.printer.PrinterActivity;


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

public class InvoiceReportProformaActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    String CounterId, counterCode, visit_date, username, flag_for_consumer_Update = "", reciept_count = "", TransId = "", disable_pos = "", str_termCondition = "0", str_img_demo_no_sale = "";
    ArrayList<InvoiceGetterSetter> invoice_List = new ArrayList<>();
    TextView text_cus_name, text_mobile_number, text_inr_value, invoice_storename, invoice_storename_address, invoice_gst_no;
    RecyclerView drawer_layout_recycle_store;
    LinearLayout rl_pos;
    double total = 0.0;
    double off_worth_total = 0.0, worth_total = 0.0, OffSameProduct = 0.0, off_worth_additional = 0.0, value_off_worth_additional = 0.0;
    boolean pos_sale_flag = false;
    // Array of choices
    SwitchCompat switch_pos_sale;
    FloatingActionButton fab;
    ImageView img_printer;
    Lorealba_Database db;
    Context context;
    ArrayList<InvoiceGetterSetter> consumerSalesHeaderList;
    HashMap<InvoiceGetterSetter, List<InvoiceGetterSetter>> listDataChild;
    JourneyPlan storeDataObject = new JourneyPlan();
    String from = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice_report_proforma);
        from = getIntent().getStringExtra("from");
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        validateui_design();
        setTitle("Pink Slip -" + username);
        prepareListData();
    }

    @SuppressLint({"RestrictedApi", "SetTextI18n", "CommitPrefEdits"})
    void validateui_design() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        counterCode = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        drawer_layout_recycle_store = findViewById(R.id.drawer_layout_recycle_store);
        text_cus_name = (TextView) findViewById(R.id.text_cus_name);
        text_mobile_number = (TextView) findViewById(R.id.text_mobile_number);
        text_inr_value = (TextView) findViewById(R.id.text_inr_value);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        img_printer = (ImageView) findViewById(R.id.img_printer);
        rl_pos = (LinearLayout) findViewById(R.id.rl_pos);

        invoice_storename = (TextView) findViewById(R.id.invoice_storename);
        invoice_storename_address = (TextView) findViewById(R.id.invoice_storename_address);
        invoice_gst_no = (TextView) findViewById(R.id.invoice_gst_no);
        switch_pos_sale = (SwitchCompat) findViewById(R.id.switch_pos_sale);

        switch_pos_sale.setSwitchPadding(40);
        switch_pos_sale.setOnCheckedChangeListener(this);
        db.open();
        storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username);
        if (storeDataObject != null && storeDataObject.getStoreName() != null) {
            invoice_storename.setText("Counter Code : " + counterCode + " , Counter Name - " + storeDataObject.getCounterName());
            invoice_storename_address.setText(storeDataObject.getAddress() + " , " + storeDataObject.getCityName());
        }

        invoice_gst_no.setText("Date : " + visit_date);
        invoice_List = (ArrayList<InvoiceGetterSetter>) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        flag_for_consumer_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update);
        reciept_count = getIntent().getStringExtra(CommonString.Key_For_Reciept_Count);
        disable_pos = getIntent().getStringExtra(CommonString.Key_For_Disable_POS_And_Save);
        str_termCondition = getIntent().getStringExtra(CommonString.FLAG_FOR_TERMCONDITION);
        str_img_demo_no_sale = getIntent().getStringExtra(CommonString.KEY_IMAGE);
        TransId = CommonFunctions.getUUID(context);

        if (invoice_List != null && !invoice_List.isEmpty()) {
            username = invoice_List.get(0).getUserName();
            text_cus_name.setText("Customer Name : " + invoice_List.get(0).getCustomer_name());
            text_mobile_number.setText("Mobile Number : " + invoice_List.get(0).getMobile_no());

            calculate_invoice_added_data(invoice_List);
            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, invoice_List));
            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
            text_inr_value.setText("" + total);
        }

        img_printer.setOnClickListener(this);
        fab.setOnClickListener(this);
        setreciept_count();
        if (disable_pos != null && disable_pos.equals("1")) {
            fab.setVisibility(View.GONE);
            rl_pos.setVisibility(View.GONE);
        }
    }

    private void setreciept_count() {
        try {
            for (int k = 0; k < invoice_List.size(); k++) {
                invoice_List.get(k).setUnique_code(TransId);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


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

        if (view.getId() == R.id.fab) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData);
            builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> new InsertAsync().execute()).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
            builder.show();
        } else if (view.getId() == R.id.img_printer) {
            startActivity(new Intent(context, PrinterActivity.class).putExtra(CommonString.TAG_OBJECT, invoice_List));
        }
    }

    private long calculate_data_insert_data() {
        long l = 0;
        try {
            if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) {
                db.open();
                db.deleteconsumersale(visit_date, Integer.parseInt(reciept_count), username);
                db.open();
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), pos_sale_flag, TransId, str_termCondition, listDataChild, consumerSalesHeaderList, str_img_demo_no_sale, from);
            } else {
                db.open();
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), pos_sale_flag, TransId, str_termCondition, listDataChild, consumerSalesHeaderList, str_img_demo_no_sale, from);
            }
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }

        return l;
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (compoundButton.getId() == R.id.switch_pos_sale) {
            pos_sale_flag = isChecked;
            Log.i("switch_compat", String.valueOf(isChecked));
        }

    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        private final 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_proforma_invoice, parent, false);
            return new ValueAdapter.MyViewHolder(view);
        }

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

            if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffSameProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffWorth") || current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("WorthWithProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffProduct")) {
                holder.select_promo_productRl.setVisibility(View.GONE);
                holder.select_promo_productRl.setId(position);

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

                holder.product.setText("Applied Promo - " + current.getPromotion_name() + " - " + current.getProduct() + " - Discounted Rs - " + current.getSkuType());
                holder.product.setId(position);

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

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

                holder.total_amount.setText(current.getTotal_amount());
                holder.total_amount.setId(position);


            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Worth")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }

            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Gift")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Gift - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Gift  - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }


            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Product")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

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

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - (" + current.getProduct().toLowerCase() + ")");
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + current.getProduct().toLowerCase());
                    holder.txt_promo_str.setId(position);
                }
            } else {
                holder.select_promo_productRl.setVisibility(View.GONE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.VISIBLE);
                holder.select_productRl.setId(position);
                if (current.getDiscount() != 0.0) {
                    String string = current.getDiscount().toString();
                    holder.product.setText(current.getProduct() + "\n" + string.substring(string.length() - 1) + "0% Discount  - " + current.getDiscounted_value());

                    holder.product.setId(position);

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

                    holder.total_amount.setText(String.valueOf(current.getActual_price_per_product()));
                    holder.total_amount.setId(position);

                    holder.qty.setText(current.getQuantity());
                    holder.qty.setId(position);
                } else {
                    holder.rate.setText(current.getProduct_rate());
                    holder.rate.setId(position);
                    holder.total_amount.setText(current.getTotal_amount());
                    holder.total_amount.setId(position);
                    holder.qty.setText(current.getQuantity());
                    holder.qty.setId(position);

                    if (!current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("Sample") || !current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("GWP")) {
                        holder.product.setText(current.getProduct() + " - Type - " + current.getStr_invoiceType());
                        holder.product.setId(position);
                    } else {
                        holder.product.setText(current.getProduct());
                        holder.product.setId(position);
                    }
                }
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView product, qty, rate, total_amount, txt_promo_str;
            LinearLayout select_promo_productRl, select_productRl;

            public MyViewHolder(View itemView) {
                super(itemView);
                product = (TextView) itemView.findViewById(R.id.product);
                qty = (TextView) itemView.findViewById(R.id.qty);
                rate = (TextView) itemView.findViewById(R.id.rate);
                total_amount = (TextView) itemView.findViewById(R.id.total_amount);
                txt_promo_str = (TextView) itemView.findViewById(R.id.txt_promo_str);
                select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl);
                select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl);
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        InvoiceReportProformaActivity.this.finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            InvoiceReportProformaActivity.this.finish();
        }

        return super.onOptionsItemSelected(item);
    }

    private void calculate_invoice_added_data(ArrayList<InvoiceGetterSetter> invoice_List) {
        double cCom = 0.0, total_INR_value = 0.0;
        try {
            for (int k = 0; k < invoice_List.size(); k++) {
                if (!invoice_List.get(k).isPromo_flag()) {
                    if (invoice_List.get(k).getDiscount() != 0.0) {
                        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(String.valueOf(amount));
                        cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                    } else {
                        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(String.valueOf(amount));
                    }

                    invoice_List.get(k).setStore_name(storeDataObject.getStoreName());
                    invoice_List.get(k).setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());

                    double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                    amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct;

                    total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount());

                    if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) {
                        invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount())));
                        invoice_List.get(k).setDiscounted_value(0.0);
                    } else {
                        invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()));
                        invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())));
                    }
                } else {
                    if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) {
                        if (invoice_List.get(k).getDiscount() != 0.0) {
                            int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                            double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate());
                            amount = amount * quantity;
                            amount = amount - Integer.parseInt(invoice_List.get(k).getSkuType());
                            invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                            cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                        } else {
                            int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                            double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate());
                            amount = amount * quantity;
                            amount = amount - Integer.parseInt(invoice_List.get(k).getSkuType());
                            invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                        }

                        invoice_List.get(k).setStore_name(storeDataObject.getStoreName());
                        invoice_List.get(k).setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
                        double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                        amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct;
                        if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) {
                            invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount())));
                            invoice_List.get(k).setDiscounted_value(0.0);
                        } else {
                            invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()));
                            invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())));
                        }

                        total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount());
                    } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffWorth") || invoice_List.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) {
                        off_worth_total = off_worth_total + Double.parseDouble(invoice_List.get(k).getProduct());
                    } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) {
                        off_worth_additional = off_worth_additional + Double.parseDouble(invoice_List.get(k).getProduct());
                    } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                        value_off_worth_additional = value_off_worth_additional + Double.parseDouble(invoice_List.get(k).getProduct());
                    } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("Worth")) {
                        worth_total = worth_total + Double.parseDouble(invoice_List.get(k).getProduct());
                    } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) {
                        OffSameProduct = OffSameProduct + Double.parseDouble(invoice_List.get(k).getProduct());
                    }
                }
            }


            total = total_INR_value - cCom;
            total = total - off_worth_total;
            total = total - value_off_worth_additional;
            total = total - worth_total;
            total = total - OffSameProduct;
            total = total - off_worth_additional;
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }
    }

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

    @SuppressLint("StaticFieldLeak")
    private class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        boolean flag = false;
        Dialog dialog = null;
        long l = 0;
        ProgressBar pb;

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

        @Override
        protected Void doInBackground(Boolean... bool) {
            l = calculate_data_insert_data();
            if (l > 0) {
                if (pos_sale_flag) {
                    if (CommonFunctions.checkNetIsAvailable(context)) {
                        CommonFunctions.call_upload(context);
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.cancel();
            if (l > 0) {
                startActivity(new Intent(context, ConsumerIntractionDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra("from", from));
                AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                InvoiceReportProformaActivity.this.finish();
            } else {
                AlertandMessages.showToastMsg(context, "Data not Saved.Please try again.");
            }
        }
    }

}
