
import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, FlatList, Alert, KeyboardAvoidingView, AppState, Keyboard } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, getKPIFields, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath, ImageFolderPath, HierarchyTbls } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, 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 CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

function SOSEyeLevel(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 [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [rerenderdata3, setrerenderdata3] = useState(0);
    const [rerenderdata4, setrerenderdata4] = useState(0);

    const [SOSStockData, setSOSStockData] = useState([]);
    const [AllSOSData, setAllSOSData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps, setGetImageProps] = useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const [GridValue, setGridValue] = useState(false);

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });
    const [FilteredPromoValues, setFilteredPromoValues] = useState([]);
    const [ShowCatWise, setShowCatWise] = useState(false);
    const [CatData, setCatData] = useState(false);
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SOSStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const PSGroupData = React.useRef(''); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
    const BGPSAllow = React.useRef(false);


    // 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');

    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};
        let ShowCatWise1 = params.ShowCatWise != null ? params.ShowCatWise : false;
        let CatData1 = params.CatData != null ? params.CatData : {};
        let isAdhoc = params.isAdhoc || false;


        setIsAdhocScreen(isAdhoc);
        setShowCatWise(ShowCatWise1);
        setCatData(CatData1);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        let cameraAllow = storeData1.CameraAllow == 'true' || storeData1.CameraAllow == 1 ? true : false;
        setStoreCameraAllow(cameraAllow);


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

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

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

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

    useEffect(() => {
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
        // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SOSStockData,pro)});
        // AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SOSStockData,pro)});
    }, [hasUnsavedChanges]);

    // useEffect(() => {
    // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SOSStockData,pro)});
    //     AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SOSStockData,pro)});
    // }, [SOSStockData]); 


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

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

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

    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else {
            console.log('hasUnsavedChanges:', hasUnsavedChanges);
            if (hasUnsavedChanges == true) {
                console.log('hasUnsavedChanges is true');
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }

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

    async function getData(storeData1, menu1, CatData1 = {}, ShowCatWise1 = false) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
            let { PSAllow, PSTableName } = menu1;
            PSTableName = PSTableName != null ? PSTableName : '';
            PSAllow = PSAllow != null ? PSAllow : false;

            let idCol = '', nameCol = '';
            if (PSTableName.toLowerCase() == HierarchyTbls.Master_Category.toLowerCase()) {
                idCol = 'CategoryId', nameCol = 'CategoryName';
            }
            else if (PSTableName.toLowerCase() == HierarchyTbls.Master_Brand.toLowerCase()) {
                idCol = 'BrandId', nameCol = 'BrandName';
            }
            else {
                idCol = 'SubCategoryId', nameCol = 'SubCategoryName';
            }
            let IdVal = CatData1[idCol];
            let NameVal = CatData1[nameCol];

            let FilteredIds = [];
            if (ShowCatWise1) {
                FilteredIds = await getWindowFilterIds(idCol, IdVal, storeData1);
            }
            setFilteredPromoValues(FilteredIds);


            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);

            // 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 sosCheckAssortmentI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SOSCheckAssortment')
            let sosCheckAssortmentObj = sosCheckAssortmentI >= 0 ? AllKPIFields[sosCheckAssortmentI] : {};
            let sosCheckAssortment = sosCheckAssortmentI >= 0 ? sosCheckAssortmentObj['KPIFieldEnable'] : false;

            let sosMSLOnlyI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SOSMSLOnly')
            let sosMSLOnlyObj = sosMSLOnlyI >= 0 ? AllKPIFields[sosMSLOnlyI] : {};
            let sosMSLOnly = sosMSLOnlyI >= 0 ? sosMSLOnlyObj['KPIFieldEnable'] : false;

            let AssortIds = sosCheckAssortment == true ? await getAssortmentIds(storeData1, sosMSLOnly) : '';
            console.log('AssortIds:', sosCheckAssortment, sosMSLOnly, AssortIds);

            //storeBGData check
            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData')
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, visiteDate } = StoreJson
                if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    // setSOSStockData(storeBGData);
                    BgUnsavedChanges(true)
                    BgWindowData(storeBGData)
                }
            }

            //  call this after storeBGData check
            if (PSAllow) {
                // if Partial save is allowed then add the currently active category or group in BG var 
                BGPSAllow.current = true;
                PSGroupData.current = CatData1;
            }

            await db.transaction(async function (txn) {

                //get data from masters
                // let join1=` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                // let selectlist1=` DISTINCT p.SOSHeaderTable,p.SOSHeaderField,p.SOSHeaderValue,p.HeaderName as HeaderName,p.SOSHeaderNonEyeLevelFacing,p.SOSHeaderEyeLevelFacingLable,p.SOSHeaderImage,p.SOSHeaderImageCount,p.SOSHeaderImageGrid`;
                // let q=`SELECT ${selectlist1} from Master_ShareOfShelfEyeLevelDefinition p ${join1} Where m.StoreId ='${StoreId}'  
                // ${sosCheckAssortment==true?` and p.SOSHeaderValue in (${AssortIds}) `:''}  
                // order by p.HeaderName `;

                //get inserted SOS data 
                // let selectlist2=` DISTINCT p.SOS_HEADER_ID as SOSHeaderId,m.SOSHeaderTable,m.SOSHeaderField,p.SOS_HDR_VALUE as SOSHeaderValue,p.HEADER_NAME as HeaderName,m.SOSHeaderNonEyeLevelFacing,m.SOSHeaderEyeLevelFacingLable,m.SOSHeaderImage,m.SOSHeaderImageCount,m.SOSHeaderImageGrid,p.SOS_HDR_FACING as SOSHdrFacing `;
                // // let join3=` INNER JOIN Mapping_StoreShareOfShelfEyeLevel mp on m.SOSDefinitionId=mp.SOSDefinitionId `;
                // let join4=` INNER JOIN Master_ShareOfShelfEyeLevelDefinition m on p.SOS_HDR_VALUE=m.SOSHeaderValue `;
                // let q2=` SELECT ${selectlist2} FROM ${AppTables.SOS_HDR_DATA} p ${join4} WHERE p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' order by p.HEADER_NAME  `;


                //get Data from masters with saved data of any
                let FilterIdsJoin = FilteredIds.length > 0 ? FilteredIds.join(',') : '';
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let join5 = ` LEFT OUTER JOIN ${AppTables.EYE_LEVEL_HDR_DATA} wd on p.SOSHeaderValue=wd.SOS_HDR_VALUE and wd.STORE_ID='${StoreId}' and wd.VISIT_DATE='${d2}'`;
                let selectlist1 = ` DISTINCT wd.SOS_HEADER_ID as SOSHeaderId,p.SOSHeaderTable,p.SOSHeaderField,p.SOSHeaderEyeLevelFacing,p.SOSHeaderValue,p.HeaderName as HeaderName,p.SOSHeaderNonEyeLevelFacing,p.SOSHeaderEyeLevelFacingLable,p.SOSHeaderNonEyeLevelFacingLable,p.SOSHeaderImage,p.SOSHeaderImageCount,p.SOSHeaderImageGrid,wd.EYE_LEVEL_HDR_FACING as SOSHdrEyeFacing,wd.NONEYE_LEVEL_HDR_FACING as SOSHdrNonEyeFacing`;
                // let selectlist2=` DISTINCT p.SOS_HEADER_ID as SOSHeaderId,m.SOSHeaderTable,m.SOSHeaderField,p.SOS_HDR_VALUE as SOSHeaderValue,p.HEADER_NAME as HeaderName,m.SOSHeaderNonEyeLevelFacing,m.SOSHeaderEyeLevelFacingLable,m.SOSHeaderImage,m.SOSHeaderImageCount,m.SOSHeaderImageGrid,p.SOS_HDR_FACING as SOSHdrFacing `;
                let q = `SELECT ${selectlist1} from Master_ShareOfShelfEyeLevelDefinition p ${join1} ${join5} Where m.StoreId ='${StoreId}'  
                ${sosCheckAssortment == true ? ` and p.SOSHeaderValue in (${AssortIds}) ` : ''}  `;
                if (ShowCatWise1 == true) {
                    q += ` and p.SOSHeaderValue in (${FilterIdsJoin}) `;
                }
                q += `order by p.HeaderName `;

                console.log('q:', q);
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    // console.log('soscats added:',txnres.rows.length);

                    if (txnres.rows.length > 0) {
                        let arr = [], allCats = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);

                            let SOSHeaderEyeLevelFacing = data.SOSHeaderEyeLevelFacing == 1 || data.SOSHeaderEyeLevelFacing == 'true' ? true : false;
                            let SOSHeaderNonEyeLevelFacing = data.SOSHeaderNonEyeLevelFacing == 1 || data.SOSHeaderNonEyeLevelFacing == 'true' ? true : false;
                            console.log("SOSHeaderEyeLevelFacing-", SOSHeaderEyeLevelFacing)
                            if (SOSHeaderEyeLevelFacing) {
                                inputRefs.current['input_' + data.SOSHeaderValue] = '';
                            }
                            if (SOSHeaderNonEyeLevelFacing) {
                                inputRefs.current['input1_' + data.SOSHeaderValue] = '';
                            }

                            let AllCData = await getChilds(storeData1, data, menu1, sosMSLOnly, sosCheckAssortment);
                            let allChilds = AllCData['allChilds'] || [];
                            let childData = AllCData['childData'] || [];
                            data['skulist'] = allChilds;
                            arr.push(data);
                            let HdrImages = await getHdrImages(storeData1, data, menu1, data.SOSHeaderImageCount);

                            let defData = { 'SOSHeaderValue': data.SOSHeaderValue, 'SOSHdrNonEyeFacing': data.SOSHeaderId != null ? data.SOSHdrNonEyeFacing : '', 'SOSHdrEyeFacing': data.SOSHeaderId != null ? data.SOSHdrEyeFacing : '', 'Images': HdrImages, 'SKUData': childData };
                            allCats.push(defData);
                            if (i == txnres.rows.length - 1) {
                                let { menuName, StoreId1, visiteDate } = bgStoreJson
                                if (!isBgDataExists) {
                                    BgWindowData(allCats)
                                }
                                setAllSOSData(arr);
                                // setSOSStockData(allCats);
                                setProcessing(false);
                            }
                        }
                    }
                    else {
                        setProcessing(false);
                        notify("No data found");
                    }
                    // else{
                    //     await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    //         // console.log('soscats',txnres2.rows.length);
                    //         if(txnres2.rows.length>0){
                    //             let arr=[],allCats=[],storeBGData1=[],bgStoreJson={};
                    //             let windData = await get_item('storeData')
                    //             if(windData!=null && windData!=''){
                    //                 let StoreJson = JSON.parse(windData)
                    //                 let { storeBGData,menuName,StoreId1,visiteDate }= StoreJson
                    //                 if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    //                     storeBGData1=storeBGData;
                    //                     bgStoreJson=StoreJson
                    //                     BgUnsavedChanges(true)
                    //                     BgWindowData(storeBGData)
                    //                     // setSOSStockData(storeBGData);
                    //                 }
                    //             }

                    //             for(var i=0;i<txnres2.rows.length;i++){
                    //                 let data =txnres2.rows.item(i);
                    //                 inputRefs.current['input_'+data.SOSHeaderValue]='';
                    //                 let AllCData=await getChilds(storeData1,data,menu1,sosMSLOnly,sosCheckAssortment);
                    //                 let allChilds=AllCData['allChilds'] || [];
                    //                 let childData=AllCData['childData'] || [];
                    //                 data['skulist']=allChilds;
                    //                 arr.push(data);
                    //                 let HdrImages=[];
                    //                 for(var s=0;s<data.SOSHeaderImageCount;s++){
                    //                     let obj={'Image1Name':'','Image1':'',img1Required:true };
                    //                     HdrImages.push(obj);
                    //                 }
                    //                 let defData={'SOSHeaderValue':data.SOSHeaderValue,'SOSHdrFacing':'','Images':HdrImages,'SKUData':childData};
                    //                 allCats.push(defData);
                    //                 if(i==txnres2.rows.length-1){
                    //                     let { menuName,StoreId1,visiteDate }=bgStoreJson
                    //                     if(storeBGData1!=null && storeBGData1!='' && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    //                         if(storeBGData1.length<=0){
                    //                             // setSOSStockData(allCats);
                    //                             BgWindowData(allCats)
                    //                         }
                    //                     }else{
                    //                         BgWindowData(allCats)
                    //                         // setSOSStockData(allCats);   
                    //                     }
                    //                     setAllSOSData(arr);
                    //                     // setSOSStockData(allCats);
                    //                     setProcessing(false);
                    //                 }
                    //             }
                    //         }else{
                    //             setProcessing(false);
                    //             notify('No data found','SHORT')
                    //         }
                    //     },function (txnE,txnerr) { console.log(txnerr); },);
                    // }
                }, function (txnE, txnerr) { console.log(txnerr); },);
                // setProcessing(false);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function getWindowFilterIds(idCol, IdVal, storeData1) {
        let AllIds = [];
        let { StoreId } = storeData1
        return new Promise((resolve, reject) => {

            db.transaction(async function (txn) {
                let join = ` inner join Mapping_StoreShareOfShelfEyeLevel s on w.SOSDefinitionId=s.SOSDefinitionId  `;
                let q = `Select w.* from Master_ShareOfShelfEyeLevelDefinition w ${join} where s.StoreId='${StoreId}' `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let Wind_data = txnres.rows.item(0);
                        let { SOSHeaderTable } = Wind_data;
                        SOSHeaderTable = SOSHeaderTable != null ? SOSHeaderTable : '';

                        let filterIdsCol = '', filterNamesCol = '';
                        if (SOSHeaderTable.toLowerCase() == HierarchyTbls.Master_Category.toLowerCase()) {
                            filterIdsCol = 'CategoryId', filterNamesCol = 'CategoryName';
                        }
                        else if (SOSHeaderTable.toLowerCase() == HierarchyTbls.Master_Brand.toLowerCase()) {
                            filterIdsCol = 'BrandId', filterNamesCol = 'BrandName';
                        }
                        else if (SOSHeaderTable.toLowerCase() == HierarchyTbls.Master_Product.toLowerCase()) {
                            filterIdsCol = 'ProductId', filterNamesCol = 'ProductName';
                        }
                        else {
                            filterIdsCol = 'SubCategoryId', filterNamesCol = 'SubCategoryName';
                        }

                        let FIdsQ = `Select Distinct p.${filterIdsCol},p.${filterNamesCol} from Product_Master p where (p.${idCol}='${IdVal}' or p.${idCol}= ${IdVal})`;
                        console.log('FIdsQ:', FIdsQ);
                        await txn.executeSql(FIdsQ, [], async function (txn2, txnres2) {
                            if (txnres.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let id_value = data[filterIdsCol];
                                    AllIds.push(id_value);
                                    if (i == txnres2.rows.length - 1) {
                                        resolve(AllIds)
                                    }
                                }
                            }
                            else {
                                resolve([]);
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve(AllIds) });


                    }
                    else {
                        resolve(AllIds)
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(AllIds) },);
            });
        }).then((val) => {
            return val
        }).catch((err) => {
            console.log(err);
            return AllIds;
        });
    }

    async function getAssortmentIds(storeData1 = {}, sosMSLOnly = false) {
        let { StoreId, ChainId, StateId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData1;
        let AllIds = [];
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let q = `select Distinct p.SOSHeaderTable,p.SOSHeaderField from Master_ShareOfShelfEyeLevelDefinition p ${join1}  Where m.StoreId ='${StoreId}' and p.SOSHeaderTable!=''  and p.SOSHeaderTable is not null  `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        let SOSHeaderTable = data['SOSHeaderTable'];
                        let SOSHeaderField = data['SOSHeaderField'];

                        let join2 = `  INNER JOIN Mapping_ProductAssortmentStorewise mp on t1.ProductId=mp.ProductId `;
                        let q2 = `select distinct t1.${SOSHeaderField} from Product_Master t1 ${join2} where mp.StoreId='${StoreId}' ${sosMSLOnly == true ? ` and  (mp.MSL='true' or mp.MSL='1' or mp.MSL =1) ` : ''}  `;
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let id = data[SOSHeaderField];
                                    AllIds.push(id);
                                    if (i == txnres2.rows.length - 1) {
                                        let AllIdsJoin = AllIds.join(',');
                                        resolve(AllIdsJoin);
                                    }
                                }
                            }
                            else {
                                resolve('')
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve('') },);
                    }
                    else {
                        resolve('')
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve('') },);
            });
        }).then((val) => {
            return val;
        }).catch((err) => {
            console.log(err);
            return '';
        });
    }

    async function getChildAssortmentIds(storeData1 = {}, sosMSLOnly = false) {
        let { StoreId, ChainId, StateId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData1;
        let AllIds = [];
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let q = `select Distinct p.SOSChildTable,p.SOSChildField from Master_ShareOfShelfEyeLevelDefinition p ${join1}  Where m.StoreId ='${StoreId}' and p.SOSChildTable!=''  and p.SOSChildTable is not null  `;

                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        let SOSChildTable = data['SOSChildTable'];
                        let SOSChildField = data['SOSChildField'];

                        let join2 = `  INNER JOIN Mapping_ProductAssortmentStorewise mp on t1.ProductId=mp.ProductId `;
                        let q2 = `select distinct t1.${SOSChildField} from Product_Master t1 ${join2} where mp.StoreId='${StoreId}' ${sosMSLOnly == true ? ` and  (mp.MSL='true' or mp.MSL='1' or mp.MSL =1) ` : ''}  `;
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let id = data[SOSChildField];
                                    AllIds.push(id);
                                    if (i == txnres2.rows.length - 1) {
                                        let AllIdsJoin = AllIds.join(',');
                                        resolve(AllIdsJoin);
                                    }
                                }
                            }
                            else {
                                resolve('')
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve('') },);
                    }
                    else {
                        resolve('')
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve('') },);
            });
        }).then((val) => {
            return val;
        }).catch((err) => {
            console.log(err);
            return '';
        });
    }


    async function getHdrImages(storeData1, cat1, menu1, SOSHeaderImageCount) {
        let allImages = [];
        let { StoreId } = storeData1;
        let { SOSHeaderId } = cat1;
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                let q = ` SELECT IMAGE1 as Image1 FROM ${AppTables.SOS_IMAGES} where SOS_HEADER_ID='${SOSHeaderId}' and TYPE='Header' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let { Image1 } = data;
                            let imagePath = Image1 != null && Image1 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + Image1 : '';
                            let obj = { 'Image1Name': data.Image1, 'Image1': imagePath };
                            allImages.push(obj);
                            if (i == txnres.rows.length - 1) {
                                resolve(allImages);
                            }
                        }
                    }
                    else {
                        if (SOSHeaderImageCount > 0) {
                            for (let s = 0; s < SOSHeaderImageCount; s++) {
                                let obj = { 'Image1Name': '', 'Image1': '', img1Required: true };
                                allImages.push(obj);
                                if (s == SOSHeaderImageCount - 1) {
                                    resolve(allImages);
                                }
                            }
                        }
                        else {
                            resolve(allImages);
                        }

                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(allImages); },);
            });
        }).catch((err) => {
            return allImages;
        })
    }

    async function getChilds(storeData1, cat1, menu1, sosMSLOnly = false, sosCheckAs = false) {
        let defData = { allChilds: [], childData: [] };
        let { StoreId, StateId } = storeData1;
        let { SOSHeaderValue } = cat1;
        // SOSChildValue
        let childAssorted = await getChildAssortmentIds(storeData1, sosMSLOnly)
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {

                // let selectlist=` p.SOSDefinitionId,p.SOSChildTable,p.SOSChildField,p.SOSChildValue,p.ChildName,p.SOSChildEyeLevelTotalFacing,p.SOSChildNonEyeLevelSelfFacing,p.SOSChildEyeLevelTotalFacingLable,p.SOSChildNonEyeLevelSelfFacingLable,p.SOSChildImage,p.SOSChildImageCount,p.SOSChildImageGrid`;
                // let join1=` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                // let q=`SELECT ${selectlist} from Master_ShareOfShelfEyeLevelDefinition p ${join1} Where m.StoreId ='${StoreId}' and p.SOSHeaderValue='${SOSHeaderValue}'  
                // ${sosCheckAs==true?` and p.SOSChildValue in (${childAssorted}) `:''}  
                // order by p.ChildName  `;

                // let selectlist2=` m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,p.SOS_CHILD_VALUE as SOSChildValue,p.CHILD_NAME as ChildName,m.SOSChildEyeLevelTotalFacing,m.SOSChildNonEyeLevelSelfFacing,m.SOSChildEyeLevelTotalFacingLable,m.SOSChildNonEyeLevelSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_FACING as TotalFacing,p.SELF_FACING as SelfNonEyeFacing`;
                // // let join3=` INNER JOIN Mapping_StoreShareOfShelfEyeLevel mp on m.SOSDefinitionId=mp.SOSDefinitionId `;
                // let join4=` INNER JOIN Master_ShareOfShelfEyeLevelDefinition m on p.SOS_DEFINITION_ID=m.SOSDefinitionId `;
                // let q2=` SELECT ${selectlist2} FROM ${AppTables.SOS_CHILD_DATA} p ${join4}  WHERE p.SOS_HDR_VALUE='${SOSHeaderValue}' and p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' order by p.CHILD_NAME  `;


                // get data from masters with saved data

                // wd.SELF_EYE_FACING as SelfEyeFacing
                let selectlist = ` p.SOSDefinitionId,p.SOSChildTable,p.SOSChildField,p.SOSChildValue,p.ChildName,p.SOSChildEyeLevelTotalFacing,p.SOSChildNonEyeLevelTotalFacing,p.SOSChildNonEyeLevelSelfFacing,p.SOSChildEyeLevelSelfFacing,p.SOSHeaderNonEyeLevelFacingLable,p.SOSChildEyeLevelTotalFacingLable,p.SOSChildEyeLevelSelfFacingLable,p.SOSChildNonEyeLevelSelfFacingLable,p.SOSChildImage,p.SOSChildImageCount,p.SOSChildImageGrid,wd.TOTAL_EYE_FACING as TotalEyeLevelFacing, wd.TOTAL_NONEYE_FACING as TotalNonEyeFacing ,wd.SELF_EYE_FACING as SelfEyeFacing ,wd.SELF_NONEYE_FACING as SelfNonEyeFacing,tg.SOSTarget`;
                // let selectlist2=` m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,p.SOS_CHILD_VALUE as SOSChildValue,p.CHILD_NAME as ChildName,m.SOSChildEyeLevelTotalFacing,m.SOSChildNonEyeLevelSelfFacing,m.SOSChildEyeLevelTotalFacingLable,m.SOSChildNonEyeLevelSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_FACING as TotalFacing,p.SELF_FACING as SelfNonEyeFacing`;
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelfEyeLevel m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let join5 = ` LEFT OUTER JOIN ${AppTables.EYE_LEVEL_CHILD_DATA} wd on p.SOSDefinitionId=wd.SOS_DEFINITION_ID and wd.SOS_HDR_VALUE='${SOSHeaderValue}' and wd.STORE_ID='${StoreId}' and wd.VISIT_DATE='${d2}'  `;
                let target_join = ` LEFT OUTER JOIN  Mapping_ShareOfShelfTarget tg on p.SOSDefinitionId=tg.SOSDefinitionId and tg.StateId='${StateId}'  `;

                let q = `SELECT ${selectlist} from Master_ShareOfShelfEyeLevelDefinition p ${join1} ${join5} ${target_join} Where m.StoreId ='${StoreId}' and p.SOSHeaderValue='${SOSHeaderValue}'  
                ${sosCheckAs == true ? ` and p.SOSChildValue in (${childAssorted}) ` : ''}  
                order by p.ChildName  `;


                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('sossubcats added', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [], arr2 = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);

                            let SOSChildEyeLevelTotalFacing = data.SOSChildEyeLevelTotalFacing == 1 || data.SOSChildEyeLevelTotalFacing == 'true' ? 1 : 0;
                            let SOSChildNonEyeLevelTotalFacing = data.SOSChildNonEyeLevelTotalFacing == 1 || data.SOSChildNonEyeLevelTotalFacing == 'true' ? 1 : 0;
                            let SOSChildNonEyeLevelSelfFacing = data.SOSChildNonEyeLevelSelfFacing == 1 || data.SOSChildNonEyeLevelSelfFacing == 'true' ? 1 : 0;
                            let SOSChildEyeLevelSelfFacing = data.SOSChildEyeLevelSelfFacing == 1 || data.SOSChildEyeLevelSelfFacing == 'true' ? 1 : 0;

                            if (SOSChildEyeLevelTotalFacing == 1) {
                                console.log("input2_", 'input2_' + SOSHeaderValue + "_" + data.SOSChildValue)
                                inputRefs.current['input2_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }
                            if (SOSChildNonEyeLevelTotalFacing == 1) {
                                console.log("input3_", 'input3_' + SOSHeaderValue + "_" + data.SOSChildValue)

                                inputRefs.current['input3_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }
                            if (SOSChildEyeLevelSelfFacing == 1) {
                                console.log("input4_", 'input4_' + SOSHeaderValue + "_" + data.SOSChildValue)

                                inputRefs.current['input4_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }
                            if (SOSChildNonEyeLevelSelfFacing == 1) {
                                console.log("input5_", 'input5_' + SOSHeaderValue + "_" + data.SOSChildValue)
                                inputRefs.current['input5_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }


                            arr.push(data);
                            let allChildImages = await getChildImages(storeData1, cat1, data, menu1, data.SOSChildImageCount);
                            let defCData = { 'SOSChildValue': data.SOSChildValue, 'TotalNonEyeFacing': data.TotalNonEyeFacing, 'TotalEyeLevelFacing': data.TotalEyeLevelFacing, 'SelfNonEyeFacing': data.SelfNonEyeFacing, 'SelfEyeFacing': data.SelfEyeFacing, 'ChildImages': (allChildImages || []) };

                            console.log("SOSChildNonEye----", defCData)
                            arr2.push(defCData);
                            if (i == txnres.rows.length - 1) {
                                defData['allChilds'] = arr;
                                defData['childData'] = arr2;
                                resolve(defData);
                            }
                        }
                    } else {
                        resolve(defData);
                    }
                    // else{
                    //     console.log('sossubcats added',txnres.rows.length);
                    //     await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    //         if(txnres2.rows.length>0){
                    //             let arr=[],arr2=[];
                    //             for(var i=0;i<txnres2.rows.length;i++){
                    //                 let data =txnres2.rows.item(i);
                    //                 let SOSChildEyeLevelTotalFacing=data.SOSChildEyeLevelTotalFacing==1 || data.SOSChildEyeLevelTotalFacing=='true'?1: 0;
                    //                 let SOSChildNonEyeLevelSelfFacing=data.SOSChildNonEyeLevelSelfFacing==1 || data.SOSChildNonEyeLevelSelfFacing=='true'?1: 0;
                    //                 if( SOSChildEyeLevelTotalFacing==1){
                    //                     inputRefs.current['input1_'+SOSHeaderValue+"_"+data.SOSChildValue]='';
                    //                 }
                    //                  if(SOSChildNonEyeLevelSelfFacing==1){
                    //                     inputRefs.current['input2_'+SOSHeaderValue+"_"+data.SOSChildValue]='';
                    //                 }
                    //                 arr.push(data);
                    //                 let allChildImages=[];
                    //                 for(var s=0;s<data.SOSChildImageCount;s++){
                    //                     let obj={'Image1Name':'','Image1':'',img1Required:true};
                    //                     allChildImages.push(obj);
                    //                 }
                    //                 let defCData={'SOSChildValue':data.SOSChildValue,'TotalFacing':'','SelfNonEyeFacing':'','ChildImages':allChildImages};
                    //                 arr2.push(defCData);
                    //                 if(i==txnres2.rows.length-1){
                    //                     defData['allChilds']=arr;
                    //                     defData['childData']=arr2;
                    //                     resolve(defData);
                    //                 }
                    //             }
                    //         }
                    //         else{
                    //             resolve(defData);
                    //         }
                    //     },function (txnE,txnerr) { console.log(txnerr); resolve(defData); },);
                    // }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);
            });
        }).catch((err) => {
            return defData;
        });
    }

    async function getChildImages(storeData1, cat1, subcat1, menu1, SOSChildImageCount) {
        let allImages = [];
        let { StoreId } = storeData1;
        let { SOSHeaderId } = cat1;
        let { SOSChildValue } = subcat1;
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                let q = ` SELECT IMAGE1 as Image1 FROM ${AppTables.SOS_IMAGES} where SOS_HEADER_ID='${SOSHeaderId}' and SOS_CHILD_VALUE='${SOSChildValue}' and TYPE='Child' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let { Image1 } = data;
                            let imagePath = Image1 != null && Image1 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + Image1 : '';
                            let obj = { 'Image1Name': Image1, 'Image1': imagePath };
                            allImages.push(obj);
                            if (i == txnres.rows.length - 1) {
                                resolve(allImages);
                            }
                        }
                    }
                    else {
                        if (SOSChildImageCount > 0) {
                            for (let s = 0; s < SOSChildImageCount; s++) {
                                let obj = { 'Image1Name': '', 'Image1': '', img1Required: true };
                                allImages.push(obj);
                                if (s == SOSChildImageCount - 1) {
                                    resolve(allImages);
                                }
                            }
                        }
                        else {
                            resolve(allImages);
                        }

                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(allImages); },);
            });
        }).catch((err) => {
            return allImages;
        })
    }




    async function getImage(imgdata) {
        let type = getImageProps.type || '';
        let cat = getImageProps.cat || {};
        let splitItem = getImageProps.splitItem || {};
        let splitItemIndex = getImageProps.splitItemIndex || 0;
        let skuItem = getImageProps.sku != null ? getImageProps.sku : {};

        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }
        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();
            ////change by jeevanp
            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')
            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            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 + ' - (' + cat.HeaderName + ')' + ' | Date:' + calculate_tym_date_over_img;

            let filename = '';
            if (type == '2') {
                filename = storeData.StoreId + '_' + cat.SOSHeaderValue + '_' + skuItem.SOSChildValue + '_' + splitItemIndex + '_' + (props.UserId || '') + '_SOSImg-' + calculate_tym_date_for_filename + '.jpg';
            }
            else {
                filename = storeData.StoreId + '_' + cat.SOSHeaderValue + '_' + splitItemIndex + '_' + (props.UserId || '') + '_SOSImg-' + calculate_tym_date_for_filename + '.jpg';
            }

            let allData = SOSStockData;
            let defData = { 'SOSHeaderValue': cat.SOSHeaderValue, 'Images': [], 'SKUData': [] };
            const catDataIndex = allData.findIndex(i => i.SOSHeaderValue == cat.SOSHeaderValue);
            const catData = catDataIndex >= 0 ? allData[catDataIndex] : {};


            if (type == '2') {
                var SKUData = catData['SKUData'] || [];
                var childIndex = SKUData.findIndex(i => i.SOSChildValue == skuItem.SOSChildValue);
                var childData = childIndex >= 0 ? SKUData[childIndex] : {};

                var ChildImages = childData['ChildImages'] || [];
                var image_key = 'Image1Name';
                var image_key_path = 'Image1';
                splitItem[image_key] = filename;
            }
            else {
                var HeaderImages = catData['Images'] || [];
                var image_key = 'Image1Name';
                var image_key_path = 'Image1';
                splitItem[image_key] = filename;
            }


            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    console.log('image marker:', uri);
                    setSelectedImg(uri)

                    if (type == '2') {
                        splitItem[image_key_path] = uri;
                        splitItemIndex >= 0 ? ChildImages[splitItemIndex] = splitItem : ChildImages.push(splitItem);
                        childData['ChildImages'] = ChildImages;
                        childIndex >= 0 ? SKUData[childIndex] = childData : SKUData.push(childData);

                        catData['SKUData'] = SKUData;
                        catDataIndex >= 0 ? allData[catDataIndex] = catData : allData.push(catData);
                        setSOSStockData(allData);
                        BgWindowData(allData)
                        // setHasUnsavedChanges(true);
                        BgUnsavedChanges(true)
                        setrerenderdata(!rerenderdata);
                    }
                    else {
                        console.log('Hdr split image updated');
                        splitItem[image_key_path] = uri;
                        splitItemIndex >= 0 ? HeaderImages[splitItemIndex] = splitItem : HeaderImages.push(splitItem);
                        catData['Images'] = HeaderImages;
                        catDataIndex >= 0 ? allData[catDataIndex] = catData : allData.push(catData);
                        // setSOSStockData(allData);
                        BgWindowData(allData)
                        // setHasUnsavedChanges(true);
                        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(cat, splitItem, splitItemIndex, type = '1', sku) {
        setErrorField({});
        setError(false);
        let GridAllow = type === '1' ? (window.SOSHeaderImageGrid === 'true' || window.SOSHeaderImageGrid == true || window.SOSHeaderImageGrid == '1' || window.SOSHeaderImageGrid == 1) : (window.SOSChildImageGrid === 'true' || window.SOSChildImageGrid == true || window.SOSChildImageGrid == '1' || window.SOSChildImageGrid == 1)
        setGridValue(GridAllow);
        setGetImageProps({ 'cat': cat, 'splitItem': splitItem, 'splitItemIndex': splitItemIndex, 'type': type, 'sku': sku });
        setShowCamera(true);
    }

    async function onFocusChange(cat, sku, inputType = '1') {
        let d = { 'catId': cat.SOSHeaderValue, 'subcatId': sku.SubSOSHeaderValue, 'inputType': inputType };
        console.log(d);
        setCurrentFocusedData(d);
    }

    async function focusToNext(cat, catIndex, skus, sku_index, type = 'EyeHEADER') {

        let activeKey = '';
        let arr = Object.keys(inputRefs.current);

        if (type == 'EyeHEADER') {
            activeKey = 'input_' + cat.SOSHeaderValue;
        } else if (type == 'NonEyeHEADER') {
            activeKey = 'input1_' + cat.SOSHeaderValue;
        } else if (type == "ChildEyeTotal") {
            activeKey = 'input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue;
        } else if (type == "ChildNonEyeTotal") {
            activeKey = 'input3_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue;
        } else if (type == "CHILD1") {
            activeKey = 'input4_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue;
        } else if (type == "CHILD2") {
            activeKey = 'input5_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue;
        }


        let activeIndex = arr.indexOf(activeKey);
        if (activeIndex < arr.length - 1) {
            let nextKey = arr[++activeIndex]
            let nextRef = inputRefs.current[nextKey];
            console.log("nextKey", activeKey, cat, nextKey, nextRef, inputRefs.current[nextKey])
            nextRef.focus();
        }
        else {
            return
        }

    }

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

    async function saveData() {
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            let { PSAllow } = currentMenu
            let deletePrevData = false;
            if (ShowCatWise && PSAllow) {
                if (FilteredPromoValues.length > 0) {
                    await removePreviousData();
                }
                else {
                    notify('Something went wrong while deleteing old data!')
                    setProcessing(false);
                    return;
                }
            } else {
                deletePrevData = true;
            }


            await db.transaction(async function (txn) {

                //  remove old data
                if (deletePrevData) {
                    let q = `DELETE FROM ${AppTables.EYE_LEVEL_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    let q2 = `DELETE FROM ${AppTables.EYE_LEVEL_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    let q3 = `DELETE FROM ${AppTables.EYE_LEVEL_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

                    await txn.executeSql(q, [], async function (txn2, txnres) {
                        console.log('stock facing hdr data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    await txn.executeSql(q2, [], async function (txn2, txnres) {
                        console.log('stock facing images deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    await txn.executeSql(q3, [], async function (txn2, txnres) {
                        console.log('stock facing child data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }

                insertData();


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

    async function removePreviousData() {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData;

        return new Promise((resolve, reject) => {

            db.transaction(async function (txn) {
                let FilterIdsJoin = FilteredPromoValues.join(',');
                let q = `SELECT * FROM ${AppTables.EYE_LEVEL_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SOS_HDR_VALUE in (${FilterIdsJoin})   `
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log("data to delete:", txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        let isHdrDel = false, isImagesDel = false, isStockDel = false;
                        for (let i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let { SOS_HEADER_ID } = data;
                            arr.push(SOS_HEADER_ID);

                            if (i == txnres.rows.length - 1) {
                                let AllHdrIds = `'${arr.join("','")}'`;

                                await txn.executeSql(`DELETE FROM ${AppTables.EYE_LEVEL_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SOS_HEADER_ID in (${AllHdrIds}) `, [], async function (txn2, txnres) {
                                    console.log('window hdr data deleted');
                                    isHdrDel = true;
                                    if (isHdrDel && isImagesDel && isStockDel) {
                                        resolve(true);
                                    }
                                }, function (txnE, txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.EYE_LEVEL_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SOS_HEADER_ID in (${AllHdrIds}) `, [], async function (txn2, txnres) {
                                    console.log('window images data deleted');
                                    isImagesDel = true;
                                    if (isHdrDel && isImagesDel && isStockDel) {
                                        resolve(true);
                                    }
                                }, function (txnE, txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.EYE_LEVEL_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SOS_HEADER_ID in (${AllHdrIds}) `, [], async function (txn2, txnres) {
                                    console.log('window stock data deleted');
                                    isStockDel = true;
                                    if (isHdrDel && isImagesDel && isStockDel) {
                                        resolve(true);
                                    }
                                }, function (txnE, txnerr) { console.log(txnerr); },);

                            }
                        }
                    }
                    else {
                        resolve(true);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);


            });

        }).then((val) => {
            return val;
        }).catch((err) => {
            console.log('error:', err);
            return false;
        })
    }

    async function insertData() {
        try {

            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {
                var values = '', stock_values = '', images_values = '', SOSHdrFacingDec = '', lastchar = '', SelfFacinglastchar = '', SelfFacingDec = '', TotalFacingDec = '', TotalFacinglastchar = '';
                for (var i = 0; i < AllSOSData.length; i++) {
                    let item = AllSOSData[i];
                    const cat = item;
                    const catIndex = i;
                    let { SOSHeaderTable, SOSHeaderField, SOSHeaderValue, HeaderName, SOSHeaderNonEyeLevelFacing, SOSHeaderEyeLevelFacingLable, SOSHeaderNonEyeLevelFacingLable, SOSHeaderImage, SOSHeaderImageCount, SOSHeaderImageGrid } = cat;
                    let SOSHeaderId = 'SOS' + i + SOSHeaderValue + moment().format('MMDDYYYYHHmmss');
                    const cindex = SOSStockData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
                    const cobj = cindex >= 0 ? SOSStockData[cindex] : {};
                    const HeaderImages = cobj['Images'] || [];
                    let SOSHdrEyeFacing = cobj['SOSHdrEyeFacing'] != null ? cobj['SOSHdrEyeFacing'] : (cobj['SOSHdrEyeFacing'] === 0 ? cobj['SOSHdrEyeFacing'] : '');
                    SOSHdrEyeFacing = SOSHdrEyeFacing + "";

                    let SOSHdrNonEyeFacing = cobj['SOSHdrNonEyeFacing'] != null ? cobj['SOSHdrNonEyeFacing'] : (cobj['SOSHdrNonEyeFacing'] === 0 ? cobj['SOSHdrNonEyeFacing'] : '');
                    SOSHdrNonEyeFacing = SOSHdrNonEyeFacing + "";


                    console.log("SOSHdrFacing:", SOSHdrEyeFacing)
                    // if decimal value is allowed in facing - then validate on save time if is there any illegal decimal value then adjust it , for e.g. 0. or .0 is not valid integer or float number 
                    // this will only alter the value of facing if it is in decimal form 
                    if (SOSHdrEyeFacing != null && SOSHdrEyeFacing != '' && SOSHdrEyeFacing.includes(".")) {
                        let SOSHdrEyeFacing_CharArr = SOSHdrEyeFacing.split(".");
                        // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                        // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                        let charbefore_dot = SOSHdrEyeFacing_CharArr.length > 0 ? (SOSHdrEyeFacing_CharArr[0] != null && SOSHdrEyeFacing_CharArr[0] != '' ? SOSHdrEyeFacing_CharArr[0] : '0') : '0';
                        let charafter_dot = SOSHdrEyeFacing_CharArr.length > 1 ? (SOSHdrEyeFacing_CharArr[1] != null && SOSHdrEyeFacing_CharArr[1] != '' ? SOSHdrEyeFacing_CharArr[1] : '0') : '0';
                        console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                        SOSHdrEyeFacing = charbefore_dot + "." + charafter_dot;
                        // lastchar=SOSHdrFacing.substring(SOSHdrFacing.length-2,SOSHdrFacing.length-1);
                        // SOSHdrFacingDec = lastchar==='.'?lastchar+"0": SOSHdrFacing;
                    }

                    if (SOSHdrNonEyeFacing != null && SOSHdrNonEyeFacing != '' && SOSHdrNonEyeFacing.includes(".")) {
                        let SOSHdrNonEyeFacing_CharArr = SOSHdrNonEyeFacing.split(".");
                        // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                        // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                        let charbefore_dot = SOSHdrNonEyeFacing_CharArr.length > 0 ? (SOSHdrNonEyeFacing_CharArr[0] != null && SOSHdrNonEyeFacing_CharArr[0] != '' ? SOSHdrNonEyeFacing_CharArr[0] : '0') : '0';
                        let charafter_dot = SOSHdrNonEyeFacing_CharArr.length > 1 ? (SOSHdrNonEyeFacing_CharArr[1] != null && SOSHdrNonEyeFacing_CharArr[1] != '' ? SOSHdrNonEyeFacing_CharArr[1] : '0') : '0';
                        console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                        SOSHdrNonEyeFacing = charbefore_dot + "." + charafter_dot;
                        // lastchar=SOSHdrFacing.substring(SOSHdrFacing.length-2,SOSHdrFacing.length-1);
                        // SOSHdrFacingDec = lastchar==='.'?lastchar+"0": SOSHdrFacing;
                    }
                    console.log("SOSHdrFacing after alter:", SOSHdrEyeFacing)

                    let this_SKUData = cobj['SKUData'] || [];
                    values += values != '' ? ' , ' : '';
                    values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderTable}','${SOSHeaderField}','${SOSHeaderValue}','${HeaderName}','${SOSHdrEyeFacing}','${SOSHdrNonEyeFacing}','${d2}') `;

                    let skulist = item['skulist'] || [];
                    let SOSHeaderImage1 = item.SOSHeaderImage == 1 || item.SOSHeaderImage == 'true' ? 1 : 0;
                    if (SOSHeaderImage1 == true) {
                        for (var k = 0; k < HeaderImages.length; k++) {
                            let imgObj = HeaderImages[k];
                            let { Image1Name, Image1 } = imgObj;
                            images_values += images_values != '' ? ' , ' : '';
                            images_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','','${(Image1Name || '')}','Header','${d2}') `;
                        }
                    }

                    for (var j = 0; j < skulist.length; j++) {
                        let skus = skulist[j];
                        let sku_index = j;
                        let { SOSDefinitionId, SOSChildTable, SOSChildField, SOSChildValue, ChildName, SOSChildEyeLevelTotalFacing, SOSChildEyeLevelSelfFacing, SOSChildNonEyeLevelSelfFacing, SOSChildEyeLevelTotalFacingLable, SOSChildNonEyeLevelSelfFacingLable, SOSChildEyeLevelSelfFacingLable, SOSChildImage, SOSChildImageCount, SOSChildImageGrid } = skus;
                        stock_values += stock_values != '' ? ' , ' : '';

                        let thisCatSkuData_i = this_SKUData.findIndex(i => i.SOSChildValue == skus.SOSChildValue);
                        let thisCatSkuData = thisCatSkuData_i >= 0 ? (this_SKUData[thisCatSkuData_i] || {}) : {};
                        let TotalFacing = thisCatSkuData.TotalFacing != null ? thisCatSkuData.TotalFacing : (thisCatSkuData.TotalFacing === 0 ? thisCatSkuData.TotalFacing : '');

                        let TotalNonEyeFacing = thisCatSkuData.TotalNonEyeFacing != null ? thisCatSkuData.TotalNonEyeFacing : (thisCatSkuData.TotalNonEyeFacing === 0 ? thisCatSkuData.TotalNonEyeFacing : '');
                        let TotalEyeLevelFacing = thisCatSkuData.TotalEyeLevelFacing != null ? thisCatSkuData.TotalEyeLevelFacing : (thisCatSkuData.TotalEyeLevelFacing === 0 ? thisCatSkuData.TotalEyeLevelFacing : '');

                        let SelfNonEyeFacing = thisCatSkuData.SelfNonEyeFacing != null ? thisCatSkuData.SelfNonEyeFacing : (thisCatSkuData.SelfNonEyeFacing === 0 ? thisCatSkuData.SelfNonEyeFacing : '');
                        let SelfEyeFacing = thisCatSkuData.SelfEyeFacing != null ? thisCatSkuData.SelfEyeFacing : (thisCatSkuData.SelfEyeFacing === 0 ? thisCatSkuData.SelfEyeFacing : '');


                        SelfNonEyeFacing = SelfNonEyeFacing + "";
                        SelfEyeFacing = SelfEyeFacing + "";

                        console.log("SelfNonEyeFacing", SelfNonEyeFacing)
                        // if decimal value is allowed in facing - then validate on save time if is there any illegal decimal value then adjust it , for e.g. 0. or .0 is not valid integer or float number 
                        // this will only alter the value of facing if it is in decimal form 

                        if (SelfEyeFacing != null && SelfEyeFacing != '' && SelfEyeFacing.includes(".")) {
                            let SelfFacing_CharArr = SelfEyeFacing.split(".");
                            // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                            // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                            let charbefore_dot = SelfFacing_CharArr.length > 0 ? (SelfFacing_CharArr[0] != null && SelfFacing_CharArr[0] != '' ? SelfFacing_CharArr[0] : '0') : '0';
                            let charafter_dot = SelfFacing_CharArr.length > 1 ? (SelfFacing_CharArr[1] != null && SelfFacing_CharArr[1] != '' ? SelfFacing_CharArr[1] : '0') : '0';
                            console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                            SelfEyeFacing = charbefore_dot + "." + charafter_dot;
                        }

                        if (SelfNonEyeFacing != null && SelfNonEyeFacing != '' && SelfNonEyeFacing.includes(".")) {
                            let SelfFacing_CharArr = SelfNonEyeFacing.split(".");
                            // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                            // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                            let charbefore_dot = SelfFacing_CharArr.length > 0 ? (SelfFacing_CharArr[0] != null && SelfFacing_CharArr[0] != '' ? SelfFacing_CharArr[0] : '0') : '0';
                            let charafter_dot = SelfFacing_CharArr.length > 1 ? (SelfFacing_CharArr[1] != null && SelfFacing_CharArr[1] != '' ? SelfFacing_CharArr[1] : '0') : '0';
                            console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                            SelfNonEyeFacing = charbefore_dot + "." + charafter_dot;
                        }

                        console.log("SelfNonEyeFacing after alter:", SelfNonEyeFacing)

                        TotalNonEyeFacing = TotalNonEyeFacing + "";
                        TotalEyeLevelFacing = TotalEyeLevelFacing + "";
                        TotalFacing = TotalFacing + "";

                        console.log("TotalFacing", TotalFacing)
                        // if decimal value is allowed in facing - then validate on save time if is there any illegal decimal value then adjust it , for e.g. 0. or .0 is not valid integer or float number 
                        // this will only alter the value of facing if it is in decimal form 
                        if (TotalFacing != null && TotalFacing != '' && TotalFacing.includes(".")) {
                            let TotalFacing_CharArr = TotalFacing.split(".");
                            // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                            // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                            let charbefore_dot = TotalFacing_CharArr.length > 0 ? (TotalFacing_CharArr[0] != null && TotalFacing_CharArr[0] != '' ? TotalFacing_CharArr[0] : '0') : '0';
                            let charafter_dot = TotalFacing_CharArr.length > 1 ? (TotalFacing_CharArr[1] != null && TotalFacing_CharArr[1] != '' ? TotalFacing_CharArr[1] : '0') : '0';
                            console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                            TotalFacing = charbefore_dot + "." + charafter_dot;
                        }

                        if (TotalEyeLevelFacing != null && TotalEyeLevelFacing != '' && TotalEyeLevelFacing.includes(".")) {
                            let TotalEyeLevelFacing_CharArr = TotalEyeLevelFacing.split(".");
                            // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                            // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                            let charbefore_dot = TotalEyeLevelFacing_CharArr.length > 0 ? (TotalEyeLevelFacing_CharArr[0] != null && TotalEyeLevelFacing_CharArr[0] != '' ? TotalEyeLevelFacing_CharArr[0] : '0') : '0';
                            let charafter_dot = TotalEyeLevelFacing_CharArr.length > 1 ? (TotalEyeLevelFacing_CharArr[1] != null && TotalEyeLevelFacing_CharArr[1] != '' ? TotalEyeLevelFacing_CharArr[1] : '0') : '0';
                            console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                            TotalEyeLevelFacing = charbefore_dot + "." + charafter_dot;
                        }
                        if (TotalNonEyeFacing != null && TotalNonEyeFacing != '' && TotalNonEyeFacing.includes(".")) {
                            let TotalNonEyeFacing_CharArr = TotalNonEyeFacing.split(".");
                            // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                            // (Warning !! more than 2 values resturn by split function on dot (.) char  will be ignored)
                            let charbefore_dot = TotalNonEyeFacing_CharArr.length > 0 ? (TotalNonEyeFacing_CharArr[0] != null && TotalNonEyeFacing_CharArr[0] != '' ? TotalNonEyeFacing_CharArr[0] : '0') : '0';
                            let charafter_dot = TotalNonEyeFacing_CharArr.length > 1 ? (TotalNonEyeFacing_CharArr[1] != null && TotalNonEyeFacing_CharArr[1] != '' ? TotalNonEyeFacing_CharArr[1] : '0') : '0';
                            console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                            TotalNonEyeFacing = charbefore_dot + "." + charafter_dot;
                        }

                        console.log("SelfNonEyeFacing after alter:", SelfNonEyeFacing)

                        const ChildImages = thisCatSkuData['ChildImages'] || [];

                        stock_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSDefinitionId}','${SOSHeaderValue}','${SOSChildTable}','${SOSChildField}','${SOSChildValue}','${ChildName}','${TotalEyeLevelFacing}','${TotalNonEyeFacing}','${SelfNonEyeFacing}','${SelfEyeFacing}','${d2}') `;

                        let SOSChildImage1 = SOSChildImage == 1 || SOSChildImage == 'true' ? 1 : 0;
                        if (SOSChildImage1 == true) {
                            for (var l = 0; l < ChildImages.length; l++) {
                                let imgObj = ChildImages[l];
                                let { Image1Name, Image1 } = imgObj;
                                images_values += images_values != '' ? ' , ' : '';
                                images_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','${SOSChildValue}','${(Image1Name || '')}','Child','${d2}') `;
                            }
                        }
                    }
                }

                console.log("values:", values)

                let add_StockHdr = `INSERT INTO ${AppTables.EYE_LEVEL_HDR_DATA} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_TABLE,SOS_HDR_FIELD,SOS_HDR_VALUE,HEADER_NAME,EYE_LEVEL_HDR_FACING,NONEYE_LEVEL_HDR_FACING,ADDED_DATE) VALUES ${values} `;
                let add_Stock = `INSERT INTO ${AppTables.EYE_LEVEL_CHILD_DATA} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_DEFINITION_ID,SOS_HDR_VALUE,SOS_CHILD_TABLE,SOS_CHILD_FIELD,SOS_CHILD_VALUE,CHILD_NAME,TOTAL_EYE_FACING,TOTAL_NONEYE_FACING,SELF_EYE_FACING,SELF_NONEYE_FACING,ADDED_DATE ) VALUES ${stock_values} `;
                let add_images = `INSERT INTO ${AppTables.EYE_LEVEL_IMAGES} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_VALUE,SOS_CHILD_VALUE,IMAGE1,TYPE,ADDED_DATE) VALUES ${images_values} `;

                console.log("add_Stock-------", add_Stock)
                await txn.executeSql(add_StockHdr, [], async function (txn2, txnres) {
                    console.log('stock facing header added');
                    await txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                        console.log('stock facing child added');

                        if (images_values != '') {
                            await txn.executeSql(add_images, [], async function (txn2, txnres) {
                                console.log('stock facing images added');
                                notify('Share Of Shelf data 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 Share Of Shelf data') },);
                        }
                        else {

                            notify('Share Of Shelf data 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 Share Of Shelf data') },);
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add Share Of Shelf data') },);
            });
        } catch (err) {
            console.log(err);
        }
    }


    async function validate() {
        function showError(obj, isErr) {
            setErrorField(obj);
            setError(isErr);
        }

        return new Promise((resolve, reject) => {
            for (const index in AllSOSData) {
                const item = AllSOSData[index];
                const cat = item;
                const catIndex = index;

                let SOSHeaderImage = item.SOSHeaderImage == 1 || item.SOSHeaderImage == 'true' ? 1 : 0;
                let SOSHeaderEyeLevelFacing = item.SOSHeaderEyeLevelFacing == 1 || item.SOSHeaderEyeLevelFacing == 'true' ? 1 : 0;
                let SOSHeaderEyeLevelFacingLable = item.SOSHeaderEyeLevelFacingLable != null ? item.SOSHeaderEyeLevelFacingLable : '';


                let SOSHeaderNonEyeLevelFacing = item.SOSHeaderNonEyeLevelFacing == 1 || item.SOSHeaderNonEyeLevelFacing == 'true' ? 1 : 0;
                let SOSHeaderNonEyeLevelFacingLable = item.SOSHeaderNonEyeLevelFacingLable != null ? item.SOSHeaderNonEyeLevelFacingLable : '';
                const cindex = SOSStockData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
                const cobj = cindex >= 0 ? SOSStockData[cindex] : {};
                const HeaderImages = cobj['Images'] || [];
                let SOSHdrEyeFacing = cobj['SOSHdrEyeFacing'] != null ? cobj['SOSHdrEyeFacing'] : '';
                let SOSHdrNonEyeFacing = cobj['SOSHdrNonEyeFacing'] != null ? cobj['SOSHdrNonEyeFacing'] : '';

                let this_SKUData = cobj['SKUData'] || [];
                let TotalSelfFacingsEntered = 0;
                let TotalSelfNonEyeFacingsEntered = 0;
                let TotalSelfEyeFacingsEntered = 0;
                console.log('StoreCameraAllow:', StoreCameraAllow);

                let errorobj = { 'EF_Cat': cat };

                if (SOSHeaderEyeLevelFacing == true && SOSHdrEyeFacing !== 0 && (SOSHdrEyeFacing == null || SOSHdrEyeFacing == '')) {
                    errorobj["EF_EyeHEADER"] = 'EyeHEADER';
                    showError(errorobj, true);
                    let refIn1 = inputRefs.current['input_' + cat.SOSHeaderValue];
                    refIn1.focus();
                    notify(`Please enter Header Facing for ${cat.HeaderName}`, 'SHORT');
                    resolve(false); return;
                }
                else if (SOSHeaderNonEyeLevelFacing == true && SOSHdrNonEyeFacing !== 0 && (SOSHdrNonEyeFacing == null || SOSHdrNonEyeFacing == '')) {
                    errorobj["EF_NonEyeHEADER"] = 'NonEyeHEADER';
                    showError(errorobj, true);
                    let refIn1 = inputRefs.current['input1_' + cat.SOSHeaderValue];
                    refIn1.focus();
                    notify(`Please enter Header Facing for ${cat.HeaderName}`, 'SHORT');
                    resolve(false); return;
                } else {
                    if (StoreCameraAllow && SOSHeaderImage == true && HeaderImages.length > 0) {
                        for (const splitItemIndex in HeaderImages) {
                            const splitItem = HeaderImages[splitItemIndex];
                            let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                            if (Image1Name == '') {
                                errorobj["EF_HdrImage"] = 'HdrImage';
                                errorobj["EF_HdrImageIndex"] = splitItemIndex;
                                showError(errorobj, true);
                                let refIn1 = inputRefs.current['input_' + cat.SOSHeaderValue];
                                refIn1.focus();
                                notify(`Please click all header images for ${cat.HeaderName}`, 'SHORT');
                                resolve(false); return;
                            }
                        }
                    }
                    let skulist = cat.skulist || [];
                    for (const sku_index in skulist) {
                        const skus = skulist[sku_index];

                        let SOSChildImage = skus.SOSChildImage == 1 || skus.SOSChildImage == 'true' ? 1 : 0;
                        let SOSChildEyeLevelTotalFacing = skus.SOSChildEyeLevelTotalFacing == 1 || skus.SOSChildEyeLevelTotalFacing == 'true' ? 1 : 0;
                        let SOSChildNonEyeLevelTotalFacing = skus.SOSChildNonEyeLevelTotalFacing == 1 || skus.SOSChildNonEyeLevelTotalFacing == 'true' ? 1 : 0;

                        let SOSChildNonEyeLevelSelfFacing = skus.SOSChildNonEyeLevelSelfFacing == 1 || skus.SOSChildNonEyeLevelSelfFacing == 'true' ? 1 : 0;
                        let SOSChildEyeLevelSelfFacing = skus.SOSChildEyeLevelSelfFacing == 1 || skus.SOSChildEyeLevelSelfFacing == 'true' ? 1 : 0;

                        let SOSChildNonEyeLevelSelfFacingLable = skus.SOSChildNonEyeLevelSelfFacingLable != null ? skus.SOSChildNonEyeLevelSelfFacingLable : '';
                        let SOSChildEyeLevelSelfFacingLable = skus.SOSChildEyeLevelSelfFacingLable != null ? skus.SOSChildEyeLevelSelfFacingLable : '';



                        let SOSChildEyeLevelTotalFacingLable = skus.SOSChildEyeLevelTotalFacingLable != null ? skus.SOSChildEyeLevelTotalFacingLable : '';
                        // let SOSChildNonEyeLevelSelfFacingLable=skus.SOSChildNonEyeLevelSelfFacingLable!=null?skus.SOSChildNonEyeLevelSelfFacingLable: '';


                        let thisCatSkuData_i = this_SKUData.findIndex(i => i.SOSChildValue == skus.SOSChildValue);
                        let thisCatSkuData = thisCatSkuData_i >= 0 ? (this_SKUData[thisCatSkuData_i] || {}) : {};
                        let TotalFacing = thisCatSkuData.TotalFacing != null ? thisCatSkuData.TotalFacing : '';

                        let TotalEyeLevelFacing = thisCatSkuData.TotalEyeLevelFacing != null ? thisCatSkuData.TotalEyeLevelFacing : '';
                        let TotalNonEyeFacing = thisCatSkuData.TotalNonEyeFacing != null ? thisCatSkuData.TotalNonEyeFacing : '';
                        let SelfNonEyeFacing = thisCatSkuData.SelfNonEyeFacing != null ? thisCatSkuData.SelfNonEyeFacing : '';
                        let SelfEyeFacing = thisCatSkuData.SelfEyeFacing != null ? thisCatSkuData.SelfEyeFacing : '';

                        const ChildImages = thisCatSkuData['ChildImages'] || [];
                        errorobj["EF_Brand"] = skus;

                        if (SOSChildEyeLevelTotalFacing == true && TotalEyeLevelFacing !== 0 && (TotalEyeLevelFacing == null || TotalEyeLevelFacing == '')) {
                            errorobj["EF_ChildEyeTotal"] = 'ChildEyeTotal';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();
                            notify(`Please enter ${SOSChildEyeLevelTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        } else if (SOSChildNonEyeLevelTotalFacing == true && TotalNonEyeFacing !== 0 && (TotalNonEyeFacing == null || TotalNonEyeFacing == '')) {
                            errorobj["EF_ChildNonEyeTotal"] = 'ChildNonEyeTotal';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input3_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();
                            notify(`Please enter ${SOSChildNonEyeLevelTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        } else if (SOSChildEyeLevelSelfFacing == true && SelfEyeFacing !== 0 && (SelfEyeFacing == null || SelfEyeFacing == '')) {
                            errorobj["EF_CHILD1"] = 'CHILD1';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input4_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();
                            notify(`Please enter ${SOSChildEyeLevelSelfFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        }
                        else if (SOSChildNonEyeLevelSelfFacing == true && SelfNonEyeFacing !== 0 && (SelfNonEyeFacing == null || SelfNonEyeFacing == '')) {
                            errorobj["EF_CHILD2"] = 'CHILD2';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input5_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();
                            notify(`Please enter ${SOSChildNonEyeLevelSelfFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        }
                        else if (SOSChildEyeLevelSelfFacing == true && SOSChildEyeLevelTotalFacing == true && (parseFloat(SelfEyeFacing) > parseFloat(TotalEyeLevelFacing))) {
                            // show error in both field : the ChildTotal and the ChildSelf

                            errorobj["EF_ChildEyeTotal"] = 'ChildEyeTotal';
                            errorobj["EF_CHILD1"] = 'CHILD1';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();

                            notify(`${SOSChildNonEyeLevelSelfFacingLable} should be less than or equals to ${SOSChildEyeLevelTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        }
                        else if (SOSChildNonEyeLevelSelfFacing == true && SOSChildNonEyeLevelTotalFacing == true && (parseFloat(SelfNonEyeFacing) > parseFloat(TotalNonEyeFacing))) {
                            // show error in both field : the ChildTotal and the ChildSelf
                            errorobj["EF_ChildNonEyeTotal"] = 'ChildNonEyeTotal';
                            errorobj["EF_CHILD2"] = 'CHILD2';
                            showError(errorobj, true);
                            let refIn1 = inputRefs.current['input3_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                            refIn1.focus();

                            notify(`${SOSChildNonEyeLevelSelfFacingLable} should be less than or equals to ${SOSChildEyeLevelTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                            resolve(false); return;
                        }
                        else {
                            TotalSelfNonEyeFacingsEntered += parseFloat(parseFloat(SelfNonEyeFacing).toFixed(2));
                            TotalSelfEyeFacingsEntered += parseFloat(parseFloat(SelfEyeFacing).toFixed(2));

                            if (sku_index == this_SKUData.length - 1) {
                                // console.log("TotalSelfFacingsEntered:",TotalSelfFacingsEntered ,",HdrFacing:",parseFloat(parseFloat(SelfEyeFacing).toFixed(2)), (TotalSelfFacingsEntered> parseFloat(SelfEyeFacing).toFixed(2)))
                                if (SOSChildNonEyeLevelSelfFacing == true && SOSHeaderNonEyeLevelFacing == true && (TotalSelfNonEyeFacingsEntered > parseFloat(parseFloat(SOSHdrNonEyeFacing).toFixed(2)))) {
                                    // show error in both field : the HdrTotal and the ChildSelf
                                    errorobj["EF_HdrFacing"] = 'HdrFacing';
                                    errorobj["EF_ChildSelf"] = 'ChildSelf';
                                    showError(errorobj, true);
                                    let refIn1 = inputRefs.current['input_' + cat.SOSHeaderValue];
                                    refIn1.focus();

                                    notify(`Sum of all ${SOSChildNonEyeLevelSelfFacingLable}  should be less than or equals to ${SOSHeaderEyeLevelFacingLable} for ${cat.HeaderName}`, 'SHORT');
                                    resolve(false); return;
                                }
                                if (SOSChildEyeLevelSelfFacing == true && SOSHeaderEyeLevelFacing == true && (TotalSelfEyeFacingsEntered > parseFloat(parseFloat(SOSHdrEyeFacing).toFixed(2)))) {
                                    // show error in both field : the HdrTotal and the ChildSelf
                                    errorobj["EF_HdrFacing"] = 'HdrFacing';
                                    errorobj["EF_ChildSelf"] = 'ChildSelf';
                                    showError(errorobj, true);
                                    let refIn1 = inputRefs.current['input_' + cat.SOSHeaderValue];
                                    refIn1.focus();

                                    notify(`Sum of all ${SOSChildNonEyeLevelSelfFacingLable}  should be less than or equals to ${SOSHeaderEyeLevelFacingLable} for ${cat.HeaderName}`, 'SHORT');
                                    resolve(false); return;
                                }
                            }

                            console.log('StoreCameraAllow:', StoreCameraAllow, SOSChildImage)

                            if (StoreCameraAllow && SOSChildImage == true && ChildImages.length > 0) {
                                for (const splitItemIndex in ChildImages) {
                                    const splitItem = ChildImages[splitItemIndex];
                                    let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                                    if (Image1Name == '') {
                                        errorobj["EF_ChildImage"] = 'ChildImage';
                                        errorobj["EF_ChildImageIndex"] = splitItemIndex;
                                        showError(errorobj, true);
                                        let refIn1 = inputRefs.current['input1_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue];
                                        refIn1.focus();

                                        notify(`Please click all child images for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                                        resolve(false); return;
                                    }
                                }
                            }
                        }
                    }
                }

                if (index == (AllSOSData.length - 1)) {
                    resolve(true); return;
                }

            }

        }).then((val) => { return val })
            .catch((err) => { console.log(err); return false });

    }

    function onStockValChange(item, skuItem, val, key, type = '') {
        setErrorField({});
        setError(false);
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }
        let allSKUData = SOSStockData;
        let defData = { 'SOSHeaderValue': item.SOSHeaderValue, 'Images': [], 'SKUData': [] };
        const catindex = allSKUData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
        const catData = catindex >= 0 ? (allSKUData[catindex] || defData) : defData;
        let AllSKUs = catData['SKUData'] || [];

        let defCData = { 'SOSChildValue': skuItem.SOSChildValue, 'ChildImages': [] };
        let skud_index = AllSKUs.findIndex(i => i.SOSChildValue == skuItem.SOSChildValue);
        const skud = skud_index >= 0 ? (AllSKUs[skud_index] || defCData) : defCData
        skud[key] = val;
        skud_index >= 0 ? AllSKUs[skud_index] = skud : AllSKUs.push(skud);
        catData['SKUData'] = AllSKUs;

        catindex >= 0 ? allSKUData[catindex] = catData : allSKUData.push(catData);
        // setSOSStockData(allSKUData);
        BgWindowData(allSKUData)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

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

        let allSKUData = SOSStockData;
        let defData = { 'SOSHeaderValue': item.SOSHeaderValue, 'Images': [], 'SKUData': [] };
        const skud_index = allSKUData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
        const skud = skud_index >= 0 ? (allSKUData[skud_index] || defData) : defData;
        skud[key] = val;
        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        // setSOSStockData(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, cat, splitChildItem, splitChildItemIndex, skus) {
        setSelectedImg(imgPath)
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        }
        else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ cat, splitChildItem, splitChildItemIndex, skus })
        // _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;

        let { cat, splitChildItem, splitChildItemIndex, skus } = reCapImgModalObj
        let camera2Label = (cat && cat.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"SOS Header 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(cat, splitChildItem, splitChildItemIndex, skus) }}>
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>

                        {!showImageSaveOp &&
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage(false) }}>

                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        )
    }

    function _renderSOSList() {

        let SOSHeaderLabel = KPIFields.findIndex(i => i.KPIFieldName == 'SOSHeaderLabel')
        let SOSHeaderObj = SOSHeaderLabel >= 0 ? KPIFields[SOSHeaderLabel] : {};
        let SOSHeaderDisName = SOSHeaderLabel >= 0 ? SOSHeaderObj['KPIFieldDisplayName'] : 'Product Facing';

        let sosDecimalValue = KPIFields.findIndex(i => i.KPIFieldName == 'SOSValueDecimalAllow')
        let sosDecimalValueObj = sosDecimalValue >= 0 ? KPIFields[sosDecimalValue] : {};
        let sosDecimalValueEnable = sosDecimalValue >= 0 ? sosDecimalValueObj['KPIFieldEnable'] : false;

        let sosPercValue = KPIFields.findIndex(i => i.KPIFieldName == 'SOSPercentageCalculate')
        let sosPercValueObj = sosPercValue >= 0 ? KPIFields[sosPercValue] : {};
        let sosPercValueEnable = sosPercValue >= 0 ? sosPercValueObj['KPIFieldEnable'] : false;

        // sosPercValueEnable=true

        console.log("sosPercValueEnable----", sosPercValueEnable)
        let decimalAllow = sosDecimalValueEnable ? 'decimal' : 'numeric';
        console.log("sosPercValueEnable--", sosPercValueEnable)

        console.log("decimalAllow:", decimalAllow);
        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior="position" enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -100)} >
                <View style={customStyle.keyba_inner_view}>

                    <FlatList
                        data={AllSOSData}
                        extraData={rerenderdata}
                        contentContainerStyle={customStyle.Win_scroll}
                        style={customStyle.Win_scrollO}
                        initialNumToRender={5}
                        listKey={(item, index) => `window_${index.toString()}`}
                        renderItem={({ item, index }) => {
                            const cat = item;
                            const catIndex = index;

                            let SOSHeaderImage = item.SOSHeaderImage == 1 || item.SOSHeaderImage == 'true' ? 1 : 0;
                            let SOSHeaderNonEyeLevelFacing = item.SOSHeaderNonEyeLevelFacing == 1 || item.SOSHeaderNonEyeLevelFacing == 'true' ? 1 : 0;
                            let SOSHeaderEyeLevelFacing = item.SOSHeaderEyeLevelFacing == 1 || item.SOSHeaderEyeLevelFacing == 'true' ? 1 : 0;

                            let SOSHeaderEyeLevelFacingLable = item.SOSHeaderEyeLevelFacingLable != null ? item.SOSHeaderEyeLevelFacingLable : '';
                            let SOSHeaderNonEyeLevelFacingLable = item.SOSHeaderNonEyeLevelFacingLable != null ? item.SOSHeaderNonEyeLevelFacingLable : '';


                            const cindex = SOSStockData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
                            const cobj = cindex >= 0 ? SOSStockData[cindex] : {};
                            const HeaderImages = cobj['Images'] || [];
                            let SOSHdrEyeFacing = cobj['SOSHdrEyeFacing'] != null ? cobj['SOSHdrEyeFacing'] : '';
                            let SOSHdrNonEyeFacing = cobj['SOSHdrNonEyeFacing'] != null ? cobj['SOSHdrNonEyeFacing'] : '';
                            // console.log("SOSHdrFacing in render :",SOSHdrFacing);
                            let this_SKUData = cobj['SKUData'] || [];
                            let show_HdrForm = SOSHeaderNonEyeLevelFacing == true || (SOSHeaderImage == true && HeaderImages.length > 0);

                            // Error Field highlight styles
                            let EF_Cat = errorfield.EF_Cat != null ? errorfield.EF_Cat : {};
                            let show_errorhere = error == true && EF_Cat.SOSHeaderValue == cat.SOSHeaderValue && EF_Cat.SOSDefinitionId == cat.SOSDefinitionId;

                            // this will show error field in red (if window is present and exist reason is enabled and not filled ) or (if window is not present and Not exist reason is enabled and not filled ) 
                            let EF_HdrFacing = errorfield.EF_HdrFacing || '';
                            let EF_EyeHEADER = errorfield.EF_EyeHEADER || '';
                            let EF_NonEyeHEADER = errorfield.EF_NonEyeHEADER || '';

                            let EStyle_HdrFacing = show_errorhere && EF_HdrFacing == 'HdrFacing' ? customStyle.stk_inptSTyle_error : {};
                            let EStyle_EyeHEADER = show_errorhere && EF_EyeHEADER == 'EyeHEADER' ? customStyle.stk_inptSTyle_error : {};
                            let EStyle_NonEyeHEADER = show_errorhere && EF_NonEyeHEADER == 'NonEyeHEADER' ? customStyle.stk_inptSTyle_error : {};



                            //get SOS Target at header from skulist first child- as all children of particular hdr will contain same SOSTarget Value
                            let child_list = cat.skulist || [];
                            let first_child = child_list.length > 0 ? child_list[0] : {};
                            let SOSTarget = first_child.SOSTarget;
                            // let SelfchildCount=0;
                            let facingPerc1 = 0;
                            let SOSChildNonEyeLevelSelfFacingFlag = 0;


                            // var filtered = cat.skulist.filter(function(item) {
                            //                         return id_filter.indexOf(item.id) !== -1 && item.gender==='m';
                            //                 });

                            let valData = this_SKUData.reduce((a, b) => (a || 0) + ((b.SelfNonEyeFacing || 0) + (b.SelfEyeFacing || 0)), 0);
                            // let SelfchildCount= valData.SelfNonEyeFacing ||0
                            let SelfchildCount = valData || 0


                            if ((SOSHeaderNonEyeLevelFacing == true) && (SelfchildCount != 0 && SOSHdrEyeFacing != 0)) {
                                facingPerc1 = ((SelfchildCount || 0) / ((SOSHdrEyeFacing || 0) + (SOSHdrNonEyeFacing || 0))) * 100
                                console.log("vdshva--", facingPerc1)
                            }
                            // if((SOSHeaderEyeLevelFacing==true) && (SelfchildCount!=0 && SOSHdrNonEyeFacing!=0) ){
                            //     facingPerc1= ((SelfchildCount||0)/(SOSHdrNonEyeFacing||0))*100
                            //     console.log("vdshva--",facingPerc1)
                            // }

                            return (
                                <View style={customStyle.opening_Stock_wrap} key={index}>
                                    <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}>
                                            <View style={customStyle.openStk_precentageViwHD}>
                                                <Text style={[customStyle.opening_Stock_catText]}>{item.HeaderName}</Text>
                                                {sosPercValueEnable == true && SOSHeaderNonEyeLevelFacing == true && <Text style={{ color: PageTheme.$text_color_900, fontSize: 13 }}>{`SOS ${facingPerc1.toFixed(0)}%`}</Text>}
                                            </View>
                                            {/* <Text style={[customStyle.opening_Stock_catText]}>{item.HeaderName }</Text> */}
                                            {/* + ` (${SOSTarget}%)` */}
                                            {SOSTarget != null && SOSTarget != '' && <Text style={[customStyle.opening_Stock_catText2]}>{`SOS Target: ${SOSTarget}%`}</Text>}
                                        </LinearGradient>
                                    </View>
                                    <View style={customStyle.SOSForm}>
                                        {show_HdrForm == true &&
                                            <View style={customStyle.SOSHdrForm}>
                                                {SOSHeaderEyeLevelFacing == true &&
                                                    <View style={customStyle.SOSform_row}>
                                                        <View style={[customStyle.SOSform_colflex]} >
                                                            <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                <Text style={customStyle.SOSform_collabel}>{SOSHeaderEyeLevelFacingLable}</Text>
                                                            </View>

                                                            <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                <TextInput
                                                                    style={[customStyle.SOSInputStyle, EStyle_EyeHEADER]}
                                                                    ref={(reff) => { inputRefs.current['input_' + cat.SOSHeaderValue] = reff; }}
                                                                    placeholder=""
                                                                    autoComplete='off'
                                                                    placeholderTextColor={PageTheme.$placeholder_color}
                                                                    value={(SOSHdrEyeFacing + '')}
                                                                    keyboardType='numeric'
                                                                    blurOnSubmit={false}
                                                                    returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                    onSubmitEditing={() => { focusToNext(cat, catIndex, "", "", "EyeHEADER") }}
                                                                    onChangeText={(val) => { onHdrStockValChange(cat, val, 'SOSHdrEyeFacing', decimalAllow) }}
                                                                />
                                                            </View>
                                                        </View>
                                                    </View>
                                                }

                                                {SOSHeaderNonEyeLevelFacing == true &&
                                                    <View style={customStyle.SOSform_row}>
                                                        <View style={[customStyle.SOSform_colflex]} >
                                                            <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                <Text style={customStyle.SOSform_collabel}>{SOSHeaderNonEyeLevelFacingLable}</Text>
                                                            </View>

                                                            <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                <TextInput
                                                                    style={[customStyle.SOSInputStyle, EStyle_NonEyeHEADER]}
                                                                    ref={(reff) => { inputRefs.current['input1_' + cat.SOSHeaderValue] = reff; }}
                                                                    placeholder=""
                                                                    autoComplete='off'
                                                                    placeholderTextColor={PageTheme.$placeholder_color}
                                                                    value={(SOSHdrNonEyeFacing + '')}
                                                                    keyboardType='numeric'
                                                                    blurOnSubmit={false}
                                                                    returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                    onSubmitEditing={() => { focusToNext(cat, catIndex, "", "", "NonEyeHEADER") }}
                                                                    onChangeText={(val) => { onHdrStockValChange(cat, val, 'SOSHdrNonEyeFacing', decimalAllow) }}
                                                                />
                                                            </View>
                                                        </View>
                                                    </View>
                                                }
                                                {(SOSHeaderImage == true && HeaderImages.length > 0) &&
                                                    <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                                        <View style={customStyle.SOSheadingsCon}>
                                                            <Text style={customStyle.SOSheadingsText}>{'Capture SOS Header Images'}</Text>
                                                        </View>
                                                        <View style={customStyle.SOShdrImagesWrap}>
                                                            <View style={[customStyle.openStk_prdCameras, customStyle.WSCameraWrap]} >
                                                                {(rerenderdata2 == rerenderdata2) &&
                                                                    HeaderImages.map((item, index) => {
                                                                        let splitItem = item;
                                                                        let splitItemIndex = index;
                                                                        let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                                                                        let Image1 = splitItem['Image1'] != null && splitItem['Image1'] != '' ? splitItem['Image1'] : '';
                                                                        let isImg1mad = splitItem['img1Required'] || false;

                                                                        let EF_HdrImageIndex = errorfield.EF_HdrImageIndex === 0 || errorfield.EF_HdrImageIndex != null ? errorfield.EF_HdrImageIndex : '';
                                                                        let show_hdrImageErrHere = EF_HdrImageIndex == splitItemIndex;

                                                                        let EF_HdrImage = errorfield.EF_HdrImage || '';
                                                                        let EStyle_HdrImage = show_errorhere && show_hdrImageErrHere && EF_HdrImage == 'HdrImage' ? customStyle.error_CatImage2 : {};

                                                                        return (
                                                                            <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]} key={'SplitItem+' + splitItemIndex}>
                                                                                {((Image1 == '' || Image1 == null) && isImg1mad) ?
                                                                                    <TouchableOpacity style={[EStyle_HdrImage]} onPress={() => { openCamera(cat, splitItem, splitItemIndex, '1') }}>
                                                                                        <CameraImg5 width={50} height={50} />
                                                                                    </TouchableOpacity> : (Image1 == '' || Image1 == null) ?
                                                                                        <TouchableOpacity style={[EStyle_HdrImage]} onPress={() => { openCamera(cat, splitItem, splitItemIndex, '1') }}>
                                                                                            <CameraImg2 width={50} height={50} />
                                                                                        </TouchableOpacity> : (Image1 != '' || Image1 != null) ?
                                                                                            <TouchableOpacity onPress={() => { OpenImgModal(Image1, cat, splitItem, splitItemIndex, '1') }}>
                                                                                                <CameraImg3 width={50} height={50}  />
                                                                                            </TouchableOpacity> : null
                                                                                }
                                                                            </View>
                                                                        );
                                                                    })
                                                                }
                                                            </View>
                                                        </View>
                                                    </View>
                                                }
                                            </View>
                                        }


                                        <View style={customStyle.SOSListHdr}>
                                            {/* <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$primary_color,PageTheme.$fourth_color,PageTheme.$primary_color,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={[customStyle.SOSheadingsCon,customStyle.SOSheadingsCon3]}>
                                    <Text style={[customStyle.SOSheadingsText,customStyle.SOSheadingsText2]}>{SOSHeaderDisName}</Text>
                                </LinearGradient> */}
                                            <View style={[customStyle.SOSheadingsCon, customStyle.SOSheadingsCon3]}>
                                                <Text style={[customStyle.SOSheadingsText]}>{SOSHeaderDisName}</Text>
                                            </View>
                                        </View>

                                        <View style={customStyle.SOSChildlist}>
                                            <View style={customStyle.opening_Stock_prds}>
                                                <FlatList
                                                    data={cat.skulist}
                                                    extraData={rerenderdata3}
                                                    renderItem={({ item, index }) => {
                                                        const skus = item;
                                                        const sku_index = index;


                                                        let SOSChildImage = skus.SOSChildImage == 1 || skus.SOSChildImage == 'true' ? 1 : 0;
                                                        let SOSChildEyeLevelTotalFacing = skus.SOSChildEyeLevelTotalFacing == 1 || skus.SOSChildEyeLevelTotalFacing == 'true' ? 1 : 0;
                                                        let SOSChildNonEyeLevelTotalFacing = skus.SOSChildNonEyeLevelTotalFacing == 1 || skus.SOSChildNonEyeLevelTotalFacing == 'true' ? 1 : 0;

                                                        let SOSChildNonEyeLevelSelfFacing = skus.SOSChildNonEyeLevelSelfFacing == 1 || skus.SOSChildNonEyeLevelSelfFacing == 'true' ? 1 : 0;
                                                        let SOSChildEyeLevelSelfFacing = skus.SOSChildEyeLevelSelfFacing == 1 || skus.SOSChildEyeLevelSelfFacing == 'true' ? 1 : 0;

                                                        let SOSChildEyeLevelTotalFacingLable = skus.SOSChildEyeLevelTotalFacingLable != null ? skus.SOSChildEyeLevelTotalFacingLable : '';
                                                        let SOSChildNonEyeLevelSelfFacingLable = skus.SOSChildNonEyeLevelSelfFacingLable != null ? skus.SOSChildNonEyeLevelSelfFacingLable : '';
                                                        let SOSChildEyeLevelSelfFacingLable = skus.SOSChildEyeLevelSelfFacingLable != null ? skus.SOSChildEyeLevelSelfFacingLable : '';

                                                        let thisCatSkuData_i = this_SKUData.findIndex(i => i.SOSChildValue == skus.SOSChildValue);
                                                        let thisCatSkuData = thisCatSkuData_i >= 0 ? (this_SKUData[thisCatSkuData_i] || {}) : {};
                                                        let TotalFacing = thisCatSkuData.TotalFacing != null ? thisCatSkuData.TotalFacing : '';
                                                        let TotalEyeLevelFacing = thisCatSkuData.TotalEyeLevelFacing != null ? thisCatSkuData.TotalEyeLevelFacing : '';
                                                        let TotalNonEyeFacing = thisCatSkuData.TotalNonEyeFacing != null ? thisCatSkuData.TotalNonEyeFacing : '';

                                                        let SelfNonEyeFacing = thisCatSkuData.SelfNonEyeFacing != null ? thisCatSkuData.SelfNonEyeFacing : '';
                                                        let SelfEyeFacing = thisCatSkuData.SelfEyeFacing != null ? thisCatSkuData.SelfEyeFacing : '';


                                                        const ChildImages = thisCatSkuData['ChildImages'] || [];

                                                        let EF_Brand = errorfield.EF_Brand != null ? errorfield.EF_Brand : {};
                                                        let show_ChildErrHere = EF_Brand.SOSChildValue == skus.SOSChildValue;

                                                        let EF_ChildTotal = errorfield.EF_ChildTotal || '';
                                                        let EStyle_ChildTotal = show_errorhere && show_ChildErrHere && EF_ChildTotal == 'ChildTotal' ? customStyle.stk_inptSTyle_error : {};

                                                        let EStyle_ChildNonEyeTotal = show_errorhere && show_ChildErrHere && EF_ChildTotal == 'ChildTotal' ? customStyle.stk_inptSTyle_error : {};


                                                        let EF_ChildSelf = errorfield.EF_ChildSelf || '';
                                                        let EStyle_ChildSelf = show_errorhere && show_ChildErrHere && EF_ChildSelf == 'ChildSelf' ? customStyle.stk_inptSTyle_error : {};
                                                        let facingPerc = 0;
                                                        if ((SOSChildEyeLevelTotalFacing == true && SOSChildNonEyeLevelSelfFacing == true) && ((SelfNonEyeFacing != 0 && TotalNonEyeFacing != 0) || (SelfEyeFacing != 0 && TotalEyeLevelFacing != 0))) {
                                                            facingPerc = (((SelfNonEyeFacing || 0) + (SelfEyeFacing)) / ((TotalEyeLevelFacing || 0) + (TotalNonEyeFacing || 0))) * 100
                                                        }
                                                        SOSChildNonEyeLevelSelfFacingFlag = SOSChildNonEyeLevelSelfFacing;
                                                        SelfchildCount = SelfNonEyeFacing;

                                                        return (
                                                            <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                                                <View style={customStyle.openStk_precentageViw}>
                                                                    <Text style={[customStyle.openStk_precentagenameB]}>{skus.ChildName}</Text>
                                                                    {sosPercValueEnable == true && SOSHeaderNonEyeLevelFacing != true && SOSHeaderEyeLevelFacing != true && <Text style={{ color: PageTheme.$text_color_900, fontSize: 13 }}>{`SOS ${facingPerc.toFixed(0)}%`}</Text>}
                                                                </View>
                                                                {/* <Text style={[customStyle.openStk_prd_nameB]}>{skus.ChildName}</Text> */}

                                                                {(SOSChildImage == true) &&
                                                                    <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>

                                                                        <View style={[customStyle.SOSheadingsCon]}>
                                                                            <Text style={[customStyle.SOSheadingsText]}>{'Capture SOS Child Images'}</Text>
                                                                        </View>
                                                                        <View style={customStyle.SOSChildImagesWrap}>
                                                                            <View style={[customStyle.openStk_prdCameras, customStyle.WSCameraWrap]} >
                                                                                {rerenderdata4 == rerenderdata4 &&
                                                                                    ChildImages.map((item, index) => {
                                                                                        let splitChildItem = item;
                                                                                        let splitChildItemIndex = index;
                                                                                        let Image1Name = splitChildItem['Image1Name'] != null && splitChildItem['Image1Name'] != '' ? splitChildItem['Image1Name'] : '';
                                                                                        let Image1 = splitChildItem['Image1'] != null && splitChildItem['Image1'] != '' ? splitChildItem['Image1'] : '';
                                                                                        let isImg1mad = splitChildItem['img1Required'] || false;

                                                                                        let EF_ChildImageIndex = errorfield.EF_ChildImageIndex === 0 || errorfield.EF_ChildImageIndex != null ? errorfield.EF_ChildImageIndex : '';
                                                                                        let show_ChildImgErrHere = EF_ChildImageIndex == splitChildItemIndex;

                                                                                        let EF_ChildImage = errorfield.EF_ChildImage || '';
                                                                                        let EStyle_ChildImage = show_errorhere && show_ChildErrHere && show_ChildImgErrHere && EF_ChildImage == 'ChildImage' ? customStyle.error_CatImage2 : {};


                                                                                        return (
                                                                                            <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]}>

                                                                                                {((Image1 == '' || Image1 == null) && isImg1mad) ?
                                                                                                    <TouchableOpacity style={[EStyle_ChildImage]} onPress={() => { openCamera(cat, splitChildItem, splitChildItemIndex, '2', skus) }}>
                                                                                                        <CameraImg5 width={50} height={50}  />
                                                                                                    </TouchableOpacity> : (Image1 == '' || Image1 == null) ?
                                                                                                        <TouchableOpacity style={[EStyle_ChildImage]} onPress={() => { openCamera(cat, splitChildItem, splitChildItemIndex, '2', skus) }}>
                                                                                                            <CameraImg2 width={50} height={50}  />
                                                                                                        </TouchableOpacity> : (Image1 != '' || Image1 != null) ?
                                                                                                            <TouchableOpacity onPress={() => { OpenImgModal(Image1, cat, splitChildItem, splitChildItemIndex, '2', skus) }}>
                                                                                                                <CameraImg3 width={50} height={50} />
                                                                                                            </TouchableOpacity> : null
                                                                                                }
                                                                                                {/* <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text> */}
                                                                                            </View>
                                                                                        );
                                                                                    })
                                                                                }
                                                                            </View>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                <View style={customStyle.SOSlist_form}>
                                                                    {SOSChildEyeLevelTotalFacing == true &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildEyeLevelTotalFacingLable}</Text>
                                                                                </View>

                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        ref={(reff) => { inputRefs.current['input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildTotal]}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(TotalEyeLevelFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "ChildEyeTotal") }}
                                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'TotalEyeLevelFacing', decimalAllow) }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}

                                                                    {SOSChildNonEyeLevelTotalFacing == true &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildNonEyeLevelTotalFacingLable}</Text>
                                                                                </View>

                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        ref={(reff) => { inputRefs.current['input3_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildNonEyeTotal]}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(TotalNonEyeFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "ChildNonEyeTotal") }}
                                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'TotalNonEyeFacing', decimalAllow) }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}

                                                                    {SOSChildEyeLevelSelfFacing == true &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildEyeLevelSelfFacingLable}</Text>
                                                                                </View>
                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildSelf]}
                                                                                        ref={(reff) => { inputRefs.current['input4_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(SelfEyeFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "CHILD1") }}
                                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'SelfEyeFacing', decimalAllow) }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}
                                                                    {SOSChildNonEyeLevelSelfFacing == true &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildNonEyeLevelSelfFacingLable}</Text>
                                                                                </View>
                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildSelf]}
                                                                                        ref={(reff) => { inputRefs.current['input5_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(SelfNonEyeFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "CHILD2") }}
                                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'SelfNonEyeFacing', decimalAllow) }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}
                                                                </View>
                                                            </View>
                                                        )
                                                    }} />
                                            </View>
                                        </View>
                                    </View>

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

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {_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} gridEnable={GridValue} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(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]}>
                    {Object.keys(storeData).length > 0 &&
                        _renderSOSList()
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={'Save'} onPress={() => { submitOpeningStock() }} />
                    </View>
                </View>
            </LinearGradient>
        </Container>
    );
}


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