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, 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 {AntDesign, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CameraImg from '../assets/performics/camera_front_image.svg'
import CustomModal from '../components/CustomModal';
import { Q_getdefaltShareofSelf } from '../constants/ConstantQueries';
import CustomCamera from '../components/Camera';
import Orientation from 'react-native-orientation-locker';

function ShareOfShelf(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 [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = 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){
        Orientation.unlockAllOrientations()
        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 allCats=[];

          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);
          await db.transaction(async function (txn) {        
            let q=Q_getdefaltShareofSelf(storeData1);
            let select=` CATEGORY_ID as CategoryId,CATEGORY as CategoryName,IMAGE `;
            let q2=` SELECT ${select} FROM ${AppTables.SHARE_OF_SHELF_IMAGE} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        arr.push(data);
                        let imagePath='file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE;
                        
                        let defData={'CategoryId':data.CategoryId,'ImageName':data.IMAGE,'ImagePath':imagePath};
                        allCats.push(defData);
                        if(i==txnres.rows.length-1){
                            setCatImages(allCats);
                            getSKU(arr,storeData1,menu1);
                        }
                    }
                }
                else{
                    await txn.executeSql(q,[],async function (txn2, txnres2) { 
                        console.log('soscats',txnres2.rows.length);
                        if(txnres2.rows.length>0){
                            let arr=[];
                            for(var i=0;i<txnres2.rows.length;i++){
                                let data =txnres2.rows.item(i);
                                arr.push(data);
                                if(i==txnres2.rows.length-1){
                                    getSKU(arr,storeData1,menu1);
                                }                                
                            }
                            
                        }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 getSKU(brands=[],storeData1={},menu1){
        
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;     
        
          await db.transaction(async function (txn) { 
            var allSKUData=[];
            await Promise.all(
                brands.map(async (item,index) => {
                    let seletlist=`SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,SUB_CATEGORY_STOCK,STOCK,IMAGE1`;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.SHARE_OF_SHELF_FACING_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${item.CategoryId}' `;
                   
                    let join=`  INNER JOIN Mapping_ShareOfShelf m on p.SubCategoryId=m.SubCategoryId`;
                    let sku_q2=`SELECT DISTINCT p.SubCategoryId,p.SubCategoryName from Product_Master p  ${join} where m.StateId='${StateId}' and m.ChainId='${ChainId}' and m.StoreTypeId='${StoreTypeId}' and (p.CategoryId='${item.CategoryId}' or p.CategoryId= ${item.CategoryId})  order by p.SubCategorySequence`;
                    
                    return await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                        if(txnres.rows.length>0){
                            let arr=[];
                            for(var i=0;i<txnres.rows.length;i++){
                                let data =txnres.rows.item(i);
                                inputRefs.current['input1_'+item.CategoryId+'_'+data.SubCategoryId]='';
                                inputRefs.current['input2_'+item.CategoryId+'_'+data.SubCategoryId]='';
                                arr.push(data);
                                let imgpath=data.IMAGE1!=null?'file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE1:'';
                                let defData={'CategoryId':item.CategoryId,'SubCategoryId':data.SubCategoryId,'subcat_facing':data.SUB_CATEGORY_STOCK,'brand_facing':data.STOCK,'ImageName':(data.IMAGE1!=null?data.IMAGE1:''),'ImagePath':imgpath};
                                
                                allSKUData.push(defData);

                                if(i==txnres.rows.length-1){
                                    item['skulist']=arr;
                                    brands[index]=item;
                                    if(index==brands.length-1){
                                        console.log('allSKUData:',allSKUData);
                                        setSKUStockData(allSKUData);
                                        setBrandData(brands);
                                        // setrerenderdata(!rerenderdata);
                                        setTimeout(()=>{setrerenderdata2(!rerenderdata2);},3000);
                                        setProcessing(false);
                                    }
                                    return item;
                                }
                            }
                        }
                        else{
                            return await txn.executeSql(sku_q2,[],async function (txn2, txnres2) { 
                                
                                if(txnres2.rows.length>0){
                                    let arr=[];
                                    for(var i=0;i<txnres2.rows.length;i++){
                                        let data =txnres2.rows.item(i);
                                        inputRefs.current['input1_'+item.CategoryId+'_'+data.SubCategoryId]='';
                                        inputRefs.current['input2_'+item.CategoryId+'_'+data.SubCategoryId]='';
                                        arr.push(data);
                                        if(i==(txnres2.rows.length-1)){                                        
                                            item['skulist']=arr;
                                            brands[index]=item;
                                            if(index==brands.length-1){
                                              
                                                setBrandData(brands);
                                                setProcessing(false);
                                            }
                                            return item;
                                        }               
                                    }
                                }
                                else{
                                    return item;
                                }
                                
                            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        }
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); return item; },);
                  return item;
                })
            ) .then((res)=>{
                
            });          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getImage(imgdata){
        let cat=getImageProps.option!=null?getImageProps.option:{};
        let type=getImageProps.type!=null?getImageProps.type:'1';
        let skuItem=getImageProps.skuItem!=null?getImageProps.skuItem:{};
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.height;
            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('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: SOS'+' | 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_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_SOS-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            

                            let allIMgs=catImages;
                            let defData={'CategoryId':cat.CategoryId};
                            let cindex=-1,imgData=defData;

                            
                            let allSKUData=SKUStockData;
                            let defData1={'CategoryId':cat.CategoryId,'SubCategoryId':skuItem.SubCategoryId};
                            const skud_index=allSKUData.findIndex(i=>i.CategoryId==cat.CategoryId && i.SubCategoryId==skuItem.SubCategoryId);
                            const skud=skud_index>=0?(allSKUData[skud_index] || defData1) : defData1;
                            

                            if(type=='2'){
                                skud['ImageName']=filename;
                            }
                            else{
                                cindex=allIMgs.findIndex(i=>i.CategoryId==cat.CategoryId);
                                imgData=cindex>=0?(allIMgs[cindex] || defData):defData;
                                imgData.ImageName=filename;
                            }
                            
                            
                            
                            // renamefile
                            let imagePath=ImageFolderPath+currentMenu.ScreenName+"/"+filename;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                                
                                if(type=='2'){
                                    skud['ImagePath']=uri;
                                    skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
                                    console.log('skud:',skud);
                                    console.log('allSKUData:',allSKUData);
                                    setSKUStockData(allSKUData);
                                    setHasUnsavedChanges(true);
                                    setrerenderdata(!rerenderdata);
                                }
                                else{
                                    imgData.ImagePath=uri; 
                                    cindex>=0?allIMgs[cindex]=imgData:allIMgs.push(imgData);
                                    setCatImages(allIMgs);
                                    setHasUnsavedChanges(true);
                                    setrerenderdata(!rerenderdata);
                                }
                                
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify('Please capture a image');
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify('Please capture a image');
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(type,option,skuItem){  
        setGetImageProps({'type':type,'option':option,'skuItem':skuItem}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    async function onFocusChange(cat,sku,inputType='1'){
        let d={'catId':cat.CategoryId,'subcatId':sku.SubCategoryId,'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.CategoryId+'_'+sku.SubCategoryId];
            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.CategoryId+'_'+sku1.SubCategoryId];
                        console.log('move to next cat refIn1:','input1_'+cat1.CategoryId+'_'+sku1.SubCategoryId)
                        refIn1.focus();
                    }
                }
            }
            else{
                // move to next subcategory
                let sku1=skulist[sku_index+1];
                let refIn1=inputRefs.current['input1_'+cat.CategoryId+'_'+sku1.SubCategoryId];
                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.SHARE_OF_SHELF_IMAGE} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q2=`DELETE FROM ${AppTables.SHARE_OF_SHELF_FACING_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('stock facing data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

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

              let seq_q=` select seq from sqlite_sequence where name="${AppTables.SHARE_OF_SHELF_IMAGE}" `;
              await txn.executeSql(seq_q,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let data=txnres.rows.item(0);
                    let seq=data.seq;
                    insertData(seq);
                }
                else{
                    insertData(0);
                }
              },function (txnE,txnerr) { console.log(txnerr); insertData(0); },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function insertData(seq=0){
        try {   
            console.log(seq);
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;

            await db.transaction(async function (txn) {
              var values='',stock_values='';
              for(var i=0;i<brandData.length;i++){
                seq++;
                let catIndex=i;
                let item=brandData[catIndex];
                let cimage=catImages.find(ci=>ci.CategoryId==item.CategoryId) || {};
                values+=values!=''?' , ':'';
                values+=` ('${StoreId}','${d2}','${item.CategoryId}','${item.CategoryName}','${cimage.ImageName || ''}','${d2}') `;
                
                let skulist=item['skulist'] || [];
                for(var j=0;j<skulist.length;j++){
                    let skuItem=skulist[j];
                    let {BrandId, BrandName,MSL,SubCategoryId,SubCategoryName}=skuItem;
                    stock_values+=stock_values!=''?' , ':'';
                    let allSKUData=SKUStockData;
                    const skud_index=allSKUData.findIndex(ci=>ci.CategoryId==item.CategoryId && ci.SubCategoryId==SubCategoryId);
                    const skud=skud_index>=0?(allSKUData[skud_index] || {}) : {};
                    stock_values+=` ('${seq}','${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${SubCategoryName}','${SubCategoryId}','${skud['subcat_facing']}','${(skud['brand_facing'])}','${(skud['ImageName']!=null?skud['ImageName']:'')}','${d2}') `;
                }
              }

              let add_StockHdr=`INSERT INTO ${AppTables.SHARE_OF_SHELF_IMAGE} (STORE_ID,VISIT_DATE,CATEGORY_ID,CATEGORY,IMAGE,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.SHARE_OF_SHELF_FACING_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,SUB_CATEGORY_STOCK,STOCK,IMAGE1,ADDED_DATE) VALUES ${stock_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 added');
                    notify('Stock facing updated successfully');
                    setProcessing(false);
                    props.navigation.goBack();
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock facing') },);
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock facing') },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


    async function validate(){
        let isValid=true;
        var i=0,j=0;
        let HdrImgAllowIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HeaderImageAllow');
        let HdrImgAllowObj=HdrImgAllowIndex>=0?KPIFields[HdrImgAllowIndex]:{};
        let isHdrImgAllow=HdrImgAllowIndex>=0?HdrImgAllowObj['KPIFieldEnable']:true;

        let ChildImgAllowIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ChildImageAllow');
        let ChildImageAllowObj=ChildImgAllowIndex>=0?KPIFields[ChildImgAllowIndex]:{};
        let isChildImageAllow=ChildImgAllowIndex>=0?ChildImageAllowObj['KPIFieldEnable']:false;
        await Promise.all(
            brandData.map(async (item,index) => {

                
            if(isValid){
                let catId=item.CategoryId;
                let cimgData=catImages.find(ci=>ci.CategoryId==catId) || {};
                if(StoreCameraAllow && isHdrImgAllow==true && (cimgData.ImagePath== null || cimgData.ImagePath=='')){
                    notify('Please click image for '+item.CategoryName,'SHORT');
                    isValid=false;
                }
                else{
                    let skulist=item.skulist || [];
                    if(skulist.length>0){
                        await Promise.all(
                            skulist.map(async (skuItem,skuIndex) => {
                                if(isValid){
                                    let skuData=SKUStockData.find(ci=>ci.CategoryId==item.CategoryId && ci.SubCategoryId==skuItem.SubCategoryId ) || {};
                                    
                                    
                                    if(StoreCameraAllow && isChildImageAllow==true && ( skuData.ImagePath== null || skuData.ImagePath=='')){
                                        notify('Please click image for '+skuItem.SubCategoryName,'SHORT');
                                        isValid=false;
                                    }
                                    else if(skuData.subcat_facing!==0 && (skuData.subcat_facing==null || skuData.subcat_facing=='')){
                                        notify('Please enter sub category facing for '+skuItem.SubCategoryName,'SHORT');
                                        isValid=false;
                                    }else if(skuData.subcat_facing!==0 && (skuData.subcat_facing!=null && skuData.subcat_facing!='' && skuData.subcat_facing.includes('.'))){
                                        notify('Please enter sub category facing in whole number for '+skuItem.SubCategoryName,'SHORT');
                                        isValid=false;
                                    }else if(skuData.brand_facing!==0 && (skuData.brand_facing==null || skuData.brand_facing=='')){
                                        notify('Please enter brand facing for '+skuItem.SubCategoryName,'SHORT');
                                        isValid=false;
                                    }else if(skuData.brand_facing!==0 && (skuData.brand_facing!=null && skuData.brand_facing!='' && skuData.brand_facing.includes('.'))){
                                        notify('Please enter brand facing in whole number for '+skuItem.SubCategoryName,'SHORT');
                                        isValid=false;
                                    }else if(parseInt(skuData.brand_facing)>parseInt(skuData.subcat_facing)){
                                        notify('Brand facing value should be less than or equal to sub category facing value for '+skuItem.SubCategoryName,'LONG');
                                        isValid=false;
                                    }else{
                                       
                                    }
                                }
                            })
                        );
                    }
                }
            }
            })
        );

        console.log('isValid:',isValid);
        return isValid;
    }

    function onStockValChange(item,skuItem,val,key,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        let allSKUData=SKUStockData;
        let defData={'CategoryId':item.CategoryId,'SubCategoryId':skuItem.SubCategoryId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==item.CategoryId && i.SubCategoryId==skuItem.SubCategoryId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;
       

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        setSKUStockData(allSKUData);
        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>
        )
      }
  
    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}`}/>        
        {_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 && 
           <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={(Platform.OS=='ios'?10:-100)} >  
                        
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                const catIndex=index;
                const cindex=catImages.findIndex(i=>i.CategoryId==item.CategoryId);
                const cimgName=cindex>=0?(catImages[cindex]?catImages[cindex].ImageName:''):'';
                const cimgPath=cindex>=0?(catImages[cindex]?catImages[cindex].ImagePath:''):'';
                const showIMg=cimgPath!='' && cimgPath!=null;

                let HdrImgAllowIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HeaderImageAllow');
                let HdrImgAllowObj=HdrImgAllowIndex>=0?KPIFields[HdrImgAllowIndex]:{};
                let isHdrImgAllow=HdrImgAllowIndex>=0?HdrImgAllowObj['KPIFieldEnable']:true;

                let ChildImgAllowIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ChildImageAllow');
                let ChildImageAllowObj=ChildImgAllowIndex>=0?KPIFields[ChildImgAllowIndex]:{};
                let isChildImageAllow=ChildImgAllowIndex>=0?ChildImageAllowObj['KPIFieldEnable']:false;

          
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={customStyle.opening_Stock_catText}>{item.CategoryName}</Text>
                            </LinearGradient>
                            {isHdrImgAllow==true && 
                            <View style={customStyle.osCat_actions}>
                                { !showIMg && 
                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera('1',item)}}>
                                        <CameraImg width={80} height={80}/>                                     
                                    </TouchableOpacity>
                                }
                                { showIMg && 
                                    <View style={customStyle.osCatImageView}>
                                        <Image style={customStyle.osCatImage} source={{uri:cimgPath}}/>
                                        {/* <Image style={customStyle.osCatImage} source={require('../assets/performics/add_image.svg')}/> */}
                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera('1',item)}}>
                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                        </TouchableOpacity>
                                    </View>                                    
                                }                                
                            </View>
                            }
                        </View>
                        <View style={customStyle.opening_Stock_prds}>
                            {
                                
                                <FlatList 
                                data={item.skulist}
                                extraData={rerenderdata2}
                                renderItem={({item,index})=>{
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.CategoryId==cat.CategoryId && i.SubCategoryId==skus.SubCategoryId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let brand_facing=thisCatSkuData.brand_facing!=null?thisCatSkuData.brand_facing:'';
                                    let subcat_facing=thisCatSkuData.subcat_facing!=null?thisCatSkuData.subcat_facing:'';

                                    let childImgPath=thisCatSkuData.ImagePath!=null?thisCatSkuData.ImagePath:'';
                                    const showSubCatIMg=childImgPath!='' && childImgPath!=null;

                                    const input1IsFocused=skus.input1IsFocused;
                                    const input2IsFocused=skus.input2IsFocused;

                                    if(input2IsFocused==1){
                                        console.log('set focus to ',cat.CategoryName,skus.SubCategoryName,'input 2')
                                    }           
                                    
                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={[customStyle.openStk_prd_nameB]}>{skus.SubCategoryName}</Text>

                                            {isChildImageAllow==true && 
                                            <View style={customStyle.SOS_imageWrap}>
                                                { !showSubCatIMg && 
                                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera('2',cat,skus)}}>
                                                        <CameraImg width={80} height={80} />                                     
                                                    </TouchableOpacity>
                                                }
                                                { showSubCatIMg && 
                                                    <View style={customStyle.osCatImageView}>
                                                        <Image style={customStyle.osCatImage} source={{uri:childImgPath}}/>
                                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera('2',cat,skus)}}>
                                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                        </TouchableOpacity>
                                                    </View>                                    
                                                }                                
                                            </View>
                                            }
                                            <View style={customStyle.openStk_prd_form}>
                                           
                                                <View style={customStyle.openStk_prd_row}>
                                                    <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_1]}>
                                                        <Text style={customStyle.openStk_prd_label}>Sub Category Facing</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input1_'+cat.CategoryId+'_'+skus.SubCategoryId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle]}              
                                                            placeholder=""    
                                                            autoComplete='off'        
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(subcat_facing+'' || '')}
                                                            keyboardType='numeric'
                                                            onSubmitEditing={()=>{focusToNext(cat,catIndex,skus,sku_index,'1')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'subcat_facing','numeric')}}
                                                        />
                                                    </View>
                                                    
                                                    <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_2]}>
                                                        <Text style={customStyle.openStk_prd_label}>Brand Facing</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input2_'+cat.CategoryId+'_'+skus.SubCategoryId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle]}              
                                                            placeholder=""     
                                                            autoComplete='off'       
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(brand_facing+'' || '')}
                                                            keyboardType='numeric'
                                                            onSubmitEditing={()=>{focusToNext(cat,catIndex,skus,sku_index,'2')}}
                                                            // onKeyPress={(e)=>{let isDot=e.nativeEvent.key=='.'; return isDot}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'brand_facing','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                            
                                            </View>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  

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