
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, Animated, AppState, Keyboard, LogBox } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
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 CustomHeader from '../components/customHeader';
import { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, Entypo, MaterialCommunityIcons } from '../components/icons';
import { stat } from 'react-native-fs';
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 { Q_getdefaltShareofSelf } from '../constants/ConstantQueries';
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';
import ImageViewer from 'react-native-image-zoom-viewer';
import MultiSelect from 'react-native-multiple-select';
import ModalSelector from 'react-native-modal-selector'
import CameraGrey from '../assets/image/camera_icon_grey.svg';

import AddIcon from '../assets/performics/add_image.svg'
import BinIcon from '../assets/performics/delete_icon_red.svg'

//jp
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath, ImageFolderPath, HierarchyTbls } from '../constants/constants';



function ShareOfShelfOneApp(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 [showImageAlert, setShowImageAlert] = 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 [ItemsInView, setItemsInView] = useState([]);

    const [InputChange, setInputChange] = useState([]);

    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const Show_zoomImageRef = useRef(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const zoomView = useRef(null);

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

    const onViewableItemsChanged = ({ viewableItems, }) => {
        // Do stuff
        console.log("onViewableItemsChanged called:")
        setItemsInView(viewableItems);
    };

    console.log('storeDatastoreData----', storeData);


    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);

    const FlatLConfCallbackPairs = useRef([{ viewabilityConfig: { itemVisiblePercentThreshold: 30 }, onViewableItemsChanged }]);

    const inputRefs = useRef({});

    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');

    const handleAddImages = (cat, type = '1', cameraType = '1', qtn = {}, skus = {}, addImg = "0") => {
        // setAddImages(prev => [...prev, prev.length]);
        let splitItem = { Image1: "", Image1Name: "", img1Required: false, addImg: 1 }

        let window = cat || {};

        let allData = SOSStockData;
        let defData = { 'SOSDefinitionId': window.SOSDefinitionId };
        const wind_index = allData.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId);
        let wind = wind_index >= 0 ? allData[wind_index] : defData;
        console.log("wind----------1", wind)


        console.log("test 4", splitItem, cameraType)

        if (cameraType == '1') {
            let splitItem = { Image1: "", Image1Name: "", img1Required: false, addImg: 1 }
            wind.Images.push(splitItem)
            wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
            console.log('split image updated 12--', wind_index, allData);
            WindowDataRef.current = allData
            setSOSStockData(allData);
            BgUnsavedChanges(true)
            setrerenderdata2(!rerenderdata2);
        }
    };

    const handleDelete = (reCapImgModalObj) => {
        let { cat, splitChildItem, splitChildItemIndex, skus, type, } = reCapImgModalObj
        let window = cat || {};
        let allData = SOSStockData;
        let defData = { 'SOSDefinitionId': window.SOSDefinitionId };
        const wind_index = allData.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId);
        let wind = wind_index >= 0 ? allData[wind_index] : defData;
        console.log("handleDelete-----", wind)

        if (type == '1') {
            wind.Images = wind?.Images?.filter((_, i) => i !== splitChildItemIndex);
            wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
            console.log('split image updated 12--', wind_index, allData);
            setTimeout(() => {
                cancelImage()
            }, 0)
            WindowDataRef.current = allData
            setSOSStockData(allData);
        } else if (type == '2') {

            var SKUData = wind['SKUData'] || [];
            var childIndex = SKUData.findIndex(i => i.SOSChildValue == skus.SOSChildValue);

            var childData = childIndex >= 0 ? SKUData[childIndex] : {};
            var ChildImages = childData['ChildImages'] || [];

            childData['ChildImages'] = ChildImages?.filter((_, i) => i !== splitChildItemIndex);;
            childIndex >= 0 ? SKUData[childIndex] = childData : SKUData.push(childData);
            wind['SKUData'] = SKUData;
            wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

            setTimeout(() => {
                cancelImage()
            }, 0)
            setSOSStockData(allData);
            BgWindowData(allData)
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata3);
        }

    };
    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();
            return unsubscribe;
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        console.log("WindowsStr------------", nextAppState + "called")
        if ((nextAppState == 'background' || nextAppState === "inactive") && 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)
            console.log("WindowsStr------------", WindowsStr)
            await set_item('storeData', WindowsStr);
        }
    }

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

    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 UpdateShow_zoomImageRef(val) {
        Show_zoomImageRef.current = val
        setShow_zoomImage(val);
    }




    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else if (Show_zoomImageRef.current == true) {
            e.preventDefault();
            UpdateShow_zoomImageRef(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 with saved data of any
                let FilterIdsJoin = FilteredIds.length > 0 ? FilteredIds.join(',') : '';
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let join5 = ` LEFT OUTER JOIN ${AppTables.SOS_HDR_DATA} wd on p.SOSHeaderValue=wd.SOS_HDR_VALUE and wd.STORE_ID='${StoreId}' and wd.VISIT_DATE='${d2}'`;
                let selectlist1 = ` DISTINCT p.SOSDefinitionId,p.HeaderAddImageAllow,p.HeaderAddImageMax,p.ChildAddImageAllow,p.ChildAddImageMax,  wd.SOS_HEADER_ID as SOSHeaderId,p.SOSHeaderTable,p.SOSRefImage,p.SOSRefImagePopUP,p.SOSHeaderField,p.SOSHeaderValue,p.HeaderName as HeaderName,p.SOSHeaderFacing,p.SOSHeaderFacingLable,p.SOSHeaderImage,p.SOSHeaderImageCount,p.SOSHeaderImageGrid,wd.SOS_HDR_FACING as SOSHdrFacing `;
                // let selectlist1 = ` DISTINCT p.SOSDefinitionId,wd.SOS_HEADER_ID as SOSHeaderId,p.SOSHeaderTable,p.SOSRefImage,p.SOSRefImagePopUP,p.SOSHeaderField,p.SOSHeaderValue,p.HeaderName as HeaderName,p.SOSHeaderFacing,p.SOSHeaderFacingLable,p.SOSHeaderImage,p.SOSHeaderImageCount,p.SOSHeaderImageGrid,wd.SOS_HDR_FACING as SOSHdrFacing `;
                // 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.SOSHeaderFacing,m.SOSHeaderFacingLable,m.SOSHeaderImage,m.SOSHeaderImageCount,m.SOSHeaderImageGrid,p.SOS_HDR_FACING as SOSHdrFacing `;
                let q = `SELECT ${selectlist1} from Master_ShareOfShelfDefinition p ${join1} ${join5} Where (m.StoreId ='${StoreId}' or m.StoreId = ${StoreId})  
                ${sosCheckAssortment == true ? ` and p.SOSHeaderValue in (${AssortIds}) ` : ''}  `;
                if (ShowCatWise1 == true) {
                    q += ` and p.SOSHeaderValue in (${FilterIdsJoin}) `;
                }
                // q+=` group by wd.SOS_HEADER_ID order by p.HeaderName `;
                q += ` group by p.SOSHeaderValue order by p.HeaderName `;

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

                    if (txnres.rows.length > 0) {
                        let arr = [], allCats = [], images = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            console.log('soscats heasder added:', data);
                            inputRefs.current['input_' + data.SOSHeaderValue] = '';
                            let AllCData = await getChilds(storeData1, data, menu1, sosMSLOnly, sosCheckAssortment);
                            let allChilds = AllCData['allChilds'] || [];
                            let childData = AllCData['childData'] || [];
                            let WindowQuestions = AllCData['WindowQuestions'] || [];
                            let WindowQA = AllCData['WindowQA'] || {};
                            let windowChildImage = AllCData['ChildImages'] || []
                            data['skulist'] = allChilds;

                            let animatedHeight = new Animated.Value(450);
                            data.animatedHeight = animatedHeight

                            arr.push(data);
                            let HdrImages = await getHdrImages(storeData1, data, menu1, data.SOSHeaderImageCount);

                            let WQr = {}; //await getWindowQuestions(data,storeData1,menu1);
                            // let WindowQuestions = WQr['WindowQuestions'] || [];
                            // let WindowQA= WQr['WindowQA'] || {};
                            let defData = { 'SOSDefinitionId': data.SOSDefinitionId, 'SOSHeaderValue': data.SOSHeaderValue, 'SOSHdrFacing': data.SOSHeaderId != null ? data.SOSHdrFacing : '', 'Images': HdrImages, 'SKUData': childData, 'WindowQA': WindowQA, WindowQuestions: WindowQuestions };
                            data['WindowQuestions'] = WindowQuestions;
                            allCats.push(defData);

                            let imgObj = { imgIndex: (i + 1), url: data.SOSRefImage, props: {} }
                            images.push(imgObj);

                            if (i == txnres.rows.length - 1) {
                                let { menuName, StoreId1, visiteDate } = bgStoreJson
                                if (!isBgDataExists) {
                                    BgWindowData(allCats)
                                }
                                setAllSOSData(arr);
                                setZoomImageUrl(images);

                                // setSOSStockData(allCats);
                                setProcessing(false);
                            }
                        }
                    }
                    else {
                        setProcessing(false);
                        notify("No data found");
                    }

                }, 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_StoreShareOfShelf s on w.SOSDefinitionId=s.SOSDefinitionId  `;
                let q = `Select Distinct w.* from Master_ShareOfShelfDefinition w ${join} where (s.StoreId='${StoreId}' or 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_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let q = `select Distinct p.SOSHeaderTable,p.SOSHeaderField from Master_ShareOfShelfDefinition p ${join1}  Where (m.StoreId ='${StoreId}' or 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}' or 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_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let q = `select Distinct p.SOSChildTable,p.SOSChildField from Master_ShareOfShelfDefinition p ${join1}  Where (m.StoreId ='${StoreId}' or 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}'or mp.StoreId= ${StoreId}) ${sosMSLOnly == true ? ` and  (mp.MSL='true' 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 getWindowQuestions(window, storeData1, menu1, SOSHeaderValue) {
        // console.log("window-----", window.SOSDefinitionId)
        let obj = { 'WindowQA': {}, 'WindowQuestions': [] }
        return new Promise((resolve, reject) => {

            db.transaction(async function (txn) {
                var q = '', selectlist = '', join = '', join2 = '';

                selectlist = ` DISTINCT  wq.SOSQuestionId,mq.SOSDefinitionId,q.SOS_CHILD_VALUE,wq.SOSQuestionCode,wq.SOSQuestionName,wq.QuestionType,wq.SOSQShowCamera,wq.SOSQCameraMandatory,wq.SOSQLengthValidationRequired,wq.SOSQMinimumChar,wq.SOSQMaximumChar,wq.SOSQDecimalPoint,wq.SOSQDateRangeMin,wq.SOSQDateRangeMax,wq.SOSQVoiceLengthInMinutes,wq.SOSQDefaultQuestionEnable,(CASE WHEN q.QUESTION_ID is not null THEN 1 ELSE 0 END) isInserted,q.IS_DISABLED,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as SOSAShowCamera,q.IMAGE1 as Image1  `;
                join2 = ` Left Outer Join ${AppTables.SOS_CHILD_QUES_DATA} q on wq.SOSQuestionId=q.QUESTION_ID and q.STORE_ID='${storeData1.StoreId}' and q.SOS_DEFINITION_ID='${window.SOSDefinitionId}' and q.SOS_HDR_VALUE='${SOSHeaderValue}' and q.SOS_CHILD_VALUE='${window.SOSChildValue}' and q.VISIT_DATE='${d2}'`;
                join = ` inner join Mapping_ShareOfShelfQuestion mq on mq.SOSQuestionId=wq.SOSQuestionId `;
                q = `select ${selectlist} from Master_ShareOfShelfQuestion wq  ${join} ${join2} where (mq.SOSDefinitionId='${window.SOSDefinitionId}' or  mq.SOSDefinitionId= ${window.SOSDefinitionId}) order by wq.SOSQuestionSequence  `;

                console.log("getWindowQuestions---", q)
                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        let wqa_obj = {};
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { isInserted } = data;
                            console.log("getWindowQuestions---data-",)
                            let answers = [];
                            data.SOSQDefaultQuestionEnable = data.SOSQDefaultQuestionEnable == 1 || data.SOSQDefaultQuestionEnable == 'true' ? true : false;
                            // data['isDisabled']=!data.SOSQDefaultQuestionEnable;
                            if (isInserted) {
                                data['isDisabled'] = data.IS_DISABLED == true || data.IS_DISABLED == "true" || data.IS_DISABLED == 1 ? true : false;
                            }
                            else {

                                data['isDisabled'] = !data.SOSQDefaultQuestionEnable;
                            }
                            if (data.QuestionType == 'Multi choice list' || data.QuestionType == 'Single choice list' || data.QuestionType == 'Rating') {
                                answers = await getWindowAnswers(data);
                                console.log("answer------", answers)
                                if (data.QuestionType == 'Rating') {
                                    data.showRating = false;
                                }
                            }
                            else if (data.QuestionType == 'Date') {
                                data.showDatePicker = false;
                            }
                            data['Answers'] = answers;

                            let id_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_AnswerId';
                            let ans_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_Answer';
                            let multi_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_MultiOption';
                            let date_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_Date';
                            let img_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_ImagePath1';
                            let imgname_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_ImageName1';
                            let rating_key = data.SOSQuestionId + "_ChildId_" + data.SOS_CHILD_VALUE + '_Rating';

                            let cam_allow = data.SOSQuestionId + '_Camera_allow';



                            let showImageTag = (data.SOSShowCamera == 'true' || data.SOSShowCamera == 1);

                            data.AnswerId != null ? wqa_obj[id_key] = data.AnswerId : '';
                            data.Answer != null ? wqa_obj[ans_key] = data.Answer : '';

                            let selansid = data.AnswerId != null ? data.AnswerId : '';

                            if (data.QuestionType == 'Multi choice list' && (selansid != '' || selansid === 0) && data.multi_op_ids != null) {
                                selansid = data.multi_op_ids ? data.multi_op_ids.split(',') : [];
                                wqa_obj[multi_key] = data.multi_op_ids;
                            }

                            if ((data.QuestionType == 'Single choice list' || data.QuestionType == 'Multi choice list') && selansid != '' && selansid != null) {
                                if (data.Answers && data.Answers.length > 0) {
                                    for (var k = 0; k < data.Answers.length; k++) {
                                        let ansss = data.Answers[k];
                                        let isandImgAl = (ansss.SOSAShowCamera == 1 || ansss.SOSAShowCamera == 'true');
                                        if (data.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                            //...changes by shaikh
                                            wqa_obj[cam_allow] = isandImgAl;
                                            showImageTag = true;
                                        }
                                        else if (data.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                            showImageTag = true;
                                        }
                                    }
                                }
                            }

                            if (showImageTag && data.Answer != null) {
                                let imgPath = (Platform.OS == 'ios' ? 'file://' : '') + ImageFolderPath + menu1.ScreenName + "/" + data.Image1;
                                wqa_obj[imgname_key] = data.Image1;
                                wqa_obj[img_key] = imgPath;
                            }



                            if (data.QuestionType == 'Date' && data.Answer != null) {
                                let dayonly = moment().format('DD');
                                let actual_date = data.Answer ? data.Answer.split('/') : [];
                                let month = actual_date[0], year = actual_date[1];
                                let fulldate = month + '/' + dayonly + '/' + year;
                                wqa_obj[date_key] = fulldate;

                            }

                            arr.push(data);

                            if (i == txnres2.rows.length - 1) {
                                obj['WindowQuestions'] = arr;
                                console.log("wqa_obj-------", wqa_obj)
                                obj['WindowQA'] = wqa_obj;
                                resolve(obj)
                            }
                        }
                    }
                    else {
                        resolve(obj)
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(obj) },);
            });
        }).then((val) => {
            return val
        }).catch((err) => {
            console.log(err);
            return obj;
        });
    }

    async function getWindowAnswers(qtn) {

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

            db.transaction(async function (txn) {
                var q = '', selectlist = '';
                selectlist = ` DISTINCT SOSAnswerId as AnswerId,SOSAnswerName as Answer,SOSAShowCamera,SOSACameraMandatory,SOSAQuestionEnable,SOSAQuestionDisable `;
                q = `select ${selectlist} from  Master_ShareOfShelfQuestion  where (SOSQuestionId='${qtn.SOSQuestionId}' or SOSQuestionId= ${qtn.SOSQuestionId})  order by SOSASequence  `;

                //console.log("getWindowAnswers----", q)
                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                resolve(arr)
                            }
                        }
                    }
                    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,img1Required,ADD_IMAGES 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, img1Required, ADD_IMAGES } = data;
                            let imagePath = Image1 == "NA" ? Image1 : (Image1 != null && Image1 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + Image1 : '');
                            let obj = { 'Image1Name': data.Image1, 'Image1': imagePath, "img1Required": img1Required, addImg: ADD_IMAGES };
                            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, addImg: 0 };
                                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) {
                // get data from masters with saved data
                let selectlist = ` Distinct p.SOSDefinitionId,p.SOSChildTable,p.SOSChildField,p.SOSChildValue,p.ChildName,p.SOSChildTotalFacing,p.SOSChildSelfFacing,p.SOSChildTotalFacingLable,p.SOSChildSelfFacingLable,p.SOSChildImage,p.SOSChildImageCount,p.SOSChildImageGrid,wd.TOTAL_FACING as TotalFacing,wd.SELF_FACING as SelfFacing,tg.SOSTarget`;
                // let selectlist2=` m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,p.SOS_CHILD_VALUE as SOSChildValue,p.CHILD_NAME as ChildName,m.SOSChildTotalFacing,m.SOSChildSelfFacing,m.SOSChildTotalFacingLable,m.SOSChildSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_FACING as TotalFacing,p.SELF_FACING as SelfFacing`;
                let join1 = ` INNER JOIN Mapping_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let join5 = ` LEFT OUTER JOIN ${AppTables.SOS_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 target_join = ` LEFT OUTER JOIN  Mapping_StoreShareOfShelfTarget tg on p.SOSDefinitionId=tg.SOSDefinitionId and tg.StoreId='${StoreId}'  `;

                let q = `SELECT ${selectlist} from Master_ShareOfShelfDefinition p ${join1} ${join5} ${target_join} Where (m.StoreId ='${StoreId}' or m.StoreId = ${StoreId}) and p.SOSHeaderValue='${SOSHeaderValue}'  
                ${sosCheckAs == true ? ` and p.SOSChildValue in (${childAssorted}) ` : ''}  
                order by p.SOSDefSequence  `;
                console.log("sossubcats-----1", q)
                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 SOSChildTotalFacing = data.SOSChildTotalFacing == 1 || data.SOSChildTotalFacing == 'true' ? 1 : 0;
                            let SOSChildSelfFacing = data.SOSChildSelfFacing == 1 || data.SOSChildSelfFacing == 'true' ? 1 : 0;
                            if (SOSChildTotalFacing == 1) {
                                inputRefs.current['input1_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }
                            if (SOSChildSelfFacing == 1) {
                                inputRefs.current['input2_' + SOSHeaderValue + "_" + data.SOSChildValue] = '';
                            }

                            let allChildImages = await getChildImages(storeData1, cat1, data, menu1, data.SOSChildImageCount);
                            let WQr = await getWindowQuestions(data, storeData1, menu1, SOSHeaderValue);
                            data['WindowQuestions'] = WQr['WindowQuestions'] || [];
                            data['WindowQA'] = WQr['WindowQA'] || {};
                            let WindowQA = WQr['WindowQA'] || {};
                            let defCData = { 'SOSChildValue': data.SOSChildValue, 'TotalFacing': data.TotalFacing, 'SelfFacing': data.SelfFacing, 'ChildImages': (allChildImages || []), 'WindowQA': WindowQA, WindowQuestions: WQr['WindowQuestions'] || [] };
                            arr.push(data);
                            arr2.push(defCData);

                            if (i == txnres.rows.length - 1) {
                                defData['allChilds'] = arr;
                                defData['childData'] = arr2;
                                defData['WindowQuestions'] = WQr['WindowQuestions'] || [];
                                defData['WindowQA'] = WQr['WindowQA'] || {};
                                resolve(defData);
                            }
                        }
                    } else {
                        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,img1Required,ADD_IMAGES 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}'  `;
                console.log("imgObjimgOb---")
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log("imgObjimgOb----q", q)
                    if (txnres.rows.length > 0) {
                        console.log("imgObjimgOb----q", q)
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            console.log("imgObjimgOb---", data)
                            let { Image1, img1Required, ADD_IMAGES } = data;
                            let imagePath = Image1 == "NA" ? Image1 : (Image1 != null && Image1 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + Image1 : '');
                            let obj = { 'Image1Name': data.Image1, 'Image1': imagePath, "img1Required": img1Required, addImg: ADD_IMAGES };
                            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, addImg: 0 };
                                allImages.push(obj);
                                if (s == SOSChildImageCount - 1) {
                                    resolve(allImages);
                                }
                            }
                        }
                        else {
                            resolve(allImages);
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(allImages); },);
            });
        }).catch((err) => {
            return allImages;
        })
    }

    ///optimize code for taking much time
    async function getImage(imgdata) {
        let type = getImageProps.type || '';
        let window = getImageProps.cat || {};
        let splitItem = getImageProps.splitItem || {};
        let splitItemIndex = getImageProps.splitItemIndex || 0;
        let qtn = getImageProps.qtn || {};
        let skus = getImageProps.skus || {};
        let addImg = getImageProps.addImg || 0

        let cameraType = getImageProps.cameraType != null ? getImageProps.cameraType : '1';
        console.log("cameraType0", cameraType, JSON.stringify(qtn) + "------------" + JSON.stringify(skus))
        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')
            ////change by jeevanp
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            let filename = storeData.StoreId + '_' + window.SOSDefinitionId + '_' + (props.UserId || '') + '_SOSImg-' + calculate_tym_date_for_filename + '.jpg';
            let allData = SOSStockData;
            let defData = { 'SOSDefinitionId': window.SOSDefinitionId };
            const wind_index = allData.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId);
            let wind = wind_index >= 0 ? allData[wind_index] : defData;
            console.log("wind----------", wind)

            if (cameraType == '2') {
                var SKUData = wind['SKUData'] || [];
                console.log("SKUData----", SKUData)
                var childIndex = SKUData.findIndex(i => i.SOSChildValue == skus.SOSChildValue);

                console.log("ChildImages---0", childIndex, skus)
                var childData = childIndex >= 0 ? SKUData[childIndex] : {};
                var ChildImages = childData['ChildImages'] || [];
                var image_key = 'Image1Name';
                var image_key_path = 'Image1';
                splitItem[image_key] = filename;
                console.log("splitItem----", splitItem)
            }
            else if (cameraType == '3') {
                var image_key = 'NAImage1';
                var image_key_path = 'NAImage1Path';
                wind[image_key] = filename;
            }
            else {
                var WindowSplits = wind.WindowSplits || [];
                var image_key = type == '1' ? 'Image1Name' : 'Image2Name';
                var image_key_path = type == '1' ? 'Image1' : 'Image2';
                splitItem[image_key] = filename;
            }

            ////change by jeevanp
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Visibility Name:' + window.HeaderName + '(' + window.SOSDefinitionId + ') | Image Type: ' + currentMenu.MenuName + ' | Date:' + calculate_tym_date_over_img;
            console.log(mark_text1 + "\n" + mark_text2, "mark_text2");
            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            console.log("imgurl ", imgurl, imagePath)
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    console.log('image marker:', imgWidth, imgHeight, uri);
                    if (cameraType == '2') {
                        splitItem[image_key_path] = uri;

                        if (addImg == 1) {
                            splitItem['addImg'] = 1
                            ChildImages.push(splitItem)
                        } else {
                            splitItemIndex >= 0 ? ChildImages[splitItemIndex] = splitItem : ChildImages.push(splitItem);
                        }
                        childData['ChildImages'] = ChildImages;
                        childIndex >= 0 ? SKUData[childIndex] = childData : SKUData.push(childData);
                        wind['SKUData'] = SKUData;
                        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

                        setSOSStockData(allData);
                        BgWindowData(allData)
                        BgUnsavedChanges(true)
                        setrerenderdata(!rerenderdata3);
                    }
                    else if (cameraType == '3') {
                        wind[image_key_path] = uri;
                        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                        WindowDataRef.current = allData
                        setSOSStockData(allData);
                        BgUnsavedChanges(true)
                        setrerenderdata(!rerenderdata);
                    }
                    else {
                        console.log('split image updated');
                        splitItem[image_key_path] = uri;
                        if (addImg == 1) {
                            splitItem['addImg'] = 1
                            // let splitItem={Image1: "",Image1Name: "",img1Required: false,addImg:1}
                            wind.Images.push(splitItem)
                        } else {
                            splitItemIndex >= 0 ? WindowSplits[splitItemIndex] = splitItem : WindowSplits.push(splitItem);
                            wind.WindowSplits = WindowSplits;
                        }

                        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                        WindowDataRef.current = allData
                        setSOSStockData(allData);
                        BgUnsavedChanges(true)
                        setrerenderdata2(!rerenderdata2);
                    }

                    setSelectedImg(uri)
                    // 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', cameraType = '1', qtn = {}, skus = {}, addImg = "0") {
        setErrorField({});
        setError(false);
        let GridAllow = false;
        console.log("type----------", qtn)
        console.log("skus2222", skus)
        if (type == '1') {
            GridAllow = cameraType == '1' ? (type === '1' ? (cat.SOSHeaderImageGrid === 'true' || cat.SOSHeaderImageGrid == true || cat.SOSHeaderImageGrid == '1' || cat.SOSHeaderImageGrid == 1) : (cat.SOSChildImageGrid === 'true' || cat.SOSChildImageGrid == true || cat.SOSChildImageGrid == '1' || cat.SOSChildImageGrid == 1)) : false
        } else {
            //GridAllow = cameraType=='1' ?( type==='2' ? (window.VisibilityImage2CameraGrid === 'true' || window.VisibilityImage2CameraGrid==true): (window.VisibilityImage2CameraGrid === 'true' || window.VisibilityImage2CameraGrid==true)):false
        }
        setGridValue(GridAllow);
        setGetImageProps({ 'cat': cat, 'splitItem': splitItem, 'splitItemIndex': splitItemIndex, 'type': type, 'cameraType': cameraType, 'qtn': qtn, 'skus': skus, addImg });
        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 = 'HEADER') {

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

        if (type == 'HEADER') {
            activeKey = 'input_' + cat.SOSHeaderValue;
        }
        else if (type == "CHILD1") {
            activeKey = 'input1_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue;
        } else if (type == "CHILD2") {
            activeKey = 'input2_' + 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", 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.SOS_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    let q2 = `DELETE FROM ${AppTables.SOS_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    let q3 = `DELETE FROM ${AppTables.SOS_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    let q4 = `DELETE FROM ${AppTables.SOS_CHILD_QUES_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    // let q5=`DELETE FROM ${AppTables.SOS_STOCK_DATA} 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); },);
                    await txn.executeSql(q4, [], async function (txn2, txnres) {
                        console.log('stock SOS Questions  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.SOS_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.SOS_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.SOS_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.SOS_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); },);

                                await txn.executeSql(`DELETE FROM ${AppTables.SOS_CHILD_QUES_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;
            db.transaction(async function (txn) {
                var values = '', stock_values = '', images_values = '', stockV = '', SOSHdrFacingDec = '', lastchar = '', SelfFacinglastchar = '', SelfFacingDec = '', TotalFacingDec = '', TotalFacinglastchar = '';
                for (var i = 0; i < AllSOSData.length; i++) {
                    let item = AllSOSData[i];
                    const cat = item;
                    console.log("checkdata---", cat);
                    const catIndex = i;
                    let { SOSHeaderTable, SOSHeaderField, SOSHeaderValue, HeaderName, SOSHeaderFacing, SOSHeaderFacingLable, 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] : {};
                    //console.log("cobj----",cobj)
                    const HeaderImages = cobj['Images'] || [];
                    // const WindowQuestions= cobj['WindowQuestions'] || [] ;
                    let SOSHdrFacing = cobj['SOSHdrFacing'] != null ? cobj['SOSHdrFacing'] : (cobj['SOSHdrFacing'] === 0 ? cobj['SOSHdrFacing'] : '');
                    SOSHdrFacing = SOSHdrFacing + "";
                    // console.log("windowquessss:",WindowQuestions)
                    console.log("SOSHdrFacing:", SOSHdrFacing);
                    // 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 (SOSHdrFacing != null && SOSHdrFacing != '' && SOSHdrFacing.includes(".")) {
                        let SOSHdrFacing_CharArr = SOSHdrFacing.split(".");
                        // there should be only two parts of this decimal value - the  value before dot(.) and the value after dot(.) 
                        let charbefore_dot = SOSHdrFacing_CharArr.length > 0 ? (SOSHdrFacing_CharArr[0] != null && SOSHdrFacing_CharArr[0] != '' ? SOSHdrFacing_CharArr[0] : '0') : '0';
                        let charafter_dot = SOSHdrFacing_CharArr.length > 1 ? (SOSHdrFacing_CharArr[1] != null && SOSHdrFacing_CharArr[1] != '' ? SOSHdrFacing_CharArr[1] : '0') : '0';
                        console.log("charbefore_dot:", charbefore_dot, ",", charafter_dot);
                        SOSHdrFacing = charbefore_dot + "." + charafter_dot;
                    }
                    console.log("SOSHdrFacing after alter:", SOSHdrFacing);

                    let this_SKUData = cobj['SKUData'] || [];
                    values += values != '' ? ' , ' : '';
                    values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderTable}','${SOSHeaderField}','${SOSHeaderValue}','${HeaderName}','${SOSHdrFacing}','${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, img1Required, addImg } = imgObj;
                            images_values += images_values != '' ? ' , ' : '';
                            images_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','','${(Image1Name || '')}','Header','${d2}','${img1Required}',${addImg || 0}) `;

                            console.log('imgObjimgOb----', imgObj);


                        }
                    }

                    for (var j = 0; j < skulist.length; j++) {
                        let skus = skulist[j];
                        let sku_index = j;
                        //console.log("skus----------", skus);
                        let { SOSDefinitionId, SOSChildTable, WindowQuestions, SOSChildField, SOSChildValue, ChildName, SOSChildTotalFacing, SOSChildSelfFacing, SOSChildTotalFacingLable, SOSChildSelfFacingLable, 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 SelfFacing = thisCatSkuData.SelfFacing != null ? thisCatSkuData.SelfFacing : (thisCatSkuData.SelfFacing === 0 ? thisCatSkuData.SelfFacing : '');
                        let WindowQA = thisCatSkuData?.WindowQA || {};
                        SelfFacing = SelfFacing + "";
                        // 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 (SelfFacing != null && SelfFacing != '' && SelfFacing.includes(".")) {
                            let SelfFacing_CharArr = SelfFacing.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);
                            SelfFacing = charbefore_dot + "." + charafter_dot;
                        }

                        // console.log("SelfFacing after alter:", SelfFacing);

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

                        //console.log("SelfFacing after alter:", SelfFacing);

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

                        stock_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSDefinitionId}','${SOSHeaderValue}','${SOSChildTable}','${SOSChildField}','${SOSChildValue}','${ChildName}','${TotalFacing}','${SelfFacing}','${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, img1Required, addImg } = imgObj;
                                images_values += images_values != '' ? ' , ' : '';
                                images_values += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','${SOSChildValue}','${(Image1Name || '')}','Child','${d2}','${img1Required}',${addImg || 0}) `;
                            }
                        }

                        // console.log("WindowQuestions-----121", WindowQuestions);
                        for (const stockProdIndex of WindowQuestions) {
                            // console.log("stockProdIndex---",stockProdIndex.SOSAShowCamera)
                            //console.log("stockProdIndex1---", SOSStockData);

                            let id_key = stockProdIndex.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_AnswerId';
                            let ans_key = stockProdIndex.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Answer';
                            let cam_allow = stockProdIndex.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Camera_allow';
                            let imgname_key = stockProdIndex.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_ImageName1';

                            const stockProd = stockProdIndex;
                            // let sd=SOSStockData.find(i=> i.SOSDefinitionId==cat?.SOSDefinitionId) || {};
                            let sd = SOSStockData.find(i => i.SOSDefinitionId == cat?.SOSDefinitionId) || {};

                            //console.log("stockProdIndex--sd-", sd);
                            // let stock=sd.Stock!=null?sd.Stock:(sd.Stock==0?sd.Stock:'');
                            let { SOSQuestionId, SOSQuestionCode, QuestionType, SOSAQuestionDisable } = stockProd;
                            // let { WindowQA}=sd
                            //console.log("check----", WindowQA, WindowQA?.[ans_key], ans_key);
                            let SOSAnswerName = WindowQA?.[ans_key] || '';
                            let SOSAnswerId = WindowQA[id_key] === 0 ? 0 : (WindowQA[id_key] || '');
                            // let SOSHeaderValue=sd.SOSHeaderValue || 0;
                            // console.log("windowqaa----", WindowQA);
                            let SOSAShowCamera = WindowQA[cam_allow] || false;
                            // console.log("showcam---", SOSAShowCamera);
                            let Image1 = (SOSAShowCamera === 1) ? WindowQA[imgname_key] : (WindowQA[imgname_key] ? WindowQA[imgname_key] : '');
                            console.log("img1----", Image1);
                            stockV += stockV != '' ? ' , ' : '';
                            stockV += ` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSDefinitionId}','${SOSHeaderValue}','${SOSQuestionId}','${SOSQuestionCode}','${QuestionType}','${SOSAnswerName}','${SOSAnswerId}','','${Image1}','${SOSAShowCamera}','','${SOSAQuestionDisable}','${d2}','${skus.SOSChildValue}') `;
                        }

                    }
                }

                console.log("values:", stockV);

                let add_StockHdr = `INSERT INTO ${AppTables.SOS_HDR_DATA} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_TABLE,SOS_HDR_FIELD,SOS_HDR_VALUE,HEADER_NAME,SOS_HDR_FACING,ADDED_DATE) VALUES ${values} `;
                let add_Stock = `INSERT INTO ${AppTables.SOS_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_FACING,SELF_FACING,ADDED_DATE ) VALUES ${stock_values} `;
                let add_ques_stock = `INSERT INTO ${AppTables.SOS_CHILD_QUES_DATA} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_DEFINITION_ID,SOS_HDR_VALUE,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,MENU_ID,IS_DISABLED,ADDED_DATE,SOS_CHILD_VALUE) VALUES ${stockV} `;
                let add_images = `INSERT INTO ${AppTables.SOS_IMAGES} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_VALUE,SOS_CHILD_VALUE,IMAGE1,TYPE,ADDED_DATE,img1Required,ADD_IMAGES) VALUES ${images_values} `;

                console.log('imgObjimgOb----12', add_images);


                console.log("add_Stock-------", stockV, "---", stockV == "");
                txn.executeSql(add_StockHdr, [], async function (txn2, txnres) {
                    console.log('stock facing header added');
                    txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                        console.log('stock facing child added');
                        if (images_values != '') {
                            txn.executeSql(add_images, [], async function (txn2, txnres) {
                                console.log('stock facing images added');
                                if (stock_values != '' && stockV != "") {
                                    await txn.executeSql(add_ques_stock, [], async function (txn2, txnres) {
                                        console.log('stock facing child added');
                                        notify('Share Of Shelf data updated successfully');
                                        setProcessing(false);
                                        // Clear store data in local storage to avoid re-setting 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 avoid re-setting 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 if (stock_values == '' || images_values == '') {
                            txn.executeSql(add_ques_stock, [], async function (txn2, txnres) {
                                console.log('stock facing child added');
                                notify('Share Of Shelf data updated successfully');
                                setProcessing(false);
                                // Clear store data in local storage to avoid re-setting 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 avoid re-setting 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 stock Question data'); });
            });
        } catch (err) {
            console.log(err);
        }
    }



    async function validate() {
        function showError(obj, isErr, msg, refKey) {
            setErrorField(obj);
            setError(isErr);
            if (refKey) {
                let refIn = inputRefs.current[refKey];
                if (refIn) refIn.focus();
            }
            if (msg) notify(msg, 'SHORT');
        }

        // let headerImagesValidation = true;

        return new Promise((resolve) => {
            for (let index = 0; index < AllSOSData.length; index++) {
                const cat = AllSOSData[index];

                let SOSHeaderImage = cat.SOSHeaderImage == 1 || cat.SOSHeaderImage == 'true' ? true : false;
                let SOSHeaderFacing = cat.SOSHeaderFacing == 1 || cat.SOSHeaderFacing == 'true' ? true : false;
                let SOSHeaderFacingLable = cat.SOSHeaderFacingLable || '';
                let SOSChildSelfFacingLable = '';

                const cobj = SOSStockData.find(i => i.SOSHeaderValue == cat.SOSHeaderValue) || {};
                const HeaderImages = cobj['Images'] || [];
                let SOSHdrFacing = cobj['SOSHdrFacing'] != null ? cobj['SOSHdrFacing'] : '';
                let this_SKUData = cobj['SKUData'] || [];

                let TotalSelfFacingsEntered = 0;
                let errorobj = { 'EF_Cat': cat };
                console.log("valida", SOSHeaderFacing == true && SOSHdrFacing !== 0 && (SOSHdrFacing == null || SOSHdrFacing == ''))

                // if(SOSHdrFacing==0){
                //     headerImagesValidation=false
                // }

                /** ---------- Header Facing Validation ---------- **/
                if (SOSHeaderFacing == true && SOSHdrFacing !== 0 && (SOSHdrFacing == null || SOSHdrFacing == '')) {
                    showError(errorobj, true, `Please enter Header Facing for ${cat.HeaderName}`, 'input_' + cat.SOSHeaderValue);
                    resolve(false); return;
                }

                /** ---------- Header Images Validation ---------- **/
                if (StoreCameraAllow && SOSHeaderImage == true && HeaderImages?.length > 0) {
                    console.log("vlai---")
                    for (const splitItemIndex in HeaderImages) {
                        const splitItem = HeaderImages[splitItemIndex];
                        console.log("splitItem----", splitItem);
                        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;
                        }
                    }
                }


                /** ---------- Child Facing Validation ---------- **/
                for (let s = 0; s < cat?.skulist.length; s++) {
                    const skus = cat.skulist[s];
                    const thisCatSkuData = this_SKUData.find(i => i.SOSChildValue == skus.SOSChildValue) || {};
                    let TotalFacing = parseFloat(thisCatSkuData.TotalFacing || 0);
                    let SelfFacing = parseFloat(thisCatSkuData.SelfFacing || 0);
                    const ChildImages = thisCatSkuData['ChildImages'] || [];
                    const WindowQA = thisCatSkuData['WindowQA'] || {};

                    let SOSChildImage = skus.SOSChildImage == 1 || skus.SOSChildImage == 'true' ? true : false;
                    let SOSChildTotalFacing = skus.SOSChildTotalFacing == 1 || skus.SOSChildTotalFacing == 'true' ? true : false;
                    let SOSChildSelfFacing = skus.SOSChildSelfFacing == 1 || skus.SOSChildSelfFacing == 'true' ? true : false;
                    SOSChildSelfFacingLable = skus.SOSChildSelfFacingLable != null ? skus.SOSChildSelfFacingLable : '';

                    errorobj["EF_Brand"] = skus;

                    console.log("childValidation--",)
                    // Total Facing required
                    if (SOSChildTotalFacing && thisCatSkuData.TotalFacing !== 0 && (thisCatSkuData.TotalFacing == null || thisCatSkuData.TotalFacing == '')) {
                        showError(errorobj, true, `Please enter ${skus.SOSChildTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,
                            'input1_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue);
                        resolve(false); return;
                    }

                    // Self Facing required
                    if (SOSChildSelfFacing && thisCatSkuData.SelfFacing !== 0 && (thisCatSkuData.SelfFacing == null || thisCatSkuData.SelfFacing == '')) {
                        showError(errorobj, true, `Please enter ${skus.SOSChildSelfFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,
                            'input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue);
                        resolve(false); return;
                    }

                    // Self ≤ Total
                    if (SOSChildSelfFacing && SOSChildTotalFacing && (SelfFacing > TotalFacing)) {
                        showError(errorobj, true, `${skus.SOSChildSelfFacingLable} should be less than or equals to ${skus.SOSChildTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,
                            'input1_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue);
                        resolve(false); return;
                    }

                    // Collect Self Facing sum
                    TotalSelfFacingsEntered += SelfFacing;

                    // Child Images required
                    console.log("valiaaaaa", StoreCameraAllow, SOSChildImage, (SOSHdrFacing != 0))
                    if (StoreCameraAllow && SOSChildImage && 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);
                                notify(`Please click all child images for ${skus.ChildName} in ${cat.HeaderName}`, 'SHORT');
                                resolve(false); return;
                            }
                        }
                    }


                    // Child Window Questions validation
                    if (skus?.WindowQuestions?.length > 0) {
                        for (const qtnIndex in skus?.WindowQuestions) {
                            const qtn = skus?.WindowQuestions[qtnIndex];
                            let selansid = '', showImageTag = false, isImageMandateforAns = false;;
                            let id_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_AnswerId';
                            let ans_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Answer';
                            let multi_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_MultiOption';
                            let date_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Date';
                            let img_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_ImagePath1';
                            // console.log("img_key---------", id_key, ans_key)
                            let imgname_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_ImageName1';
                            let rating_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Rating';
                            let isDisabled = qtn.isDisabled;
                            if (!isDisabled) {
                                let list_mcdata = [];
                                errorobj['EF_qtn'] = qtn;
                                let isImgAllowed = (qtn.SOSQShowCamera == 'true' || qtn.SOSQShowCamera == 1);
                                let checkForAnsKey = (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'Date' || qtn.QuestionType == 'Rating' || qtn.QuestionType == 'QR');
                                if (qtn.QuestionType == 'Single choice list') {
                                    selansid = WindowQA[id_key];
                                }
                                else if (qtn.QuestionType == 'Multi choice list') {
                                    selansid = WindowQA[multi_key] != null && WindowQA[multi_key] != '' ? WindowQA[multi_key].split(',') : [];
                                }

                                if (qtn.QuestionType == 'Multi choice list' && selansid.length <= 0) {
                                    errorobj['EF_Qtn_MultiChoice'] = 'Qtn_MultiChoice';
                                    showError(errorobj, true);
                                    notify(`${ST.Pleaseselectoptionsfortherequiredfield} ${ST.In} ${qtn.HeaderName}`, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (checkForAnsKey && (Object.keys(WindowQA).indexOf(ans_key) < 0 || (Object.keys(WindowQA).indexOf(ans_key) >= 0 && WindowQA[ans_key] === ''))) {
                                    errorobj['EF_Qtn_Date'] = 'Qtn_Date';
                                    showError(errorobj, true);
                                    let msg = (qtn.QuestionType == 'Date' ? `${ST.Pleasepickadatefortherequiredfield} ${ST.In} ${qtn.HeaderName}` : (qtn.QuestionType == 'Rating' ? `${ST.Pleaseselectratingfortherequiredfield} ${ST.In} ${window.HeaderName}` : `${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.HeaderName}`));
                                    notify(msg, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (Object.keys(WindowQA).indexOf(id_key) < 0 || (Object.keys(WindowQA).indexOf(id_key) >= 0 && (WindowQA[id_key] === ''))) {
                                    errorobj['EF_Qtn_Input'] = 'Qtn_Input';
                                    showError(errorobj, true);
                                    notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${cat.HeaderName}`, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (isImgAllowed && (Object.keys(WindowQA).indexOf(img_key) < 0 || (Object.keys(WindowQA).indexOf(img_key) >= 0 && WindowQA[img_key] === ''))) {
                                    errorobj['EF_Qtn_Image'] = 'Qtn_Image';
                                    showError(errorobj, true);
                                    // notify(`${ST.Pleaseaddimages} ${ST.In} ${window.HeaderName}`,'SHORT');
                                    resolve(false); return;
                                } else {
                                    console.log('no condition found');
                                }

                                if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                                    if (qtn.Answers && qtn.Answers.length > 0) {
                                        for (var j = 0; j < qtn.Answers.length; j++) {
                                            let ansss = qtn.Answers[j];
                                            let isandImgAl = (ansss.SOSAShowCamera == 'true' || ansss.SOSAShowCamera == 1);
                                            isImageMandateforAns = (ansss.SOSACameraMandatory == 'true' || ansss.SOSACameraMandatory == 1);
                                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                                showImageTag = true;
                                                isImageMandateforAns = true;
                                            }
                                            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                                showImageTag = true;
                                            }
                                        }
                                    }
                                }

                                if (showImageTag && isImageMandateforAns && (Object.keys(WindowQA).indexOf(img_key) < 0 || (Object.keys(WindowQA).indexOf(img_key) >= 0 && WindowQA[img_key] === ''))) {
                                    errorobj['EF_Qtn_Image'] = 'Qtn_Image';
                                    showError(errorobj, true);
                                    notify(`${ST.Pleaseaddimages} ${ST.In} ${qtn.SOSQuestionName}`, 'SHORT');
                                    resolve(false); return;
                                }
                            }
                        }
                    }
                }

                /** ---------- Header vs Child Self Facing Validation ---------- **/
                console.log("SOSChildSelfFacingLable---", SOSChildSelfFacingLable)
                if (SOSHeaderFacing && TotalSelfFacingsEntered > parseFloat(SOSHdrFacing)) {
                    errorobj["EF_HdrFacing"] = 'HdrFacing';
                    errorobj["EF_ChildSelf"] = 'ChildSelf';
                    showError(
                        errorobj,
                        true,
                        `Sum of all ${SOSChildSelfFacingLable || 'Child Self Facing'} should be less than or equal to ${SOSHeaderFacingLable || 'Header Facing'} for ${cat.HeaderName}`,
                        'input_' + cat.SOSHeaderValue
                    ); resolve(false); return;
                }

                // ✅ Last Category reached → success
                if (index === AllSOSData.length - 1) {
                    resolve(true); return;
                }
            }
        }).catch((err) => {
            console.log("Validation error:", 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;

        console.log("windowChildImage2-------", key == "SOSHdrFacing" && val == "0", key, val)
        console.log("headerStock---val is valid5", key == "SOSHdrFacing" && val == "0", key, val);

        if (key == "SOSHdrFacing" && val == "0") {
            console.log("headerStock---val is 0");
            skud.Images = skud?.Images?.filter((item) => {
                console.log("item----", item, item.addImg, item.addImg != "1");
                return item.addImg != "1"
            })?.map(vl => ({
                ...vl,
                Image1Name: "NA",
                Image1: "NA"
            })) || [];

            skud.SKUData = skud?.SKUData?.map(sku => {
                const updatedChildImages = sku?.ChildImages?.filter((item) => {
                    return item.addImg != "1"
                }).map(img => ({
                    ...img,
                    Image1Name: "NA",
                    Image1: "NA"
                })) || [];

                // const updatedChildImagesF = sku?.ChildImages?.filter(img => ({
                //     ...img,
                //     Image1Name: "NA",
                //     Image1: "NA"
                // })) || [];

                return {
                    ...sku,
                    TotalFacing: "0",
                    SelfFacing: "0",
                    ...(updatedChildImages.length > 0 && { ChildImages: updatedChildImages })
                };
            }) || [];

        } else if (key === "SOSHdrFacing" && val !== "0") {
            skud.Images = skud?.Images?.map(vl => ({
                ...vl,
                Image1Name: vl?.Image1Name === "NA" ? "" : vl?.Image1Name,
                Image1: vl?.Image1 === "NA" ? "" : vl?.Image1
            })) || [];

            skud.SKUData = skud?.SKUData?.map(sku => {
                const updatedChildImages = sku?.ChildImages?.map(img => ({
                    ...img,
                    Image1Name: img?.Image1Name === "NA" ? "" : img?.Image1Name,
                    Image1: img?.Image1 === "NA" ? "" : img?.Image1
                })) || [];

                return {
                    ...sku,
                    TotalFacing: sku?.TotalFacing === "0" ? "" : sku?.TotalFacing,
                    SelfFacing: sku?.SelfFacing === "0" ? "" : sku?.SelfFacing,
                    ...(updatedChildImages.length > 0 && { ChildImages: updatedChildImages })
                };
            }) || [];
        }

        skud[key] = val;
        console.log("headerStock---skud", JSON.stringify(skud));
        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        console.log("headerStock---", JSON.stringify(allSKUData) + "\n" + val + "\n" + key);



        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, type, cameraType, skus) {
        setSelectedImg(imgPath)
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        }
        else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ cat, splitChildItem, splitChildItemIndex, type, cameraType, skus })
    }

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

    function _OpenCaptureImage_Modal(img) {

        const isImageCap = (img != '' || img != null) ? true : false;

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

                        <View style={{ flexDirection: "row", justifyContent: splitChildItem?.addImg == 1 ? "space-between" : "center", width: "80%" }}>
                            {!showImageSaveOp &&
                                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage(false) }}>
                                    <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                                </TouchableOpacity>
                            }
                            {splitChildItem?.addImg == 1 &&
                                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { handleDelete(reCapImgModalObj) }}>
                                    <Text style={customStyle.PromoImgModal_Cancel_btnText}>{"Delete"}</Text>
                                </TouchableOpacity>
                            }
                        </View>
                    </View>
                }
            </CustomModal>
        )
    }

    function _renderHeader(currentIndex) {
        return (
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex + 1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={() => { UpdateShow_zoomImageRef(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24} />
                </TouchableOpacity>
            </View>
        )
    }

    function openImageRefView(windowIndex = 0) {
        setrefImageIndex(windowIndex);
        UpdateShow_zoomImageRef(true);
    }

    function render_Picker(label_key, value_key, onChange = () => { }, selected_data = {}) {
        var data = [];
        let qtn = selected_data.qtn || {};
        let window = selected_data.window || {};
        let skus = selected_data.skus || {};
        let isQtnDisabled = qtn.isDisabled != null || qtn.isDisabled != '' ? false : true;
        let allAnswers = qtn.Answers || [];

        allAnswers.map((item, index) => {
            let obj = { key: index, label: item[label_key], value: item[value_key] };
            if (selected_data.value == item[label_key])
                // console.log("selected---",selected_data.value, item[label_key])
                obj['component'] = <View style={customStyle.addvis_selectedOpStyle}>
                    <Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text>
                </View>;
            data.push(obj);
        });

        return (
            <ModalSelector
                data={data}
                touchableActiveOpacity={0.8}
                style={customStyle.addVisPickerStyle}
                onChange={(option) => { onChange(option, qtn, window, skus); }}
                overlayStyle={customStyle.addVisPickerOverlay}
                cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                optionStyle={customStyle.addvis_opStyle}
                optionTextStyle={customStyle.addvis_opTextStyle}
                optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                selectedKey={'1'}
                disabled={isQtnDisabled}
            >
                <Text style={[customStyle.WQPicker_InputStyle, (isQtnDisabled ? customStyle.addVisPicker_Dis_InputStyle : {})]}>
                    {(selected_data.value != null && selected_data.value != '' ? selected_data.value : '-' + ST.select + '-')}
                </Text>
            </ModalSelector>
        )
    }




    function onselectionChange(option, qtn, window, skus) {
        setErrorField({});
        setError(false);

        let allData = SOSStockData;
        console.log("kkk---", allData)
        // let allData= WindowData

        let item = window;
        let skuItem = skus;

        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': [], 'WindowQA': {} };
        let skud_index = AllSKUs.findIndex(i => i.SOSChildValue == skuItem.SOSChildValue);
        const skud = skud_index >= 0 ? (AllSKUs[skud_index] || defCData) : defCData
        let WindowQA = skud['WindowQA'] || {};

        let id_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_AnswerId';
        let ans_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Answer';
        WindowQA[id_key] = option.value;
        WindowQA[ans_key] = option.label;
        skud['WindowQA'] = WindowQA

        skud_index >= 0 ? AllSKUs[skud_index] = skud : AllSKUs.push(skud);

        console.log("skud--------12-", AllSKUs)

        catData['SKUData'] = AllSKUs;

        catindex >= 0 ? allSKUData[catindex] = catData : allSKUData.push(catData);
        // // setSOSStockData(allSKUData);
        BgWindowData([...allSKUData])
        // *************************************************************************************************
        let aq_ans = qtn.Answers != null ? qtn.Answers : [];
        let ans_obj = aq_ans.find(i => i.AnswerId == option.value) || {};
        let EQtns = ans_obj.SOSAQuestionEnable != null && ans_obj.SOSAQuestionEnable != '' ? ans_obj.SOSAQuestionEnable.replace(' ', '').split(',') : [];
        let DQtns = ans_obj.SOSAQuestionDisable != null && ans_obj.SOSAQuestionDisable != '' ? ans_obj.SOSAQuestionDisable.replace(' ', '').split(',') : [];

        let sqtns = window.WindowQuestions || []

        if (EQtns.length > 0) {
            enableQtns(sqtns, EQtns, DQtns, data, wind, wind_index, allData, window)
        }
        else if (DQtns.length > 0) {
            disableQtns(sqtns, DQtns, data, wind, wind_index, allData, window)
        }
        else {
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }
        BgUnsavedChanges(true)

    }

    async function disableQtns(sqtns, DQtns, data, wind = {}, wind_index = -1, allData = [], window = {}) {

        if (DQtns.length > 0) {
            new Promise.all(
                DQtns.map((qid, q_index) => {
                    let s_qtnindex = sqtns.findIndex(i => i.SOSQuestionId == qid) || {};
                    let s_qtn = sqtns[s_qtnindex];
                    if (s_qtn != null) {
                        s_qtn['isDisabled'] = true
                        sqtns[s_qtnindex] = s_qtn;
                        let id_key = s_qtn.SOSQuestionId + '_AnswerId';
                        let ans_key = s_qtn.SOSQuestionId + '_Answer';
                        data[id_key] = 0;
                        data[ans_key] = '';

                        wind['WindowQA'] = data;
                        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                        return false
                    } else {
                        return false
                    }
                })
            ).then(async (val) => {
                let allwindows = Windows;
                let windowIndex = allwindows.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId)
                if (windowIndex >= 0) {
                    window['WindowQuestions'] = sqtns;
                    allwindows[windowIndex] = window;
                    WindowDataRef.current = allData
                    BgWindowData(allData);
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
            })
        }
    }

    async function enableQtns(sqtns, EQtns, DQtns, data, wind = {}, wind_index = -1, allData = [], window = {}) {
        new Promise.all(
            EQtns.map((qid, q_index) => {
                let s_qtnindex = sqtns.findIndex(i => i.SOSQuestionId == qid) || {};
                let s_qtn = sqtns[s_qtnindex];
                if (s_qtn != null) {
                    s_qtn['isDisabled'] = false
                    sqtns[s_qtnindex] = s_qtn;
                    return false
                }
                else {
                    return false
                }
            })
        ).then(async (val) => {
            if (DQtns.length > 0) {
                await disableQtns(sqtns, DQtns, data, wind, wind_index, allData, window)
            }
            else {
                let allwindows = SOSStockData;
                let windowIndex = allwindows.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId)
                if (windowIndex > 0) {
                    window['WindowQuestions'] = sqtns;
                    allwindows[windowIndex] = window;
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
            }
        })
    }


    async function setMultiSelectValue(selectedItems = [], qtn = {}, window = {}) {
        setErrorField({});
        setError(false);
        console.log('setMultiSelectValue', selectedItems);
        let id_key = qtn.SOSQuestionId + '_AnswerId';
        let ans_key = qtn.SOSQuestionId + '_Answer';
        let multi_key = qtn.SOSQuestionId + '_MultiOption';

        let allData = SOSStockData;
        let defData = { 'SOSDefinitionId': window.SOSDefinitionId };
        const wind_index = allData.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId);
        let wind = wind_index >= 0 ? allData[wind_index] : defData;
        let obj = wind.WindowQA || {};
        obj[id_key] = 0;
        obj[multi_key] = selectedItems.join(',');
        let anss = [];
        selectedItems.map((itemValue) => {
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue);
            if (ans.Answer) { anss.push(ans.Answer) }
        });
        obj[ans_key] = anss.join(',');
        console.log('obj:', obj);

        wind['WindowQA'] = obj;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

        WindowDataRef.current = allData
        BgWindowData(allData);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value, qtn, window, type = "") {
        // console.log("value--",value)
        if (value != '') {
            let isValid = validateNumber(value, type);
            if (!isValid) {
                return;
            }
        }

        setErrorField({});
        setError(false);
        let id_key = qtn.SOSQuestionId + '_AnswerId';
        let ans_key = qtn.SOSQuestionId + '_Answer';

        let allData = SOSStockData;
        // console.log("def---", window.SOSDefinitionId)
        let defData = { 'SOSDefinitionId': window.SOSDefinitionId };
        const wind_index = allData.findIndex(i => i.SOSDefinitionId == window.SOSDefinitionId);
        //console.log("windindx---", wind_index)
        let wind = wind_index >= 0 ? allData[wind_index] : defData;
        let obj = wind.WindowQA || {};

        if (qtn.QuestionType == 'Date') {
            let date_key = qtn.SOSQuestionId + '_Date';
            let d = value != null ? new Date(value) : new Date();
            let mfdate = moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn, window, false);
            obj[id_key] = 0;
            obj[ans_key] = mfdate;
            obj[date_key] = moment(d).format('MM/DD/YYYY');
        }
        else {
            obj[id_key] = 0;
            obj[ans_key] = value;
        }

        console.log(value, obj);
        wind['WindowQA'] = obj;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

        WindowDataRef.current = allData
        BgWindowData(allData);
        BgUnsavedChanges(true)
        console.log("tyeop-14")
        setrerenderdata(!rerenderdata);
    }

    function renderDatePicker(qtn, window) {
        let qtnn = qtn;
        let DateRange = qtn.DateRange;
        let maxDate = moment().add(10, 'years').format('MM/DD/YYYY');
        let minDate = moment().subtract(10, 'years').format('MM/DD/YYYY');
        if (DateRange == 'RFD') {
            maxDate = moment().format('MM/DD/YYYY');
        }
        else if (DateRange == 'RPD') {
            minDate = moment().format('MM/DD/YYYY');
        }

        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={(dateValue != null && dateValue != '' ? new Date(dateValue) : new Date())}
                mode={'date'}
                display="default"
                onChange={(event, selectedDate) => { setTextValue(selectedDate, qtnn, window) }}
                maximumDate={new Date(maxDate)}
                minimumDate={new Date(minDate)}
            />
        );
    }

    const prevHdrFacingRef = useRef({});
    const alertActiveRef = useRef(false);
    const pendingCatRef = useRef(null);
    const decimalAllowRef = useRef(null);
    const zeroFacingActionRef = useRef(null);


    const hasCapturedImages = (cat) => {

        const wIndex = SOSStockData.findIndex(
            i => i.SOSHeaderValue === cat.SOSHeaderValue
        );

        if (wIndex < 0) return false;

        const wind = SOSStockData[wIndex];

        // HEADER
        const headerImages =
            wind?.Images?.some(img => img?.Image1);

        // CHILD
        const childImages =
            wind?.SKUData?.some(sku =>
                sku?.ChildImages?.some(img => img?.Image1)
            );

        return headerImages || childImages;
    };

    function _renderZeroFacingAlert() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={'All captured images/data will be deleted. Continue?'}
                showModal={showImageAlert}
            >
                <View style={customStyle.storelVisitM_options}>
                    {/* CANCEL */}
                    <TouchableOpacity
                        style={customStyle.storelVisitM_op_btn}
                        onPress={() => {
                            setShowImageAlert(false);
                            alertActiveRef.current = false;
                            // restore previous value
                            const prevVal =
                                prevHdrFacingRef.current?.[pendingCatRef.current?.SOSHeaderValue];

                            if (pendingCatRef.current) {
                                onHdrStockValChange(
                                    pendingCatRef.current,
                                    prevVal || '',
                                    'SOSHdrFacing',
                                    decimalAllowRef.current
                                );
                            }
                        }}
                    >
                        <Text style={customStyle.storelVisitM_op_btnText}>
                            Cancel
                        </Text>
                    </TouchableOpacity>

                    {/* YES */}
                    <TouchableOpacity
                        style={customStyle.storelVisitM_op_btn}
                        onPress={() => {
                            setShowImageAlert(false);
                            zeroFacingActionRef.current?.();
                            alertActiveRef.current = false;
                        }}
                    >
                        <Text style={customStyle.storelVisitM_op_btnText}>
                            Yes
                        </Text>
                    </TouchableOpacity>

                </View>
            </CustomModal>
        );
    }

    // const handleZeroFacingAlert = (cat, newVal, decimalAllow) => {
    //     if (alertActiveRef.current) return;
    //     // const prevVal = prevHdrFacingRef.current[cat.SOSHeaderValue];
    //     // if (newVal === "0" && prevVal && prevVal !== "0") {
    //     if (newVal === "0" && hasCapturedImages(cat)) {
    //         alertActiveRef.current = true;
    //         // Store pending action
    //         zeroFacingActionRef.current = () => {
    //             onHdrStockValChange(cat, "0", 'SOSHdrFacing', decimalAllow);
    //             cleanupImagesOnZeroFacing(cat);
    //         };
    //         pendingCatRef.current = cat;
    //         decimalAllowRef.current = decimalAllow;
    //         setShowImageAlert(true);
    //     }
    // };

    const handleZeroFacingAlert = (cat, newVal, decimalAllow) => {
        if (alertActiveRef.current) return;
        if (newVal === "0" && hasCapturedImages(cat)) {
            alertActiveRef.current = true;
            zeroFacingActionRef.current = () => {
                // ✅ ONLY CLEANUP
                cleanupImagesOnZeroFacing(cat);
                onHdrStockValChange(cat, "0", 'SOSHdrFacing', decimalAllow);

                alertActiveRef.current = false;
            };
            pendingCatRef.current = cat;
            decimalAllowRef.current = decimalAllow;
            setShowImageAlert(true);
        }
    };




    const cleanupImagesOnZeroFacing = (window) => {
        // Use ref so we have latest data when called from async alert callback
        let allData = [...(WindowDataRef.current || SOSStockData)];
        const wIndex = allData.findIndex(
            i => i.SOSHeaderValue === window.SOSHeaderValue
        );

        if (wIndex < 0) return;
        let wind = { ...allData[wIndex] };
        wind.SOSHdrFacing = "0";
        /* ---------- HEADER IMAGES ---------- */
        wind.Images = (wind.Images || []).map(img => {
            // remove ONLY user added images
            if (Number(img.addImg) === 1) return null;
            // ✅ VERY IMPORTANT CHANGE HERE
            return {
                ...img,
                Image1: "NA",     // ⭐⭐⭐⭐⭐ THIS FIXES YOUR BUG
                Image1Name: ""
            };

        }).filter(Boolean);


        /* ---------- CHILD IMAGES ---------- */

        let SKUData = wind.SKUData || [];
        SKUData = SKUData.map(sku => {
            return {
                ...sku,
                ChildImages: (sku.ChildImages || []).map(img => {
                    if (Number(img.addImg) === 1) return null;
                    return {
                        ...img,
                        Image1: "NA",   // ⭐⭐⭐⭐⭐ SAME FIX
                        Image1Name: ""
                    };
                }).filter(Boolean)
            };
        });

        wind.SKUData = SKUData;
        allData[wIndex] = wind;
        WindowDataRef.current = allData;
        setSOSStockData(allData);
        setrerenderdata2(prev => !prev);
        setrerenderdata3(prev => !prev);
        setrerenderdata4(prev => !prev);
        BgUnsavedChanges(true);
    };


    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 SOSFacingMaxValue = KPIFields.findIndex(i => i.KPIFieldName == 'SOSFacingMaxValue')
        let SOSFacingObj = SOSFacingMaxValue >= 0 ? KPIFields[SOSFacingMaxValue] : {};
        let SOSFacingMaxDisplayName = SOSFacingMaxValue >= 0 ? SOSFacingObj['KPIFieldDisplayName'] : '';
        let SOSFacingValueEnable = SOSFacingMaxValue >= 0 ? SOSFacingObj['KPIFieldEnable'] : false;

        const maxFacingVal = Number(SOSFacingMaxDisplayName);

        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;
        let decimalAllow = sosDecimalValueEnable ? 'decimal' : 'numeric';
        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior={Platform.OS == 'ios' ? "padding" : "position"} enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 0 : -100)} >
                <View style={customStyle.keyba_inner_view}>

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

                            let RefImage = cat.SOSRefImage;
                            let SOSHeaderImage = item.SOSHeaderImage == 1 || item.SOSHeaderImage == 'true' ? 1 : 0;
                            let SOSHeaderFacing = item.SOSHeaderFacing == 1 || item.SOSHeaderFacing == 'true' ? 1 : 0;
                            let SOSHeaderFacingLable = item.SOSHeaderFacingLable != null ? item.SOSHeaderFacingLable : '';
                            let SOSRefImagePopUp = item.SOSRefImagePopUP == 'true' || item.SOSRefImagePopUP == true ? true : false;
                            let WindowQuestions = cat.WindowQuestions || [];
                            const cindex = SOSStockData.findIndex(i => i.SOSHeaderValue == item.SOSHeaderValue);
                            const cobj = cindex >= 0 ? SOSStockData[cindex] : {};
                            const HeaderImages = cobj['Images'] || [];
                            let SOSHdrFacing = cobj['SOSHdrFacing'] != null ? cobj['SOSHdrFacing'] : '';
                            let this_SKUData = cobj['SKUData'] || [];
                            let QuestionsData = cobj.WindowQA || {};
                            let show_HdrForm = SOSHeaderFacing == 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 EStyle_HdrFacing = show_errorhere && EF_HdrFacing == 'HdrFacing' ? 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 SOSChildSelfFacingFlag = 0;


                            let isVisible = Boolean(ItemsInView.find(({ item: i, isViewable }) => i.SOSHeaderValue == item.SOSHeaderValue && isViewable))

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

                            if (isVisible && cat.animatedHeight != null) {
                                setTimeout(() => {
                                    Animated.timing(cat.animatedHeight, {
                                        toValue: 0,
                                        duration: 800,
                                        useNativeDriver: false,
                                    }).start();
                                }, (props.RefImagePopUpTime || 0) * 1000)
                            }

                            if ((SOSHeaderFacing == true || SOSHeaderFacing == 1) && (SelfchildCount != 0 && SOSHdrFacing != 0)) {
                                facingPerc1 = ((SelfchildCount || 0) / (SOSHdrFacing || 0)) * 100
                                console.log("vdshva--", facingPerc1)
                            }

                            let HeaderAddImageAllow = (cat?.HeaderAddImageAllow ? true : false) || false
                            let ChildAddImageAllow = (cat?.ChildAddImageAllow ? true : false) || false

                            const isHdrFacingZero = Number(SOSHdrFacing) === 0;

                            let tempHeaderDisable = HeaderImages?.some(item => !item?.Image1);
                            let HeaderAddImageMax = cat?.HeaderAddImageMax <= HeaderImages.length
                            let AddDisable = SOSHeaderFacing && isHdrFacingZero ? true : (tempHeaderDisable ? true : HeaderAddImageMax && !tempHeaderDisable);

                            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 && SOSHeaderFacing==true&& <Text style={customStyle.opening_Stock_catText3}>{`SOS ${facingPerc1.toFixed(0)}%`}</Text> } */}
                                            </View>
                                            {/* <Text style={[customStyle.opening_Stock_catText]}>{item.HeaderName }</Text> */}
                                            {/* + ` (${SOSTarget}%)`*/}
                                            {(sosPercValueEnable == true || sosPercValueEnable == 1) && (SOSHeaderFacing == true || SOSHeaderFacing == 1) && <Text style={customStyle.opening_Stock_catText2}>{`SOS Percent: ${facingPerc1.toFixed(0)}%`}</Text>}
                                            {SOSTarget != null && SOSTarget != '' && <Text style={[customStyle.opening_Stock_catText2]}>{`SOS Target: ${SOSTarget}%`}</Text>}
                                            <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={() => { openImageRefView(index) }}>
                                                <Entypo name='image-inverted' size={24} color={PageTheme.$primary_color} />
                                            </TouchableOpacity>
                                        </LinearGradient>
                                    </View>
                                    {SOSRefImagePopUp &&
                                        <Animated.View
                                            style={[{
                                                backgroundColor: "#fff",
                                                width: "100%",
                                                // height: 300,
                                                height: cat.animatedHeight,
                                                // borderRadius: 10,
                                                paddingBottom: 10,
                                                // shadowColor: "#000",
                                                // elevation: 5
                                            }]}
                                        >
                                            <Image style={[{ width: "100%", height: '100%' }]} resizeMode='contain' source={{ uri: RefImage }} />

                                        </Animated.View>}
                                    <View style={customStyle.SOSForm}>
                                        {show_HdrForm == true &&
                                            <View style={customStyle.SOSHdrForm}>
                                                {SOSHeaderFacing == true && !SOSFacingValueEnable &&
                                                    <View style={customStyle.SOSform_row}>
                                                        <View style={[customStyle.SOSform_colflex]} >
                                                            <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                <Text style={customStyle.SOSform_collabel}>{SOSHeaderFacingLable}</Text>
                                                            </View>

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

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

                                                            <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                {/* <TextInput
                                                                    style={[customStyle.SOSInputStyle, EStyle_HdrFacing]}
                                                                    ref={(reff) => { inputRefs.current['input_' + cat.SOSHeaderValue] = reff; }}
                                                                    placeholder=""
                                                                    autoComplete='off'
                                                                    placeholderTextColor={PageTheme.$placeholder_color}
                                                                    value={(SOSHdrFacing + '')}
                                                                    // maxLength={10}
                                                                    keyboardType='numeric'
                                                                    blurOnSubmit={false}
                                                                    contextMenuHidden={true}
                                                                    returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                    onSubmitEditing={() => { focusToNext(cat, catIndex, "", "", "HEADER") }}
                                                                    onChangeText={(val) => {
                                                                        if (val >= 0 && val <= maxFacingVal) {
                                                                             onHdrStockValChange(cat, val, 'SOSHdrFacing', decimalAllow);

                                                                         }
                                                                        else if (val === '') {
                                                                            // Handle clearing the input
                                                                            onHdrStockValChange(cat, '', 'SOSHdrFacing', decimalAllow);
                                                                        } else {
                                                                            notify(`Please fill the value less than and equal to ${maxFacingVal}`, "LONG");
                                                                        }
                                                                    }}
                                                                /> */}

                                                                <TextInput
                                                                    style={[customStyle.SOSInputStyle, EStyle_HdrFacing]}
                                                                    ref={(reff) => {
                                                                        inputRefs.current['input_' + cat.SOSHeaderValue] = reff;
                                                                    }}
                                                                    value={(SOSHdrFacing + '')}
                                                                    keyboardType='numeric'
                                                                    onFocus={() => {
                                                                        prevHdrFacingRef.current[cat.SOSHeaderValue] = SOSHdrFacing;
                                                                    }}

                                                                    onChangeText={(val) => {
                                                                        // normalize leading zeros
                                                                        if (val.length > 1 && val.startsWith("0")) {
                                                                            val = String(parseInt(val, 10));
                                                                        }
                                                                        if (val === "") {
                                                                            console.log("headerStock---val is valid3", val);
                                                                            onHdrStockValChange(cat, '', 'SOSHdrFacing', decimalAllow);
                                                                            return;
                                                                        }
                                                                        if (val === "0" && SOSHdrFacing !== "0") {

                                                                            if (!hasCapturedImages(cat)) {
                                                                                console.log("headerStock---val is valid4", val);
                                                                                onHdrStockValChange(cat, "0", 'SOSHdrFacing', decimalAllow);
                                                                                return;
                                                                            }
                                                                            console.log("headerStock---val is valid2", val);
                                                                            handleZeroFacingAlert(cat, val, decimalAllow);
                                                                            return;
                                                                        }
                                                                        if (val >= 0 && val <= maxFacingVal) {
                                                                            console.log("headerStock---val is valid1", val);
                                                                            onHdrStockValChange(cat, val, 'SOSHdrFacing', decimalAllow);
                                                                        }
                                                                        else {
                                                                            notify(
                                                                                `Please fill the value less than and equal to ${maxFacingVal}`,
                                                                                "LONG"
                                                                            );
                                                                        }
                                                                    }}
                                                                />

                                                            </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, { marginBottom: 10 }]} key={'SplitItem+' + splitItemIndex}>
                                                                                {((Image1 == '' || Image1 == null) && isImg1mad) ?
                                                                                    <TouchableOpacity style={[EStyle_HdrImage]} onPress={() => { openCamera(cat, splitItem, splitItemIndex, '1', '1', {}, {}) }}>
                                                                                        <CameraImg5 width={50} height={50} />
                                                                                    </TouchableOpacity> : (Image1 == '' || Image1 == null) ?
                                                                                        <TouchableOpacity style={[EStyle_HdrImage]} onPress={() => { openCamera(cat, splitItem, splitItemIndex, '1', '1', {}, {}) }}>
                                                                                            <CameraImg2 width={50} height={50} />
                                                                                        </TouchableOpacity> : (Image1 == "NA") ?
                                                                                            <TouchableOpacity onPress={() => { }}>
                                                                                                <CameraGrey width={50} height={50} />
                                                                                            </TouchableOpacity> : (Image1 != '' || Image1 != null) ?
                                                                                                <TouchableOpacity onPress={() => { OpenImgModal(Image1, cat, splitItem, splitItemIndex, '1') }}>
                                                                                                    <CameraImg3 width={50} height={50} />
                                                                                                </TouchableOpacity> : null
                                                                                }
                                                                            </View>
                                                                        );
                                                                    })
                                                                }

                                                                <>
                                                                    {HeaderAddImageAllow &&
                                                                        <View style={{ flexDirection: 'row', flexWrap: 'wrap', }}>
                                                                            <TouchableOpacity
                                                                                disabled={AddDisable}
                                                                                style={{ marginRight: 10, opacity: AddDisable ? 0.4 : 1 }}

                                                                                onPress={() => openCamera(cat, {}, 0, '1', '1', {}, {}, 1)}>
                                                                                <AddIcon width={48} height={48} />
                                                                            </TouchableOpacity>
                                                                        </View>}
                                                                </>


                                                            </View>




                                                        </View>

                                                    </View>
                                                }
                                            </View>
                                        }


                                        <View style={customStyle.SOSListHdr}>
                                            <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;
                                                        console.log("SOSChildImage",SOSChildImage)
                                                        let SOSChildTotalFacing = skus.SOSChildTotalFacing == 1 || skus.SOSChildTotalFacing == 'true' ? 1 : 0;
                                                        let SOSChildSelfFacing = skus.SOSChildSelfFacing == 1 || skus.SOSChildSelfFacing == 'true' ? 1 : 0;
                                                        let SOSChildTotalFacingLable = skus.SOSChildTotalFacingLable != null ? skus.SOSChildTotalFacingLable : '';
                                                        let SOSChildSelfFacingLable = skus.SOSChildSelfFacingLable != null ? skus.SOSChildSelfFacingLable : '';

                                                        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 SelfFacing = thisCatSkuData.SelfFacing != null ? thisCatSkuData.SelfFacing : '';
                                                        const ChildImages = thisCatSkuData['ChildImages'] || [];
                                                        const WindowQA = thisCatSkuData?.WindowQA || {}
                                                        let addDisableChild1 = ChildImages?.some(item => !item?.Image1);
                                                        // Child Image Max and Disabled btn 
                                                        let ChildAddImageMax = cat?.ChildAddImageMax <= ChildImages.length
                                                       // let addDisableChild = isHdrFacingZero ? true : (addDisableChild1 ? true : ChildAddImageMax && !addDisableChild1)
                                                        let addDisableChild = (SOSHeaderFacing && isHdrFacingZero) ? true : (addDisableChild1 ? true : ChildAddImageMax && !addDisableChild1)
                                                        console.log("addDisableChild", addDisableChild,ChildImages,addDisableChild1)
                                                        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 EF_ChildSelf = errorfield.EF_ChildSelf || '';
                                                        let EStyle_ChildSelf = show_errorhere && show_ChildErrHere && EF_ChildSelf == 'ChildSelf' ? customStyle.stk_inptSTyle_error : {};
                                                        let facingPerc = 0;
                                                        if (((SOSChildTotalFacing == true || SOSChildTotalFacing == 1) && (SOSChildSelfFacing == true || SOSChildSelfFacing == 1)) && (SelfFacing != 0 && TotalFacing != 0)) {
                                                            facingPerc = ((SelfFacing || 0) / (TotalFacing || 0)) * 100
                                                        }
                                                        SOSChildSelfFacingFlag = SOSChildSelfFacing;
                                                        SelfchildCount = SelfFacing;

                                                        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 && SOSHeaderFacing != 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 && ChildImages.length>0) &&
                                                                    <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]}>
                                                                                                {/* CameraGrey */}
                                                                                                {console.log("sku1111", skus)}
                                                                                                {((Image1 == '' || Image1 == null) && isImg1mad) ?
                                                                                                    <TouchableOpacity style={[EStyle_ChildImage]} onPress={() => { openCamera(cat, splitChildItem, splitChildItemIndex, '2', '2', skus, skus) }}>
                                                                                                        <CameraImg5 width={50} height={50} />
                                                                                                    </TouchableOpacity> : (Image1 == '' || Image1 == null) ?
                                                                                                        <TouchableOpacity style={[EStyle_ChildImage]} onPress={() => { openCamera(cat, splitChildItem, splitChildItemIndex, '2', '2', skus, skus) }}>
                                                                                                            <CameraImg2 width={50} height={50} />
                                                                                                        </TouchableOpacity> : (Image1 == "NA") ?
                                                                                                            <TouchableOpacity onPress={() => { }}>
                                                                                                                <CameraGrey width={50} height={50} />
                                                                                                            </TouchableOpacity> : (Image1 != '' || Image1 != null) ?
                                                                                                                <TouchableOpacity onPress={() => { OpenImgModal(Image1, cat, splitChildItem, splitChildItemIndex, '2', skus, skus) }}>
                                                                                                                    <CameraImg3 width={50} height={50} />
                                                                                                                </TouchableOpacity> : null
                                                                                                }
                                                                                            
                                                                                            </View>
                                                                                        );
                                                                                    })
                                                                                }

                                                                                {SOSChildImage == true && ChildImages.length>0 && ChildAddImageAllow &&
                                                                                    <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
                                                                                        <TouchableOpacity disabled={addDisableChild}
                                                                                            onPress={() => openCamera(cat, {}, 0, '2', '2', skus, skus, 1)}
                                                                                            style={{ opacity: addDisableChild ? 0.4 : 1, marginRight: 10 }}
                                                                                        >
                                                                                            <AddIcon width={48} height={48} />
                                                                                        </TouchableOpacity>
                                                                                    </View>}
                                                                            </View>
                                                                        </View>
                                                                    </View>
                                                                }




                                                                <View style={customStyle.SOSlist_form}>
                                                                    {SOSChildTotalFacing == true && !SOSFacingValueEnable &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildTotalFacingLable}</Text>
                                                                                </View>

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

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

                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        ref={(reff) => { inputRefs.current['input1_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildTotal]}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(TotalFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        // maxLength={5}
                                                                                        contextMenuHidden={true}
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "CHILD1") }}
                                                                                        // onChangeText={(val)=>{ onStockValChange(cat,skus,val,'TotalFacing',decimalAllow)}}
                                                                                        onChangeText={(val) => {
                                                                                            if (val >= 0 && val <= maxFacingVal) {
                                                                                                onStockValChange(cat, skus, val, 'TotalFacing', decimalAllow)
                                                                                            } else if (val === '') {
                                                                                                // Handle clearing the input
                                                                                                onStockValChange(cat, skus, '', 'TotalFacing', decimalAllow)
                                                                                            } else {
                                                                                                notify(`Please fill the value less than and equal to ${maxFacingVal}`, "LONG");
                                                                                            }
                                                                                        }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}




                                                                    {SOSChildSelfFacing == true && !SOSFacingValueEnable &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildSelfFacingLable}</Text>
                                                                                </View>
                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildSelf]}
                                                                                        ref={(reff) => { inputRefs.current['input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(SelfFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        maxLength={5}
                                                                                        contextMenuHidden={true}
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "CHILD2") }}
                                                                                        onChangeText={(val) => { onStockValChange(cat, skus, val, 'SelfFacing', decimalAllow) }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}

                                                                    {SOSChildSelfFacing == true && SOSFacingValueEnable &&
                                                                        <View style={customStyle.SOSform_row}>
                                                                            <View style={[customStyle.SOSform_colflex]} >
                                                                                <View style={[customStyle.SOSform_col1, customStyle.SOSform_colsCommon]}>
                                                                                    <Text style={customStyle.SOSform_collabel}>{SOSChildSelfFacingLable}</Text>
                                                                                </View>
                                                                                <View style={[customStyle.SOSform_col2, customStyle.SOSform_colsCommon]}>
                                                                                    <TextInput
                                                                                        style={[customStyle.SOSInputStyle, EStyle_ChildSelf]}
                                                                                        ref={(reff) => { inputRefs.current['input2_' + cat.SOSHeaderValue + '_' + skus.SOSChildValue] = reff; }}
                                                                                        placeholder=""
                                                                                        autoComplete='off'
                                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                                        value={(SelfFacing + '')}
                                                                                        keyboardType='numeric'
                                                                                        // maxLength={maxFacingVal}
                                                                                        contextMenuHidden={true}
                                                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                        blurOnSubmit={false}
                                                                                        onSubmitEditing={() => { focusToNext(cat, catIndex, skus, sku_index, "CHILD2") }}
                                                                                        // onChangeText={(val)=>{ onStockValChange(cat,skus,val,'SelfFacing',decimalAllow)}}
                                                                                        // Handle change to restrict value between 0 and 499
                                                                                        onChangeText={(val) => {
                                                                                            if (val >= 0 && val <= maxFacingVal) {
                                                                                                onStockValChange(cat, skus, val, 'SelfFacing', decimalAllow);
                                                                                            } else if (val === '') {
                                                                                                // Handle clearing the input
                                                                                                onStockValChange(cat, skus, '', 'SelfFacing', decimalAllow);
                                                                                            } else {
                                                                                                notify(`Please fill the value less than and equal to ${maxFacingVal}`, "LONG");
                                                                                                // If the value is outside the range, you can show an error or ignore it
                                                                                            }
                                                                                        }}
                                                                                    />
                                                                                </View>
                                                                            </View>
                                                                        </View>}
                                                                    {(skus?.WindowQuestions.length > 0) &&
                                                                        <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                                                            <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$fourth_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                                                                <Text style={customStyle.windhdrText}>{currentMenu.MenuName + ' Questions'}</Text>
                                                                            </LinearGradient>
                                                                            {/* {WindowQuestions.map((item,index)=>{ */}
                                                                            {skus?.WindowQuestions?.map((item, index) => {

                                                                                let qtn = item;
                                                                                let qtnIndex = index;
                                                                                let selansid = '', selanswer = '', selimg = '', showImageTag = false;
                                                                                let id_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_AnswerId';
                                                                                let ans_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Answer';
                                                                                let multi_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_MultiOption';
                                                                                let date_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Date';
                                                                                let img_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_ImagePath1';
                                                                                {/* console.log("img---",img_key) */ }
                                                                                let imgname_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_ImageName1';
                                                                                let rating_key = qtn.SOSQuestionId + "_ChildId_" + skus.SOSChildValue + '_Rating';

                                                                                let list_mcdata = [];
                                                                                let SOSQDefaultQuestionEnable = qtn.SOSQDefaultQuestionEnable == 'true' || qtn.SOSQDefaultQuestionEnable == 1 || qtn.SOSQDefaultQuestionEnable == '1' ? true : false;
                                                                                let isDisabled = qtn.isDisabled;
                                                                                if (qtn.QuestionType == 'Single choice list') {
                                                                                    selansid = WindowQA[id_key] != null ? WindowQA[id_key] : '';
                                                                                    selanswer = WindowQA[ans_key] != null ? WindowQA[ans_key] : '';
                                                                                }
                                                                                else if (qtn.QuestionType == 'Multi choice list') {
                                                                                    if (qtn.Answers != null) {
                                                                                        for (var i = 0; i < qtn.Answers.length; i++) {
                                                                                            let obj = { 'AnswerId': parseInt(qtn.Answers[i].AnswerId), 'Answer': qtn.Answers[i].Answer };
                                                                                            list_mcdata.push(obj);
                                                                                        }
                                                                                    }
                                                                                    selansid = WindowQA[multi_key] != null && WindowQA[multi_key] != '' ? WindowQA[multi_key].split(',') : [];
                                                                                    console.log("selansid--", selansid)
                                                                                    if (selansid != null && selansid.length > 0) {
                                                                                        let arr = [];
                                                                                        for (var i = 0; i < selansid.length; i++) {
                                                                                            arr.push(parseInt(selansid[i]));
                                                                                        }
                                                                                        selansid = arr;
                                                                                    }
                                                                                    // if(selansid!=null && selansid.length>0){
                                                                                    //     let arr=[];
                                                                                    //     for(var i=0;i<selansid.length;i++){
                                                                                    //         arr.push(parseInt(selansid[i]));
                                                                                    //     }
                                                                                    //     selansid=arr;
                                                                                    // }
                                                                                }
                                                                                else if (qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Date') {
                                                                                    selansid = WindowQA[ans_key] != null && WindowQA[ans_key] != undefined ? WindowQA[ans_key] : "";
                                                                                    selanswer = (qtn.QuestionType == 'Date') ? (WindowQA[date_key] || moment().format('MM/DD/YYYY')) : '';
                                                                                    showImageTag = (qtn.SOSQShowCamera == 1 || qtn.SOSQShowCamera == 'true');
                                                                                }
                                                                                else if (qtn.QuestionType == 'Rating' || qtn.QuestionType == 'QR') {
                                                                                    selanswer = WindowQA[ans_key] ? WindowQA[ans_key] : '';
                                                                                }


                                                                                if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                                                                                    if (qtn.Answers && qtn.Answers.length > 0) {
                                                                                        for (var i = 0; i < qtn.Answers.length; i++) {
                                                                                            let ansss = qtn.Answers[i];
                                                                                            let isandImgAl = (ansss.SOSAShowCamera == 'true' || ansss.SOSAShowCamera == 1);

                                                                                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                                                                                showImageTag = true;
                                                                                            }
                                                                                            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                                                                                showImageTag = true;
                                                                                            }

                                                                                        }
                                                                                    }
                                                                                }

                                                                                if (showImageTag) {
                                                                                    {/* selimg=WindowQA[img_key]!=null && WindowQA[img_key]!=''?'file://'+WindowQA[img_key]:''; */ }

                                                                                    selimg = WindowQA[img_key] != null && WindowQA[img_key] !== "" ? "file://" + WindowQA[img_key] : "";
                                                                                    console.log("checkselimg--", selimg)
                                                                                }

                                                                                let EF_qtn = errorfield.EF_qtn != null ? errorfield.EF_qtn : {};
                                                                                let showQtnErrHere = EF_qtn.SOSQuestionId == qtn.SOSQuestionId;
                                                                                //Qtn_MultiChoice
                                                                                let EF_Qtn_MultiChoice = errorfield.EF_Qtn_MultiChoice || '';
                                                                                let EStyle_Qtn_MultiChoice = show_errorhere && showQtnErrHere && EF_Qtn_MultiChoice == 'Qtn_MultiChoice' ? customStyle.stk_MultiSSTyle_error : {};


                                                                                let EF_Qtn_Date = errorfield.EF_Qtn_Date || '';
                                                                                let EStyle_Qtn_Date = show_errorhere && showQtnErrHere && EF_Qtn_Date == 'Qtn_Date' ? customStyle.stk_inptSTyle_error : {};

                                                                                let EF_Qtn_Input = errorfield.EF_Qtn_Input || '';
                                                                                let EStyle_Qtn_Input = show_errorhere && showQtnErrHere && EF_Qtn_Input == 'Qtn_Input' ? customStyle.stk_inptSTyle_error : {};

                                                                                let EF_Qtn_Image = errorfield.EF_Qtn_Image || '';
                                                                                let EStyle_Qtn_Image = show_errorhere && showQtnErrHere && EF_Qtn_Image == 'Qtn_Image' ? customStyle.stk_inptSTyle_error : {};


                                                                                if (!isDisabled) {
                                                                                    return (
                                                                                        <View style={[customStyle.sform_group2,]} key={'Qtn_' + qtnIndex} >
                                                                                            <Text style={[customStyle.sform_label3]}>{qtn.SOSQuestionName}</Text>
                                                                                            {qtn.QuestionType == 'Single choice list' && qtn.Answers &&
                                                                                                render_Picker('Answer', 'AnswerId', onselectionChange, { value: selanswer, qtn: qtn, window: cat, skus })
                                                                                            }

                                                                                            {qtn.QuestionType == 'Multi choice list' && qtn.Answers &&
                                                                                                <MultiSelect
                                                                                                    items={list_mcdata}
                                                                                                    uniqueKey="AnswerId"
                                                                                                    onSelectedItemsChange={(selectedItems) => { setMultiSelectValue(selectedItems, qtn, window) }} //setMultiSelectValue(selectedItems,qtn)
                                                                                                    selectedItems={selansid}
                                                                                                    selectText="Pick Items"
                                                                                                    searchInputPlaceholderText={ST.SearchItems + "..."}
                                                                                                    // onChangeInput={ (text)=> console.log(text)}
                                                                                                    tagRemoveIconColor={PageTheme.$primary_color}
                                                                                                    tagBorderColor={PageTheme.$primary_color}
                                                                                                    tagTextColor={PageTheme.$primary_color}
                                                                                                    selectedItemTextColor={PageTheme.$primary_color}
                                                                                                    selectedItemIconColor={PageTheme.$primary_color}
                                                                                                    itemTextColor={PageTheme.$text_color}
                                                                                                    displayKey="Answer"
                                                                                                    searchInputStyle={customStyle.wind_MultiSearchInputStyle}
                                                                                                    styleMainWrapper={EStyle_Qtn_MultiChoice}
                                                                                                    submitButtonColor={PageTheme.$primary_color}
                                                                                                    submitButtonText={ST.Submit}
                                                                                                />
                                                                                            }

                                                                                            {(qtn.QuestionType == 'Number' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Text') &&
                                                                                                <TextInput
                                                                                                    style={[customStyle.WQ_InputStyle, EStyle_Qtn_Input]}
                                                                                                    placeholder=""
                                                                                                    autoComplete='off'
                                                                                                    placeholderTextColor={PageTheme.$placeholder_color}
                                                                                                    // keyboardType={'ascii-capable'}
                                                                                                    keyboardType={(qtn.QuestionType == 'Decimal' ? 'decimal-pad' : (qtn.QuestionType == 'Text' ? 'default' : 'number-pad'))}
                                                                                                    value={(selansid + '')}
                                                                                                    onChange={(e) => console.log("onchangeVal--", e.value)}
                                                                                                    onChangeText={(val) => { setTextValue(val, qtn, cat, (qtn.QuestionType == 'Decimal' ? 'decimal' : (qtn.QuestionType == 'Text' ? 'text' : 'numeric'))) }}
                                                                                                />
                                                                                            }
                                                                                            {
                                                                                                (qtn.QuestionType == 'Date') &&
                                                                                                <View style={[customStyle.surveyQtn_datePicker_con, EStyle_Qtn_Date]}>
                                                                                                    <Text style={customStyle.WQ_datePicker_text}>{selansid != '' ? selansid : 'MM/YYYY'}</Text>
                                                                                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={() => { setDateValue(selanswer); showQtnDatePicker(qtn, window, true) }}>
                                                                                                        <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                                                                    </TouchableOpacity>
                                                                                                </View>
                                                                                            }
                                                                                            {
                                                                                                (qtn.QuestionType == 'QR') &&
                                                                                                <View style={customStyle.surveyQtn_datePicker_con}>
                                                                                                    <Text style={customStyle.WQ_datePicker_text}>{selanswer != '' ? selanswer : ''}</Text>
                                                                                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={() => { setQREnable(true); setQRqtnData({ qtn, window }); setShowQRCamera(true); }}>
                                                                                                        {/* <Fontisto size={20} color={PageTheme.$accent_color} name="date"/> */}
                                                                                                        <Ionicons name="camera" color={PageTheme.$accent_color} size={24} />
                                                                                                    </TouchableOpacity>
                                                                                                </View>
                                                                                            }
                                                                                            {((qtn.showDatePicker == true || qtn.showDatePicker == 'true') && (qtn.QuestionType == 'Date')) &&
                                                                                                renderDatePicker(qtn, window)
                                                                                            }
                                                                                            {
                                                                                                (qtn.QuestionType == 'Rating') &&
                                                                                                <View style={customStyle.surveyQtn_datePicker_con}>
                                                                                                    <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                                                                    <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={() => { setRatingQtn(qtn); setRatingWindow(window); setShowRating(true); }}>
                                                                                                        <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag" />
                                                                                                    </TouchableOpacity>
                                                                                                </View>
                                                                                            }



                                                                                            {
                                                                                                showImageTag &&
                                                                                                <View style={[customStyle.store_audit_img_con, EStyle_Qtn_Image]}>
                                                                                                    <Image source={(selimg != '' && selimg != null) ? { uri: selimg } : require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image, ((selimg != '' && selimg != null) ? { resizeMode: 'contain' } : { width: 100, height: 150, resizeMode: 'stretch', alignSelf: 'center' })]} />
                                                                                                    <TouchableOpacity style={customStyle.store_audit_pickimg_btn} onPress={() => {
                                                                                                        openCamera(cat, {}, 0, '1', '2', qtn, skus)
                                                                                                    }}>
                                                                                                        <Entypo name="camera" color={PageTheme.$text_color} size={28} />
                                                                                                    </TouchableOpacity>
                                                                                                </View>
                                                                                            }
                                                                                        </View>
                                                                                    )
                                                                                }
                                                                                else {
                                                                                    return null;
                                                                                }
                                                                            })}
                                                                        </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} />}
            <View style={{ zIndex: 10 }}>
                <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            </View>
            {_OpenCaptureImage_Modal()}
            {_render_Alert()}
            {_renderZeroFacingAlert()}
            <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>
            {show_zoomImage &&
                <View style={customStyle.album_ZOOM_wrap}>
                    <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} index={refImageIndex}
                        renderHeader={_renderHeader} renderIndicator={() => null}
                    />
                </View>
            }
        </Container>
    );
}


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