
import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, KeyboardAvoidingView, AppState,DeviceEventEmitter, Keyboard} 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, UploadData2, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath,} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, 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 { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_icon.svg'
import cameraImg2 from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getdefaltShareofSelf } from '../constants/ConstantQueries';
import CustomCamera from '../components/Camera';
import IRLogin from '../components/IRLogin';
import ImageViewer from 'react-native-image-zoom-viewer';
import { getMethodName, METHODS } from '../constants/methodNames';

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 { SyncIRsessionsInKPI } from '../constants/uploadData';

function ShareOfShelfOneAppIR_Only(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 [SOSIRImages, setSOSIRImages] = useState([]);
    // const [GbTempSessionId, setGbTempSessionId] = useState("");
    const SOSIRImages=useRef([]);
    const GbTempSessionId=useRef("");
    const GbTempSessionObj=useRef({});
    const [AllSOSData, setAllSOSData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [showUploadAlert, setshowUploadAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const showCameraRef = useRef(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [GridValue, setGridValue] = useState(false);

    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [show_zoomImage2, setShow_zoomImage2] = useState(false);
    const Show_zoomImageRef=useRef(false);
    const Show_zoomImageRef2=useRef(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [zoomImageUrl2, setZoomImageUrl2] = useState([]);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [refImageIndex2, setrefImageIndex2] = useState(0);
    const zoomView=useRef(null);
    const zoomView2=useRef(null);

    const [showRetakeModal, setshowRetakeModal] = useState(false);
    const [retakeMData, setretakeMData] = useState({});
    
    const [isDataExists, setisDataExists] = useState(false);
    const [isDataUploaded, setisDataUploaded] = useState("N");
    const sessionsToUpload = useRef([]);
    const sessionsToUploadDetails = useRef([]);
    const sessionsUploadedCount = useRef(0);
    const sessionsReceived = useRef(0);

    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 [windIRParams, setWindIRParams] = useState({});

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(SOSStockData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');

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

    const inputRefs = useRef({});

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

    
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        console.log('storeData1.CameraAllow:',storeData1);
        setStoreCameraAllow(cameraAllow);
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName

        let IR_Creds=props.IR_Creds!=null && props.IR_Creds!=""?JSON.parse(props.IR_Creds):[];
        let IR_CredsObj=IR_Creds.length>0?IR_Creds[0]:{};
        let SOS_IRCreds=IR_CredsObj.ShareOfShelf!=null && IR_CredsObj.ShareOfShelf.length>0?IR_CredsObj.ShareOfShelf[0]:{};
        setWindIRParams(SOS_IRCreds);
        
        getData(storeData1,menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const removeIRListener=DeviceEventEmitter.addListener('onIRImageUpload',(data)=>{ onIRImageUpload(data,storeData1,menu1)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            IRLogin.deRegisterReceiver();
            AppStateSubscription.remove();
            removeIRListener.remove();
            return unsubscribe;
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               bg_GbTempSessionId:GbTempSessionId.current,
               bg_SOSIRImages:SOSIRImages.current,
               visiteDate:d2
           }
           let WindowsStr= await JSON.stringify(newData)
           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 UpdateShowCameraRef(val){
        showCameraRef.current=val
        setShowCamera(val);
    }

    async function onIRImageUpload(data,storeData1,menu1){
        console.log('onIRImageUpload on receive',data);
        let {message,sessionId,status}=data;
        let snum=sessionsReceived.current+1;
        let su_num=sessionsUploadedCount.current;
        console.log('onreceive data',data);
        sessionsReceived.current=snum;
        let thisIR_SessObjIndex=sessionsToUploadDetails.current.findIndex(i=>i.TEMP_SESSION_ID==sessionId);
        let thisIR_SessObj=sessionsToUploadDetails.current[thisIR_SessObjIndex];
        if(status!=null && status=='200' && sessionId!=null && sessionId!=''){
            
            let UnSessionId=await IRLogin.getDataIRSession(sessionId);
            if(UnSessionId!=null && UnSessionId!=''){
                sessionsUploadedCount.current=++su_num;
                let isUpdated=await UpdateIRUploadStatus(storeData1,menu1,sessionId,UnSessionId);
                let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,UnSessionId,message,status,thisIR_SessObj);
                console.log("su_num:",su_num);
                if(isUploaded){
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:"+sessionId);
                }
                else{
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:"+sessionId);
                }

            }
            else{
                console.log('OnReceived UnSessionId get',UnSessionId);
                notify("Cannot upload images for session:"+sessionId+". Universal Id not found");
                let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,"",message,status,thisIR_SessObj);
                if(isUploaded){
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:"+sessionId);
                }
                else{
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:"+sessionId);
                }

            }
            
        }
        else{
            console.log('Cannot get OnReceived UnSessionId');
            notify((message!=null && message!=""?message+". ":"")+"Cannot upload images for session:"+sessionId);
            let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,"",message,status,thisIR_SessObj);
            if(isUploaded){
                console.log('Image Uploaded');
                notify("Images Log uploaded for session:"+sessionId);
            }
            else{
                console.log('cannot Uploaded image');
                notify("cannot upload log for session:"+sessionId);
            }
            
          
        }
        
        console.log("check snum and su_num:",snum,su_num,sessionsToUpload.current.length);
        // if last broadcast received either uploaded or not update the processing status to false
        if(snum==sessionsToUpload.current.length){
            setProcessing(false);
            console.log('Deregister event when last received');
            IRLogin.deRegisterReceiver();
        }

        // All IR Sessions with Images Uploaded : set DataUploaded Status to U (Fully Upload)
        if(su_num==sessionsToUpload.current.length){
            setisDataUploaded("U");
            setProcessing(false);
            notify("All IR images uploaded!");
            console.log('set all uploaded true to U');
        }
        // Some Of IR Sessions with Images Uploaded but some are yet pending : set DataUploaded Status to P (Partial Upload)
        else if(su_num>0 && su_num!=sessionsToUpload.current.length){
            // setProcessing(false);
            setisDataUploaded("P");
            notify("Some IR Images are still not uploaded!");
            console.log('set all uploaded true to P');
        }
    }

   

    function  onBeforeRemove(e){
        if(showCameraRef.current==true){
            e.preventDefault();
            UpdateShowCameraRef(false);
        }
        else if(Show_zoomImageRef.current==true || Show_zoomImageRef2.current==true){
            e.preventDefault();
            UpdateShow_zoomImageRef(false);
            UpdateShow_zoomImageRef2(false);
        }
        else{
            console.log('hasUnsavedChanges:',hasUnsavedChanges);
            if (hasUnsavedChangesRef.current==true) {
                console.log('hasUnsavedChanges is true');
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function UpdateShow_zoomImageRef(val){
        Show_zoomImageRef.current=val
        setShow_zoomImage(val);
    }

    function UpdateShow_zoomImageRef2(val){
        Show_zoomImageRef2.current=val
        setShow_zoomImage2(val);
    }

    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){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            

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

            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 CameraIROnceOnlyIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='CameraIROnceOnly')
            let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?AllKPIFields[CameraIROnceOnlyIndex]:{};
            let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;

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

           
            await db.transaction(async function (txn) {    

                // delete data 
                // let dq1=`delete from ${AppTables.SOS_HDR_DATA}`
                // await txn.executeSql(dq1,[],async function (txn2, txnres) { 
                //     console.log('data removed SOS_HDR_DATA');
                // },function (txnE,txnerr) { console.log(txnerr); },);

                // let dq2=`delete from ${AppTables.SOS_CHILD_DATA}`
                // await txn.executeSql(dq2,[],async function (txn2, txnres) { 
                //     console.log('data removed SOS_CHILD_DATA');
                // },function (txnE,txnerr) { console.log(txnerr); },);

                // let dq3=`delete from ${AppTables.SOS_IMAGES}`
                // await txn.executeSql(dq3,[],async function (txn2, txnres) { 
                //     console.log('data removed SOS_IMAGES');
                // },function (txnE,txnerr) { console.log(txnerr); },);

                // let dq4=`delete from ${AppTables.SOS_IR_IMAGES}`
                // await txn.executeSql(dq4,[],async function (txn2, txnres) { 
                //     console.log('data removed SOS_IR_IMAGES');
                // },function (txnE,txnerr) { console.log(txnerr); },);

                // let dq5=`delete from ${AppTables.SOS_IRUPLOAD}`
                // let dq5=`Update ${AppTables.SOS_IRUPLOAD} set UN_SESSION_ID='',UPLOAD_STATUS='0',SYNC_STATUS='' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                // await txn.executeSql(dq5,[],async function (txn2, txnres) { 
                //     console.log('data removed SOS_IRUPLOAD');
                // },function (txnE,txnerr) { console.log(txnerr); },);
                
                let join1=` INNER JOIN Mapping_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let selectlist1=` DISTINCT p.SOSDefinitionName,p.SOSHeaderTable,p.SOSHeaderField,p.SOSHeaderValue,p.HeaderName as HeaderName,p.SOSHeaderFacing,p.SOSHeaderFacingLable,p.SOSHeaderImage,p.SOSHeaderImageCount,p.SOSHeaderImageGrid`;
                let q=`SELECT ${selectlist1} from Master_ShareOfShelfDefinition p ${join1} Where m.StoreId ='${StoreId}'  
                ${sosCheckAssortment==true?` and p.SOSHeaderValue in (${AssortIds}) `:''}  
                order by p.HeaderName `;
    

                let selectlist2=` DISTINCT m.SOSDefinitionName,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 qIRSelect='',join5='';
                
                if(!CameraIROnceOnly){ // If IR camera is shown for each window
                    join5=`Left outer join ${AppTables.SOS_IRUPLOAD} u on  p.SOS_HDR_VALUE=u.SOS_HDR_VALUE and u.STORE_ID='${StoreId}' and u.TYPE='Header' and u.VISIT_DATE='${d2}' `
                    qIRSelect=` ,u.TEMP_SESSION_ID as TempSessionId,u.UN_SESSION_ID as UploadSessionId,u.UPLOAD_STATUS as UploadStatus,u.SYNC_STATUS as SyncStatus,u.SESSION_STORECODE as Sess_StoreCode,u.SESSION_TASKNAME as Sess_TaskName,u.SESSION_CATNAME as Sess_CatName,u.SESSION_PHOTOTYPE as Sess_PhotoType`;
                }
                let join4=` INNER JOIN Master_ShareOfShelfDefinition m on p.SOS_HDR_VALUE=m.SOSHeaderValue `;
                let q2=` SELECT ${selectlist2} ${qIRSelect} FROM ${AppTables.SOS_HDR_DATA} p ${join4} ${join5} WHERE p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' order by p.HEADER_NAME  `;
                
                // console.log("q2:",q2);
                let storeBGData1=[],bgStoreJson={}, isBGDataExists=false;
                let windData = await get_item('storeData')
                if(windData!=null && windData!=''){
                    let StoreJson = await JSON.parse(windData)
                    let { storeBGData,menuName,StoreId1,visiteDate,bg_SOSIRImages,bg_GbTempSessionId }= StoreJson
                    
                    // Check if bg data exists for this Store and menu on today date
                    if(menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                        isBGDataExists=true;

                        // Check if added sos data exists in bg data
                        if(storeBGData.length>0){
                            storeBGData1=storeBGData;
                            bgStoreJson=StoreJson
                            // setSOSStockData(storeBGData);
                            BgUnsavedChanges(true)
                            BgWindowData(storeBGData)
                        }

                        // Check if IR Images and session present in bg data 
                        if(bg_GbTempSessionId!=null && bg_GbTempSessionId!='' && bg_SOSIRImages!=null && bg_SOSIRImages.length>0){
                            SOSIRImages.current=bg_SOSIRImages;
                            GbTempSessionId.current=bg_GbTempSessionId;
                        }
                    }

                    
                }
                console.log("isBGDataExists:",isBGDataExists,windData);

                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                    // console.log('soscats added:',txnres.rows.length);
                   
                    if(txnres.rows.length>0){
                        let arr=[],allCats=[];
                        for(var i=0;i<txnres.rows.length;i++){

                            let data =txnres.rows.item(i);
                            // console.log("data.TempSessionId",data.TempSessionId);
                            let SOSHeaderFacing=data.SOSHeaderFacing==1 || data.SOSHeaderFacing=='true'?1: 0;

                            // console.log('SOS data:',i,data);
                            if( SOSHeaderFacing==1){
                                inputRefs.current['input_'+data.SOSHeaderValue]='';
                            }
                            
                            let AllCData=await getChilds(storeData1,data,menu1,sosMSLOnly,sosCheckAssortment);
                            let allChilds=AllCData['allChilds'] || [];
                            let childData=AllCData['childData'] || [];
                            data['skulist']=allChilds;
                            arr.push(data);
                            let HdrImages=await getHdrImages(storeData1,data,menu1);

                            let HdrIRImages=[],zoomIRImages=[];
                            
                            if(CameraIROnceOnly==true){
                                HdrIRImages=[];
                            }else{
                                let HdrIRImageObj=await getHdrIRImages(storeData1,data,menu1,"1");
                                HdrIRImages=HdrIRImageObj!=null && HdrIRImageObj["allImages"]!=null?HdrIRImageObj["allImages"]:[];
                                zoomIRImages=HdrIRImageObj!=null && HdrIRImageObj["zoomIRImages"]!=null?HdrIRImageObj["zoomIRImages"]:[];
                            }
                            
                            
                            let defData={'SOSHeaderValue':data.SOSHeaderValue,'SOSHdrFacing':data.SOSHdrFacing,'Images':HdrImages,'IRImages':HdrIRImages,'zoomIRImages':zoomIRImages,'TempSessionId':data.TempSessionId,'SKUData':childData,'Sess_StoreCode':data.Sess_StoreCode,'Sess_TaskName':data.Sess_TaskName,'Sess_CatName':data.Sess_CatName,'Sess_PhotoType':data.Sess_PhotoType};
                            allCats.push(defData);

                            if(i==txnres.rows.length-1){

                                // set IR Images Upload Status if KPI IR flag is enabled
                                if(CameraIROnceOnly){ // Camera for each window is not enabled
                                    if(!isBGDataExists){
                                        let sosImagesObj=await getHdrIRImages(storeData1,data,menu1,"2");
                                        
                                        let AllSOSIRImages=sosImagesObj!=null && sosImagesObj["allImages"]!=null?sosImagesObj["allImages"]:[];
                                        let AllzoomIRImages=sosImagesObj!=null && sosImagesObj["zoomIRImages"]!=null?sosImagesObj["zoomIRImages"]:[];
                                        // setSOSIRImages(AllSOSIRImages);
                                        SOSIRImages.current=AllSOSIRImages;
                                        setZoomImageUrl2(AllzoomIRImages);
                                    }
                                    let isChecked=await getUploadIRStatus(storeData1,menu1);
                                }
                            

                                if(!isBGDataExists){ //set current data in list if bg data does not exists
                                    BgWindowData(allCats)   
                                }
                                
                                setAllSOSData(arr);
                                setisDataExists(true);
                                setProcessing(false);
                            }
                        }
                    }
                    else{
                        await txn.executeSql(q,[],async function (txn2, txnres2) { 
                            // console.log('soscats',txnres2.rows.length);
                            if(txnres2.rows.length>0){
                                let arr=[],allCats=[];
                                for(var i=0;i<txnres2.rows.length;i++){
                                    let data =txnres2.rows.item(i);
                                    let SOSHeaderFacing=data.SOSHeaderFacing==1 || data.SOSHeaderFacing=='true'?1: 0;

                                    if( SOSHeaderFacing==1){
                                        inputRefs.current['input_'+data.SOSHeaderValue]='';
                                    }
                                    
                                    let AllCData=await getChilds(storeData1,data,menu1,sosMSLOnly,sosCheckAssortment);
                                    let allChilds=AllCData['allChilds'] || [];
                                    let childData=AllCData['childData'] || [];
                                    data['skulist']=allChilds;
                                    arr.push(data);
                                    let HdrImages=[];
                                    for(var s=0;s<data.SOSHeaderImageCount;s++){
                                        let obj={'Image1Name':'','Image1':'',img1Required:true };
                                        HdrImages.push(obj);
                                    }
                                    let defData={'SOSHeaderValue':data.SOSHeaderValue,'SOSHdrFacing':'','Images':HdrImages,'IRImages':[],'SKUData':childData};
                                    allCats.push(defData);
                                    if(i==txnres2.rows.length-1){
                                        if(!isBGDataExists){ //set current data in list if bg data does not exists
                                            // setSOSStockData(allCats);
                                            BgWindowData(allCats)   
                                        }
                                        
                                        setAllSOSData(arr);
                                        // setSOSStockData(allCats);
                                        setProcessing(false);
                                    }
                                }
                            }else{
                                setProcessing(false);
                                notify('No data found','SHORT')
                            }
                        },function (txnE,txnerr) { console.log(txnerr); },);
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);
                // setProcessing(false);
            });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getUploadIRStatus(storeData1,menu1){
        let allImages=[];
        let {StoreId} =storeData1;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) { 
                let q=` SELECT Distinct TEMP_SESSION_ID as TempSessionId,UN_SESSION_ID as UploadSessionId,UPLOAD_STATUS as UploadStatus,SYNC_STATUS as SyncStatus,SESSION_STORECODE as Sess_StoreCode,SESSION_TASKNAME as Sess_TaskName,SESSION_CATNAME as Sess_CatName,SESSION_PHOTOTYPE as Sess_PhotoType FROM ${AppTables.SOS_IRUPLOAD} where TYPE='Header' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let isfullyUploaded=true;
                        //No Loop required, As For CameraIROnceOnly enabled condition only one TempSessionId will be genrated per KPI
                        let data =txnres.rows.item(0);
                        let {Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType}=data;
                        if(data.UploadStatus=='1' && isDataUploaded!='P' && isDataUploaded!='U'){
                            console.log('getUploadIRStatus success: U');
                            // Stop Upload and Editing both when fully uploaded
                            setisDataUploaded("U");
                        }
                        // setGbTempSessionId(data.TempSessionId);
                        GbTempSessionId.current=data.TempSessionId;
                        let obj={Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType};
                        GbTempSessionObj.current=obj;
                        resolve(true);
                    }
                    else{
                        resolve(true);
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(false); },);
            });        
        }).catch((err)=>{
            return false;
        })
    }


    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}' and p.SOSHeaderTable!=''  and p.SOSHeaderTable is not null  `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let data =txnres.rows.item(0);
                        let SOSHeaderTable=data['SOSHeaderTable'];
                        let SOSHeaderField=data['SOSHeaderField'];
                        
                        let join2=`  INNER JOIN Mapping_ProductAssortmentStorewise mp on t1.ProductId=mp.ProductId `;
                        let q2=`select distinct t1.${SOSHeaderField} from Product_Master t1 ${join2} where mp.StoreId='${StoreId}' ${sosMSLOnly==true?` and  (mp.MSL='true' or mp.MSL='1') `:''}  `;
                        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}' and p.SOSChildTable!=''  and p.SOSChildTable is not null  `;

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


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

    async function getHdrIRImages(storeData1,cat1,menu1,type="1"){
       
        let res={allImages:[],zoomIRImages:[]}
        let {StoreId} =storeData1;
        let {SOSHeaderId} =cat1;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) { 
                let q=` SELECT IMAGE1 as Image1 FROM ${AppTables.SOS_IR_IMAGES} where   `;
                if(type=='2'){
                    // dont append SOSHeaderId condition
                }
                else{
                    q+=` SOS_HEADER_ID='${SOSHeaderId}' and `;
                }
                q+=` TYPE='Header' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`;

                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let arr=[],arr2=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            let obj={'ImagePath':data.Image1};
                            arr.push(obj);

                            let imgObj={imgIndex:(i+1),url: data.Image1, props: {}}
                            arr2.push(imgObj);
                            if(i==txnres.rows.length-1){
                                res['allImages']=arr
                                res['zoomIRImages']=arr2
                                resolve(res);
                            }
                        }
                    }
                    else{
                        resolve(res);
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(res); },);
            });        
        }).catch((err)=>{
            return res;
        })
    }

    async function getChilds(storeData1,cat1,menu1,sosMSLOnly=false,sosCheckAs=false){
        let defData={allChilds:[],childData:[]};
        let {StoreId} =storeData1;
        let {SOSHeaderValue} =cat1;
        // SOSChildValue
        let childAssorted = await getChildAssortmentIds(storeData1,sosMSLOnly)
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) { 
                let selectlist=` p.SOSDefinitionId,p.SOSChildTable,p.SOSChildField,p.SOSChildValue,p.ChildName,p.SOSChildTotalFacing,p.SOSChildSelfFacing,p.SOSChildTotalFacingLable,p.SOSChildSelfFacingLable,p.SOSChildImage,p.SOSChildImageCount,p.SOSChildImageGrid`;
                let join1=` INNER JOIN Mapping_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
                let q=`SELECT ${selectlist} from Master_ShareOfShelfDefinition p ${join1} Where m.StoreId ='${StoreId}' and p.SOSHeaderValue='${SOSHeaderValue}'  
                ${sosCheckAs==true?` and p.SOSChildValue in (${childAssorted}) `:''}  
                order by p.ChildName  `;
            
                let selectlist2=` m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,p.SOS_CHILD_VALUE as SOSChildValue,p.CHILD_NAME as ChildName,m.SOSChildTotalFacing,m.SOSChildSelfFacing,m.SOSChildTotalFacingLable,m.SOSChildSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_FACING as TotalFacing,p.SELF_FACING as SelfFacing`;
                // let join3=` INNER JOIN Mapping_StoreShareOfShelf mp on m.SOSDefinitionId=mp.SOSDefinitionId `;
                let join4=` INNER JOIN Master_ShareOfShelfDefinition m on p.SOS_DEFINITION_ID=m.SOSDefinitionId `;
                let q2=` SELECT ${selectlist2} FROM ${AppTables.SOS_CHILD_DATA} p ${join4}  WHERE p.SOS_HDR_VALUE='${SOSHeaderValue}' and p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' order by p.CHILD_NAME  `;
            
    
                await txn.executeSql(q2,[],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]='';
                            }

                            arr.push(data);
                            let allChildImages=await getChildImages(storeData1,cat1,data,menu1);
                            let defCData={'SOSChildValue':data.SOSChildValue,'TotalFacing':data.TotalFacing,'SelfFacing':data.SelfFacing,'ChildImages':(allChildImages || [])};
                            
                            arr2.push(defCData);
                            if(i==txnres.rows.length-1){
                                defData['allChilds']=arr;
                                defData['childData']=arr2;
                                resolve(defData);
                            }
                        }
                    }
                    else{
                        console.log('sossubcats added',txnres.rows.length);
                        await txn.executeSql(q,[],async function (txn2, txnres2) { 
                            if(txnres2.rows.length>0){
                                let arr=[],arr2=[];
                                for(var i=0;i<txnres2.rows.length;i++){
                                    let data =txnres2.rows.item(i);
                                    let 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]='';
                                    }
                                    arr.push(data);
                                    let allChildImages=[];
                                    for(var s=0;s<data.SOSChildImageCount;s++){
                                        let obj={'Image1Name':'','Image1':'',img1Required:true};
                                        allChildImages.push(obj);
                                    }
                                    let defCData={'SOSChildValue':data.SOSChildValue,'TotalFacing':'','SelfFacing':'','ChildImages':allChildImages};
                                    arr2.push(defCData);
                                    if(i==txnres2.rows.length-1){
                                        defData['allChilds']=arr;
                                        defData['childData']=arr2;
                                        resolve(defData);
                                    }
                                }
                            }
                            else{
                                resolve(defData);
                            }
                        },function (txnE,txnerr) { console.log(txnerr); resolve(defData); },);
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(defData); },);
            });        
        }).catch((err)=>{
            return defData;
        });
    }

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

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

        if(typeof imgdata=='object' && imgdata.errorCode=='camera_unavailable'){
            notify(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

             let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
             let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

             console.log("time", picture_clicked_time);
      console.log("time1", picture_clicked_time_for_pic_name);
      let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
      let calculate_tym_date_over_img = picture_clicked_time;

            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Share Of Shelf - ('+cat.HeaderName+')'+' | Date:'+calculate_tym_date_over_img;
           
           
            let filename='';
            if(type=='2'){
                filename=storeData.StoreId+'_'+cat.SOSHeaderValue+'_'+skuItem.SOSChildValue+'_'+splitItemIndex+'_'+(props.UserId || '')+'_SOSImg-'+calculate_tym_date_for_filename+'.jpg';
            }
            else{
                filename=storeData.StoreId+'_'+cat.SOSHeaderValue+'_'+splitItemIndex+'_'+(props.UserId || '')+'_SOSImg-'+calculate_tym_date_for_filename+'.jpg';
            }

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

            if(type=='2'){
                var SKUData=catData['SKUData'] || [];
                var childIndex=SKUData.findIndex(i=>i.SOSChildValue==skuItem.SOSChildValue) ;
                var childData=childIndex>=0?SKUData[childIndex]:{};
                
                var ChildImages=childData['ChildImages'] || [];
                var image_key='Image1Name';
                var image_key_path='Image1';
                splitItem[image_key]=filename;
            }
            else{
                var HeaderImages=catData['Images'] || [];
                var image_key='Image1Name';
                var image_key_path='Image1';
                splitItem[image_key]=filename;
            }
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            
                // file resized now rename file
                RNFS.copyFile(imgurl, imagePath)
                .then(async(resn) => {
                    // render data with clicked image
                    let uri='file://'+imagePath;
                    console.log('image marker:',uri);
                    setSelectedImg(uri)

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

                        catData['SKUData']=SKUData;
                        catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                        setSOSStockData(allData);
                        BgWindowData(allData)
                        // setHasUnsavedChanges(true);
                        BgUnsavedChanges(true)
                        setrerenderdata(!rerenderdata);
                    }
                    else{
                        console.log('Hdr split image updated');
                        splitItem[image_key_path]=uri;
                        splitItemIndex>=0?HeaderImages[splitItemIndex]=splitItem:HeaderImages.push(splitItem);
                        catData['Images']=HeaderImages;
                        catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                        // setSOSStockData(allData);
                        BgWindowData(allData)
                        // setHasUnsavedChanges(true);
                        BgUnsavedChanges(true)
                        setrerenderdata(!rerenderdata);
                    }

                    // add metdata then resize image and restored back to the imagePath
                    let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                    let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                    console.log("image restored:",is_restored);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });                
        }        
    }
  
  
    async function openCamera(cat,splitItem,splitItemIndex,type='1',sku){ 
        setErrorField({});
        setError(false);
        let GridAllow = type==='1' ? (window.SOSHeaderImageGrid === 'true' || window.SOSHeaderImageGrid==true || window.SOSHeaderImageGrid=='1'|| window.SOSHeaderImageGrid==1): (window.SOSChildImageGrid === 'true' || window.SOSChildImageGrid==true ||  window.SOSChildImageGrid=='1' ||  window.SOSChildImageGrid==1)
        setGridValue(GridAllow);  
        setGetImageProps({'cat':cat,'splitItem':splitItem,'splitItemIndex':splitItemIndex,'type':type,'sku':sku}); 
        UpdateShowCameraRef(true);
    }
    async function StartCameraSession(cat,type='1',sku){
        setErrorField({});
        setError(false);
        let IR_Creds=props.IR_Creds!=null && props.IR_Creds!=""?JSON.parse(props.IR_Creds):[];
        let IR_CredsObj=IR_Creds.length>0?IR_Creds[0]:{};

        cat=cat!=null?cat:{},
        sku=sku!=null?sku:{};
        let newStdata=storeData;
        if(IR_CredsObj.UseStoreCode!=1){
            newStdata.StoreCode=newStdata.StoreId;
        }
        let obj={"StoreData":newStdata};
        
        

        // Option values for Perfetti paid visibility if IR shown in header only
        // obj["category_name"]="multi";
        // obj["task_name"]="multi-shelf";
        // obj["photo_type"]="shelf";

        

        if(type=='1' && windIRParams.category_name=='AsDefined'){ // if IR Camera is present for each category
            let {SOSDefinitionName}=cat;
            console.log("SOSDefinitionName:",SOSDefinitionName);
            obj["category_name"]=SOSDefinitionName || '';
            obj["task_name"]=SOSDefinitionName || '';
            obj["photo_type"]=windIRParams.photo_type || '';
        }
        else{ // if IR Camera is present only in header
            obj["category_name"]=windIRParams.category_name || '';
            obj["task_name"]=windIRParams.task_name || '';
            obj["photo_type"]=windIRParams.photo_type || '';
        }
        let st1=JSON.stringify(obj);

        //storeData,cat,type,sku
        console.log("ir camera obj:",obj.category_name,obj.task_name,obj.photo_type,newStdata.StoreCode);
        let TempSessionId= await IRLogin.StartIRSession(st1);//"8099b819-0979-40d2-950e-489566041484";//
        console.log('TempSessionId :',TempSessionId,newStdata.StoreCode);
        if(TempSessionId!=null){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
            // let imgObj=Images[Images.length-1];

            console.log('Images from session :',IRCamImages);

            if(type=='2'){
                // setGbTempSessionId(TempSessionId);
                GbTempSessionId.current=TempSessionId;
                let sessObj={}
                sessObj['Sess_StoreCode'] =newStdata.StoreCode;
                sessObj['Sess_TaskName'] =obj["task_name"];
                sessObj['Sess_CatName'] =obj["category_name"];
                sessObj['Sess_PhotoType'] =obj["photo_type"];
                // setSOSIRImages(IRCamImages);
                GbTempSessionObj.current=sessObj;
                SOSIRImages.current=IRCamImages;
                setIRZoomImages(IRCamImages);
            }
            else{
                let zoomIRImages=await getIRZoomImages(IRCamImages)
                console.log("getIRZoomImages res:",zoomIRImages);

                let allData=SOSStockData;
                let defData={'SOSHeaderValue':cat.SOSHeaderValue,'SOSHdrFacing':'','Images':[],'IRImages':[],'SKUData':[]};
                const catDataIndex=allData.findIndex(i=>i.SOSHeaderValue==cat.SOSHeaderValue) ;
                const catData=catDataIndex>=0?allData[catDataIndex]:defData;
                catData['IRImages'] =IRCamImages;
                catData['zoomIRImages'] =zoomIRImages;
                catData['TempSessionId'] =TempSessionId;
                catData['Sess_StoreCode'] =newStdata.StoreCode;
                catData['Sess_TaskName'] =obj["task_name"];
                catData['Sess_CatName'] =obj["category_name"];
                catData['Sess_PhotoType'] =obj["photo_type"];
                catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                console.log("allData:",allData);
                setSOSStockData(allData);
            }

            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
            
            // stop image processing loader after all images get from sessionID
            setProcessing(false);
            setLoaderTitle('loading...');
            
        }
        else{
            notify('Cannot capture images as getting Session Null.');
        }
        
    }


    async function ResumeCameraSession(cat,type='1',sku){
        cat=cat!=null?cat:{},
        sku=sku!=null?sku:{};

        let allData=SOSStockData;
        let defData={'SOSHeaderValue':cat.SOSHeaderValue,'SOSHdrFacing':'','Images':[],'IRImages':[],'SKUData':[]};
        const catDataIndex=allData.findIndex(i=>i.SOSHeaderValue==cat.SOSHeaderValue) ;
        const catData=catDataIndex>=0?allData[catDataIndex]:defData;
            
        //storeData,cat,type,sku
        let TempSessionId="";
        if(type=='2'){
            TempSessionId= GbTempSessionId.current;
        }
        else{
            TempSessionId= catData.TempSessionId;
        }
        console.log('TempSessionId of cat :',TempSessionId);
        if(TempSessionId!=null){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let retTempSessionId=await IRLogin.ResumeIRSession(TempSessionId);//"8099b819-0979-40d2-950e-489566041484";//
            console.log('retTempSessionId :',retTempSessionId);
            if(retTempSessionId!=null){
                // start fetching images after capturing photos
                

                let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Images from session :',IRCamImages);

                if(type=='2'){
                    // setSOSIRImages(IRCamImages);
                    SOSIRImages.current=IRCamImages;
                    setIRZoomImages(IRCamImages);
                }
                else{
                    let zoomIRImages=await getIRZoomImages(IRCamImages)
                    catData['IRImages'] =IRCamImages;
                    catData['zoomIRImages'] =zoomIRImages;
                    catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                    console.log("allData2:",allData);
                    setSOSStockData(allData);
                }
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
                
                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
            }
            else{
                notify('Cannot capture images as getting Session Null.');
            }
            
        }
        else{
            notify('Cannot capture images as getting Session Null.');
        }
        
    }

    async function DeleteIRPhoto(){
        console.log('DeleteIRPhoto called');
        setshowRetakeModal(false);
        let {cat,type,IRImgIndex,IRimgPath}= retakeMData;
        cat=cat!=null?cat:{},
        type=type!=null?type:'1';
        IRImgIndex=IRImgIndex!=null?IRImgIndex:'';
        IRimgPath=IRimgPath!=null?IRimgPath:'';
        

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

        let TempSessionId="";
        console.log("type:",type,GbTempSessionId.current);
        if(type=='2'){
            TempSessionId=GbTempSessionId.current;
        }
        else{
            TempSessionId=catData['TempSessionId'];
        }

        // let st1=JSON.stringify(storeData);
        //storeData,cat,type,sku
        console.log('DeleteIRPhoto sessionID :',TempSessionId);
        if(TempSessionId!=null || TempSessionId!=''){
            setLoaderTitle('Removing Image...');
            setProcessing(true);
            let isDeleted= await IRLogin.DeleteIRSessionPhoto(TempSessionId,IRimgPath);//"8099b819-0979-40d2-950e-489566041484";//
            console.log('DeleteIRPhoto isDeleted :',isDeleted);
            if(isDeleted){
                setLoaderTitle('Processing Image...');
                
                let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Deleted, Images from session :',IRCamImages);
                if(type=='2'){
                    // setSOSIRImages(IRCamImages);
                    SOSIRImages.current=IRCamImages;
                    setIRZoomImages(IRCamImages);
                }
                else{
                    let zoomIRImages=await getIRZoomImages(IRCamImages)
                    catData['IRImages'] =IRCamImages;
                    catData['zoomIRImages'] =zoomIRImages;
                    catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                    setSOSStockData(allData);
                }
                
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
                
                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
                
            }
            else{
                notify('Cannot delete photo!.');
            }

        }
        else{
            notify('Cannot delete photo! Found Null Session.');
        }
        
    }

    async function RetakeIRPhoto(){
        setshowRetakeModal(false);
        let {cat,type,IRImgIndex,IRimgPath}= retakeMData;
        cat=cat!=null?cat:{},
        type=type!=null?type:'1';
        IRImgIndex=IRImgIndex!=null?IRImgIndex:'';
        IRimgPath=IRimgPath!=null?IRimgPath:'';
        

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

        let TempSessionId="";
        if(type=='2'){
            TempSessionId=GbTempSessionId.current;
        }
        else{
            TempSessionId=catData['TempSessionId'];
        }
        

        // let st1=JSON.stringify(storeData);
        //storeData,cat,type,sku
        console.log('Retake sessionID :',TempSessionId);
        if(TempSessionId!=null || TempSessionId!=''){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let isRetakeDone= await IRLogin.RetakeIRSessionPhoto(TempSessionId,IRimgPath);//"8099b819-0979-40d2-950e-489566041484";//
            console.log('Retake isRetakeDone :',isRetakeDone);
            if(isRetakeDone){
                setTimeout(async ()=>{
                    let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                    console.log('Retake Images from session :',IRCamImages);
                    if(type=='2'){
                        // setSOSIRImages(IRCamImages);
                        SOSIRImages.current=IRCamImages;
                        setIRZoomImages(IRCamImages);
                    }
                    else{
                        let zoomIRImages=await getIRZoomImages(IRCamImages)
                        catData['IRImages'] =IRCamImages;
                        catData['zoomIRImages'] =zoomIRImages;
                        catDataIndex>=0?allData[catDataIndex]=catData:allData.push(catData);
                        setSOSStockData(allData);
                    }
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                    
                    // stop image processing loader after all images get from sessionID
                    setProcessing(false);
                    setLoaderTitle('loading...');
                },1000);
            }
            else{
                notify('Error occur while retaking photo!.');
            }

        }
        else{
            notify('Cannot start camera! Found Null Session.');
        }
        
    }
    // Start Upload for IR images 
    async function UploadIRSessions(){
        setshowUploadAlert(false);
        sessionsToUpload.current=[];
        sessionsReceived.current=0;
        sessionsUploadedCount.current=0;
        
        try{
            let {StoreId}=storeData;
            setLoaderTitle('Uploading Images...');
            setProcessing(true);

            // Global Upload function
            // Sync Status for IR images
            // From Infilect SDK 1.3.6 - The Images are uploading on realtime bases i.e. As the images are clicked by user the Images are getting uploaded to infilect server.
            // In this case call below func to check the status of images that is already being uploaded by Real Time processing
            let sync_result=await SyncIRsessionsInKPI(props,storeData,AppTables.SOS_IRUPLOAD,AppTables.SOS_IR_IMAGES);
            let {isUploadStarted,AllDataUploaded,noDataFound,success,sessionList,sessionListWithDetails}=sync_result;
            console.log("Sync Resp sync_result:",sync_result);
            if(!success){
                notify('Cannot Upload Data! Something went wrong.');
                setProcessing(false);
            }
            else{
                if(noDataFound){
                    notify('No session to upload!');
                    setisDataUploaded('U');
                    setProcessing(false);
                }
                else{
                    if(!isUploadStarted && AllDataUploaded){
                        notify('All images synced! No session to upload.');
                        setisDataUploaded('U');
                        setProcessing(false);
                    }else if(isUploadStarted){
                        sessionsToUpload.current=sessionList;
                        sessionsToUploadDetails.current=sessionListWithDetails;
                    }
                }
            }
            
        }catch(e){
            console.log('Uploading Issue:',e);
            setProcessing(false);
        }
        
        
    }

    async function UpdateIRUploadStatus(storeData1,menu1,TempSessionId,UnSessionId){
        console.log('UpdateIRUploadStatus');
        return new Promise((resolve,reject)=>{

            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            db.transaction(async function (txn) {    
                // update upload status and sync status here : when files are uploaded and we have got the universal session id for that 
                let q=`Update ${AppTables.SOS_IRUPLOAD} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                // console.log("update IR Upload q:",q);
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('Updated IR Upload Status');
                    // console.log("update IR Upload q2:",q2);
                    let q2=`Update ${AppTables.SOS_IR_IMAGES} set UN_SESSION_ID='${UnSessionId}' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                    await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                        console.log('Updated IR Upload Images Status');
                        resolve(true);
                    },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
                    
                },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
            });  
        }).catch((Err)=>{
            console.log('Error in UpdateIRUploadStatus:',Err);
            return false;
        })
        
                    
        
    }

    async function LogImageUpload(storeData1,menu1,TempSessionId,UnSessionId,message,status,thisIR_SessObj={}){
        let {StoreId,StoreName}=storeData1;
        const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
        const nowTime=moment().format('HH:mm:ss');
        let ImageCount=await getImageCount(storeData1,menu1,TempSessionId);
        let {SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE}=thisIR_SessObj;

        ////Replaced special charecter and white space
        let storeTittle = StoreName.replace(`@!%&`, '').replace(' ', '-');
        console.log("storeTittle:",storeTittle,StoreName);
 
        let obj={};
        obj['StoreId']=StoreId;
        obj['Username']=props.UserId;
        obj['VisitDate']=d2;
        obj['InTime']=nowTime;
        obj['TempSessionId']=TempSessionId;
        obj['UnSessionId']=UnSessionId;
        obj['Status']=status;
        obj['Message']=message;
        obj['ImageCount']=ImageCount;
        obj['StoreTitle']=storeTittle;
        obj['StoreCode']=SESSION_STORECODE;
        obj['TaskName']=SESSION_TASKNAME;
        obj['CategoryName']=SESSION_CATNAME;
        obj['PhotoType']=SESSION_PHOTOTYPE;
        obj['KPIType']=currentMenu.MenuName;
        obj['ScreenName']=currentMenu.ScreenName;
        obj['UploadType']="New";

                                
        let postData={};
        postData['MID']=0;
        postData['Keys']='IR_UPLOAD_LOG_MSG';
        postData['JsonData']=JSON.stringify(obj);
        postData['UserId']=props.UserId;

        console.log('postData',postData);
        
        return await UploadData2(url,postData)
        .then((res)=>{
            if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
                return true;
            }
            return false;
        })
        .catch((err)=>{
            console.log(err);
            return false;
        });
    }

    async function getImageCount(storeData1,menu1,TempSessionId){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        console.log('storeData in getImageCount',storeData1);
        return new Promise((resolve,reject)=>{

            
            db.transaction(async function (txn) {    

                let q=`select DISTINCT TEMP_SESSION_ID,count(IMAGE1) as ImageCount from ${AppTables.SOS_IR_IMAGES}  where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}'  group by TEMP_SESSION_ID `;
                console.log('q',q);
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('ImageCount rows:',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let data =txnres.rows.item(0);
                        console.log('data:',data)
                        console.log('Image Count for TempSessionId:',data.ImageCount);
                        resolve(data.ImageCount);
                    }
                    else{
                        resolve(0);
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr);resolve(0); },);
            });  
        }).catch((Err)=>{
            console.log('Error in getImageCount:',Err);
            return 0;
        })
        
                    
        
    }
    

    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 onSubmitData(){
        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;
            await db.transaction(async function (txn) {   

              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_IR_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q5=`DELETE FROM ${AppTables.SOS_IRUPLOAD} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              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('SOS IR images deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              await txn.executeSql(q5,[],async function (txn2, txnres) { 
                console.log('SOS session status deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

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

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

            let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='CameraIROnceOnly')
            let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
            let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;

            
            await db.transaction(async function (txn) {
              var values='',stock_values='',images_values='',IRimages_values='',IRsessions='';
              
              for(var i=0;i<AllSOSData.length;i++){
                let item=AllSOSData[i];
                const cat=item;
                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]:{};
                const HeaderImages=cobj['Images'] || [] ;
                let SOSHdrFacing="0";
                let CatIRImages=cobj['IRImages']!=null?cobj['IRImages'] : [] ;
                let TempSessionId= cobj.TempSessionId!=null?cobj.TempSessionId:'';
                let Sess_StoreCode=cobj.Sess_StoreCode!=null?cobj.Sess_StoreCode:'';
                let Sess_TaskName=cobj.Sess_TaskName!=null?cobj.Sess_TaskName:'';
                let Sess_CatName=cobj.Sess_CatName!=null?cobj.Sess_CatName:'';
                let Sess_PhotoType=cobj.Sess_PhotoType!=null?cobj.Sess_PhotoType:'';

                let this_SKUData=cobj['SKUData'] || [];

                values+=values!=''?' , ':'';
                values+=` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderTable}','${SOSHeaderField}','${SOSHeaderValue}','${HeaderName}','${SOSHdrFacing}','${d2}') `;
                
                // Add IR session upload status for each category 
                if(!CameraIROnceOnly){
                    IRsessions+=IRsessions!=''?' , ':'';
                    IRsessions+=` ('${SOSHeaderId}','${StoreId}','${d2}','','${SOSHeaderValue}','','${TempSessionId}','','0','0','Header','${Sess_StoreCode}','${Sess_TaskName}','${Sess_CatName}','${Sess_PhotoType}','${d2}') `;
                }

                let skulist=item['skulist'] || [];


                if(!CameraIROnceOnly){
                    for(var l=0;l<CatIRImages.length;l++){
                        let imgObj=CatIRImages[l];
                        let {ImagePath}=imgObj;
                        IRimages_values+=IRimages_values!=''?' , ':'';
                        IRimages_values+=` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','','${(ImagePath || '')}','Header','${TempSessionId}','','${d2}') `;
                    }
                }


                for(var j=0;j<skulist.length;j++){
                    let skus=skulist[j];
                    let sku_index=j;
                    let {SOSDefinitionId,SOSChildTable,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="0.0";
                    let SelfFacing="0.0";
                            
                    stock_values+=` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSDefinitionId}','${SOSHeaderValue}','${SOSChildTable}','${SOSChildField}','${SOSChildValue}','${ChildName}','${TotalFacing}','${SelfFacing}','${d2}') `;
                    
                }
              }



              
              if(CameraIROnceOnly){
                IRimages_values='';
                for(var l=0;l<SOSIRImages.current.length;l++){
                    let imgObj=SOSIRImages.current[l];
                    let {ImagePath}=imgObj;
                    IRimages_values+=IRimages_values!=''?' , ':'';
                    IRimages_values+=` ('','${StoreId}','${d2}','','','${(ImagePath || '')}','Header','${GbTempSessionId.current}','','${d2}') `;
                    
                }

                let {Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType}=GbTempSessionObj.current;
                Sess_StoreCode=Sess_StoreCode || '';
                Sess_TaskName=Sess_TaskName || '';
                Sess_CatName=Sess_CatName || '';
                Sess_PhotoType=Sess_PhotoType || '';
                // Add IR session upload status once only for whole KPI
                IRsessions+=IRsessions!=''?' , ':'';
                IRsessions+=` ('','${StoreId}','${d2}','','','','${GbTempSessionId.current}','','0','0','Header','${Sess_StoreCode}','${Sess_TaskName}','${Sess_CatName}','${Sess_PhotoType}','${d2}') `;
              }

              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_images=`INSERT INTO ${AppTables.SOS_IMAGES} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_VALUE,SOS_CHILD_VALUE,IMAGE1,TYPE,ADDED_DATE) VALUES ${images_values} `;
              let add_IRimages=`INSERT INTO ${AppTables.SOS_IR_IMAGES} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_HDR_VALUE,SOS_CHILD_VALUE,IMAGE1,TYPE,TEMP_SESSION_ID,UN_SESSION_ID,ADDED_DATE) VALUES ${IRimages_values} `;
              
              let add_IRUploadS=`INSERT INTO ${AppTables.SOS_IRUPLOAD} (SOS_HEADER_ID,STORE_ID,VISIT_DATE,SOS_DEFINITION_ID,SOS_HDR_VALUE,SOS_CHILD_VALUE,TEMP_SESSION_ID,UN_SESSION_ID,UPLOAD_STATUS,SYNC_STATUS,TYPE,SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE,ADDED_DATE) VALUES ${IRsessions} `;
             
              
              await txn.executeSql(add_StockHdr,[],async function (txn2, txnres) { 
                console.log('stock facing header added');
                await txn.executeSql(add_Stock,[],async function (txn2, txnres) { 
                    console.log('stock facing child added');
                    var isImageAdded=true,isIRImageAdded=true,isIRStatusAdded=true;
                    if(images_values!=''){
                        isImageAdded=executeSDQuery(txn,add_images);
                    }
                    if(IRimages_values!=''){
                        isIRImageAdded=executeSDQuery(txn,add_IRimages);
                    }
                    if(IRsessions!=''){
                        isIRStatusAdded=executeSDQuery(txn,add_IRUploadS);
                    }

                    if(!isImageAdded){
                        setProcessing(false);notify('Cannot add Share Of Shelf Images data');
                    }
                    else if(!isIRImageAdded){
                        setProcessing(false);notify('Cannot add Share Of Shelf IR Images data');
                    }
                    else if(!isIRStatusAdded){
                        setProcessing(false);notify('Cannot add Share Of Shelf IR Session data');
                    }
                    else{
                        console.log('stock facing IR Upload status added');
                        notify('Share Of Shelf data updated successfully');
                        setProcessing(false);
                        setisDataExists(true);
                        // setshowUploadAlert(true);
                        await clear_item('storeData'); //clear bg data 
                        BgUnsavedChanges(false);// when all data saved clear the unsaved changes flag 
                        props.navigation.goBack();// send back 
                    }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add Share Of Shelf data') },);
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add Share Of Shelf data') },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }

    async function executeQuery(q){
        return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
            await txn.executeSql(q,[],async function (txn2, txnres2) {           
              resolve(true);
            },function(Etxn,txnerr){console.log(txnerr);resolve(false) });
          }); 
        }).then((val)=>{
          return val;
        }).catch((err)=>{
            console.log(err);
          return false;
        })
    }

    async function executeSDQuery(txn,q){
    // execute savedata queries
      return new Promise((resolve,reject)=>{
        txn.executeSql(q,[],async function (txn2, txnres2) {  
            resolve(true);
        },function(Etxn,txnerr){console.log(txnerr);resolve(false); });
        
      }).then((val)=>{
        return val;
      }).catch((err)=>{
          console.log(err);
        return false;
      })
    }
  


    async function validate(){

        let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='CameraIROnceOnly')
        let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
        let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;

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

                
                let skulist=item.skulist || [];

                // check if child image available (in header )
                let firstSkuObj=skulist.length>0?skulist[0]:{};
                
                const cindex=SOSStockData.findIndex(i=>i.SOSHeaderValue==item.SOSHeaderValue);
                const cobj=cindex>=0?SOSStockData[cindex]:{};

                let CatIRImages=cobj['IRImages']!=null?cobj['IRImages'] : [] ;
                let TempSessionId= cobj.TempSessionId!=null?cobj.TempSessionId:'';

                if(StoreCameraAllow && CameraIROnceOnly==false && (CatIRImages.length==0 || TempSessionId=="")){
                    notify(`Please click header image for SOS`,'SHORT');
                    resolve(false);return;
                }

                if(index==(AllSOSData.length-1)){
                    
                    if(StoreCameraAllow && CameraIROnceOnly==true && (SOSIRImages.current.length==0 || GbTempSessionId.current=="")){
                        notify(`Please click header image for SOS`,'SHORT');
                        resolve(false);return;
                    }
                    else{
                        resolve(true);return;
                    }
                }
            }
        }).then((val)=>{return val})
        .catch((err)=>{console.log(err); return false});

    }

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

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

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

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

        let allSKUData=SOSStockData;
        let defData={'SOSHeaderValue':item.SOSHeaderValue,'Images':[],'SKUData':[]};
        const skud_index=allSKUData.findIndex(i=>i.SOSHeaderValue==item.SOSHeaderValue);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;
        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        // setSOSStockData(allSKUData);
        BgWindowData(allSKUData)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function openRetakeOp(cat, type='1',IRImgIndex,IRimgPath){
        let data={'cat':cat,'type':type,'IRImgIndex':IRImgIndex,'IRimgPath':IRimgPath};
        setretakeMData(data);
        setshowRetakeModal(true);
    }

    
    function closeRetakeOp(){
        setretakeMData({})
        setshowRetakeModal(false);
    }

    function setIRZoomImages(IRCamImages){
        let z_images=[];
        for(let ci in IRCamImages){
            let img=IRCamImages[ci];
            let img_obj={imgIndex:(ci+1),url: img.ImagePath, props: {}}
            
            z_images.push(img_obj);
            if(ci==IRCamImages.length-1){
                setZoomImageUrl2(z_images);
            }
        }
    }

    async function getIRZoomImages(IRCamImages){
        return new Promise((resolve,reject)=>{
            let z_images=[];
            for(let ci in IRCamImages){
                let img=IRCamImages[ci];
                let img_obj={imgIndex:(ci+1),url: img.ImagePath, props: {}}
                
                z_images.push(img_obj);
                if(ci==IRCamImages.length-1){
                    resolve(z_images)
                }
            }
        }).catch((err)=>{
            console.log(err);
            return [];
        })
    }

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

    function openImageRefView2(ImageIndex=0,catIndex,Type='2'){
        if(Type=='1'){
            let cat=AllSOSData[catIndex];
            const catDataIndex=SOSStockData.findIndex(i=>i.SOSHeaderValue==cat.SOSHeaderValue) ;
            const catData=catDataIndex>=0?SOSStockData[catDataIndex]:{};
            let zoomIRImages=catData.zoomIRImages!=null && catData.zoomIRImages!=""? catData.zoomIRImages:[];
            setZoomImageUrl2(zoomIRImages);
        }
        setrefImageIndex2(ImageIndex);
        UpdateShow_zoomImageRef2(true);
    }

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

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

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

      function _render_RetakePopup(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'If any image is blurred you can "Retake" or "Delete" the Image?'}
            showModal={showRetakeModal}
          >
            <View style={customStyle.IRretakeM_options}>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{RetakeIRPhoto()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$primary_color}/>    
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Retake</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{DeleteIRPhoto()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <FontAwesome name='trash' size={20} color={PageTheme.$red}/>     
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Delete</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{closeRetakeOp()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <Entypo name='cross' size={20} color={PageTheme.$red}/> 
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Cancel</Text>
                </View>
              </TouchableOpacity>
             
            
              
            </View>
          </CustomModal>
        )
      }

    function _render_UploadAlert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Upload IR Images! You cannot edit after images uploaded to the server!'}
            showModal={showUploadAlert}
          >
            <View style={customStyle.storelVisitM_options}>
             <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setshowUploadAlert(false)}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{UploadIRSessions()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
    }

    function _renderIRCamera(cat,CatIRImages,TempSessionId,type='1',catIndex=''){
        
        let isSaveDisabled=(isDataUploaded=='U' || isDataUploaded=='P');
        let isResumeDisabled=(TempSessionId==null || TempSessionId=='' || TempSessionId=='undefined' || isSaveDisabled==true);
                
        return (
            <View style={(type=='2'?customStyle.IRCamOnceWrap:[customStyle.openStk_prd_borderT,customStyle.pt10])}>
                <View style={customStyle.SOSheadingsCon}>
                    <Text style={customStyle.SOSheadingsText}>{'Capture SOS Header Images'}</Text>
                </View>
                <View style={[customStyle.IRCamWrapper]}>
                    <View style={customStyle.IRCamImgWrap}>
                    { (CatIRImages!=null && CatIRImages.length>0) && 
                        CatIRImages.map((IRImg,IRImgIndex)=>{
                            let IRimgPath=IRImg.ImagePath;
                            return(
                                <TouchableOpacity style={customStyle.IRCamImageView} key={IRImgIndex} onPress={()=>{openImageRefView2(IRImgIndex,catIndex,type)}}>
                                    {(IRimgPath!=null && IRimgPath!='') && <Image style={customStyle.IRCamImage} source={{uri:IRimgPath}}/>}
                                    {(IRimgPath==null || IRimgPath=='') && <View style={customStyle.IRCamImage}></View>}
                                    <TouchableOpacity style={[customStyle.IRCamImage_OpBtn,isSaveDisabled?{backgroundColor:PageTheme.$text_color_light}:{}]} disabled={isSaveDisabled} onPress={()=>{openRetakeOp(cat,type,IRImgIndex,IRimgPath)}}>
                                        <MaterialCommunityIcons name='camera-retake' size={15} color={PageTheme.$accent_color}/>                                   
                                    </TouchableOpacity>
                                </TouchableOpacity>  
                            );
                        })
                                                        
                    } 
                    </View>     
                    <View style={[customStyle.IRCamCon,(type=='2'?customStyle.IRCamConBG:{})]}>
                        <TouchableOpacity style={[customStyle.IRCamBtns,customStyle.IRCamStartSess]} disabled={isSaveDisabled} onPress={()=>{StartCameraSession(cat,type)}}>   
                            <AntDesign name='play' size={30} color={(isSaveDisabled?PageTheme.$text_color_light:PageTheme.$primary_color)}/>
                            <Text style={[customStyle.IRCamBtnsText,(isSaveDisabled?{color:PageTheme.$text_color_light}:{})]}>Start Session</Text>
                        </TouchableOpacity> 
                        <TouchableOpacity style={[customStyle.IRCamBtns,customStyle.IRCamStartSess]} disabled={isResumeDisabled} onPress={()=>{ResumeCameraSession(cat,type)}} >   
                            <AntDesign name='pausecircle' size={30} color={(isResumeDisabled?PageTheme.$text_color_light:PageTheme.$primary_color)}/>
                            <Text style={[customStyle.IRCamBtnsText,(isResumeDisabled?{color:PageTheme.$text_color_light}:{})]}>Resume Session</Text>
                        </TouchableOpacity>   
                    </View>      
                </View>
            </View>
        )
    }


    function _renderIRCameraOnce(){
        let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='CameraIROnceOnly')
        let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
        let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;

        if(CameraIROnceOnly){
            return _renderIRCamera({},SOSIRImages.current,GbTempSessionId.current,'2');
        }
        else{
            return (<View></View>);
        }
        
    }
    

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

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

    function _renderSOSList(){

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

        let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='CameraIROnceOnly')
        let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
        let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;

        let decimalAllow = sosDecimalValueEnable ? 'decimal': 'numeric'

        let isSaveDisabled=(isDataUploaded=='U' || isDataUploaded=='P');

        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={(Platform.OS=='ios'?10:-100)} >  
            <View style={customStyle.keyba_inner_view}>
                 
            <FlatList 
            data={AllSOSData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.Win_scroll} 
            style={customStyle.Win_scrollO}
            initialNumToRender={5}
            ListHeaderComponent={()=>{
               return _renderIRCameraOnce()
            }}
            listKey={(item, index) => `window_${index.toString()}`}
            renderItem={({item,index})=>{
                const cat=item;
                const catIndex=index;

                let SOSHeaderImage=true;//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: '';
                

                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'] || [];
                // check if child image available in header 
                let firstSkuObj=cat.skulist.length>0?cat.skulist[0]:{};
                let isChildImgEnabled=firstSkuObj.SOSChildImage==1 || firstSkuObj.SOSChildImage=='true'?1: 0;

                // let show_HdrForm=(CameraIROnceOnly==false && (SOSHeaderImage==true || isChildImgEnabled));
                
                let CatIRImages=cobj['IRImages']!=null?cobj['IRImages'] : [] ;
                let TempSessionId= cobj.TempSessionId!=null?cobj.TempSessionId:'';
                
                //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;

                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}>
                                <Text style={[customStyle.opening_Stock_catText]}>{item.HeaderName }</Text>
                                {SOSTarget!=null && SOSTarget!='' && <Text style={[customStyle.opening_Stock_catText2]}>{`SOS Target: ${SOSTarget}%`}</Text>}
                            </LinearGradient>
                        </View>
                        <View style={customStyle.SOSForm}>
                            <View style={customStyle.SOSHdrForm}>
                                {CameraIROnceOnly==false && 
                                    _renderIRCamera(cat,CatIRImages,TempSessionId,'1',catIndex)
                                }
                            </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 thisCatSkuData_i=this_SKUData.findIndex(i=>i.SOSChildValue==skus.SOSChildValue);
                                        // let thisCatSkuData=thisCatSkuData_i>=0?(this_SKUData[thisCatSkuData_i] || {}):{};
                                        
                                        return(
                                            <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                                <Text style={[customStyle.openStk_prd_name]}>{skus.ChildName}</Text>
                                            </View>
                                        )
                                    }}/>
                                </View>
                            </View>
                        </View>
                        
                    </View>
                );
            }}
            />
            </View> 
            </KeyboardAvoidingView>
        )
    }
  
    function _renderBtns(){
        
        let isUploadDisabled=isDataUploaded=='U';
        let isSaveDisabled=(isDataUploaded=='U' || isDataUploaded=='P');

        let colors1=(isUploadDisabled?[PageTheme.$tertiary_color,PageTheme.$tertiary_color]:[PageTheme.$secondary_color_light,PageTheme.$gradient2, PageTheme.$primary_color]);
        let colors2=(isSaveDisabled?[PageTheme.$tertiary_color,PageTheme.$tertiary_color]:[PageTheme.$secondary_color_light,PageTheme.$gradient2, PageTheme.$primary_color]);
        
        return (
            <View style={customStyle.opening_Stock_btnWrap}>
                <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}} /> 
            </View> 
               
        )
    }


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true}  title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_OpenCaptureImage_Modal()}
        {_render_Alert()}
        {_render_RetakePopup()}
        {_render_UploadAlert()}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName}  gridEnable={GridValue} onImageCaptured={(imgData)=>{UpdateShowCameraRef(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{UpdateShowCameraRef(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()
            }

            {_renderBtns()}

         </View>      
       </LinearGradient> 
       {/* {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} 
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }   */}

        {show_zoomImage2 && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView2} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl2} index={refImageIndex2} 
            renderHeader={(currentIndex)=>{return  _renderHeader(currentIndex,zoomImageUrl2)}} renderIndicator={()=>null}
            />
        </View>        
        }
      </Container>   
    ); 
}
  

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