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 { Image, TextInput, View, Text, TouchableOpacity, Platform, FlatList, Alert, KeyboardAvoidingView, BackHandler, AppState, 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, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import CustomModal from '../components/CustomModal';
import CustomCamera from '../components/Camera';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import { CustomPicker } from '../components/CustomPicker';
function OpeningStock(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('loading...');
    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 [KPIFields, setKPIFields] = useState([]);
    const [KPIFieldsWithoutFilter, setKPIFieldsWithoutFilter] = useState([]);
    const [catImages, setCatImages] = useState([]);
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const showCameraRef = React.useRef(false);
    const [getImageProps, setGetImageProps] = useState({});
    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [disableEdit, setDisableEdit] = useState(false);
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SKUStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const catImagesRef = React.useRef(catImages);
    //filter data 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 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();
            return unsubscribe;
        };

    }, []);

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


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

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

    function BgShowCamera(val) {
        showCameraRef.current = val
        setShowCamera(val);
    }



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

    function BgCatImages(val) {
        catImagesRef.current = val
        setCatImages(val);
    }

    function onRemoveScreen(e) {
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
                {
                    text: "Cancel",
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: "OK", onPress: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

    async function getData(storeData1, menu1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId, StoreClassId, StoreCategoryId } = 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)
            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SwitchingCamera');
            let SwitchingCameraObj = SwitchingCameraI >= 0 ? AllKPIFields[SwitchingCameraI] : {};
            let SwitchingCamera = SwitchingCameraI >= 0 ? SwitchingCameraObj['KPIFieldEnable'] : false;
            setShowSwitchCamera(SwitchingCamera);
            let isdisable = await getIsLastVisitStockAvlbl(storeData1, menu1);
            console.log("isdisable", isdisable);
            setDisableEdit(isdisable);
            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 ShowCompetionSkuNo = ShowCompetionObj?.KPIFieldDisplayName || 0
            let ShowCompetionSkuNoSplitArr = ShowCompetionObj?.KPIFieldDisplayName?.split(",") || []
            const isCompetitorValues = ShowCompetionSkuNoSplitArr;
            console.log('iscompetitorValues1', isCompetitorValues)
            // const isCompetitorClause = `(${isCompetitorValues.join(",")})`;
            // Check if isCompetitorValues is empty, null, or undefined
            let isCompetitorClause = !isCompetitorValues || isCompetitorValues.length === 0 ? "p.IsCompetitor = 0" : `p.IsCompetitor IN (${isCompetitorValues.join(",")})`;
            console.log("checkiscpmp1--", isCompetitorClause)
            //allow insert only if LastVisitStock Exists and OPS does not already exists for this storeid
            let isInsertLastVisitValid = false;//await checkInsertLastVisitValid(storeData1,menu1);
            let seq = 0;
            if (isInsertLastVisitValid) {
                seq = await getSeq();
            }
            console.log("isInsertLastVisitValid:", isInsertLastVisitValid, seq);
            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData')
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, BgCatImage, visiteDate } = StoreJson
                if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {

                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    // setSKUStockData(storeBGData);
                    if (BgCatImage.length > 0) {
                        isBgDataExists = true;
                        BgCatImages(BgCatImage)
                    }
                    if (storeBGData.length > 0) {
                        isBgDataExists = true;
                        BgWindowData(storeBGData);
                    }
                    BgUnsavedChanges(true)

                }
            }

            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 leftjoin = `Left join ${AppTables.INSERT_OPENINGHEADER_DATA} lt on lt.CATEGORY_ID = p.CategoryId and lt.STORE_ID='${StoreId}' and lt.VISIT_DATE='${d2}'`
                let q = `SELECT DISTINCT ifnull(lt.IMAGE,'')as IMAGE,ifnull(lt.IMAGEPATH,'')as IMAGEPATH, c.CategoryId,c.CategoryName,'' as MSL from Master_Category c ${join} ${join2} ${leftjoin} where mp.StoreId='${StoreId}' ${(isCOMPStockAllow == true ? '' : ` and ${isCompetitorClause} `)}  order by p.CategorySequence`;
                let arr2 = [defCat];
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let catobj = { "CategoryId": data.CategoryId, "CategoryName": data.CategoryName }
                            arr.push(data);
                            arr2.push(catobj);
                            let defData = { 'CategoryId': data.CategoryId, 'ImageName': data.IMAGE, 'ImagePath': data.IMAGEPATH };
                            allCats.push(defData);
                            if (i == txnres.rows.length - 1) {
                                BgCatImages(allCats);
                                setcatFilter(arr2);
                                setrerenderdata(!rerenderdata);
                                getSKU(arr, storeData1, AllKPIFields, menu1, isBgDataExists, isInsertLastVisitValid, seq);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

            });
        } catch (err) {
            console.log(err);
        }
    }

    async function getIsLastVisitStockAvlbl(storeData1, menu1) {
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                let q = `select * from LastVisit_ClosingStock where StoreId='${storeData1.StoreId}'`;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        resolve(true);
                    }
                    else {
                        resolve(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
            });
        }).catch((err) => {
            return false;
        });
    }

    async function getSKU(brands = [], storeData1 = {}, AllKPIFields = [], menu1 = {}, isBgDataExists = false, isInsertLastVisitValid = false, seq = 0) {

        try {
            let { StoreId } = storeData1;
            let isExpStockIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ExpiredStock')
            let isExpStockPIObj = isExpStockIndex >= 0 ? AllKPIFields[isExpStockIndex] : {};
            let isExpStockEnable = isExpStockIndex >= 0 ? isExpStockPIObj['KPIFieldEnable'] : true;
            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 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 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(",")})`;
            let arr2 = [defSubCat];
            let arr3 = [defBrand];
            db.transaction(async function (txn) {
                var allSKUData = [];
                var stock_values = '', values = '';
                let insertCouunt = 0, prdLoadedForCatCount = 0;
                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 seletlist = `distinct ifnull(sl.STOCK,'') as SALE_stock,s.EXPIRYSTOCK1,s.EXPIRYSTOCK2,s.EXPIRYSTOCK3,s.EXPIRYSTOCK4,s.PRODUCT as ProductName,s.PRODUCT_ID as ProductId,s.MSL,s.ARTICLE_CODE,s.MIDDAY_STOCK,s.OPENING_STOCK,s.CLOSING_STOCK,s.EXPIRY_ISOPEN,s.EXPIRY_STK,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}' `;
                        // add Last Visit Stock join for prefilled functionality
                        let join6 = '', selectl_lv = '';
                        if (isInsertLastVisitValid) {
                            selectl_lv = ` ,lv.ClosingStock as LV_ClosingStock,lv.CLS_ExpiryStock1 as LV_CLS_ExpiryStock1,lv.CLS_ExpiryStock2 as LV_CLS_ExpiryStock2,lv.CLS_ExpiryStock3 as LV_CLS_ExpiryStock3,lv.CLS_ExpiryStock4 as LV_CLS_ExpiryStock4`;
                            join6 = `  Left Outer join LastVisit_ClosingStock lv on lv.ProductId=p.ProductId and lv.StoreId='${StoreId}' `;
                        }
                        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.BrandName,p.BrandId,p.IsCompetitor,m.MSL,m.ArticleCode,p.SubCategoryName, p.SubCategoryId,p.BrandName,p.BrandId ${selectl_lv} from Product_Master p  ${join} ${join2} ${join6} ${leftjoin} where m.StoreId='${StoreId}' and (p.CategoryId='${item.CategoryId}' or p.CategoryId= ${item.CategoryId})  ${(isCOMPStockAllow == true ? '' : ` and  ${isCompetitorClause} `)}  ORDER BY m.MSL desc, p.IsCompetitor ASC, p.ProductName ASC`;
                        seq++;
                        //build insert values array if InsertLastVisit is allowed
                        if (isInsertLastVisitValid) {
                            values += values != '' ? ' , ' : '';
                            values += ` ('${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${item.MSL}','','','${d2}') `;
                        }
                        return await txn.executeSql(sku_q, [], async function (txn2, txnres) {
                            console.log("chekecc----->", sku_q)
                            if (txnres.rows.length > 0) {
                                let arr = [];
                                for (var i = 0; i < txnres.rows.length; i++) {
                                    let data = txnres.rows.item(i);
                                    inputRefs.current['input1_' + item.CategoryId + '_' + data.ProductId] = '';
                                    if ((isExpStockEnable && !isStockCalculateEnable) || isExpStock2Enable) {
                                        inputRefs.current['input2_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    if (isExpStock3Enable) {
                                        inputRefs.current['input3_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    if (isExpStock4Enable) {
                                        inputRefs.current['input4_' + 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 defData = { 'CategoryId': item.CategoryId, 'ProductId': data.ProductId, 'Stock': String(data.OPENING_STOCK), 'ExpiryStock': String(data.EXPIRY_STK), 'ExpiryStock1': String(data.EXPIRYSTOCK1), 'ExpiryStock2': String(data.EXPIRYSTOCK2), 'ExpiryStock3': String(data.EXPIRYSTOCK3), 'ExpiryStock4': String(data.EXPIRYSTOCK4), 'SALE_stock': data.SALE_stock };
                                    allSKUData.push(defData);
                                    if (i == txnres.rows.length - 1) {
                                        item['skulist'] = arr;
                                        brands[index] = item;
                                        prdLoadedForCatCount++;
                                        if (prdLoadedForCatCount == brands.length) { //index==brands.length-1
                                            if (!isBgDataExists) {
                                                BgWindowData(allSKUData);
                                            }
                                            setBrandData(brands);
                                            setGlobalBrandData(brands);
                                            setsubcatFilter(arr2);
                                            setbrandFilter(arr3);
                                            setTimeout(() => { setrerenderdata2(!rerenderdata2); }, 3000);
                                            setProcessing(false);
                                        }
                                        return item;
                                    }
                                }
                            }
                            else {
                                return await txn.executeSql(sku_q2, [], async function (txn2, txnres2) {
                                    console.log("loaded count:", sku_q2, txnres2.rows.length, ',catid:', item.CategoryId);
                                    if (txnres2.rows.length > 0) {
                                        let arr = [], hdrseq = seq;
                                        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 ((isExpStockEnable && !isStockCalculateEnable)) {
                                                inputRefs.current['input2_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock1Enable) {
                                                inputRefs.current['input3_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }

                                            if (isExpStock2Enable) {
                                                inputRefs.current['input4_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock3Enable) {
                                                inputRefs.current['input5_' + item.CategoryId + '_' + data.ProductId] = '';
                                            }
                                            if (isExpStock4Enable) {
                                                inputRefs.current['input6_' + 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);
                                            }
                                            //build insert values array if InsertLastVisit is allowed
                                            if (isInsertLastVisitValid) {
                                                let stock = data.LV_ClosingStock != null && data.LV_ClosingStock != 'undefined' ? data.LV_ClosingStock : '0';
                                                let lvCLS1 = data.LV_CLS_ExpiryStock1 != null && data.LV_CLS_ExpiryStock1 != 'undefined' ? data.LV_CLS_ExpiryStock1 : '0';
                                                let lvCLS2 = data.LV_CLS_ExpiryStock2 != null && data.LV_CLS_ExpiryStock2 != 'undefined' ? data.LV_CLS_ExpiryStock2 : '0';
                                                let lvCLS3 = data.LV_CLS_ExpiryStock3 != null && data.LV_CLS_ExpiryStock3 != 'undefined' ? data.LV_CLS_ExpiryStock3 : '0';
                                                let lvCLS4 = data.LV_CLS_ExpiryStock4 != null && data.LV_CLS_ExpiryStock4 != 'undefined' ? data.LV_CLS_ExpiryStock4 : '0';
                                                //prefil values if InsertLastVisit is allowed
                                                let defData = { 'CategoryId': item.CategoryId, 'ProductId': data.ProductId, 'Stock': stock, 'ExpiryStock': 0, 'ExpiryStock1': lvCLS1, 'ExpiryStock2': lvCLS2, 'ExpiryStock3': lvCLS3, 'ExpiryStock4': lvCLS4, 'SALE_stock': data.SALE_stock };
                                                allSKUData.push(defData);
                                                stock_values += stock_values != '' ? ' , ' : '';
                                                stock_values += ` ('${hdrseq}','${StoreId}','${d2}','${item.CategoryId}','${item.CategoryName}','${data.BrandId}','${data.BrandName}','${data.ProductId}','${data.ProductName}','${data.MSL}','${stock}','','','${isExpStockEnable}','0','${d2}') `;
                                                insertCouunt++;
                                            }

                                            if (i == (txnres2.rows.length - 1)) {
                                                item['skulist'] = arr;
                                                brands[index] = item;
                                                prdLoadedForCatCount++;
                                                if (prdLoadedForCatCount == brands.length) {
                                                    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;
                    })
                ).then((res) => {
                });
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function getSeq() {
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                // select autogenerated seq from Header Table.
                let seq_q = `select seq from sqlite_sequence where name="${AppTables.INSERT_OPENINGHEADER_DATA}" `;
                await txn.executeSql(seq_q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        let seq = data.seq;
                        resolve(seq);
                    }
                    else {
                        resolve(0);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(0); },);
            });
        }).catch((e) => {
            console.log(e);
            return 0;
        });
    }


    async function focusToNext(cat, sku, type = '1') {
        let activeKey = '';
        let arr = Object.keys(inputRefs.current);
        if (type == "1") {
            activeKey = 'input1_' + cat.CategoryId + '_' + sku.ProductId;
        } else if (type == "2") {
            activeKey = 'input2_' + cat.CategoryId + '_' + sku.ProductId;
        } else if (type == "3") {
            activeKey = 'input3_' + cat.CategoryId + '_' + sku.ProductId;
        } else if (type == "4") {
            activeKey = 'input4_' + cat.CategoryId + '_' + sku.ProductId;
        } else if (type == "5") {
            activeKey = 'input5_' + cat.CategoryId + '_' + sku.ProductId;
        } else if (type == "6") {
            activeKey = 'input6_' + 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.focus();
        }
        else {
            return
        }
    }

    async function getImage(imgdata) {
        let cat = getImageProps.option || '';
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify('Camera unavailable');
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;
            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_OpeningStk-' + calculate_tym_date_for_filename + '.jpg';
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName + ' (OPS) | Date:' + calculate_tym_date_over_img;
            let allIMgs = catImages;
            let defData = { 'CategoryId': cat.CategoryId };
            const cindex = allIMgs.findIndex(i => i.CategoryId == cat.CategoryId);
            const imgData = cindex >= 0 ? (allIMgs[cindex] || defData) : defData;
            imgData.ImageName = filename;
            let imagePath = ImageFolderPath + currentMenu.ScreenName + "/" + filename;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    imgData.ImagePath = uri;
                    cindex >= 0 ? allIMgs[cindex] = imgData : allIMgs.push(imgData);
                    setSelectedImg(uri)
                    BgCatImages(allIMgs)
                    BgUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                    // add metdata then resize image and restored back to the imagePath
                    let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
                    let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
                    console.log("image restored:", is_restored);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });
        }
    }

    async function openCamera(option) {
        setGetImageProps({ 'option': option });
        BgShowCamera(true);
        setErrorField({});
        setError(false);
    }

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

    async function saveData() {
        BgUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {
            let { StoreId } = storeData;
            await db.transaction(async function (txn) {
                let q = `DELETE FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                let q2 = `DELETE FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                //  remove old data
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('stock data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);
                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    console.log('stock header data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);
                let seq_q = ` select seq from sqlite_sequence where name="${AppTables.INSERT_OPENINGHEADER_DATA}" `;
                await txn.executeSql(seq_q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        let seq = data.seq;
                        insertData(seq);
                    }
                    else {
                        insertData(0);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); insertData(0); },);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function insertData(seq = 0) {
        try {
            console.log(seq);
            let ProductList = []
            let isSALEExists = await checkMDStockScreenExists(storeData, 'SALE')
            let { StoreId, ExpiryStock } = storeData;
            let isExpStockIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiredStock')
            let isExpStockPIObj = isExpStockIndex >= 0 ? KPIFields[isExpStockIndex] : {};
            let isExpStockEnable = isExpStockIndex >= 0 ? isExpStockPIObj['KPIFieldEnable'] : 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;
            await db.transaction(async function (txn) {
                var values = '', stock_values = '';
                for (var i = 0; i < globalBrandData.length; i++) {
                    seq++;
                    let catIndex = i;
                    let item = globalBrandData[catIndex];
                    let cimage = catImages.find(ci => ci.CategoryId == item.CategoryId) || {};
                    values += values != '' ? ' , ' : '';
                    values += ` ('${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${item.MSL}','${cimage.ImageName}','${cimage.ImagePath}','${d2}') `;
                    let skulist = item['skulist'] || [];
                    for (var j = 0; j < skulist.length; j++) {
                        let skuItem = skulist[j];
                        let { BrandId, BrandName, MSL, ArticleCode, ProductId, ProductName, IsCompetitor } = skulist[j];
                        ArticleCode = ArticleCode != null && ArticleCode != undefined && ArticleCode != 'undefined' && ArticleCode != '' ? ArticleCode : ''
                        stock_values += stock_values != '' ? ' , ' : '';
                        let allSKUData = SKUStockData;
                        const skud_index = allSKUData.findIndex(ci => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId);
                        const skud = skud_index >= 0 ? (allSKUData[skud_index] || {}) : {};
                        let StockData = '0';
                        let expStock = isExpStockEnable == true && isStockCalculateEnable == false ? (skud['ExpiryStock'] != null ? skud['ExpiryStock'] : '0') : '0';
                        let expStock1 = isExpStock1Enable == true ? (skud['ExpiryStock1'] != null ? skud['ExpiryStock1'] : '0') : '0';
                        let expStock2 = isExpStock2Enable == true ? (skud['ExpiryStock2'] != null ? skud['ExpiryStock2'] : '0') : '0';
                        let expStock3 = isExpStock3Enable == true ? (skud['ExpiryStock3'] != null ? skud['ExpiryStock3'] : '0') : '0';
                        let expStock4 = isExpStock4Enable == true ? (skud['ExpiryStock4'] != null ? skud['ExpiryStock4'] : '0') : '0';
                        if (isStockCalculateEnable) {
                            StockData = parseInt(expStock1) + parseInt(expStock2) + parseInt(expStock3) + parseInt(expStock4)
                        } else {
                            StockData = skud['Stock'];
                            if (StockData === null || StockData === '' || StockData === undefined) {
                                StockData = '0';
                            }
                            if (parseInt(StockData) != 0) {
                                ProductList.push(ProductId)
                            }
                        }
                        stock_values += ` ('${seq}','${StoreId}','${d2}','${item.CategoryId}','${item.CategoryName}','${BrandId}','${BrandName}','${ProductId}','${ProductName}','${MSL}','${ArticleCode}','${StockData}','','','${ExpiryStock}','${expStock}','${expStock1}','${expStock2}','${expStock3}','${expStock4}','${d2}',${IsCompetitor}) `;
                    }
                }
                let add_StockHdr = `INSERT INTO ${AppTables.INSERT_OPENINGHEADER_DATA} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${values} `;
                let add_Stock = `INSERT INTO ${AppTables.STOCK_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,CATEGORY_ID,CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,ARTICLE_CODE,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK,EXPIRYSTOCK1,EXPIRYSTOCK2,EXPIRYSTOCK3,EXPIRYSTOCK4,ADDED_DATE,IsCompetitor) VALUES ${stock_values} `;
                await txn.executeSql(add_StockHdr, [], async function (txn2, txnres) {
                    console.log('stock header added');
                    await txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                        console.log('stock added');
                        if (isSALEExists) {
                            let saleDQ = `Delete from ${AppTables.SALES} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PRODUCT_ID not in (${ProductList.join(',')}) `
                            txn.executeSql(saleDQ, [], function (txn2, txnres) {
                                console.log('sales deleted successfully');
                            }, function (txnE, txnerr) { console.log(txnerr); },);
                        }
                        notify('Stock updated successfully');
                        setProcessing(false);
                        // clear store data in local storage to avoiding re-set data for the store  
                        clear_item('storeData')
                        props.navigation.goBack();
                    }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add stock') },);
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add stock') },);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function validate() {
        let isValid = true;
        var i = 0, j = 0;
        let isSALEExists = await checkMDStockScreenExists(storeData, 'SALE')
        let isExpMandIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiredStockMandatory')
        let isExpMandKPIObj = isExpMandIndex >= 0 ? KPIFields[isExpMandIndex] : {};
        let isExpMandEnable = isExpMandIndex >= 0 ? isExpMandKPIObj['KPIFieldEnable'] : true;
        let isExpStockIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiredStock')
        let isExpStockPIObj = isExpStockIndex >= 0 ? KPIFields[isExpStockIndex] : {};
        let isExpStockEnable = isExpStockIndex >= 0 ? isExpStockPIObj['KPIFieldEnable'] : true;
        let ShowSubCatImageIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowSubCatImage')
        let ShowSubCatImageObj = ShowSubCatImageIndex >= 0 ? KPIFields[ShowSubCatImageIndex] : {};
        let ShowSubCatImageEnable = ShowSubCatImageIndex >= 0 ? ShowSubCatImageObj['KPIFieldEnable'] : 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;
        let isDefaultStockIndex = KPIFields.findIndex(i => i.KPIFieldName == 'DefaultStockValue')
        let isDefaultStockPIObj = isDefaultStockIndex >= 0 ? KPIFields[isDefaultStockIndex] : {};
        let isDefaultStockEnable = isDefaultStockIndex >= 0 ? isDefaultStockPIObj['KPIFieldEnable'] : false;
        let oneStockExists = true;

        await Promise.all(
            globalBrandData.map(async (item, index) => {
                if (isValid) {
                    let catId = item.CategoryId;
                    let errorobj = { 'EF_brand': item };
                    let cimgData = catImages.find(ci => ci.CategoryId == catId) || {};
                    if (ShowSubCatImageEnable == true && (cimgData.ImagePath == null || cimgData.ImagePath == '')) {
                        notify('Please click image for ' + item.CategoryName, 'SHORT');
                        isValid = false;
                        errorobj['EF_ImageKey'] = 'Image1';
                        setErrorField(errorobj);
                        setError(true);
                    }
                    else {
                        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
                                        let show_errorH = false, error_HInputKey = '', error_HInputKey2 = '', error_HInputKeyEx1 = '', error_HInputKeyEx2 = '', error_HInputKeyEx3 = '', error_HInputKeyEx4 = '';
                                        let skuDataStock = skuData?.Stock ? skuData?.Stock : (isDefaultStockEnable ? "0" : null);
                                        let skuDataExpiryStock = skuData?.ExpiryStock ? skuData?.ExpiryStock : (isDefaultStockEnable ? "0" : null);
                                        let skuDataExpiryStock1 = skuData?.ExpiryStock1 ? skuData?.ExpiryStock1 : (isDefaultStockEnable ? "0" : null);
                                        let skuDataExpiryStock2 = skuData?.ExpiryStock2 ? skuData?.ExpiryStock2 : (isDefaultStockEnable ? "0" : null);
                                        let skuDataExpiryStock3 = skuData?.ExpiryStock3 ? skuData?.ExpiryStock3 : (isDefaultStockEnable ? "0" : null);
                                        let skuDataExpiryStock4 = skuData?.ExpiryStock3 ? skuData?.ExpiryStock4 : (isDefaultStockEnable ? "0" : null);
                                        if (isStockCalculateEnable != true) {
                                            let stockCheck = parseInt(skuDataStock) || 0
                                            if (stockCheck > 0) {
                                                oneStockExists = false;
                                            }
                                            if (skuDataStock != 0 && (!Boolean(skuDataStock))) {
                                                isValid = false;
                                                show_errorH = true, error_HInputKey = 'input1_';
                                            }
                                            else if (skuDataStock != 0 && skuDataStock !== '' && !validateNumber(skuDataStock, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKey = 'input1_';
                                            } else if (skuDataStock != '' && parseInt(skuData?.SALE_stock) > parseInt(skuDataStock)) {
                                                notify('STOCK value must NOT BE LESS than entered SALE' + ' Stock ' + ST.for + ' ' + skuItem.ProductName, 'LONG');
                                                isValid = false;
                                                show_errorH = true, error_HInputKey = 'input1_';
                                            }
                                            else if ((isExpMandEnable == 1 && isExpStockEnable == true) && skuDataExpiryStock !== 0 && (skuDataExpiryStock == null || skuDataExpiryStock == '')) {
                                                notify('Please enter expiry stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKey2 = 'input2_';
                                            }
                                            else if ((isExpMandEnable == 1 && isExpStockEnable == true) && skuDataExpiryStock !== 0 && skuDataExpiryStock != '' && !validateNumber(skuDataExpiryStock, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' expiry stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKey2 = 'input2_';
                                            }
                                            else if (isExpStockEnable == true && (parseInt(skuDataExpiryStock) > parseInt(skuDataStock))) {
                                                notify('Expiry Stock value should be less than or equal to Stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKey = 'input1_', error_HInputKey2 = 'input2_';
                                            }

                                            if (show_errorH) {
                                                errorobj['EF_InputKey'] = error_HInputKey;
                                                errorobj['EF_InputKey2'] = error_HInputKey2;
                                                setErrorField(errorobj)
                                                setError(true)
                                                if (error_HInputKey != null && error_HInputKey != '') {
                                                    let refIn1 = inputRefs.current[error_HInputKey + error_bid + '_' + error_pid];
                                                    refIn1.focus();
                                                }
                                                else if (error_HInputKey2 != '') {
                                                    let refIn1 = inputRefs.current[error_HInputKey2 + error_bid + '_' + error_pid];
                                                    refIn1.focus();
                                                }
                                            }
                                        } else {
                                            if ((isExpStock1Enable == true) && skuDataExpiryStock1 != 0 && (skuDataExpiryStock1 == null || skuDataExpiryStock1 == '')) {
                                                notify('Please enter expiry stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx1 = 'input3_';
                                            }
                                            else if ((isExpStock1Enable == true) && skuDataExpiryStock1 != 0 && skuDataExpiryStock1 != '' && !validateNumber(skuDataExpiryStock1, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' expiry stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx1 = 'input3_';
                                            } else if ((isExpStock2Enable == true) && skuDataExpiryStock2 != 0 && (skuDataExpiryStock2 == null || skuDataExpiryStock2 == '')) {
                                                notify('Please enter expiry stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx2 = 'input4_';
                                            }
                                            else if ((isExpStock2Enable == true) && skuDataExpiryStock2 != 0 && skuDataExpiryStock2 != '' && !validateNumber(skuDataExpiryStock2, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' expiry stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx2 = 'input4_';
                                            } else if ((isExpStock3Enable == true) && skuDataExpiryStock3 != 0 && (skuDataExpiryStock3 == null || skuDataExpiryStock3 == '')) {
                                                notify('Please enter expiry stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx3 = 'input5_';
                                            }
                                            else if ((isExpStock3Enable == true) && skuDataExpiryStock3 != 0 && skuDataExpiryStock3 != '' && !validateNumber(skuDataExpiryStock3, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' expiry stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx3 = 'input5_';
                                            } else if ((isExpStock4Enable == true) && skuDataExpiryStock4 != 0 && (skuDataExpiryStock4 == null || skuDataExpiryStock4 == '')) {
                                                notify('Please enter expiry stock for ' + skuItem.ProductName, 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx4 = 'input6_';
                                            }
                                            else if ((isExpStock4Enable == true) && skuDataExpiryStock4 != 0 && skuDataExpiryStock4 != '' && !validateNumber(skuDataExpiryStock4, 'numeric', false)) {
                                                notify('Please enter whole numbers only for ' + skuItem.ProductName + ' expiry stock', 'SHORT');
                                                isValid = false;
                                                show_errorH = true, error_HInputKeyEx4 = 'input6_';
                                            }

                                            if (show_errorH) {
                                                errorobj['error_HInputKeyEx1'] = error_HInputKeyEx1;
                                                errorobj['error_HInputKeyEx2'] = error_HInputKeyEx2;
                                                errorobj['error_HInputKeyEx3'] = error_HInputKeyEx3;
                                                errorobj['error_HInputKeyEx4'] = error_HInputKeyEx4;
                                                setErrorField(errorobj)
                                                setError(true)
                                                if (error_HInputKey != null && error_HInputKey != '') {
                                                    let refIn1 = inputRefs.current[error_HInputKey + error_bid + '_' + error_pid];
                                                    refIn1.focus();
                                                }
                                                else if (error_HInputKey2 != '') {
                                                    let refIn1 = inputRefs.current[error_HInputKey2 + error_bid + '_' + error_pid];
                                                    refIn1.focus();
                                                }
                                            }
                                        }
                                    }
                                })
                            );
                        }
                    }
                }
            })
        );

        if (isValid && isSALEExists && oneStockExists) {
            notify("Fill Stock greater than 0 for atleast one product", 'SHORT');
            isValid = false;
        }

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

        if (val.length > 1 && val[0] === '0') {
            val = val.replace(/^0+/, '');
        }

        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 _render_Alert() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={'Do you really want to save data?'}
                showModal={showAlert}
            >
                <View style={customStyle.storelVisitM_options}>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowAlert(false) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { saveData() }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
                    </TouchableOpacity>
                </View>
            </CustomModal>
        )
    }


    async function OpenImgModal(imgPath, item) {
        setSelectedImg(imgPath)
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        }
        else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ item })
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)

    }

    function cancelImage() {
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
    }

    function _OpenCaptureImage_Modal(img) {
        const isImageCap = (img != '' || img != null) ? true : false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let { item } = reCapImgModalObj
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={currentMenu.MenuName + " Image"}
                message={camera2Label}
                titleStyle={customStyle.PromoImgModal_title}
                messageStyle={customStyle.PromoImgModal_subtitle}
                showModal={showModal}
            >
                {
                    isImageCap &&
                    <View style={customStyle.PromoImgModalCon}>
                        <View style={customStyle.PromoImgModal_ImgWrap}>
                            <Image style={[customStyle.PromoImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: SelectedImg }} />
                        </View>
                        <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={() => { openCamera(item) }}>
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>

                        {!showImageSaveOp &&
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        )
    }

    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) {
        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);
        }
    }
    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 == 'OPCatFilter')
        let salesCatFilterObj = salesCatFilterI >= 0 ? KPIFields[salesCatFilterI] : {};
        let salesCatFilter = salesCatFilterI >= 0 ? salesCatFilterObj['KPIFieldEnable'] : false;

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

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

        if (rerenderdata == rerenderdata && (salesCatFilter || salesSubCatFilter || salesBrandFilter)) {
            return (
                <View>
                    {salesCatFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{'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]}>{'SubCategory'}</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]}>{'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;
        }
    }


    // ✅ 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 _renderStocks() {
        let isExpStockIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiredStock')
        let isExpStockPIObj = isExpStockIndex >= 0 ? KPIFields[isExpStockIndex] : {};
        let isExpStockEnable = isExpStockIndex >= 0 ? isExpStockPIObj['KPIFieldEnable'] : true;

        let ShowSubCatImageIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowSubCatImage')
        let ShowSubCatImageObj = ShowSubCatImageIndex >= 0 ? KPIFields[ShowSubCatImageIndex] : {};
        let ShowSubCatImageEnable = ShowSubCatImageIndex >= 0 ? ShowSubCatImageObj['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;

        let isDefaultStockIndex = KPIFields.findIndex(i => i.KPIFieldName == 'DefaultStockValue')
        let isDefaultStockPIObj = isDefaultStockIndex >= 0 ? KPIFields[isDefaultStockIndex] : {};
        let isDefaultStockEnable = isDefaultStockIndex >= 0 ? isDefaultStockPIObj['KPIFieldEnable'] : false;
        let isDefaultStockValue = isDefaultStockEnable ? "0" : "";


        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) => {
            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={Platform.OS == 'ios' ? "padding" : "position"} enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -100)} >
                <FlatList
                    data={brandData}
                    extraData={rerenderdata}
                    contentContainerStyle={customStyle.opening_Stock_scroll}
                    style={customStyle.opening_Stock_scrollOuter}
                    ListHeaderComponent={_renderSalesFilter}
                    nestedScrollEnabled={true}
                    removeClippedSubviews={false}
                    scrollToOverflowEnabled={true}
                    legacyImplementation={true}
                    renderItem={({ item, index }) => {
                        const cat = item;
                        const catIndex = index;
                        const cindex = catImages.findIndex(i => i.CategoryId == item.CategoryId);
                        const cimgName = cindex >= 0 ? (catImages[cindex] ? catImages[cindex].ImageName : '') : '';
                        const cimgPath = cindex >= 0 ? (catImages[cindex] ? catImages[cindex].ImagePath : '') : '';
                        const showIMg = cimgPath != '' && cimgPath != null;

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

                        let errorStyle_Image1 = error && error_bid == cat.CategoryId && EF_ImageKey == 'Image1' ? customStyle.error_CatImage2 : {};

                        return (
                            <View style={customStyle.opening_Stock_wrap}>
                                <View style={customStyle.opening_Stock_cat}>
                                    <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>
                                    {ShowSubCatImageEnable == true &&
                                        <View style={customStyle.osCat_actions}>

                                            {!showIMg ?
                                                <TouchableOpacity style={[errorStyle_Image1]} onPress={() => { openCamera(item) }}>
                                                    <CameraImg5 width={50} height={50} />
                                                </TouchableOpacity> : showIMg ?
                                                    <TouchableOpacity onPress={() => { OpenImgModal(cimgPath, item) }}>
                                                        <CameraImg3 width={50} height={50} />
                                                    </TouchableOpacity> : null
                                            }
                                        </View>
                                    }
                                </View>
                                <View style={customStyle.opening_Stock_prds}>
                                    {

                                        <FlatList
                                            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 stock = thisCatSkuData.Stock != null ? thisCatSkuData.Stock : '';
                                                let ex_stock = thisCatSkuData.ExpiryStock != null ? thisCatSkuData.ExpiryStock : '';

                                                let ex_stock1 = thisCatSkuData.ExpiryStock1 != null ? thisCatSkuData.ExpiryStock1 : '';
                                                let ex_stock2 = thisCatSkuData.ExpiryStock2 != null ? thisCatSkuData.ExpiryStock2 : '';
                                                let ex_stock3 = thisCatSkuData.ExpiryStock3 != null ? thisCatSkuData.ExpiryStock3 : '';
                                                let ex_stock4 = thisCatSkuData.ExpiryStock4 != null ? thisCatSkuData.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 EF_InputKey2 = errorfield.EF_InputKey2;
                                                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 errorStyle_EXPS = (error && show_errorhere && EF_InputKey2 == 'input2_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx1 = (error && show_errorhere && errorfield.error_HInputKeyEx1 == 'input1_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx2 = (error && show_errorhere && errorfield.error_HInputKeyEx2 == 'input2_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx3 = (error && show_errorhere && errorfield.error_HInputKeyEx3 == 'input3_' ? customStyle.stk_inptSTyle_error : {});
                                                let error_HInputKeyEx4 = (error && show_errorhere && errorfield.error_HInputKeyEx4 == 'input4_' ? customStyle.stk_inptSTyle_error : {});


                                                return (
                                                    <View
                                                        style={[customStyle.openStk_prd_Con, getBackgroundStyle(skus)]}
                                                        key={sku_index}
                                                    >
                                                        {/* <Text style={customStyle.openStk_prd_name}>{skus.ProductName +  " - "+skus.ArticleCode }</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_prd_form}>
                                                            {isStockCalculateEnable == 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]}>{"Total Stock"}</Text>
                                                                        <TextInput
                                                                            editable={false}
                                                                            // defaultValue={isDefaultStockValue}
                                                                            selectTextOnFocus={false}
                                                                            style={[customStyle.openStk_EXP_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2]}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(calVal == 0 ? isDefaultStockValue : (calVal + '' || isDefaultStockValue))}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                        />
                                                                    </View>
                                                                </View>
                                                            }
                                                            {isExpStockEnable == true && isStockCalculateEnable != true &&
                                                                <View style={customStyle.openStk_prd_row}>
                                                                    <View style={[customStyle.openStk_prd_col50, customStyle.openStk_prd_col50_1]}>
                                                                        <Text style={customStyle.openStk_prd_label}>Stock</Text>
                                                                        <TextInput
                                                                            ref={(reff) => { inputRefs.current['input1_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_inputShort, errorStyle_ST]}
                                                                            placeholder=""
                                                                            // defaultValue={stock+''||isDefaultStockValue}
                                                                            autoComplete='off'
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(stock != null ? stock + '' : isDefaultStockValue)}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '1') }}
                                                                            // onBlur={(e) => {onChangeValidate(cat,cat_index,skus,sku_index)}}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'Stock', 'numeric') }}
                                                                        />
                                                                    </View>
                                                                    <View style={[customStyle.openStk_prd_col50, customStyle.openStk_prd_col50_2]}>
                                                                        <Text style={customStyle.openStk_prd_label}>Expiry Stock</Text>
                                                                        <TextInput
                                                                            ref={(reff) => { inputRefs.current['input2_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_inputShort, errorStyle_EXPS]}
                                                                            placeholder=""
                                                                            autoComplete='off'
                                                                            // defaultValue={ex_stock+'' || isDefaultStockValue}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(ex_stock + '' || isDefaultStockValue)}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '2') }}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'ExpiryStock', 'numeric') }}
                                                                        />
                                                                    </View>
                                                                </View>
                                                            }

                                                            {isExpStockEnable == false && isStockCalculateEnable != true &&
                                                                <View style={customStyle.openStk_prd_row}>
                                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>Stock</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=""
                                                                            autoComplete='off'
                                                                            // defaultValue={stock+''||isDefaultStockValue}
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(stock + '' || isDefaultStockValue)}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'Stock', 'numeric') }}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '1') }}
                                                                        />
                                                                    </View>
                                                                </View>
                                                            }

                                                            {isExpStock1Enable == 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]}>{isExpStock1DisplayName}</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_HInputKeyEx1]}
                                                                            placeholder=""
                                                                            autoComplete='off'
                                                                            // defaultValue={ex_stock1+'' || isDefaultStockValue}  
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(ex_stock1 + '' || isDefaultStockValue)}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'ExpiryStock1', 'numeric') }}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '3') }}
                                                                        />
                                                                    </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['input4_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx2]}
                                                                            placeholder=""
                                                                            autoComplete='off'
                                                                            // defaultValue={ex_stock2+'' ||isDefaultStockValue}  
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(ex_stock2 + '' || isDefaultStockValue)}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'ExpiryStock2', 'numeric') }}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '4') }}
                                                                        />
                                                                    </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['input5_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx3]}
                                                                            placeholder=""
                                                                            autoComplete='off'
                                                                            // defaultValue={ex_stock3+'' ||isDefaultStockValue}  
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(ex_stock3 + '' || isDefaultStockValue)}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'ExpiryStock3', 'numeric') }}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '5') }}
                                                                        />
                                                                    </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['input6_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx4]}
                                                                            placeholder=""
                                                                            autoComplete='off'
                                                                            // defaultValue={ex_stock4+'' ||isDefaultStockValue}  
                                                                            editable={!disableEdit}
                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                            value={(ex_stock4 + '' || isDefaultStockValue)}
                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                            maxLength={6}
                                                                            keyboardType='number-pad'
                                                                            blurOnSubmit={false}
                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'ExpiryStock4', 'numeric') }}
                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '6') }}
                                                                        />
                                                                    </View>
                                                                </View>
                                                            }


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

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

    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}`} />
            {_OpenCaptureImage_Modal()}
            {_render_Alert()}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { BgShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { BgShowCamera(false); }} />

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    <View style={[customStyle.storel_searchbar2]}>
                        <TextInput
                            style={[customStyle.storel_searchInput]}
                            placeholder={'Search by Product Name'}
                            autoComplete='off'
                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                            placeholderTextColor={PageTheme.$placeholder_color}
                            value={searchedItem}
                            onChangeText={(val) => { setSearchedItem(val); FilterStores(val, filtervalue) }}
                        />

                        <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem, filtervalue) }}>
                            {/* {console.log('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" */}
                    {!processing && ((MSLDataInfo?.isMSLProduct && MSLDataInfo?.Color_MSL !== "")
                        || (MSLDataInfo?.isNonMSLProduct && MSLDataInfo?.Color_NONMSL !== "")
                        || (MSLDataInfo?.isCompProduct && MSLDataInfo?.Color_Competition !== "")) && ThreeColorIndicator()}

                    {Object.keys(storeData).length > 0 && _renderStocks()}
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        {!disableEdit && <GradientButton {...props} title={'Save'} onPress={() => { submitOpeningStock() }} />}
                        {disableEdit && <GradientButton {...props} title={'Save'} onPress={() => { submitOpeningStock() }} disabled={true} colors={[PageTheme.$text_color_light, PageTheme.$text_color_light]} />}
                    </View>
                </View>
            </LinearGradient>
        </Container>
    );
}


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