package cpm.com.gskmtorange.gsk_dailyentry;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.dailyentry.OrderTakingActivity;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.StockFacing_PlanogramTrackerDataGetterSetter;

public class OrderStatusDetailActivity extends AppCompatActivity{
    ExpandableListView expandableListView;
    private Context context;
    TextView txt_mslAvailabilityName;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> headerDataList;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> childDataList;
    List<MSL_AvailabilityStockFacingGetterSetter> hashMapListHeaderData;
    HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> hashMapListChildData;
    List<Integer> checkHeaderArray = new ArrayList<>();
    boolean checkflag = true;    ExpandableListAdapter adapter;
    ImageView camera1, camera2, camera3, camera4;
    LinearLayout lin_camera1, lin_camera2, lin_camera3, lin_camera4;
    GSKOrangeDB db;
    String categoryName, categoryId, storeId, Error_Message = "";
    String store_id, store_flag_hide, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id, camera_allow, country_id, store_flag_str;
    boolean isDialogOpen = true;
    private SharedPreferences preferences;
    int scrollPosition = 0;

    String str_planogram = "", _pathforcheck = "";
    EditText storepoET,podateET;

    ArrayList<StockFacing_PlanogramTrackerDataGetterSetter> planogramShelfHeaderDataList = new ArrayList<>();
    ArrayList<StockFacing_PlanogramTrackerDataGetterSetter> planogramSkuChildDataList;
    HashMap<StockFacing_PlanogramTrackerDataGetterSetter, ArrayList<StockFacing_PlanogramTrackerDataGetterSetter>> planogramHashMapListChildData = new HashMap<>();
    boolean editFlag = false;
    //temp
    public static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/";
    //ImageView bmImage;
    RelativeLayout view;
    RadioButton radio_yes,radio_no;
    RadioGroup radio_group;
    String isExist="";
    String sys_po_number="";
    TextView sys_gen_poTV,lineitemTV;
    LinearLayout poLL;
    String storepo ="";
    TextView storepoTV,podateTV;
    String SYS_PO_NUM,PO_NUM,PO_DATE,LINE,POID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        try {
            setContentView(R.layout.activity_order_status_detail);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
            txt_mslAvailabilityName = (TextView) findViewById(R.id.txt_mslAvailabilityName);
            camera1 = (ImageView) findViewById(R.id.img_camera1);
            camera2 = (ImageView) findViewById(R.id.img_camera2);
            camera3 = (ImageView) findViewById(R.id.img_camera3);
            camera4 = (ImageView) findViewById(R.id.img_camera4);
            storepoTV =  findViewById(R.id.storepoTV);
            lineitemTV =  findViewById(R.id.lineitemTV);
            podateTV =  findViewById(R.id.podateTV);
            poLL = findViewById(R.id.poLL);

            sys_gen_poTV =  findViewById(R.id.sys_gen_poTV);
            podateTV = findViewById(R.id.podateTV);

            lin_camera1 = (LinearLayout) findViewById(R.id.lin_camera1);
            lin_camera2 = (LinearLayout) findViewById(R.id.lin_camera2);
            lin_camera3 = (LinearLayout) findViewById(R.id.lin_camera3);
            lin_camera4 = (LinearLayout) findViewById(R.id.lin_camera4);
            context = this;
            db = new GSKOrangeDB(this);
            db.open();

            //preference data
            preferences = PreferenceManager.getDefaultSharedPreferences(this);
            CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
            store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
            store_flag_hide = preferences.getString(CommonString.KEY_STORE_FLAG_FACING_HIDE, null);

            visit_date = preferences.getString(CommonString.KEY_DATE, null);
            date = preferences.getString(CommonString.KEY_DATE, null);
            username = preferences.getString(CommonString.KEY_USERNAME, null);
            intime = preferences.getString(CommonString.KEY_STORE_IN_TIME, "");
            keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
            class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
            storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
            camera_allow = preferences.getString(CommonString.KEY_CAMERA_ALLOW, "");
            country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
            store_flag_str = preferences.getString(CommonString.KEY_STORE_FLAG, null);


            //Intent data
            categoryName = getIntent().getStringExtra("categoryName");
            categoryId = getIntent().getStringExtra("categoryId");
            SYS_PO_NUM = getIntent().getStringExtra("SYS_PO_NUM");
            PO_NUM = getIntent().getStringExtra("PO_NUM");
            PO_DATE = getIntent().getStringExtra("PO_DATE");
            LINE = getIntent().getStringExtra("LINE");
            POID = getIntent().getStringExtra("POID");
           // Log.e("poid",POID);
           // Log.e("podetai",SYS_PO_NUM + ","+PO_NUM + ","+PO_DATE + ","+LINE);

           // toolbar.setTitle("Order Status" + "-"+"Entry");
            toolbar.setTitle(context.getString(R.string.order_status_entry));
            setSupportActionBar(toolbar);

            sys_gen_poTV.setText(SYS_PO_NUM);
            storepoTV.setText(PO_NUM);
            podateTV.setText(PO_DATE);
            lineitemTV.setText(LINE);

            // Log.e("sys_po_num",sys_po_number +","+timeMilli);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            str_planogram = CommonString.getDownloadedImageFolder(context);

            prepareList();

            //Camera
          //  prepareDefaultList();

           // cameraMethod();

            final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    expandableListView.clearFocus();
                    adapter.notifyDataSetChanged();

                        if (validateData(hashMapListHeaderData, hashMapListChildData)) {
                            db.open();
                            if (db.checkOrder_Received_Data(store_id, categoryId)) {
                                db.updateOrder_Received_data(storepoTV.getText().toString(), sys_gen_poTV.getText().toString(), podateTV.getText().toString(), store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                Toast.makeText(context, getResources().getString(R.string.update_message), Toast.LENGTH_SHORT).show();
                            } else {
                                db.InsertOrderReceivedStatusData(POID, storepoTV.getText().toString(), sys_gen_poTV.getText().toString(), podateTV.getText().toString(), store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                Toast.makeText(context, getResources().getString(R.string.save_message), Toast.LENGTH_SHORT).show();
                            }
                            finish();
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);

                           /* String order_received_xml = "";
                            String onXML = "";

                            ArrayList<MSL_AvailabilityStockFacingGetterSetter> orderreceiveddata = db.getOrder_RECEIVED_UploadServerData(store_id);

                            if (orderreceiveddata.size() > 0) {
                                for (int j = 0; j < orderreceiveddata.size(); j++) {
                                    onXML = "[ORDER_CONFIRM]"
                                            + "[MID]" + 0 + "[/MID]"
                                            + "[USERID]" + username + "[/USERID]"
                                            + "[CATEGORY_ID]" + orderreceiveddata.get(j).getCategory_id() + "[/CATEGORY_ID]"
                                            + "[PO_DATE]" + orderreceiveddata.get(j).getPO_Date() + "[/PO_DATE]"
                                            + "[POID]" + orderreceiveddata.get(j).getPOID() + "[/POID]"
                                            + "[SKU_ID]" + orderreceiveddata.get(j).getSku_id() + "[/SKU_ID]"
                                            + "[PO_QTY]" + orderreceiveddata.get(j).getOrderqty() + "[/PO_QTY]"
                                            + "[ACTUAL_QTY]" + orderreceiveddata.get(j).getFacing() + "[/ACTUAL_QTY]" +
                                            "[/ORDER_CONFIRM]";

                                    order_received_xml = order_received_xml + onXML;
                                }

                                final String sos_xml = "[DATA]" + order_received_xml + "[/DATA]";
                                Log.e("order_xml", sos_xml);

                        } */

                        }
                        else{
                            for (int i = 0; i < adapter.getGroupCount(); i++)
                                expandableListView.expandGroup(i);
                        }

                }
            });

            expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                    expandableListView.invalidate();

                    int lastItem = firstVisibleItem + visibleItemCount;

                    if (firstVisibleItem == 0) {
                        fab.show();//.setVisibility(View.VISIBLE);
                    } else if (lastItem == totalItemCount) {
                        fab.hide();//setVisibility(View.INVISIBLE);
                    } else {
                        fab.show();//setVisibility(View.VISIBLE);
                    }
                }

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

            // Listview Group click listener
            expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                    return false;
                }
            });

            // Listview Group expanded listener
            expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                @Override
                public void onGroupExpand(int groupPosition) {
                    InputMethodManager inputManager = (InputMethodManager) context
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (getWindow().getCurrentFocus() != null) {
                        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        getCurrentFocus().clearFocus();
                    }
                }
            });

            // Listview Group collasped listener
            expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
                @Override
                public void onGroupCollapse(int groupPosition) {
                    InputMethodManager inputManager = (InputMethodManager) context
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (getWindow().getCurrentFocus() != null) {
                        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        getCurrentFocus().clearFocus();
                    }
                }
            });

            // Listview on child click listener
            expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                            int childPosition, long id) {
                    return false;
                }
            });
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        
    }

    boolean validateData(List<MSL_AvailabilityStockFacingGetterSetter> listDataHeader,
                         HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> listDataChild) {
        boolean flag = true, child_flag = true, all_flag = true;
        checkHeaderArray.clear();
        int childCount = 0;
        //temp list data for empty only
        List<MSL_AvailabilityStockFacingGetterSetter> listDataHeaderTemp = new ArrayList<>();
        HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> listDataChildTemp = new HashMap<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            flag = true;

            List<MSL_AvailabilityStockFacingGetterSetter> listTemp = new ArrayList<>();
            for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) {
                child_flag = true;
                MSL_AvailabilityStockFacingGetterSetter data = listDataChild.get(listDataHeader.get(i)).get(j);

                String faceup = data.getFacing();
               // Log.e("facevalue",faceup);

                //Company_id
                if (listDataChild.get(listDataHeader.get(i)).get(j).getCompany_id().equals("1")) {
                    if (store_flag_hide.equals("0")) {
                        if (faceup.equals("")) {
                            if (!checkHeaderArray.contains(i)) {
                                checkHeaderArray.add(i);
                            }
                           // scrollPosition = i + j + childCount;
                            all_flag = false;
                            flag = false;
                            child_flag = false;
                            Error_Message = getResources().getString(R.string.faceup_value);
                           // Toast.makeText(context, getResources().getString(R.string.faceup_value), Toast.LENGTH_SHORT).show();
                            Toast.makeText(context, getResources().getString(R.string.pls_fill_order_qty), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                if (!child_flag)
                    listTemp.add(data);
            }

            if (flag == false) {
                listDataHeaderTemp.add(listDataHeader.get(i));
               // listDataChildTemp.put(listDataHeader.get(i), listTemp);
            } else {
                childCount = childCount + listDataChild.get(listDataHeader.get(i)).size();
            }
        }

        if (!all_flag) {
            adapter.notifyDataSetChanged();
            /*adapter = new ExpandableListAdapter(this, listDataHeaderTemp, listDataChildTemp);
            expandableListView.setAdapter(adapter);*/
            checkflag = false;
        } else {
            checkflag = true;
        }
        return all_flag;
    }

    private void prepareList() {
       // Log.e("store_flag_hide",store_flag_hide);
        try {
            hashMapListHeaderData = new ArrayList<>();
            hashMapListChildData = new HashMap<>();

            //Header
            if (country_id.equals("7") || country_id.equals("8")) {
              //  Log.e("childlistsize2", String.valueOf(headerDataList.size()));
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, null, null, null, store_id, CommonString.TABLE_MAPPING_STOCK_STOREWISE, CommonString.TABLE_MAPPING_SOS_TARGET, store_flag_hide);
            } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
               // Log.e("childlistsize1", String.valueOf(headerDataList.size()));
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, keyAccount_id, storeType_id, class_id, store_id, CommonString.TABLE_MAPPING_STOCK_ADHOC, CommonString.TABLE_MAPPING_SOS_TARGET_ADHOC, store_flag_hide);
            } else {
                //Log.e("categorydata",categoryId + ","+keyAccount_id + ","+storeType_id+","+class_id+","+store_id);
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, keyAccount_id, storeType_id, class_id, store_id, CommonString.TABLE_MAPPING_STOCK, CommonString.TABLE_MAPPING_SOS_TARGET, store_flag_hide);
              //  Log.e("childlistsize", String.valueOf(headerDataList.size()));
            }

            if (headerDataList.size() > 0) {
                for (int i = 0; i < headerDataList.size(); i++) {
                    hashMapListHeaderData.add(headerDataList.get(i));
                    //childDataList = new ArrayList<>();
                    childDataList = db.getOrder_RECEIVED_SKU_AfterSaveData(categoryId, headerDataList.get(i).getBrand_id(), store_id);
                    if (!(childDataList.size() > 0)) {
                        if (country_id.equals("7") || country_id.equals("8")) {
                            childDataList = db.getOrderReceivedSKUData(headerDataList.get(i).getSub_category_id(), categoryId, headerDataList.get(i).getBrand_id(), null, null, null, store_id, CommonString.TABLE_MAPPING_STOCK_STOREWISE, store_flag_hide);
                        } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                            childDataList = db.getOrderReceivedSKUData(headerDataList.get(i).getSub_category_id(), categoryId, headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id, store_id, CommonString.TABLE_MAPPING_STOCK_ADHOC, store_flag_hide);
                        } else {
                            //childDataList = db.getMSL_Availability_StockFacingSKUData(headerDataList.get(i).getSub_category_id(), categoryId, headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id, store_id, CommonString.TABLE_MAPPING_STOCK, store_flag_hide);
                            childDataList = db.getOrderReceivedSKUData(headerDataList.get(i).getSub_category_id(), categoryId, headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id, store_id, CommonString.TABLE_MAPPING_STOCK, store_flag_hide);
                        }
                    }
                    else{

                    }
                    hashMapListChildData.put(hashMapListHeaderData.get(i), childDataList);
                }
            }

            adapter = new ExpandableListAdapter(this, hashMapListHeaderData, hashMapListChildData);
            expandableListView.setAdapter(adapter);

            //expand all
            for (int i = 0; i < adapter.getGroupCount(); i++)
                expandableListView.expandGroup(i);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

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

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

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

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MSL_AvailabilityStockFacingGetterSetter headerTitle = (MSL_AvailabilityStockFacingGetterSetter) getGroup(groupPosition);

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_order_taking, null, false);
            }

            TextView txt_categoryHeader = (TextView) convertView.findViewById(R.id.txt_categoryHeader);
            RelativeLayout rel_header = (RelativeLayout) convertView.findViewById(R.id.rel_categoryHeader);
            ImageView img_camera = (ImageView) convertView.findViewById(R.id.img_camera);
            CardView card_view = (CardView) convertView.findViewById(R.id.card_view);

            txt_categoryHeader.setTypeface(null, Typeface.BOLD);

            if (headerTitle.getCompany_id().equals("1")) {
                txt_categoryHeader.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            } else {
                txt_categoryHeader.setTextColor(getResources().getColor(R.color.black));
            }
            txt_categoryHeader.setText(headerTitle.getSub_category() + "-" + headerTitle.getBrand());


            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                } else {
                    card_view.setCardBackgroundColor(getResources().getColor(R.color.grey_background));
                }
            }

            //empty check color change
            /*if (headerTitle.getCompany_id().equals("1")) {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        //card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                    }
                }
            } else {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.black));
                    }
                }
            }*/

            return convertView;
        }

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

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

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

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
                                 View convertView, ViewGroup parent) {

            final MSL_AvailabilityStockFacingGetterSetter childData =
                    (MSL_AvailabilityStockFacingGetterSetter) getChild(groupPosition, childPosition);
            OrderStatusDetailActivity.ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_order_received_status_child, null, false);
                holder = new OrderStatusDetailActivity.ViewHolder();
                holder.cardView = (CardView) convertView.findViewById(R.id.card_view);
                holder.lin_category = (LinearLayout) convertView.findViewById(R.id.lin_category);
                holder.txt_skuName = (TextView) convertView.findViewById(R.id.txt_skuName);
                holder.poqtyTV = (TextView) convertView.findViewById(R.id.poqtyTV);
                holder.txt_mbq = (TextView) convertView.findViewById(R.id.txt_mbq);
                holder.toggle_available = (ToggleButton) convertView.findViewById(R.id.toggle_available);
                holder.facing = (EditText) convertView.findViewById(R.id.ed_facing);
                holder.facing.setFilters(new InputFilter[]{new OrderStatusDetailActivity.DecimalDigitsInputFilter(3, 1)});
                holder.stock = (EditText) convertView.findViewById(R.id.ed_stock);
                holder.ed_pricing = (EditText) convertView.findViewById(R.id.ed_pricing);

                holder.facing_view = convertView.findViewById(R.id.facing_view);
                holder.stock_view = convertView.findViewById(R.id.stock_view);
                holder.pricing_view = convertView.findViewById(R.id.pricing_view);
                convertView.setTag(holder);
            } else {
                holder = (OrderStatusDetailActivity.ViewHolder) convertView.getTag();
            }

            holder.poqtyTV.setText(context.getString(R.string.po_qty) + ":"+childData.getOrderqty());
           // holder.poqtyTV.setText("PO QTY" + ":"+childData.getOrderqty());
            // uae facing hide
            /*if (store_flag_hide.equals("1")) {
                holder.facing.setVisibility(View.GONE);
                holder.facing_view.setVisibility(View.GONE);
            } else {
                holder.facing.setVisibility(View.VISIBLE);
                holder.facing_view.setVisibility(View.VISIBLE);
            }*/
            //usk
           /* if (childData.getPricing().equals("0")) {
                holder.ed_pricing.setVisibility(View.GONE);
                holder.pricing_view.setVisibility(View.GONE);
                holder.ed_pricing.setId(childPosition);
                holder.pricing_view.setId(childPosition);
            } else {
                holder.ed_pricing.setVisibility(View.VISIBLE);
                holder.pricing_view.setVisibility(View.VISIBLE);
                holder.ed_pricing.setId(childPosition);
                holder.pricing_view.setId(childPosition);
            }*/

            holder.txt_skuName.setText(childData.getSku());
            // holder.txt_mbq.setText(childData.getMbq());

           /* if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.colorOrange));

                //holder.txt_mbq.setVisibility(View.VISIBLE);
                holder.toggle_available.setVisibility(View.VISIBLE);
                // holder.facing.setVisibility(View.VISIBLE);
                if (country_id.equals("6")) {
                    holder.stock.setVisibility(View.VISIBLE);
                    holder.stock_view.setVisibility(View.VISIBLE);
                } else {
                    if (childData.getToggleValue().equals("1")) {
                        holder.stock.setVisibility(View.GONE);
                        holder.stock_view.setVisibility(View.GONE);
                    } else {
                        holder.stock.setVisibility(View.VISIBLE);
                        holder.stock_view.setVisibility(View.VISIBLE);
                    }
                }


            } else {

                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
              //  holder.txt_mbq.setVisibility(View.GONE);
                holder.toggle_available.setVisibility(View.GONE);
                // holder.facing.setVisibility(View.VISIBLE);
                holder.stock.setVisibility(View.GONE);
                holder.stock_view.setVisibility(View.GONE);
            }*/

            if (childData.getCompany_id().equals("1")) {
                holder.txt_skuName.setTextColor(getResources().getColor(R.color.colorPrimary));
            } else {
                holder.txt_skuName.setTextColor(getResources().getColor(R.color.black));
            }


            final OrderStatusDetailActivity.ViewHolder finalHolder = holder;
            holder.toggle_available.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (buttonView.isPressed()) {

                        editFlag = true;

                        if (isChecked) {
                            childData.setToggleValue("1");
                            //for Egypt
                            if (country_id.equals("6")) {
                                finalHolder.stock.setVisibility(View.VISIBLE);
                            } else {
                                finalHolder.stock.setVisibility(View.GONE);
                            }

                        /*childData.setStock("");
                        childData.setFacing("");*/
                        } else {
                       /* childData.setStock("");
                        childData.setFacing("");*/
                            childData.setToggleValue("0");
                            finalHolder.stock.setVisibility(View.VISIBLE);

                            //If MBQ Value is 0
                            if (Integer.parseInt(childData.getMbq()) == 0) {
                                childData.setStock("0");
                                childData.setFacing("0");
                            } else {
                                //for Egypt
                                if (country_id.equals("6")) {
                                    childData.setStock("");
                                    childData.setFacing("");
                                }
                            }

                        /* else {
                            if (finalHolder.facing.getText().toString() != null && !finalHolder.facing.getText().toString().equals("")) {
                                if (Integer.parseInt(finalHolder.facing.getText().toString()) >= 0
                                        && Integer.parseInt(finalHolder.facing.getText().toString()) >= Integer.parseInt(childData.getMbq())) {
                                    childData.setFacing("");
                                    finalHolder.facing.setText("");
                                }
                            }
                        }*/
                        }

                        expandableListView.clearFocus();
                        expandableListView.invalidateViews();
                    }
                }
            });

            /*if (childData.getToggleValue().equals("1")) {
                holder.toggle_available.setChecked(true);
                if (country_id.equals("6") && childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                    finalHolder.stock.setVisibility(View.VISIBLE);
                } else {
                    finalHolder.stock.setVisibility(View.GONE);
                    childData.setStock("");
                }


            } else {
                holder.toggle_available.setChecked(false);
                finalHolder.stock.setVisibility(View.VISIBLE);
            }*/


            /*holder.stock.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    final EditText caption = (EditText) v;
                    String edStock = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                    *//*if (!childData.getFacing().equals("") && Integer.parseInt(stock) >= 0 && Integer.parseInt(childData.getFacing()) < Integer.parseInt(stock)) {

                    }*//*
                    editFlag = true;
                    if (!edStock.equals("")) {
                        String stock = edStock;

                        //for Egypt
                        if (country_id.equals("6") && childData.getToggleValue().equals("1")) {
                            if (!childData.getFacing().equals("")) {
                                if (Integer.parseInt(stock) >= 0 && Double.parseDouble(childData.getFacing()) <= Integer.parseInt(stock)) {

                                    childData.setStock(stock);
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(OrderStatusDetailActivity.this);
                                    builder.setMessage(getString(R.string.check_faceup))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    finalHolder.stock.setText("");
                                                    dialog.dismiss();

                                                }
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            } else {
                                childData.setStock(stock);
                            }
                        } else {
                            int mbq = Integer.parseInt(childData.getMbq());
                            if (mbq != 0) {
                                if (Integer.parseInt(stock) >= 0 && Integer.parseInt(stock) < mbq) {

                                    if (!childData.getFacing().equals("")) {
                                        if (Integer.parseInt(stock) >= 0 && Double.parseDouble(childData.getFacing()) <= Integer.parseInt(stock)) {

                                            childData.setStock(stock);
                                        } else {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(OrderStatusDetailActivity.this);
                                            builder.setMessage(getString(R.string.check_faceup))
                                                    .setCancelable(false)
                                                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int id) {
                                                            finalHolder.stock.setText("");
                                                            dialog.dismiss();

                                                        }
                                                    });
                                            AlertDialog alert = builder.create();
                                            alert.show();
                                        }
                                    } else {
                                        childData.setStock(stock);
                                    }
                                } else {
                                    if (isDialogOpen) {
                                        isDialogOpen = !isDialogOpen;
                                        AlertDialog.Builder builder = new AlertDialog.Builder(OrderStatusDetailActivity.this);
                                        builder.setMessage(getString(R.string.check_stock))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        finalHolder.stock.setText("");
                                                        dialog.dismiss();
                                                        isDialogOpen = !isDialogOpen;
                                                    }
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                }
                            } else {
                                if (Integer.parseInt(stock) > 0) {
                                    if (isDialogOpen) {
                                        isDialogOpen = !isDialogOpen;
                                        AlertDialog.Builder builder = new AlertDialog.Builder(OrderStatusDetailActivity.this);
                                        builder.setMessage(getString(R.string.check_stock))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        finalHolder.stock.setText("");
                                                        dialog.dismiss();
                                                        isDialogOpen = !isDialogOpen;
                                                    }
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                }
                            }
                        }
                    } else {
                        childData.setStock("");
                    }
                }
            });*/
            /* holder.stock.setText(childData.getStock());*/

            /*holder.ed_pricing.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        final EditText Caption = (EditText) v;
                        String value1 = Caption.getText().toString().replaceFirst("^0+(?!$)", "");
                        if (value1.equals("")) {
                            childData.setPricingStock("");
                            finalHolder.ed_pricing.setText("");
                            finalHolder.ed_pricing.setId(childPosition);
                        } else {
                            childData.setPricingStock(value1);
                            finalHolder.ed_pricing.setText(value1);
                            finalHolder.ed_pricing.setId(childPosition);
                        }
                    }
                }
            });*/

            // holder.ed_pricing.setText(childData.getPricingStock());


            final OrderStatusDetailActivity.ViewHolder finalHolder1 = holder;
            final OrderStatusDetailActivity.ViewHolder finalHolder2 = holder;
            holder.facing.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    final EditText caption = (EditText) v;
                    String edFaceup = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                    editFlag = true;

                    if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                        //int num = Integer.parseInt(edFaceup);
                        double faceup = Double.parseDouble(edFaceup);
                        int num = (int) faceup;
                        //int faceint = (int)(faceup - Math.floor( faceup ));
                        int faceint = (int) ((faceup % 1.0) * 10);
                        if (faceint != 0) {
                            if ((faceup % 1.0) * 10 != 5) {
                                faceint = 5;
                                edFaceup = String.valueOf(num + faceint / 10.0);
                                finalHolder2.facing.setText(edFaceup);
                            }
                        }


                        /*Double faceup = Double.parseDouble(edFaceup);
                        DecimalFormat twoDForm = new DecimalFormat(".#");
                        faceup=  Double.valueOf(twoDForm.format(faceup));*/
                    }


                    boolean isFill = false;

                    //Toggle is no selected

                    if (country_id.equals("6")) {
                        if (!childData.getStock().equals("")) {

                            String faceup = edFaceup.replaceFirst("^0+(?!$)", "");

                            if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                                if (Double.parseDouble(faceup) <= Integer.parseInt(childData.getStock())) {

                                    isFill = true;

                          /*          if (!edFaceup.equals("")) {
                                        childData.setFacing(faceup);
                                    } else {
                                        childData.setFacing("");
                                    }*/
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(OrderStatusDetailActivity.this);
                                    builder.setMessage(getString(R.string.check_faceup))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    finalHolder1.facing.setText("");
                                                    dialog.dismiss();
                                                    finalHolder2.facing.setText("");
                                                }
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            } else {
                                isFill = true;
                            }
                            //  }
                        } else {
                            isFill = true;
                        }
                    } else {
                        isFill = true;
                    }

                    if (isFill) {
                        if (!edFaceup.equals("") && !edFaceup.equals(".")) {
                            String faceup = "";
                            if (edFaceup.equals("0") || edFaceup.equals(".0")) {
                                faceup = "0";
                            } else {
                                faceup = edFaceup.replaceFirst("^0+(?!$)", "");
                                //faceup = new DecimalFormat("##.#").format(Double.parseDouble(faceup));
                            }

                            // String str2 = PerfectDecimal(faceup, 3, 1);
                            childData.setFacing(faceup);
                        } else {
                            childData.setFacing("");
                        }
                    }
                }
            });

            holder.facing.setText(childData.getFacing());

            //empty check color change
            if (!checkflag) {
                boolean tempflag = false;
                //usk pricing
                /*if (!childData.getPricing().equals("0")) {
                    if (holder.ed_pricing.getText().toString().equals("")) {
                        holder.ed_pricing.setBackgroundColor(getResources().getColor(R.color.white));
                        holder.ed_pricing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.ed_pricing.setHint(getString(R.string.empty));
                        tempflag = true;
                    }
                }*/

                if (holder.facing.getText().toString().equals("")) {
                    holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                    holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    holder.facing.setHint(getString(R.string.empty));
                    tempflag = true;
                }

                if (childData.getCompany_id().equals("1")) {
                    holder.facing.setHint("");
                  /*  if (childData.getToggleValue().equals("0")) {
                        if (holder.stock.getText().toString().equals("")) {
                            holder.stock.setBackgroundColor(getResources().getColor(R.color.white));
                            holder.stock.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                            holder.stock.setHint(getString(R.string.empty));
                            tempflag = true;
                        }

                        if (holder.facing.getText().toString().equals("")) {
                            holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                            holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                            holder.facing.setHint(getString(R.string.empty));
                            tempflag = true;
                        }
                    } else {

                    }*/
                    if (tempflag) {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.lin_category.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        if (childData.getCompany_id().equals("1")) {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.colorOrange));
                        } else {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                        }
                    }
                } else {
                    if (holder.facing.getText().toString().equals("")) {
                        holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                        holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.facing.setHint(getString(R.string.empty));
                        tempflag = true;
                    }

                    if (tempflag) {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.lin_category.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        if (childData.getCompany_id().equals("1")) {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.colorOrange));
                        } else {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                        }
                    }
                }
            }

            return convertView;
        }

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

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
    public class ViewHolder {
        CardView cardView;
        TextView txt_skuName, txt_mbq,poqtyTV;
        ToggleButton toggle_available;
        LinearLayout lin_category;
        EditText facing, stock, ed_pricing;
        View stock_view, pricing_view, facing_view;
    }

    public class DecimalDigitsInputFilter implements InputFilter {
        Pattern mPattern;

        public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher matcher = mPattern.matcher(dest);
            if (!matcher.matches())
                return "";
            return null;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //return super.onOptionsItemSelected(item);
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
        return super.onOptionsItemSelected(item);
    }

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