import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme } from "../styles/Global";
import { TextInput, View, Text, TouchableOpacity, FlatList, Alert, KeyboardAvoidingView, Animated, AppState, Platform, Keyboard } from 'react-native';
import { connect, } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { checkMDStockScreenExists, getKPIFields, getKPIFieldsWithSpecific, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db, } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import GradientButton from '../components/gradientButton';
import CustomModal from '../components/CustomModal';
import { CustomPicker } from '../components/CustomPicker';
import { ConfirmSaveAlert } from '../components/alert';

function MiddayStock(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState(ST.Loadingwithdots);
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [KPIFieldsWithoutFilter, setKPIFieldsWithoutFilter] = useState([]);
    const [isMiddayStockReceived, setIsMiddayStockReceived] = useState(0);
    const animatedChoice = useRef(new Animated.Value(0)).current;
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SKUStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const isMiddayStockRef = React.useRef(isMiddayStockReceived);
    //filter states
    const [globalBrandData, setGlobalBrandData] = useState([]);
    const [filtervalue, setFilterValue] = useState({});
    const [catfilter, setcatFilter] = useState([]);
    const [subcatfilter, setsubcatFilter] = useState([]);
    const [brandfilter, setbrandFilter] = useState([]);
    const [searchedItem, setSearchedItem] = useState('');
    const defCat = { "CategoryId": "", "CategoryName": "-Select-" };
    const defSubCat = { 'SubCategoryId': "", 'SubCategoryName': "-Select-" };
    const defBrand = { 'BrandId': "", 'BrandName': "-Select-" };
    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    const [searchedmiddyItem, setSearchedMiddyItem] = useState('');
    const [filterData, setFilterData] = useState([]);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const handleSearch = text => {
        setSearchedMiddyItem(text);
        const filteredList = brandData[0].skulist?.filter(item => {
            console.log(item?.ProductName, 'item....JJJj....');
            return (
                item?.ProductName?.toLowerCase()?.includes(text?.toLowerCase())
                //   ||  item?.ChildName?.toLowerCase()?.includes(text?.toLowerCase())
            );
        });
        setFilterData(filteredList);
    };
    const inputRefs = useRef({});
    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');
    // ✅ single object state for all colors
    const [MSLDataInfo, setMSLDataInfo] = useState({
        Color_MSL: "",
        isMSLProduct: false,
        Color_NONMSL: "",
        isNonMSLProduct: false,
        Color_Competition: "",
        isCompProduct: false
    });

    useEffect(() => {
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};

        let isAdhoc = params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        getData(storeData1, menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(SKUStockData,pro)});     
            return unsubscribe;
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                isMiddayStockReceived1: isMiddayStockRef.current,
                visiteDate: d2
            }
            let WindowsStr = JSON.stringify(newData)
            await set_item('storeData', WindowsStr);
        }
    }


    useEffect(() => {
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);

    function onBeforeRemove(e) {
        if (hasUnsavedChanges == true) {
            e.preventDefault(); // Prevent default behavior of leaving the screen
            onRemoveScreen(e);
        }
        else {
            return;
        }
    }

    function BgUnsavedChanges(val) {
        hasUnsavedChangesRef.current = val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val) {
        WindowDataRef.current = val
        setSKUStockData(val);
    }

    function BgisMiddayRec(val) {
        isMiddayStockRef.current = val
        setIsMiddayStockReceived(val);
    }

    function onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: ST.Ok, onPress: async () => {
                        // setHasUnsavedChanges(false);
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

    async function getData(storeData1, menu1) {
        try {
            let { StoreId } = storeData1;
            let allCats = [];
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            let AllKPIFieldsWithoutFilter = await getKPIFieldsWithSpecific();
            setKPIFieldsWithoutFilter(AllKPIFieldsWithoutFilter)
            ///get MSL Info
            const result = await fetchDataFromDB(storeData1, AllKPIFieldsWithoutFilter, AllKPIFields);
            setMSLDataInfo(result)
            await db.transaction(async function (txn) {
                let join = ' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
                let join2 = ` INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId `;
                let q = `SELECT DISTINCT c.CategoryId,c.CategoryName,'' as MSL from Master_Category c ${join} ${join2}  where mp.StoreId='${StoreId}' order by p.CategorySequence`;
                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [], arr2 = [defCat];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let catobj = { "CategoryId": data.CategoryId, "CategoryName": data.CategoryName }
                            arr.push(data);
                            arr2.push(catobj);
                            if (i == txnres2.rows.length - 1) {
                                setcatFilter(arr2);
                                setrerenderdata(!rerenderdata);
                                getSKU(arr, storeData1, menu1);
                            }
                        }

                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function getSKU(brands = [], storeData1 = {}, menu1 = {}) {
        try {
            let { StoreId, } = storeData1;
            let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
            let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
            let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
            let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
            let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
            let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
            let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
            let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
            let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;

            let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
            let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
            let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;

            let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
            let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
            let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;
            let arr2 = [defSubCat];
            let arr3 = [defBrand];
            var allSKUData = [], storeBGData1 = [], isMiddayStockReceived2 = 0, bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData')
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, isMiddayStockReceived1, visiteDate } = StoreJson
                if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    isMiddayStockReceived2 = isMiddayStockReceived1
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    BgUnsavedChanges(true)
                    BgWindowData(storeBGData);
                }
            }

            await db.transaction(async function (txn) {
                await Promise.all(
                    brands.map(async (item, index) => {
                        let leftjoin = `  Left Outer join (select * from ${AppTables.SALES} where CATEGORY_ID='${item.CategoryId}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}' group by PRODUCT_ID ) sl on sl.PRODUCT_ID=p.ProductId`;
                        let join = `  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
                        let join2 = `  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                        let sku_q2 = `select distinct ifnull(sl.STOCK,'') as SALE_stock,p.ProductName,p.ProductId,p.SubCategoryName, p.SubCategoryId,p.BrandName,p.BrandId,m.MSL,m.ArticleCode,p.IsCompetitor from Product_Master p  ${join} ${join2} ${leftjoin} where m.StoreId='${StoreId}' and (p.CategoryId='${item.CategoryId}' or p.CategoryId= ${item.CategoryId}) and (CompanyId='1' or  CompanyId=1) ORDER BY m.MSL desc, p.IsCompetitor ASC, p.ProductName ASC`;

                        let seletlist = `distinct ifnull(sl.STOCK,'') as SALE_stock,s.MIDDAY_EXPIRYSTOCK1,s.MIDDAY_EXPIRYSTOCK2,s.MIDDAY_EXPIRYSTOCK3,s.MIDDAY_EXPIRYSTOCK4,s.PRODUCT as ProductName,s.PRODUCT_ID as ProductId,s.MSL,s.ARTICLE_CODE,s.MIDDAY_STOCK,s.OPENING_STOCK,s.EXPIRYSTOCK1,s.EXPIRYSTOCK2,s.EXPIRYSTOCK3,s.EXPIRYSTOCK4 ,s.CLOSING_STOCK,s.EXPIRY_ISOPEN,s.EXPIRY_STK,s.ISMDST_PRESENT,p.SubCategoryName, p.SubCategoryId,p.BrandName,p.BrandId,p.IsCompetitor `;
                        let join4 = `inner join Product_Master p on s.PRODUCT_ID=p.ProductId`;
                        let sku_q = `SELECT ${seletlist} FROM ${AppTables.STOCK_DATA} s ${join4} ${leftjoin} WHERE s.STORE_ID='${StoreId}' and s.VISIT_DATE='${d2}' and s.CATEGORY_ID='${item.CategoryId}' ORDER BY s.MSL desc, p.IsCompetitor ASC, p.ProductName ASC `;

                        return await txn.executeSql(sku_q, [], async function (txn2, txnres) {
                            if (txnres.rows.length > 0) {
                                let arr = [];
                                let IsMidDayPresent = 0;
                                for (var i = 0; i < txnres.rows.length; i++) {
                                    let data = txnres.rows.item(i);
                                    if (!isStockCalculateEnable) {
                                        inputRefs.current['input1_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    if (isExpStock1Enable) {
                                        inputRefs.current['input2_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    if (isExpStock2Enable) {
                                        inputRefs.current['input3_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    if (isExpStock3Enable) {
                                        inputRefs.current['input4_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    if (isExpStock4Enable) {
                                        inputRefs.current['input5_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    arr.push(data);

                                    let subcatIndex = arr2.findIndex(i => i.SubCategoryId == data.SubCategoryId)
                                    let subcatobj = { 'SubCategoryId': data.SubCategoryId, 'SubCategoryName': data.SubCategoryName }
                                    if (subcatIndex < 0) {
                                        arr2.push(subcatobj);

                                    }

                                    let subbrandIndex = arr3.findIndex(i => i.BrandId == data.BrandId)
                                    let subbrandobj = { 'BrandId': data.BrandId, 'BrandName': data.BrandName }
                                    if (subbrandIndex < 0) {
                                        arr3.push(subbrandobj);

                                    }

                                    let { menuName, StoreId1, visiteDate } = bgStoreJson
                                    if (isBgDataExists) {
                                        IsMidDayPresent = (isMiddayStockReceived2 == 1 || isMiddayStockReceived2 == '1') ? 1 : 0;
                                    } else {
                                        if (i == 0 && isMiddayStockReceived == 0) {
                                            console.log("data.ISMDST_PRESENT:", data.ISMDST_PRESENT);
                                            IsMidDayPresent = data.ISMDST_PRESENT == '1' ? 1 : 0;
                                        }
                                    }
                                    let defData = { 'CategoryId': item.CategoryId, 'ProductId': data.ProductId, 'MiddayStock': data.MIDDAY_STOCK, 'MIDDAY_ExpiryStock1': data.MIDDAY_EXPIRYSTOCK1, 'MIDDAY_ExpiryStock2': data.MIDDAY_EXPIRYSTOCK2, 'MIDDAY_ExpiryStock3': data.MIDDAY_EXPIRYSTOCK3, 'MIDDAY_ExpiryStock4': data.MIDDAY_EXPIRYSTOCK4, 'SALE_stock': data.SALE_stock };
                                    allSKUData.push(defData);
                                    if (i == txnres.rows.length - 1) {
                                        item['skulist'] = arr;
                                        brands[index] = item;
                                        if (index == brands.length - 1) {

                                            console.log('IsMidDayPresent:', IsMidDayPresent);
                                            Animated.timing(animatedChoice, {
                                                toValue: IsMidDayPresent,
                                                duration: 400,
                                                useNativeDriver: false,
                                            }).start();
                                            BgisMiddayRec(IsMidDayPresent)

                                            if (!isBgDataExists) {
                                                BgWindowData(allSKUData)
                                            }

                                            setBrandData(brands);
                                            setGlobalBrandData(brands);
                                            setsubcatFilter(arr2);
                                            setbrandFilter(arr3);
                                            setProcessing(false);
                                        }
                                        return item;
                                    }
                                }
                            }
                            else {
                                return await txn.executeSql(sku_q2, [], async function (txn2, txnres2) {
                                    if (txnres2.rows.length > 0) {
                                        let arr = [];
                                        for (var i = 0; i < txnres2.rows.length; i++) {
                                            let data = txnres2.rows.item(i);
                                            if (!isStockCalculateEnable) {
                                                inputRefs.current['input1_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock1Enable) {
                                                inputRefs.current['input2_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock2Enable) {
                                                inputRefs.current['input3_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock3Enable) {
                                                inputRefs.current['input4_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock4Enable) {
                                                inputRefs.current['input5_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            arr.push(data);
                                            let subcatIndex = arr2.findIndex(i => i.SubCategoryId == data.SubCategoryId)
                                            let subcatobj = { 'SubCategoryId': data.SubCategoryId, 'SubCategoryName': data.SubCategoryName }
                                            if (subcatIndex < 0) {
                                                arr2.push(subcatobj);
                                            }
                                            let subbrandIndex = arr3.findIndex(i => i.BrandId == data.BrandId)
                                            let subbrandobj = { 'BrandId': data.BrandId, 'BrandName': data.BrandName }
                                            if (subbrandIndex < 0) {
                                                arr3.push(subbrandobj);

                                            }
                                            if (i == (txnres2.rows.length - 1)) {
                                                item['skulist'] = arr;
                                                brands[index] = item;
                                                if (index == brands.length - 1) {
                                                    if (!isBgDataExists) {
                                                        BgWindowData(allSKUData)
                                                    } else {
                                                        let IsMidDayPresent = (isMiddayStockReceived2 == 1 || isMiddayStockReceived2 == '1') ? 1 : 0;
                                                        Animated.timing(animatedChoice, {
                                                            toValue: IsMidDayPresent,
                                                            duration: 400,
                                                            useNativeDriver: false,
                                                        }).start();
                                                        BgisMiddayRec(IsMidDayPresent)
                                                    }
                                                    setBrandData(brands);
                                                    setGlobalBrandData(brands);
                                                    setsubcatFilter(arr2);
                                                    setbrandFilter(arr3);
                                                    setProcessing(false);
                                                }
                                                return item;
                                            }
                                        }
                                    }
                                    else {
                                        return item;
                                    }
                                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        return item;
                    })
                );
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function focusToNext(cat, sku, type = '1') {
        let activeKey = '';
        let arr = Object.keys(inputRefs.current);
        activeKey = 'input' + type + '_' + cat.CategoryId + '_' + sku.ProductId;
        let activeIndex = arr.indexOf(activeKey);
        if (activeIndex < arr.length - 1) {
            let nextKey = arr[++activeIndex]
            let nextRef = inputRefs.current[nextKey];
            console.log("nextKey", nextKey, nextRef, inputRefs.current[nextKey])
            nextRef.focus();
        }
        else {
            return
        }
    }

    async function submitOpeningStock() {
        let isvalid = await validate();
        if (isvalid) {
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData() {
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);
        let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
        let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
        let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
        let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
        let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
        let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
        let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
        let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
        let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
        let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
        let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
        let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
        let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
        let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
        let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;

        try {
            let { StoreId, } = storeData;
            await db.transaction(async function (txn) {
                console.log("isMiddayStockReceived:", isMiddayStockReceived);
                if (isMiddayStockReceived == 0) {
                    let q = `UPDATE ${AppTables.STOCK_DATA} SET MIDDAY_STOCK='0',ISMDST_PRESENT='${isMiddayStockReceived}' WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`
                    await txn.executeSql(q, [], async function (txn2, txnres) {
                        afterUpdate();
                    }, function (txnE, txnerr) { console.log(txnerr); notify(ST.OopsErroroccurwhileupdatingMiddayStock); },);
                }
                else {

                    let q = `SELECT DISTINCT KEY_ID,CATEGORY_ID FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`
                    await txn.executeSql(q, [], async function (txn2, txnres) {
                        if (txnres.rows.length > 0) {
                            for (var i = 0; i < txnres.rows.length; i++) {
                                let catdata = txnres.rows.item(i);
                                let c_index = i;
                                let q2 = `SELECT * FROM ${AppTables.STOCK_DATA} WHERE CATEGORY_ID='${catdata.CATEGORY_ID}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`

                                await txn.executeSql(q2, [], async function (txn2, txnres2) {
                                    // console.log("Products count:",catdata.CATEGORY_ID,txnres2.rows.length);
                                    if (txnres2.rows.length > 0) {
                                        for (var j = 0; j < txnres2.rows.length; j++) {
                                            let skuData = txnres2.rows.item(j);
                                            let p_index = j, new_q = "";
                                            let thisCatSkuData_i = SKUStockData.findIndex(ci => ci.CategoryId == catdata.CATEGORY_ID && ci.ProductId == skuData.PRODUCT_ID);
                                            let thisCatSkuData = thisCatSkuData_i >= 0 ? (SKUStockData[thisCatSkuData_i] || {}) : {};
                                            let md_Stock = thisCatSkuData.MiddayStock != null && thisCatSkuData.MiddayStock != '' ? thisCatSkuData.MiddayStock : '0';

                                            let expStock1 = isExpStock1Enable == true ? (thisCatSkuData['MIDDAY_ExpiryStock1'] != null ? thisCatSkuData['MIDDAY_ExpiryStock1'] : '0') : '0';
                                            let expStock2 = isExpStock2Enable == true ? (thisCatSkuData['MIDDAY_ExpiryStock2'] != null ? thisCatSkuData['MIDDAY_ExpiryStock2'] : '0') : '0';
                                            let expStock3 = isExpStock3Enable == true ? (thisCatSkuData['MIDDAY_ExpiryStock3'] != null ? thisCatSkuData['MIDDAY_ExpiryStock3'] : '0') : '0';
                                            let expStock4 = isExpStock4Enable == true ? (thisCatSkuData['MIDDAY_ExpiryStock4'] != null ? thisCatSkuData['MIDDAY_ExpiryStock4'] : '0') : '0';

                                            console.log("Products Stock:", catdata.CATEGORY_ID, skuData.PRODUCT_ID, md_Stock);

                                            if (isStockCalculateEnable) {
                                                let StockData = parseInt(expStock1) + parseInt(expStock2) + parseInt(expStock3) + parseInt(expStock4)
                                                new_q = `UPDATE ${AppTables.STOCK_DATA} SET MIDDAY_STOCK='${(StockData || '0')}',ISMDST_PRESENT='${isMiddayStockReceived}', MIDDAY_EXPIRYSTOCK1=='${expStock1}',MIDDAY_EXPIRYSTOCK2=='${expStock2}',MIDDAY_EXPIRYSTOCK3=='${expStock3}',MIDDAY_EXPIRYSTOCK4=='${expStock4}'  WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${catdata.CATEGORY_ID}' and PRODUCT_ID='${skuData.PRODUCT_ID}' `;
                                            } else {
                                                new_q = `UPDATE ${AppTables.STOCK_DATA} SET MIDDAY_STOCK='${(md_Stock || '0')}',ISMDST_PRESENT='${isMiddayStockReceived}'  WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${catdata.CATEGORY_ID}' and PRODUCT_ID='${skuData.PRODUCT_ID}' `;
                                            }

                                            await txn.executeSql(new_q, [], async function (txn2, txnres3) {

                                                if (c_index == txnres.rows.length - 1 && p_index == txnres2.rows.length - 1) {
                                                    afterUpdate();
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); notify(ST.OopsErroroccurwhileupdatingMiddayStock) },);
                                        }
                                    } else {
                                        if (c_index == txnres.rows.length - 1) {
                                            setProcessing(false);
                                        }
                                    }
                                }, function (txnE, txnerr) { console.log(txnerr); },);
                            }
                        }
                        else {
                            setProcessing(false);
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function afterUpdate() {
        setProcessing(false);
        notify(ST.MiddayStockupdatedsuccessfully);
        props.navigation.goBack();
    }


    async function validate() {
        let isValid = true, isAnyFilled = false;
        var i = 0, j = 0, error_Type = "";
        let isMdStockMandIndex = KPIFields.findIndex(i => i.KPIFieldName == 'MidDayStockMandatory')
        let isMdStockMandKPIObj = isMdStockMandIndex >= 0 ? KPIFields[isMdStockMandIndex] : {};
        let isMdStockMandEnable = isMdStockMandIndex >= 0 ? isMdStockMandKPIObj['KPIFieldEnable'] : true;

        let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
        let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
        let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
        let isExpStock1DisplayName = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldDisplayName'] : "ExpStock 1";

        let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
        let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
        let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
        let isExpStock2DisplayName = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldDisplayName'] : "ExpStock 2";

        let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
        let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
        let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
        let isExpStock3DisplayName = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldDisplayName'] : "ExpStock 3";

        let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
        let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
        let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
        let isExpStock4DisplayName = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldDisplayName'] : "ExpStock 4";

        let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
        let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
        let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;


        if (isMiddayStockReceived == 1) {
            await Promise.all(
                globalBrandData.map(async (item, index) => {
                    if (isValid) {
                        let catId = item.CategoryId;
                        let errorobj = { 'EF_brand': item };
                        let skulist = item.skulist || [];
                        if (skulist.length > 0) {
                            await Promise.all(
                                skulist.map(async (skuItem, skuIndex) => {
                                    if (isValid) {
                                        let skuData = SKUStockData.find(ci => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId) || {};
                                        errorobj['EF_product'] = skuItem;
                                        let error_bid = item.CategoryId
                                        let error_pid = skuItem.ProductId
                                        console.log("OPS-----", skuItem.OPENING_STOCK)
                                        let show_errorH = false, error_HInputKey = '', error_HInputKeyEx1 = '', error_HInputKeyEx2 = '', error_HInputKeyEx3 = '', error_HInputKeyEx4 = '';
                                        if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && isStockCalculateEnable == false && skuData.MiddayStock !== 0 && (skuData.MiddayStock == null || skuData.MiddayStock == '')) {
                                            notify(ST.PleaseenterMiddayStockfor + skuItem.ProductName, 'SHORT');
                                            isValid = false;
                                            show_errorH = true, error_HInputKey = 'input1_', error_Type = 'input1_';
                                        }
                                        else if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && isStockCalculateEnable == false && skuData.MiddayStock != '' && parseInt(skuData?.SALE_stock) > (parseInt(skuData.MiddayStock) + parseInt(skuItem.OPENING_STOCK))) {
                                            notify('MidDay + Opening STOCK value must NOT BE LESS than entered SALE ' + ST.for + ' ' + skuItem.ProductName, 'LONG');
                                            isValid = false;
                                            show_errorH = true, error_HInputKey = 'input1_';
                                        }
                                        else if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && (isExpStock1Enable == true) && skuData.MIDDAY_ExpiryStock1 !== 0 && (skuData.MIDDAY_ExpiryStock1 == null || skuData.MIDDAY_ExpiryStock1 == '')) {
                                            notify(ST.Pleaseenter + isExpStock1DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                            isValid = false;
                                            show_errorH = true, error_HInputKeyEx1 = 'input2_', error_Type = 'input2_';
                                        } else if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && (isExpStock2Enable == true) && skuData.MIDDAY_ExpiryStock2 !== 0 && (skuData.MIDDAY_ExpiryStock2 == null || skuData.MIDDAY_ExpiryStock2 == '')) {
                                            notify(ST.Pleaseenter + isExpStock2DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                            isValid = false;
                                            show_errorH = true, error_HInputKeyEx2 = 'input3_', error_Type = 'input3_';
                                        } else if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && (isExpStock3Enable == true) && skuData.MIDDAY_ExpiryStock3 !== 0 && (skuData.MIDDAY_ExpiryStock3 == null || skuData.MIDDAY_ExpiryStock3 == '')) {
                                            notify(ST.Pleaseenter + isExpStock3DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                            isValid = false;
                                            show_errorH = true, error_HInputKeyEx3 = 'input4_', error_Type = 'input4_';
                                        } else if ((isMdStockMandEnable == 1 || isMdStockMandEnable == 'true') && (isExpStock4Enable == true) && skuData.MIDDAY_ExpiryStock4 !== 0 && (skuData.MIDDAY_ExpiryStock4 == null || skuData.MIDDAY_ExpiryStock4 == '')) {
                                            notify(ST.Pleaseenter + isExpStock4DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                            isValid = false;
                                            show_errorH = true, error_HInputKeyEx4 = 'input5_', error_Type = 'input5_';
                                        }

                                        if (skuData.MiddayStock === 0 || (skuData.MiddayStock != null && skuData.MiddayStock != '')) {
                                            isAnyFilled = true;
                                        } else if (skuData.MIDDAY_ExpiryStock1 === 0 || (skuData.MIDDAY_ExpiryStock1 != null && skuData.MIDDAY_ExpiryStock1 != '')) {
                                            isAnyFilled = true;
                                        } else if (skuData.MIDDAY_ExpiryStock2 === 0 || (skuData.MIDDAY_ExpiryStock2 != null && skuData.MIDDAY_ExpiryStock2 != '')) {
                                            isAnyFilled = true;
                                        } else if (skuData.MIDDAY_ExpiryStock3 === 0 || (skuData.MIDDAY_ExpiryStock3 != null && skuData.MIDDAY_ExpiryStock3 != '')) {
                                            isAnyFilled = true;
                                        } else if (skuData.MIDDAY_ExpiryStock4 === 0 || (skuData.MIDDAY_ExpiryStock4 != null && skuData.MIDDAY_ExpiryStock4 != '')) {
                                            isAnyFilled = true;
                                        }

                                        if (index == globalBrandData.length - 1 && skuIndex == skulist.length - 1 && !isAnyFilled) {
                                            notify(ST.PleaseenterMiddayStockforatleastoneProductIfnotpresentthenEnter0, 'SHORT');
                                            isValid = false;
                                        }

                                        if (show_errorH) {
                                            errorobj['EF_InputKey'] = error_HInputKey;
                                            errorobj['error_HInputKeyEx1'] = error_HInputKeyEx1;
                                            errorobj['error_HInputKeyEx2'] = error_HInputKeyEx2;
                                            errorobj['error_HInputKeyEx3'] = error_HInputKeyEx3;
                                            errorobj['error_HInputKeyEx4'] = error_HInputKeyEx4;

                                            setErrorField(errorobj)
                                            setError(true)
                                            let refIn1 = inputRefs.current[error_Type + error_bid + '_' + error_pid];
                                            refIn1.focus();
                                        }
                                    }
                                })
                            );
                        }
                    }
                })
            );
        }

        console.log('isValid:', isValid);
        return isValid;
    }

    function onStockValChange(item, skuItem, val, key, type = '') {
        setError(false)
        setErrorField({})
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }

        let allSKUData = SKUStockData;
        let defData = { 'CategoryId': item.CategoryId, 'ProductId': skuItem.ProductId };
        const skud_index = allSKUData.findIndex(i => i.CategoryId == item.CategoryId && i.ProductId == skuItem.ProductId);
        const skud = skud_index >= 0 ? (allSKUData[skud_index] || defData) : defData;
        skud[key] = val;

        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        // setSKUStockData(allSKUData);
        BgWindowData(allSKUData)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    // function onChoiceSelect(val) {
    //      setShowRAllC_M(true);
    //         return;
    //     var val1 = val == 1 ? 1 : 0;
    //     if (animatedChoice != null) {
    //         Animated.timing(animatedChoice, {
    //             toValue: val1,
    //             duration: 400,
    //             useNativeDriver: false,
    //         }).start();
    //     }
    //     // setIsMiddayStockReceived(val);
    //     BgisMiddayRec(val)
    //     // setHasUnsavedChanges(true);
    //     BgUnsavedChanges(true)
    // }

    function onChoiceSelect(val, key) {
        if (val == 0 && BgisMiddayRec.length > 0) {
            setShowRAllC_M(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        BgisMiddayRec(val)
        BgUnsavedChanges(true)
        if (val == 0) {
            BgisMiddayRec([])
        }
    }

    function onConfirmRemoveAll() {
        // Remove all data 
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        BgUnsavedChanges(true)
        BgWindowData([])
        BgisMiddayRec([])
        setShowRAllC_M(false);
    }
    function FilterStores(searchedQry) {
        searchedQry = searchedQry.toLowerCase();
        console.log('searchedQry', searchedQry);
        let arr = [];
        var arr2 = {};
        var newBrand = {};
        if (searchedQry != null && searchedQry != '') {
            // globalBrandData.map((item,index)=>{
            for (let i = 0; i < globalBrandData.length; i++) {
                let item = globalBrandData[i];
                let skulist = item.skulist || [];
                arr2 = Object.assign({ 'test': '1' }, item);
                let newSkulist = [];

                for (let j = 0; j < skulist.length; j++) {
                    let brand = skulist[j];

                    let { ProductName } = brand;
                    if (ProductName.toLowerCase().includes(searchedQry)) {
                        newSkulist.push(brand);
                    }
                }

                if (newSkulist.length > 0) {
                    let obj = { ...item, skulist: [...newSkulist] }
                    console.log("obj---", obj)
                    arr.push(obj);
                }

            }
        }
        else {
            arr = globalBrandData;
        }

        console.log('globalBrandData:', globalBrandData)
        setBrandData(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }


    // function FilterStores(searchedQry,filtervalue1){
    //     searchedQry=searchedQry.toLowerCase();
    //     console.log('searchedQry',searchedQry);
    //     let arr=[];
    //     let newBrandList=[];
    //     let filterCatId=filtervalue1.CategoryId;
    //     let filterSubCatId=filtervalue1.SubCategoryId;
    //     let filterBrandId=filtervalue1.BrandId;

    //     console.log('filterCatId',filterCatId)
    //     console.log('filterSubCatId',filterSubCatId)
    //     console.log('filterBrandId',filterBrandId)

    //     if((searchedQry!=null && searchedQry!='') || (filterCatId!=null && filterCatId!='') || (filterSubCatId!=null && filterSubCatId!='') || (filterBrandId!=null && filterBrandId!='') ){
    //         console.log('searchquerytrue')
    //         for(let i=0;i<globalBrandData.length;i++){
    //             let item=globalBrandData[i];
    //             // console.log('item',item)
    //             let {CategoryId}=item;
    //             let skulist=item.skulist || [];

    //             let newBrand=Object.assign({'test2':'2'} , item);
    //             let newSkulist=[];



    //             for(let j=0;j<skulist.length;j++){
    //                 let sku=skulist[j];
    //                 let {ProductName,SubCategoryId,BrandId}=sku;


    //                 let isQueryMatched=false,isCatMatch=false,isSubCatMatch=false,isBrandMatch=false;
    //                 if((searchedQry!=null && searchedQry!='') && ProductName.toLowerCase().includes(searchedQry)){

    //                     isQueryMatched=true;
    //                 }
    //                 else if(searchedQry==''|| searchedQry==null){
    //                     isQueryMatched=true;
    //                 }


    //                 if((filterCatId!=null && filterCatId!='') && filterCatId==CategoryId){
    //                     isCatMatch=true;

    //                 }
    //                 else if(filterCatId=='' || filterCatId==null){
    //                     isCatMatch=true;
    //                 }

    //                 if((filterSubCatId!=null && filterSubCatId!='') && filterSubCatId==SubCategoryId){
    //                     isSubCatMatch=true;

    //                 }
    //                 else if(filterSubCatId=='' || filterSubCatId==null){
    //                     isSubCatMatch=true;
    //                 }

    //                 if((filterBrandId!=null && filterBrandId!='') && filterBrandId==BrandId){
    //                     isBrandMatch=true;

    //                 }
    //                 else if(filterBrandId=='' || filterBrandId==null){
    //                     isBrandMatch=true;
    //                 }

    //                 if(isQueryMatched && isCatMatch && isSubCatMatch && isBrandMatch){
    //                     newSkulist.push(sku);
    //                 }

    //                 if(j==skulist.length-1){
    //                     newBrand.skulist=newSkulist;

    //                     if(newBrand.skulist.length>0){
    //                         newBrandList.push(newBrand);
    //                         // console.log('push',newBrandList.push(newBrand))
    //                         // console.log('newBrandList',newBrandList)
    //                         // console.log('newBrand',newBrand)


    //                     }
    //                 }
    //             }


    //         }
    //     }
    //     else{
    //         newBrandList=globalBrandData;
    //     }

    //     setBrandData(newBrandList);
    //     setrerenderdata(!rerenderdata)
    //     setrerenderdata2(!rerenderdata2)
    // }

    async function onselectionChange(option, keyLbl, keyVal, otherData) {
        // console.log('trueeeeeeeeeeee')
        setProcessing(true);
        // let CategoryName=otherData.CategoryName!=null?otherData.CategoryName:'';
        let data = filtervalue || {};
        // console.log('setFilterValue',data)
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        await FilterHierarchy(keyVal, option.value);
        if (keyVal == "CategoryId") {
            data["SubCategoryId"] = defSubCat.SubCategoryId;
            data["SubCategoryName"] = defSubCat.SubCategoryName;
            data["BrandId"] = defBrand.BrandId;
            data["BrandName"] = defBrand.BrandName;
        }
        else if (keyVal == "SubCategoryId") {
            data["BrandId"] = defBrand.BrandId;
            data["BrandName"] = defBrand.BrandName;
        }
        setFilterValue(data);
        FilterStores(searchedItem, data)
        console.log('filtersrores', searchedItem, data)

        setrerenderdata(!rerenderdata);
        setrerenderdata2(!rerenderdata2)
        setProcessing(false);
    }


    async function FilterHierarchy(keyVal, val) {

        let join = `  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;// assortment join

        let { StoreId, ChainId, StateId, StoreCategoryId, StoreClassId, StoreTypeId } = storeData
        if (keyVal == "CategoryId") {
            // Filter Brand based on category
            let brandq = `Select Distinct p.BrandId,p.BrandName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.CategoryId='${val}' or p.CategoryId= ${val}) and (CompanyId='1' or CompanyId=1) order by p.BrandSequence `;
            let brands = await executeQuery(brandq, [defBrand]);
            setbrandFilter(brands);
            // Filter Sub cats based on category
            let subcatq = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.CategoryId='${val}' or p.CategoryId= ${val}) and (CompanyId='1' or CompanyId=1) order by p.BrandSequence `;
            let subCats = await executeQuery(subcatq, [defSubCat]);
            setsubcatFilter(subCats);
        }
        else if (keyVal == "SubCategoryId") {
            // Filter Brands based on Sub-category
            let brandq = `Select Distinct p.BrandId,p.BrandName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.SubCategoryId='${val}' or p.SubCategoryId= ${val}) and (CompanyId='1' or CompanyId=1) order by p.BrandSequence `;
            let brands = await executeQuery(brandq, [defBrand]);
            setbrandFilter(brands);
        }
    }

    async function executeQuery(query, defData) {
        return await new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                await txn.executeSql(query, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let arr = defData;
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            arr.push(data);

                            if (i == txnres.rows.length - 1) {
                                resolve(arr);
                            }
                        }
                    }
                    else {
                        resolve(defData);
                    }

                }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);
                // setProcessing(false);
            });
        }).catch((err) => {
            console.log(err);
            return defData;
        })
    }

    function clearFilter(obj, key1, key2) {
        let fdata = filtervalue;
        fdata[key1] = obj[key1];
        fdata[key2] = obj[key2];
        if (key1 == "CategoryId") {
            fdata["SubCategoryId"] = defSubCat.SubCategoryId;
            fdata["SubCategoryName"] = defSubCat.SubCategoryName;
            fdata["BrandId"] = defBrand.BrandId;
            fdata["BrandName"] = defBrand.BrandName;
        }
        else if (key1 == "SubCategoryId") {
            fdata["BrandId"] = defBrand.BrandId;
            fdata["BrandName"] = defBrand.BrandName;
        }
        setFilterValue(fdata);
        FilterStores(searchedItem, fdata);
    }

    function _renderSalesFilter() {
        let salesCatFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'MDCatFilter')
        let salesCatFilterObj = salesCatFilterI >= 0 ? KPIFields[salesCatFilterI] : {};
        let salesCatFilter = salesCatFilterI >= 0 ? salesCatFilterObj['KPIFieldEnable'] : false;

        let salesSubCatFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'MDSubCatFilter')
        let salesSubCatFilterObj = salesSubCatFilterI >= 0 ? KPIFields[salesSubCatFilterI] : {};
        let salesSubCatFilter = salesSubCatFilterI >= 0 ? salesSubCatFilterObj['KPIFieldEnable'] : false;

        let salesBrandFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'MDBrandFilter')
        let salesBrandFilterObj = salesBrandFilterI >= 0 ? KPIFields[salesBrandFilterI] : {};
        let salesBrandFilter = salesSubCatFilterI >= 0 ? salesBrandFilterObj['KPIFieldEnable'] : false;

        if (rerenderdata == rerenderdata && (salesCatFilter || salesSubCatFilter || salesBrandFilter)) {
            return (
                <View>
                    {/* <View style={[customStyle.storel_searchbar2,,customStyle.mb10]}>
                    <TextInput 
                        style={[customStyle.storel_searchInput]}
                        placeholder={ST.SearchByProductName}
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color} 
                        value={searchedItem}
                        onChangeText={(val)=>{setSearchedItem(val); FilterStores(val,filtervalue)}}
                    />
                    
                    <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem,filtervalue)}}>
                        <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
                    </TouchableOpacity>
                </View> */}
                    {salesCatFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{ST.Category}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, catfilter, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: filtervalue.CategoryId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(catfilter[0], 'CategoryId', 'CategoryName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}

                    {salesSubCatFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{ST.SubCategorytrim}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, subcatfilter, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: filtervalue.SubCategoryId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(subcatfilter[0], 'SubCategoryId', 'SubCategoryName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}

                    {salesBrandFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{ST.Brand}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, brandfilter, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: filtervalue.BrandId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(brandfilter[0], 'BrandId', 'BrandName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}
                </View>
            )
        }
        else {
            return null;
        }
    }


    function _render_Alert() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={ST.Doyoureallywanttosavedata}
                showModal={showAlert}
            >
                <View style={customStyle.storelVisitM_options}>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowAlert(false) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { saveData() }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>{ST.Yes}</Text>
                    </TouchableOpacity>
                </View>
            </CustomModal>
        )
    }


    // ✅ async function OUTSIDE return(), INSIDE component
    const fetchDataFromDB = async (storeData, AllKPIFieldsWithoutFilter, AllKPIFields) => {
        let isColor_MSLIndex = AllKPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_MSL')
        let isColor_MSLObj = isColor_MSLIndex >= 0 ? AllKPIFieldsWithoutFilter[isColor_MSLIndex] : {};
        let isColor_MSLEnable = isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldEnable'] : false;
        let Color_MSL = isColor_MSLEnable && isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldDisplayName'] : ""

        let isColor_NONMSLIndex = AllKPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_NONMSL')
        let isColor_NONMSLObj = isColor_NONMSLIndex >= 0 ? AllKPIFieldsWithoutFilter[isColor_NONMSLIndex] : {};
        let isColor_NONMSLEnable = isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldEnable'] : false;
        let Color_NONMSL = isColor_NONMSLEnable && isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldDisplayName'] : ""

        let isColor_CompetitionIndex = AllKPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_Competition')
        let isColor_CompetitionObj = isColor_CompetitionIndex >= 0 ? AllKPIFieldsWithoutFilter[isColor_CompetitionIndex] : {};
        let isColor_CompetitionEnable = isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldEnable'] : false;
        let Color_Competition = isColor_CompetitionEnable && isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldDisplayName'] : ""
        console.log("Color_MSL----", Color_MSL, Color_NONMSL, Color_Competition)

        let COMPStockAllow_Index = AllKPIFields.findIndex(i => i.KPIFieldName == 'COMPStockAllow');
        let COMPStockAllow_Obj = COMPStockAllow_Index >= 0 ? AllKPIFields[COMPStockAllow_Index] : {};
        let isCOMPStockAllow = COMPStockAllow_Index >= 0 ? COMPStockAllow_Obj['KPIFieldEnable'] : false;
        let ShowCompetionSku = AllKPIFields?.findIndex((i) => i.KPIFieldName == "ShowCompetionSku");
        let ShowCompetionObj = ShowCompetionSku >= 0 ? AllKPIFields[ShowCompetionSku] : {};
        let ShowCompetionSkuNoSplitArr = ShowCompetionObj?.KPIFieldDisplayName?.split(",") || []
        const isCompetitorValues = ShowCompetionSkuNoSplitArr;
        let isCompetitorClause = !isCompetitorValues || isCompetitorValues.length === 0 ? "p.IsCompetitor = 0" : `p.IsCompetitor IN (${isCompetitorValues.join(",")})`;

        try {
            const menuQuery = `SELECT DISTINCT p.IsCompetitor, m.MSL FROM Product_Master p INNER JOIN Mapping_ProductAssortmentStorewise m ON p.ProductId = m.ProductId INNER JOIN Master_Category mc ON mc.CategoryId = p.CategoryId
                                    WHERE m.StoreId = '${storeData?.StoreId}' ${isCOMPStockAllow ? '' : `AND ${isCompetitorClause}`}`;

            const result = await new Promise((resolve, reject) => {
                db.transaction(txn => {
                    txn.executeSql(
                        menuQuery, [],
                        (txn2, txnres) => {
                            const len = txnres.rows.length;
                            let isMSLProduct = false, isNonMSLProduct = false, isCompProduct = false;
                            for (let i = 0; i < len; i++) {
                                let msls = txnres.rows.item(i);
                                console.log("msls------------", msls)
                                if (msls?.MSL === 1 && Color_MSL !== "") {
                                    isMSLProduct = true;
                                }
                                if (msls?.MSL === 0 && Color_NONMSL !== "") {
                                    isNonMSLProduct = true;
                                }
                                if (msls?.IsCompetitor === 1 && Color_Competition !== "") {
                                    isCompProduct = true;
                                }
                            }
                            resolve({
                                Color_MSL,
                                isMSLProduct,
                                Color_NONMSL,
                                isNonMSLProduct,
                                Color_Competition,
                                isCompProduct
                            });
                        }, (txn, err) => {
                            console.error('DB error:', err);
                            reject(err);
                            return true;
                        }
                    );
                });
            });

            return result;

        } catch (e) {
            console.log("Error", e);
            return {
                Color_MSL,
                isMSLProduct: false,
                Color_NONMSL,
                isNonMSLProduct: false,
                Color_Competition,
                isCompProduct: false
            };
        }
    };

    function ThreeColorIndicator() {
        return (
            <View
                style={{
                    flexDirection: 'row',
                    justifyContent: 'space-around',
                    alignItems: 'flex-end',
                    marginTop: 13,
                }}
            >
                {MSLDataInfo?.isMSLProduct && (
                    <View style={{ alignItems: 'center' }}>
                        <View
                            style={{
                                width: 60,
                                height: 15,
                                borderRadius: 2,
                                backgroundColor: MSLDataInfo?.Color_MSL,
                                marginBottom: 3,
                            }}
                        />
                        <Text style={{ color: 'black', fontWeight: '600', fontSize: 13 }}>MSL</Text>
                    </View>
                )}

                {MSLDataInfo?.isNonMSLProduct && (
                    <View style={{ alignItems: 'center' }}>
                        <View
                            style={{
                                width: 60,
                                height: 15,
                                borderRadius: 2,
                                backgroundColor: MSLDataInfo?.Color_NONMSL,
                                marginBottom: 3,
                            }}
                        />
                        <Text style={{ color: 'black', fontWeight: '600', fontSize: 13 }}>Non-MSL</Text>
                    </View>
                )}

                {MSLDataInfo?.isCompProduct && (
                    <View style={{ alignItems: 'center' }}>
                        <View
                            style={{
                                width: 60,
                                height: 15,
                                borderRadius: 2,
                                backgroundColor: MSLDataInfo?.Color_Competition,
                                marginBottom: 3,
                            }}
                        />
                        <Text style={{ color: 'black', fontWeight: '600', fontSize: 13 }}>Comp</Text>
                    </View>
                )}

            </View>
        );
    };

    function _renderStock() {
        let xpos = 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }


        let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
        let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
        let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
        let isExpStock1DisplayName = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldDisplayName'] : "ExpStock 1";

        let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
        let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
        let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
        let isExpStock2DisplayName = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldDisplayName'] : "ExpStock 2";

        let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
        let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
        let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
        let isExpStock3DisplayName = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldDisplayName'] : "ExpStock 3";

        let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
        let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
        let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
        let isExpStock4DisplayName = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldDisplayName'] : "ExpStock 4";

        let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
        let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
        let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;

        let isColor_MSLIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_MSL')
        let isColor_MSLObj = isColor_MSLIndex >= 0 ? KPIFieldsWithoutFilter[isColor_MSLIndex] : {};
        let isColor_MSLEnable = isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldEnable'] : false;
        let Color_MSL = isColor_MSLEnable && isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldDisplayName'] : ""

        let isColor_NONMSLIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_NONMSL')
        let isColor_NONMSLObj = isColor_NONMSLIndex >= 0 ? KPIFieldsWithoutFilter[isColor_NONMSLIndex] : {};
        let isColor_NONMSLEnable = isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldEnable'] : false;
        let Color_NONMSL = isColor_NONMSLEnable && isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldDisplayName'] : ""

        let isColor_CompetitionIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_Competition')
        let isColor_CompetitionObj = isColor_CompetitionIndex >= 0 ? KPIFieldsWithoutFilter[isColor_CompetitionIndex] : {};
        let isColor_CompetitionEnable = isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldEnable'] : false;
        let Color_Competition = isColor_CompetitionEnable && isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldDisplayName'] : ""
        console.log("Color_MSL----", Color_MSL, Color_NONMSL, Color_Competition)

        const getBackgroundStyle = (skus) => {
            console.log("skucvbn", skus)
            if (skus?.MSL && skus?.MSL === 1 && skus?.IsCompetitor === 0 && Color_MSL !== "") {
                return { backgroundColor: Color_MSL };
            }
            if (skus?.MSL === 0 && skus?.IsCompetitor === 0 && Color_NONMSL !== "") {
                return { backgroundColor: Color_NONMSL };
            }
            if (skus?.IsCompetitor === 1 && Color_Competition !== "") {
                return { backgroundColor: Color_Competition };
            }

            return null;
        };

        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior="position" enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -125)} >

                <View style={[customStyle.addvis_pCon]}>
                    <Text style={[customStyle.addvis_pText]}>{ST.StockReceived}</Text>
                    <View style={customStyle.addvis_pChoiceBoxCon}>
                        <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
                            <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isMiddayStockReceived == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                            {
                                transform: [{
                                    translateX: xpos
                                }],
                            }
                            ]}></Animated.View>
                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1) }}>
                                <Text style={[customStyle.openStkCh_text, (isMiddayStockReceived == 1 ? customStyle.openStkCh_textactive : {})]}>{ST.Yes}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0) }}>
                                <Text style={[customStyle.openStkCh_text, (isMiddayStockReceived == 0 ? customStyle.openStkCh_textactive : {})]}>{ST.No}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                {isMiddayStockReceived == '1' &&
                    <View style={customStyle.storel_searchbar}>
                        <TextInput
                            style={[customStyle.storel_searchInput]}
                            placeholder={ST.SearchByProductName}
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color}
                            value={searchedItem}
                            onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
                        />
                        <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
                            <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
                        </TouchableOpacity>
                    </View>
                }
                {/* "calling msl , non-msl and competitor products color indicator" */}
                {isMiddayStockReceived == '1' && !processing && ((MSLDataInfo?.isMSLProduct && MSLDataInfo?.Color_MSL !== "")
                    || (MSLDataInfo?.isNonMSLProduct && MSLDataInfo?.Color_NONMSL !== "")
                    || (MSLDataInfo?.isCompProduct && MSLDataInfo?.Color_Competition !== "")) && ThreeColorIndicator()}

                {isMiddayStockReceived == '1' &&
                    <FlatList
                        data={brandData}
                        extraData={rerenderdata}
                        ListHeaderComponent={_renderSalesFilter}
                        contentContainerStyle={[customStyle.opening_Stock_scroll]}
                        style={[customStyle.opening_Stock_scrollOuter]}
                        nestedScrollEnabled={true}
                        scrollToOverflowEnabled={true}
                        removeClippedSubviews={false}
                        legacyImplementation={true}
                        renderItem={({ item, index }) => {
                            const cat = item;
                            const catIndex = index;

                            // get error field brand id
                            let EF_brand = errorfield.EF_brand != null ? errorfield.EF_brand : {};
                            let error_bid = EF_brand.CategoryId || '';

                            return (
                                <View style={[customStyle.opening_Stock_wrap]}>

                                    {/* <View style={[
                        customStyle.storel_searchbar,
                        {marginHorizontal:1, marginTop:-10 }
                    ]}>
                     <TextInput 
                         style={[customStyle.storel_searchInput]}
                         placeholder={ST.SearchByProductName}
                         autoComplete='off'
                         placeholderTextColor={PageTheme.$placeholder_color} 
                         value={searchedmiddyItem}
                         onChangeText={text => handleSearch(text)}
                     />
                     
                     <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem,filtervalue)}}>
                         <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
                     </TouchableOpacity>
                     </View> */}
                                    <View style={customStyle.opening_Stock_prds}>
                                        {/* {filterData.length != 0 ?  */}
                                        <View style={[customStyle.opening_Stock_cat, customStyle.mt10,]}>
                                            <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                                <Text style={customStyle.opening_Stock_catText}>{item.CategoryName}</Text>
                                            </LinearGradient>

                                        </View>
                                        {/* :''} */}

                                        {<FlatList
                                            data={searchedmiddyItem !== '' ? filterData : item.skulist}
                                            //  data={item.skulist}
                                            extraData={rerenderdata2}
                                            nestedScrollEnabled={true}
                                            removeClippedSubviews={false}
                                            scrollToOverflowEnabled={true}
                                            legacyImplementation={true}
                                            renderItem={({ item, index }) => {
                                                const skus = item;
                                                const sku_index = index;
                                                let calVal = 0;
                                                let thisCatSkuData_i = SKUStockData.findIndex(i => i.CategoryId == cat.CategoryId && i.ProductId == skus.ProductId);
                                                let thisCatSkuData = thisCatSkuData_i >= 0 ? (SKUStockData[thisCatSkuData_i] || {}) : {};
                                                let md_Stock = thisCatSkuData.MiddayStock != null ? thisCatSkuData.MiddayStock : '';

                                                let ex_stock1 = thisCatSkuData.MIDDAY_ExpiryStock1 != null ? thisCatSkuData.MIDDAY_ExpiryStock1 : '';
                                                let ex_stock2 = thisCatSkuData.MIDDAY_ExpiryStock2 != null ? thisCatSkuData.MIDDAY_ExpiryStock2 : '';
                                                let ex_stock3 = thisCatSkuData.MIDDAY_ExpiryStock3 != null ? thisCatSkuData.MIDDAY_ExpiryStock3 : '';
                                                let ex_stock4 = thisCatSkuData.MIDDAY_ExpiryStock4 != null ? thisCatSkuData.MIDDAY_ExpiryStock4 : '';

                                                if (isStockCalculateEnable) {
                                                    calVal = parseInt(ex_stock1 || 0) + parseInt(ex_stock2 || 0) + parseInt(ex_stock3 || 0) + parseInt(ex_stock4 || 0)
                                                }
                                                // get error field product id
                                                let EF_product = errorfield.EF_product != null ? errorfield.EF_product : {};
                                                let error_pid = EF_product.ProductId || '';
                                                let EF_InputKey = errorfield.EF_InputKey;
                                                let show_errorhere = error_bid == cat.CategoryId && error_pid == skus.ProductId;

                                                let errorStyle_ST = (error && show_errorhere && EF_InputKey == 'input1_' ? customStyle.stk_inptSTyle_error : {});

                                                let error_HInputKeyEx1 = (error && show_errorhere && errorfield.error_HInputKeyEx1 == 'input2_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx2 = (error && show_errorhere && errorfield.error_HInputKeyEx2 == 'input3_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx3 = (error && show_errorhere && errorfield.error_HInputKeyEx3 == 'input4_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx4 = (error && show_errorhere && errorfield.error_HInputKeyEx4 == 'input5_' ? customStyle.stk_inptSTyle_error : {});

                                                return (
                                                    <View style={[customStyle.openStk_prd_Con, getBackgroundStyle(skus)]} key={sku_index}>
                                                        {/* <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text> */}
                                                        <Text style={customStyle.openStk_prd_name}>
                                                            {skus.ArticleCode && skus.ArticleCode.trim() !== ""
                                                                ? `${skus.ProductName} [${skus.ArticleCode}]`
                                                                : skus.ARTICLE_CODE && skus.ARTICLE_CODE.trim() !== ""
                                                                    ? `${skus.ProductName} [${skus.ARTICLE_CODE}]`
                                                                    : skus.ProductName}
                                                        </Text>
                                                        <View style={[customStyle.openStk_prddetails, customStyle.openStk_prd_borderT, customStyle.openStk_prd_borderB]}>
                                                            <View style={customStyle.openStk_prdd_wrap}>
                                                                <Text style={customStyle.openStk_prdd_flabel}>{ST.OpeningStock} :</Text>
                                                                <Text style={customStyle.openStk_prdd_fvalue}>{skus.OPENING_STOCK}</Text>
                                                            </View>
                                                        </View>
                                                        {isStockCalculateEnable == true &&
                                                            <View style={[customStyle.openStk_prd_row, { marginTop: 3 }]}>
                                                                <View style={[customStyle.openStk_prd_colflex]}>
                                                                    <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.MiddayStock}</Text>
                                                                    <TextInput
                                                                        editable={false}
                                                                        selectTextOnFocus={false}
                                                                        style={[customStyle.openStk_EXP_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2]}
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        value={(calVal == 0 ? "" : (calVal + '' || ''))}
                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                        maxLength={6}
                                                                        keyboardType='number-pad'
                                                                        blurOnSubmit={false}
                                                                    />
                                                                    <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "3%" }]}>{ST.OpS}</Text>
                                                                </View>
                                                            </View>
                                                        }
                                                        {isStockCalculateEnable != true &&
                                                            <View style={customStyle.openStk_prd_form}>
                                                                <View style={customStyle.openStk_prd_row}>
                                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.MiddayStock}</Text>
                                                                        <TextInput
                                                                            ref={(reff) => { inputRefs.current['input1_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, errorStyle_ST]}
                                                                            placeholder=""
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(md_Stock != null ? md_Stock + '' : '')}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            blurOnSubmit={false}
                                                                            autoComplete='off'
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '1') }}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'MiddayStock', 'numeric') }}
                                                                        />
                                                                    </View>
                                                                </View>
                                                            </View>
                                                        }

                                                        {isExpStock1Enable == true &&
                                                            <View style={[customStyle.openStk_prd_row, { marginBottom: 3, marginTop: 4 }]}>
                                                                <View style={[customStyle.openStk_prd_colflex]}>
                                                                    <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{isExpStock1DisplayName}</Text>
                                                                    <TextInput
                                                                        ref={(reff) => { inputRefs.current['input2_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                        style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx1]}
                                                                        placeholder=""
                                                                        autoComplete='off'
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        value={(ex_stock1 + '' || '')}
                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                        maxLength={6}
                                                                        keyboardType='number-pad'
                                                                        blurOnSubmit={false}
                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'MIDDAY_ExpiryStock1', 'numeric') }}
                                                                        onSubmitEditing={() => { focusToNext(cat, skus, '2') }}
                                                                    />
                                                                    <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "4%" }]}>{skus.EXPIRYSTOCK1}</Text>
                                                                </View>
                                                            </View>
                                                        }
                                                        {isExpStock2Enable == true &&
                                                            <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                <View style={[customStyle.openStk_prd_colflex]}>
                                                                    <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{isExpStock2DisplayName}</Text>
                                                                    <TextInput
                                                                        ref={(reff) => { inputRefs.current['input3_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                        style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx2]}
                                                                        placeholder=""
                                                                        autoComplete='off'
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        value={(ex_stock2 + '' || '')}
                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                        maxLength={6}
                                                                        keyboardType='number-pad'
                                                                        blurOnSubmit={false}
                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'MIDDAY_ExpiryStock2', 'numeric') }}
                                                                        onSubmitEditing={() => { focusToNext(cat, skus, '3') }}
                                                                    />
                                                                    <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "4%" }]}>{skus.EXPIRYSTOCK2}</Text>
                                                                </View>
                                                            </View>
                                                        }
                                                        {isExpStock3Enable == true &&
                                                            <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                <View style={[customStyle.openStk_prd_colflex]}>
                                                                    <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{isExpStock3DisplayName}</Text>
                                                                    <TextInput
                                                                        ref={(reff) => { inputRefs.current['input4_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                        style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx3]}
                                                                        placeholder=""
                                                                        autoComplete='off'
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        value={(ex_stock3 + '' || '')}
                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                        maxLength={6}
                                                                        keyboardType='number-pad'
                                                                        blurOnSubmit={false}
                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'MIDDAY_ExpiryStock3', 'numeric') }}
                                                                        onSubmitEditing={() => { focusToNext(cat, skus, '4') }}
                                                                    />
                                                                    <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "4%" }]}>{skus.EXPIRYSTOCK3}</Text>
                                                                </View>
                                                            </View>
                                                        }
                                                        {isExpStock4Enable == true &&
                                                            <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                <View style={[customStyle.openStk_prd_colflex]}>
                                                                    <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{isExpStock4DisplayName}</Text>
                                                                    <TextInput
                                                                        ref={(reff) => { inputRefs.current['input5_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                        style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx4]}
                                                                        placeholder=""
                                                                        autoComplete='off'
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        value={(ex_stock4 + '' || '')}
                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                        maxLength={6}
                                                                        keyboardType='number-pad'
                                                                        blurOnSubmit={false}
                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'MIDDAY_ExpiryStock4', 'numeric') }}
                                                                        onSubmitEditing={() => { focusToNext(cat, skus, '5') }}
                                                                    />
                                                                    <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "4%" }]}>{skus.EXPIRYSTOCK4}</Text>
                                                                </View>
                                                            </View>
                                                        }

                                                    </View>
                                                )
                                            }} />
                                        }
                                    </View>
                                </View>
                            );
                        }}
                    />
                }
            </KeyboardAvoidingView>
        )
    }

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {_render_Alert()}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, 'Do you really want to remove all visibility data?')}
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>

                    {Object.keys(storeData).length > 0 &&
                        _renderStock()
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={ST.Save} onPress={() => { submitOpeningStock() }} />
                    </View>
                </View>
            </LinearGradient>
        </Container>
    );
}


export default connect(mapStateToProps, mapDispatchToProps)(MiddayStock);