
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} 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} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, 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';

function ShareOfShelfOneApp(props) { 
    const route = useRoute();
  
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [rerenderdata3, setrerenderdata3]= useState(0);
    const [rerenderdata4, setrerenderdata4]= useState(0);
    
    
    const [SOSStockData, setSOSStockData] = useState([]);
    const [AllSOSData, setAllSOSData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [KPIFields, setKPIFields] = useState([]);

    const 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;
        setStoreCameraAllow(cameraAllow);
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

        props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            props.navigation.removeListener('beforeRemove', onBeforeRemove);
        };
    }, []);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            console.log('hasUnsavedChanges:',hasUnsavedChanges);
            if (hasUnsavedChanges==true) {
                console.log('hasUnsavedChanges is true');
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: () => {setHasUnsavedChanges(false);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);
          await db.transaction(async function (txn) {    
            // let join2=' INNER JOIN Mapping_ProductAssortment mp on p.ProductId=mp.ProductId ';
            let join1=` INNER JOIN Mapping_StoreShareOfShelf m on p.SOSDefinitionId=m.SOSDefinitionId `;
            let selectlist1=` DISTINCT 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}' order by p.HeaderName `;
   

            let selectlist2=` DISTINCT p.SOS_HEADER_ID as SOSHeaderId,m.SOSHeaderTable,m.SOSHeaderField,p.SOS_HDR_VALUE as SOSHeaderValue,p.HEADER_NAME as HeaderName,m.SOSHeaderFacing,m.SOSHeaderFacingLable,m.SOSHeaderImage,m.SOSHeaderImageCount,m.SOSHeaderImageGrid,p.SOS_HDR_FACING as SOSHdrFacing `;
            // let join3=` INNER JOIN Mapping_StoreShareOfShelf mp on m.SOSDefinitionId=mp.SOSDefinitionId `;
            let join4=` INNER JOIN Master_ShareOfShelfDefinition m on p.SOS_HDR_VALUE=m.SOSHeaderValue `;
            let q2=` SELECT ${selectlist2} FROM ${AppTables.SOS_HDR_DATA} p ${join4} WHERE p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' order by p.HEADER_NAME  `;
            
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let arr=[],allCats=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        let AllCData=await getChilds(storeData1,data);
                        let allChilds=AllCData['allChilds'] || [];
                        let childData=AllCData['childData'] || [];
                        data['skulist']=allChilds;
                        arr.push(data);
                        let HdrImages=await getHdrImages(storeData1,data);
                        let defData={'SOSHeaderValue':data.SOSHeaderValue,'SOSHdrFacing':data.SOSHdrFacing,'Images':HdrImages,'SKUData':childData};
                        allCats.push(defData);
                        if(i==txnres.rows.length-1){
                            setAllSOSData(arr);
                            setSOSStockData(allCats);
                            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 AllCData=await getChilds(storeData1,data);
                                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':''};
                                    HdrImages.push(obj);
                                }
                                let defData={'SOSHeaderValue':data.SOSHeaderValue,'SOSHdrFacing':'','Images':HdrImages,'SKUData':childData};
                                allCats.push(defData);
                                if(i==txnres2.rows.length-1){
                                    setAllSOSData(arr);
                                    setSOSStockData(allCats);
                                    setProcessing(false);
                                }
                            }
                        }else{
                            setProcessing(false);
                            notify('No data found','SHORT')
                        }
                    },function (txn2, txnerr) { console.log(txnerr); },);
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
            // setProcessing(false);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getHdrImages(storeData1,cat1){
        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://'+common_ImagePath+Image1:'';
                            let obj={'Image1Name':data.Image1,'Image1':imagePath};
                            allImages.push(obj);
                            if(i==txnres.rows.length-1){
                                resolve(allImages);
                            }
                        }
                    }
                    else{
                        resolve(allImages);
                    }
                },function (txn2, txnerr) { console.log(txnerr); resolve(allImages); },);
            });        
        }).catch((err)=>{
            return allImages;
        })
    }

    async function getChilds(storeData1,cat1){
        let defData={allChilds:[],childData:[]};
        let {StoreId} =storeData1;
        let {SOSHeaderValue} =cat1;
        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}'  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);
                            arr.push(data);
                            let allChildImages=await getChildImages(storeData1,cat1,data);
                            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);
                                    arr.push(data);
                                    let allChildImages=[];
                                    for(var s=0;s<data.SOSChildImageCount;s++){
                                        let obj={'Image1Name':'','Image1':''};
                                        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 (txn2, txnerr) { console.log(txnerr); resolve(defData); },);
                    }
                },function (txn2, txnerr) { console.log(txnerr); resolve(defData); },);
            });        
        }).catch((err)=>{
            return defData;
        });
    }

    async function getChildImages(storeData1,cat1,subcat1){
        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://'+common_ImagePath+Image1:'';
                            let obj={'Image1Name':Image1,'Image1':imagePath};
                            allImages.push(obj);
                            if(i==txnres.rows.length-1){
                                resolve(allImages);
                            }
                        }
                    }
                    else{
                        resolve(allImages);
                    }
                },function (txn2, 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.height;
           
            
            let picture_clicked_time=new Date();
            picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
            
            
            const mark_text1=picture_clicked_time;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Share Of Shelf'+' | Date:'+picture_clicked_time;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let picture_clickedd=new Date();
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename='';
                            if(type=='2'){
                                filename=storeData.StoreId+'_'+cat.SOSHeaderValue+'_'+skuItem.SOSChildValue+'_'+splitItemIndex+'_'+(props.UserId || '')+'_SOSImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            }
                            else{
                                filename=storeData.StoreId+'_'+cat.SOSHeaderValue+'_'+splitItemIndex+'_'+(props.UserId || '')+'_SOSImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            }

                            console.log('filename:',filename);
                            
                            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;
                            }
                            
                            
                            
                            // renamefile
                            let imagePath=`${common_ImagePath}${filename}`;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                               console.log('image marker:',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);
                                    setHasUnsavedChanges(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);
                                    setHasUnsavedChanges(true);
                                    setrerenderdata(!rerenderdata);
                                }
                                
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(cat,splitItem,splitItemIndex,type='1',sku){  
        setGetImageProps({'cat':cat,'splitItem':splitItem,'splitItemIndex':splitItemIndex,'type':type,'sku':sku}); 
        setShowCamera(true);
    }

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

    async function focusToNext(cat,index,sku,sku_index,inputType='1'){
        console.log('focusToNext',index);
        let data=brandData;
        
        if(inputType=='1'){
            let refIn2=inputRefs.current['input2_'+cat.SOSHeaderValue+'_'+sku.SubSOSHeaderValue];
            refIn2.focus();
        }
        else{
            let ccat_index=index;
            let skulist=cat.skulist || [];
            if(sku_index==skulist.length-1){ // if last subcategory element
                //then move to next category
                console.log('move to next cat',ccat_index,data.length)
                if(ccat_index==data.length-1){
                    return;
                }
                else{
                    ccat_index+=1;
                    console.log('move to next cat n:',ccat_index)
                    let cat1=data[ccat_index];
                    let skulist1=cat1.skulist || [];
                    if(skulist1.length>0){
                        let sku1=skulist1[0];
                        let refIn1=inputRefs.current['input1_'+cat1.SOSHeaderValue+'_'+sku1.SubSOSHeaderValue];
                        console.log('move to next cat refIn1:','input1_'+cat1.SOSHeaderValue+'_'+sku1.SubSOSHeaderValue)
                        refIn1.focus();
                    }
                }
            }
            else{
                // move to next subcategory
                let sku1=skulist[sku_index+1];
                let refIn1=inputRefs.current['input1_'+cat.SOSHeaderValue+'_'+sku1.SubSOSHeaderValue];
                refIn1.focus();
            }
            
            
            
        }

    }

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

    async function saveData(){
        setHasUnsavedChanges(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}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('stock facing hdr data deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);

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

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

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

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

            await db.transaction(async function (txn) {
              var values='',stock_values='',images_values='';
              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=cobj['SOSHdrFacing']!=null?cobj['SOSHdrFacing']:'';
                let this_SKUData=cobj['SKUData'] || [];

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

                for(var j=0;j<skulist.length;j++){
                    let skus=skulist[j];
                    let sku_index=j;
                    let {SOSDefinitionId,SOSChildTable,SOSChildField,SOSChildValue,ChildName,SOSChildTotalFacing,SOSChildSelfFacing,SOSChildTotalFacingLable,SOSChildSelfFacingLable,SOSChildImage,SOSChildImageCount,SOSChildImageGrid}=skus;
                    stock_values+=stock_values!=''?' , ':'';

                    let thisCatSkuData_i=this_SKUData.findIndex(i=>i.SOSChildValue==skus.SOSChildValue);
                    let thisCatSkuData=thisCatSkuData_i>=0?(this_SKUData[thisCatSkuData_i] || {}):{};
                    let TotalFacing=thisCatSkuData.TotalFacing!=null?thisCatSkuData.TotalFacing:'';
                    let SelfFacing=thisCatSkuData.SelfFacing!=null?thisCatSkuData.SelfFacing:'';
                    const ChildImages=thisCatSkuData['ChildImages'] || [] ;
                                        
                    stock_values+=` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSDefinitionId}','${SOSHeaderValue}','${SOSChildTable}','${SOSChildField}','${SOSChildValue}','${ChildName}','${TotalFacing}','${SelfFacing}','${d2}') `;
                    
                    let SOSChildImage1=SOSChildImage==1 || SOSChildImage=='true'?1: 0;
                    if(SOSChildImage1==true){
                        for(var l=0;l<ChildImages.length;l++){
                            let imgObj=ChildImages[l];
                            let {Image1Name,Image1}=imgObj;
                            images_values+=images_values!=''?' , ':'';
                            images_values+=` ('${SOSHeaderId}','${StoreId}','${d2}','${SOSHeaderValue}','${SOSChildValue}','${(Image1Name || '')}','Child','${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} `;
              
              
              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');
                    await txn.executeSql(add_images,[],async function (txn2, txnres) { 
                        console.log('stock facing images added');
                        notify('Share Of Shelf data updated successfully');
                        setProcessing(false);
                        props.navigation.goBack();
                    },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add Share Of Shelf data') },);
                },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add Share Of Shelf data') },);
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add Share Of Shelf data') },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


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

                let SOSHeaderImage=item.SOSHeaderImage==1 || item.SOSHeaderImage=='true'?1: 0;
                let 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'] || [];
                let TotalSelfFacingsEntered=0;
                if(SOSHeaderFacing==true && (SOSHdrFacing==null || SOSHdrFacing=='')){
                    notify(`Please enter Header Facing for ${cat.HeaderName}`,'SHORT');
                    resolve(false);return;
                }
                else{
                    if(StoreCameraAllow && SOSHeaderImage==true && HeaderImages.length>0)
                    {
                        for(const splitItemIndex in HeaderImages){
                            const splitItem=HeaderImages[splitItemIndex];
                            let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                            if(Image1Name==''){
                                notify(`Please click all header images for ${cat.HeaderName}`,'SHORT');
                                resolve(false);return;
                            }
                        }
                    }
                    let skulist=cat.skulist || [];
                    for(const sku_index in skulist){
                        const skus=skulist[sku_index];

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


                        let thisCatSkuData_i=this_SKUData.findIndex(i=>i.SOSChildValue==skus.SOSChildValue);
                        let thisCatSkuData=thisCatSkuData_i>=0?(this_SKUData[thisCatSkuData_i] || {}):{};
                        let TotalFacing=thisCatSkuData.TotalFacing!=null?thisCatSkuData.TotalFacing:'';
                        let SelfFacing=thisCatSkuData.SelfFacing!=null?thisCatSkuData.SelfFacing:'';
                        const ChildImages=thisCatSkuData['ChildImages'] || [] ;
                        if(SOSChildTotalFacing==true && (TotalFacing==null || TotalFacing=='')){
                            notify(`Please enter ${SOSChildTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,'SHORT');
                            resolve(false);return;
                        }
                        else if(SOSChildSelfFacing==true && (SelfFacing==null || SelfFacing=='')){
                            notify(`Please enter ${SOSChildSelfFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,'SHORT');
                            resolve(false);return;
                        }
                        else if(SOSChildSelfFacing==true &&  SOSChildTotalFacing==true && (parseInt(SelfFacing)> parseInt(TotalFacing))){
                            notify(`${SOSChildSelfFacingLable} should be less than or equals to ${SOSChildTotalFacingLable} for ${skus.ChildName} in ${cat.HeaderName}`,'SHORT');
                            resolve(false);return;
                        }
                        else{
                            TotalSelfFacingsEntered+=parseInt(SelfFacing);
                            if(sku_index==this_SKUData.length-1){
                                if(SOSChildSelfFacing==true &&  SOSHeaderFacing==true && (TotalSelfFacingsEntered> parseInt(SOSHdrFacing))){
                                    notify(`Sum of all ${SOSChildSelfFacingLable}  should be less than or equals to ${SOSHeaderFacingLable} for ${cat.HeaderName}`,'SHORT');
                                    resolve(false);return;
                                }
                            }

                            if(StoreCameraAllow && SOSChildImage==true && ChildImages.length>0)
                            {
                                for(const splitItemIndex in ChildImages){
                                    const splitItem=ChildImages[splitItemIndex];
                                    let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                                    if(Image1Name==''){
                                        notify(`Please click all child images for ${skus.ChildName} in ${cat.HeaderName}`,'SHORT');
                                        resolve(false);return;
                                    }
                                }
                            }
                        }
                    }
                }

                if(index==(AllSOSData.length-1)){
                    resolve(true);return;
                }
                
            }
            
        }).then((val)=>{return val})
        .catch((err)=>{console.log(err); return false});

    }

    function onStockValChange(item,skuItem,val,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify('Please enter whole numbers only','SHORT');
                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);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onHdrStockValChange(item,val,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify('Please enter whole numbers only','SHORT');
                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);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

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


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

                let SOSHeaderImage=item.SOSHeaderImage==1 || item.SOSHeaderImage=='true'?1: 0;
                let 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'] || [];

                
                
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={[customStyle.opening_Stock_catText]}>{item.HeaderName}</Text>
                            </LinearGradient>
                        </View>
                        <View style={customStyle.SOSForm}>
                            <View style={customStyle.SOSHdrForm}>
                                {SOSHeaderFacing==true && 
                                    <View style={customStyle.SOSform_row}>
                                        <View style={[customStyle.SOSform_colflex]} >
                                            <View style={[customStyle.SOSform_col1,customStyle.SOSform_colsCommon]}>
                                                <Text style={customStyle.SOSform_collabel}>{SOSHeaderFacingLable}</Text>
                                            </View>
                                            
                                            <View style={[customStyle.SOSform_col2,customStyle.SOSform_colsCommon]}>
                                                <TextInput 
                                                    style={[customStyle.SOSInputStyle]}
                                                    placeholder=""            
                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                    value={(SOSHdrFacing+'')}
                                                    keyboardType='numeric'
                                                    onChangeText={(val)=>{ onHdrStockValChange(cat,val,'SOSHdrFacing','numeric')}}
                                                    autoComplete='off'
                                                />
                                            </View>
                                        </View>
                                    </View>
                                }
                                {(SOSHeaderImage==true && HeaderImages.length>0) && 
                                <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <View style={customStyle.SOSheadingsCon}>
                                        <Text style={customStyle.SOSheadingsText}>{'Capture SOS Header Images'}</Text>
                                    </View>
                                    <View style={customStyle.SOShdrImagesWrap}>
                                        <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]} >
                                        {(rerenderdata2==rerenderdata2) && 
                                            HeaderImages.map((item,index)=>{
                                                let splitItem=item;
                                                let splitItemIndex=index;
                                                let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                                                let Image1=splitItem['Image1']!=null && splitItem['Image1']!=''?splitItem['Image1']:'';
                                                
                                                return(
                                                    <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]} key={'SplitItem+'+splitItemIndex}>
                                                        { (Image1=='' || Image1==null) && 
                                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin,customStyle.SOSCameraBtn]} onPress={()=>{openCamera(cat,splitItem,splitItemIndex,'1')}}>
                                                                <SvgXml width={40} height={40} xml={cameraImg}/>                                     
                                                            </TouchableOpacity>
                                                        }
                                                        { (Image1!='' && Image1!=null) && 
                                                            <View style={customStyle.osCatImageView}>
                                                                <Image style={customStyle.osCatImage} source={{uri:Image1}}/>
                                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(cat,splitItem,splitItemIndex,'1')}}>
                                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                                </TouchableOpacity>
                                                            </View>                                    
                                                        }       
                                                        {/* <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text> */}
                                                    </View>     
                                                );
                                            })
                                        }
                                        </View>
                                    </View>
                                </View>
                                }
                            </View>
                            <View style={customStyle.SOSListHdr}>
                                <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$primary_color,PageTheme.$fourth_color,PageTheme.$primary_color,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={[customStyle.SOSheadingsCon,customStyle.SOSheadingsCon3]}>
                                    <Text style={[customStyle.SOSheadingsText,customStyle.SOSheadingsText2]}>{'Product Facings'}</Text>
                                </LinearGradient>
                            </View>
                            <View style={customStyle.SOSChildlist}>
                                <View style={customStyle.opening_Stock_prds}>
                                    <FlatList 
                                    data={cat.skulist}
                                    extraData={rerenderdata3}
                                    renderItem={({item,index})=>{
                                        const skus=item;
                                        const sku_index=index;

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

                                        let thisCatSkuData_i=this_SKUData.findIndex(i=>i.SOSChildValue==skus.SOSChildValue);
                                        let thisCatSkuData=thisCatSkuData_i>=0?(this_SKUData[thisCatSkuData_i] || {}):{};
                                        let TotalFacing=thisCatSkuData.TotalFacing!=null?thisCatSkuData.TotalFacing:'';
                                        let SelfFacing=thisCatSkuData.SelfFacing!=null?thisCatSkuData.SelfFacing:'';
                                        const ChildImages=thisCatSkuData['ChildImages'] || [] ;
                                        
                                        return(
                                            <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                                <Text style={[customStyle.openStk_prd_nameB]}>{skus.ChildName}</Text>
                                                {(SOSChildImage==true && ChildImages.length>0) && 
                                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                                        
                                                        <View style={[customStyle.SOSheadingsCon,customStyle.SOSheadingsCon2]}>
                                                            <Text style={[customStyle.SOSheadingsText,customStyle.SOSheadingsText2]}>{'Capture SOS Child Images'}</Text>
                                                        </View>
                                                        <View style={customStyle.SOSChildImagesWrap}>
                                                        <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]} >
                                                        {   rerenderdata4==rerenderdata4 && 
                                                            ChildImages.map((item,index)=>{
                                                                let splitChildItem=item;
                                                                let splitChildItemIndex=index;
                                                                let Image1Name=splitChildItem['Image1Name']!=null && splitChildItem['Image1Name']!=''?splitChildItem['Image1Name']:'';
                                                                let Image1=splitChildItem['Image1']!=null && splitChildItem['Image1']!=''?splitChildItem['Image1']:'';
                                                                
                                                                return(
                                                                    <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                                                        { (Image1=='' || Image1==null) && 
                                                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(cat,splitChildItem,splitChildItemIndex,'2',skus)}}>
                                                                                <SvgXml width={80} height={80} xml={cameraImg2}/>                                     
                                                                            </TouchableOpacity>
                                                                        }
                                                                        { (Image1!='' && Image1!=null) && 
                                                                            <View style={customStyle.osCatImageView}>
                                                                                <Image style={customStyle.osCatImage} source={{uri:Image1}}/>
                                                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(cat,splitChildItem,splitChildItemIndex,'2',skus)}}>
                                                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                                                </TouchableOpacity>
                                                                            </View>                                    
                                                                        }       
                                                                        {/* <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text> */}
                                                                    </View>  
                                                                );
                                                            })
                                                        }
                                                        </View>
                                                        </View>
                                                    </View>
                                                }
                                                <View style={customStyle.SOSlist_form}>
                                                    {SOSChildTotalFacing==true && 
                                                    <View style={customStyle.SOSform_row}>
                                                        <View style={[customStyle.SOSform_colflex]} >
                                                            <View style={[customStyle.SOSform_col1,customStyle.SOSform_colsCommon]}>
                                                                <Text style={customStyle.SOSform_collabel}>{SOSChildTotalFacingLable}</Text>
                                                            </View>
                                                            
                                                            <View style={[customStyle.SOSform_col2,customStyle.SOSform_colsCommon]}>
                                                                <TextInput 
                                                                    style={[customStyle.SOSInputStyle]}
                                                                    placeholder=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(TotalFacing+'')}
                                                                    keyboardType='numeric'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'TotalFacing','numeric')}}
                                                                    autoComplete='off'
                                                                />
                                                            </View>
                                                        </View>
                                                    </View>}
                                                    {SOSChildSelfFacing==true && 
                                                    <View style={customStyle.SOSform_row}>
                                                        <View style={[customStyle.SOSform_colflex]} >
                                                            <View style={[customStyle.SOSform_col1,customStyle.SOSform_colsCommon]}>
                                                                <Text style={customStyle.SOSform_collabel}>{SOSChildSelfFacingLable}</Text>
                                                            </View>
                                                            <View style={[customStyle.SOSform_col2,customStyle.SOSform_colsCommon]}>
                                                                <TextInput 
                                                                    style={[customStyle.SOSInputStyle]}
                                                                    placeholder=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(SelfFacing+'')}
                                                                    keyboardType='numeric'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'SelfFacing','numeric')}}
                                                                    autoComplete='off'
                                                                />
                                                            </View>
                                                        </View>
                                                    </View>}
                                                
                                                </View>
                                            </View>
                                        )
                                    }}/>
                                </View>
                            </View>
                        </View>
                        
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_render_Alert()}
        <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 && 
           _renderSOSList()
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  

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