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, BackHandler, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, Fontisto, Ionicons, 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 CheckBox from '@react-native-community/checkbox';

import CameraImg from '../assets/performics/camera_front_image.svg'
import { ConfirmSaveAlert, ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import DateTimePicker from '@react-native-community/datetimepicker';
import CustomModal2 from '../components/CustomModal2';

function StockWithCat(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 [currentMenu, setCurrentMenu] = useState({});
    const [Category, setCategory] = useState({});
    const [subCatData, setSubCatData] = useState([]);
    const [globalSubCatData, setGlobalSubCatData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [catData, setCatData] = useState({});
    const [SKUStockData, setSKUStockData] = useState([]);

    const [currentStock, setCurrentStock] = useState({});
    const [currentInputIndex, setCurrentInputIndex] = useState(0);
    const [currentProduct, setCurrentProduct] = useState({});

    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [showStockModal, setShowStockModal] = useState(false);
    const [showDatePicker, setShowDatePicker] = useState(false);
    const [rerendermodal, setrerendermodal] = useState(0);
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveSKU, setToRemoveSKU] = useState({});
    const [showRemoveConfirm_M, setShowRemoveConfirm_M] = useState(false);
    const [searchedItem, setSearchedItem]= useState('');
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [activeSections,setActiveSections]= 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 cat=params.category || {};
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCategory(cat);
        setCurrentMenu(menu1);
            
        getData(storeData1,cat,menu1);

        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            return unsubscribe;
        };
       
    }, []);

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==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,cat,menu1){   
          
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);

          // set switch camera flag as defined in mapping menu flag (if exists)
          let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
          let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
          let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
          setShowSwitchCamera(SwitchingCamera);
          
          let AllKPIFieldEnable ={}
          if(AllKPIFields != null && AllKPIFields.length>0){
            
            let isStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='Stock')
            let isStockKPIObj=isStockIndex>=0?AllKPIFields[isStockIndex]:{};
            let isStockEnable=isStockIndex>=0?isStockKPIObj['KPIFieldEnable']:true;

            let isBRStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='BackRoomStock')
            let isBRStockKPIObj=isBRStockIndex>=0?AllKPIFields[isBRStockIndex]:{};
            let isBRStockEnable=isBRStockIndex>=0?isBRStockKPIObj['KPIFieldEnable']:true;

            let isDStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='DamageStock')
            let isDStockKPIObj=isDStockIndex>=0?AllKPIFields[isDStockIndex]:{};
            let isDStockEnable=isDStockIndex>=0?isDStockKPIObj['KPIFieldEnable']:false;

            let isLStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='LostStock')
            let isLStockKPIObj=isLStockIndex>=0?AllKPIFields[isLStockIndex]:{};
            let isLStockEnable=isLStockIndex>=0?isLStockKPIObj['KPIFieldEnable']:false;

            let isExStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
            let isExStockKPIObj=isExStockIndex>=0?AllKPIFields[isExStockIndex]:{};
            let isExStockEnable=isExStockIndex>=0?isExStockKPIObj['KPIFieldEnable']:false;

            let isMFDIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='MFD')
            let isMFD_KPIObj=isMFDIndex>=0?AllKPIFields[isMFDIndex]:{};
            let isMFDEnable=isMFDIndex>=0?isMFD_KPIObj['KPIFieldEnable']:false;

            let NrExpiry1Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry1')
            let NrExpiry1KPIObj=NrExpiry1Index>=0?AllKPIFields[NrExpiry1Index]:{};
            let NrExpiry1Enable=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldEnable']:false;

            let NrExpiry2Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry2')
            let NrExpiry2KPIObj=NrExpiry2Index>=0?AllKPIFields[NrExpiry2Index]:{};
            let NrExpiry2Enable=NrExpiry2Index>=0?NrExpiry2KPIObj['KPIFieldEnable']:false;

            let NrExpiry3Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry3')
            let NrExpiry3KPIObj=NrExpiry1Index>=0?AllKPIFields[NrExpiry3Index]:{};
            let NrExpiry3Enable=NrExpiry1Index>=0?NrExpiry3KPIObj['KPIFieldEnable']:false;

            AllKPIFieldEnable ={
                isStockEnable,
                isBRStockEnable,
                isDStockEnable,
                isLStockEnable,
                isExStockEnable,
                NrExpiry1Enable,
                NrExpiry2Enable,
                NrExpiry3Enable,
            }


          }
          await db.transaction(async function (txn) {  

            // let dq=`Select * FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            // let dq2=`select * FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            // let dq3=`select * FROM ${AppTables.STOCKWITHCAT_MFD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            
            // //  remove old data
            // await txn.executeSql(dq,[],async function (txn2, txnres) { 
            //     console.log('stock data deleted',txnres.rows.length);
            // },function (txnE,txnerr) { console.log(txnerr); },);

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

            // await txn.executeSql(dq3,[],async function (txn2, txnres) { 
            //   console.log('stock mfd data deleted',txnres.rows.length);
            // },function (txnE,txnerr) { console.log(txnerr); },);

            let q2=` SELECT CATEGORY_ID as CategoryId,CATEGORY as CategoryName,MSL,IMAGE,IMAGEPATH FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}' and VISIT_DATE='${d2}' `;
            
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                console.log('added products cats:',txnres.rows.length)
                if(txnres.rows.length>0){
                    let data =txnres.rows.item(0);
                    let defData={'CategoryId':data.CategoryId,'ImageName':data.IMAGE,'ImagePath':data.IMAGEPATH};
                   
                    let subcats=await getSubCats(storeData1,menu1,data,true,AllKPIFieldEnable);
                    setCatData(defData);
                    setSubCatData(subcats);
                    setGlobalSubCatData(subcats);
                    setProcessing(false);
                }
                else{
                    let subcats=await getSubCats(storeData1,menu1,cat,false,AllKPIFieldEnable);
                    setSubCatData(subcats);
                    setGlobalSubCatData(subcats);
                    setProcessing(false);
                }
            },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
            // setProcessing(false);

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

    async function getSubCats(storeData1,menu1,item,isInserted=false,AllKPIFieldEnable={}){
        let allSKUData=[];
        
        let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
            
                let join=`  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
                let join2=` inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                let s_q=`select distinct p.SubCategoryId,p.SubCategoryName from Product_Master p  ${join} ${join2} where m.StoreId='${StoreId}' and (p.CategoryId='${item.CategoryId}' or p.CategoryId=${item.CategoryId}) and (CompanyId='1' or CompanyId=1) order by p.SubCategoryName,p.BrandName`;
                await txn.executeSql(s_q,[],async function (txn2, txnres) { 
                    console.log('SubCats len:',txnres.rows.length)
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            data['isSubCatCollapsed']=false;
                            let pr_d=await getSKU(storeData1,item,data,allSKUData,AllKPIFieldEnable);

                            let products=pr_d['products'];
                            let products_data=pr_d['products_data'];
                            data['skulist']=products

                            allSKUData.concat(products_data);
                            arr.push(data);

                            if(i==txnres.rows.length-1){
                                setSKUStockData(allSKUData);
                                resolve(arr);
                            }
                        }
                    }
                    else{
                        resolve([])
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve([]) },);
                // setProcessing(false);
                
              });  
        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log(err);
            return [];
        })
    }

    async function setOnFocus(item,type='1'){
        let key='input'+type+'_'+item.ProductId;
        let arr=Object.keys(inputRefs.current);
        let activeIndex=arr.indexOf(key);
        console.log('setfocus activeindex:',activeIndex);
        setCurrentInputIndex(activeIndex);
    }

    async function focusToNext(){

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

    async function getSKU(storeData1,cat,subcat,allSKUData=[],AllKPIFieldEnable={}){
        let sku_ret={'products':[],'products_data':allSKUData};
        let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock,StoreClassId,StoreCategoryId}=storeData1; 

        let {isStockEnable,
            isBRStockEnable,
            isDStockEnable,
            isLStockEnable,
            isExStockEnable,
            NrExpiry1Enable,
            NrExpiry2Enable,
            NrExpiry3Enable,}=AllKPIFieldEnable   
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) { 
               
                // get from stored data if exists
                let seletlist=`STOCK_UID,PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK`;
                let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}'   and SUB_CATEGORY_ID='${subcat.SubCategoryId}'  `;
         
                // else get products from masters
                let join=`  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
                let join2=`  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                let sku_q2=`select distinct p.ProductName,p.ProductId,p.BrandName,p.BrandId,p.SubCategoryName,p.SubCategoryId,m.MSL from Product_Master p  ${join} ${join2} where m.StoreId='${StoreId}' and (p.CategoryId='${cat.CategoryId}' or p.CategoryId= ${cat.CategoryId}) and (p.SubCategoryId='${subcat.SubCategoryId}' or p.SubCategoryId= ${subcat.SubCategoryId}) and (CompanyId='1' or  CompanyId= 1) order by p.ProductSequence`;
                await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                    console.log('txnres.rows.length:',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            console.log('data',data);
                            data['Old_Stock']=data.STOCK;
                            data['OldDamagedStock']=data.DAMAGED_STOCK;
                            data['OldLostStock']=data.LOST_STOCK;
                            data['OldExStock']=data.EXPIRY_STOCK;
                            
                            let mfdStocks=await getMFDStockData(data);
                            let defData={'ProductId':data.ProductId,'Stock':data.STOCK,'BackRoomStock':data.BACKROOM_STOCK,'ExpiryStock':data.EXPIRY_STOCK,'DamagedStock':data.DAMAGED_STOCK,'LostStock':data.LOST_STOCK,'mfdStocks':(mfdStocks || []),'isSKUPresent':data.IS_SKU_STOCK_PRESENT,'showAllSKU_Fields':(data.IS_SKU_STOCK_PRESENT==1),'NearExpiry1':data.NREXPIRY1_STOCK,'NearExpiry2':data.NREXPIRY2_STOCK,'NearExpiry3':data.NREXPIRY3_STOCK};
                            
                            if(isStockEnable ){
                                inputRefs.current['input1_'+data.ProductId]='';
                            }
                            if(isBRStockEnable ){
                                inputRefs.current['input2_'+data.ProductId]='';
                            }
                            if(isDStockEnable ){
                                inputRefs.current['input3_'+data.ProductId]='';
                            }
                            if(isLStockEnable ){
                                inputRefs.current['input4_'+data.ProductId]='';
                            }
                            if(isExStockEnable ){
                                inputRefs.current['input5_'+data.ProductId]='';
                            }
                            if(NrExpiry1Enable ){
                                inputRefs.current['input6_'+data.ProductId]='';
                            }
                            if(NrExpiry2Enable ){
                                inputRefs.current['input7_'+data.ProductId]='';
                            }
                            if(NrExpiry3Enable ){
                                inputRefs.current['input8_'+data.ProductId]='';
                            }

                            allSKUData.push(defData);
                            arr.push(data);

                            if(i==txnres.rows.length-1){
                                sku_ret['products']=arr;
                                sku_ret['products_data']=allSKUData;
                                resolve(sku_ret);
                            }
                        }
                    }
                    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);

                                    if(isStockEnable ){
                                        inputRefs.current['input1_'+data.ProductId]='';
                                    }
                                    if(isBRStockEnable ){
                                        inputRefs.current['input2_'+data.ProductId]='';
                                    }
                                    if(isDStockEnable ){
                                        inputRefs.current['input3_'+data.ProductId]='';
                                    }
                                    if(isLStockEnable ){
                                        inputRefs.current['input4_'+data.ProductId]='';
                                    }
                                    if(isExStockEnable ){
                                        inputRefs.current['input5_'+data.ProductId]='';
                                    }
                                    if(NrExpiry1Enable ){
                                        inputRefs.current['input6_'+data.ProductId]='';
                                    }
                                    if(NrExpiry2Enable ){
                                        inputRefs.current['input7_'+data.ProductId]='';
                                    }
                                    if(NrExpiry3Enable ){
                                        inputRefs.current['input8_'+data.ProductId]='';
                                    }

                                    let defData={'ProductId':data.ProductId,'Stock':'','BackRoomStock':'','ExpiryStock':'','DamagedStock':'','LostStock':'','mfdStocks':[],'isSKUPresent':'','showAllSKU_Fields':false};
                                    allSKUData.push(defData);
                                    arr.push(data);
                                    if(i==(txnres2.rows.length-1)){   
                                        sku_ret['products']=arr;
                                        sku_ret['products_data']=allSKUData;                                     
                                        resolve(sku_ret);
                                    }               
                                }
                            }
                            else{
                                resolve(sku_ret);
                            }
                            
                        },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); resolve(sku_ret); },);
                    }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); resolve(sku_ret); },);      
    
                        
            });  
        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log('getSKU err:',err);
            return sku_ret;
        })
                   
              
    }

    async function getMFDStockData(skud){
        
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                let q=`select * from ${AppTables.STOCK2_MFD_DATA} where STOCK_UID='${skud.STOCK_UID}'`;
                await txn.executeSql(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);
                            let obj={'date':new Date(data.DATE),'mfd':data.MFD,'stock':data.STOCK,'lotno':data.LOT_NO}
                            
                            arr.push(obj);
                            if(i==txnres.rows.length-1){
                                console.log('mfdStocks',arr);
                                resolve(arr)
                            }
                        }
                    }
                    else{
                        resolve([])
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve([]) },);
            });
        }).catch((err)=>{
            console.log(err);
            return [];
        })
    }

    async function getImage(imgdata){
        let cat=getImageProps.option || '';
        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.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

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

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

            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_Stock-'+calculate_tym_date_for_filename+'.jpg';
            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName+' | Date:'+calculate_tym_date_over_img;
 
            
            let allIMgData=catData;
            allIMgData.ImageName=filename;

            let imagePath='file://'+ImageFolderPath+currentMenu.ScreenName+"/"+filename;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri=imagePath;
                console.log('image marker',uri);
                allIMgData.ImagePath=uri; 
                
                setCatData(allIMgData);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
            })
            .catch(err => {
                console.log('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });                  
                                   
        }        
    }
  
    async function openCamera(option){ 
        setGetImageProps({'option':option}); 
        console.log('openCamera');
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    async function submitOpeningStock(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
           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.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and CATEGORY_ID='${Category.CategoryId}' `;
              let q2=`DELETE FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  and CATEGORY_ID='${Category.CategoryId}'`;
              let q3=`DELETE FROM ${AppTables.STOCKWITHCAT_MFD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and CATEGORY_ID='${Category.CategoryId}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('stock data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

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

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


              let seq_q=` select seq from sqlite_sequence where name="${AppTables.STOCKWITHCAT_HDR_DATA}" `;
              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,ExpiryStock}=storeData;
            console.log('insertData');
            await db.transaction(async function (txn) {
              var values='',stock_values='',mfdStockV='';
            //   values+=values!=''?' , ':'';
              values+=` ('${StoreId}','${d2}','${Category.CategoryName}','${Category.CategoryId}','','${(catData.ImageName || '')}','${(catData.ImagePath || '')}','${d2}') `;
              
              
              for(var i=0;i<globalSubCatData.length;i++){
                seq++;
                let subcatIndex=i;
                let item=globalSubCatData[subcatIndex];
                let skulist=item['skulist'] || [];
                for(var k=0;k<skulist.length;k++){
                    let skuItem=skulist[k];
                    let SKU_UID='SKU'+seq+k+(Math.floor(Math.random()*1000)+1);
                    let {BrandId,BrandName,SubCategoryId,SubCategoryName,MSL,ProductId,ProductName}=skuItem;
                    stock_values+=stock_values!=''?' , ':'';
                    let allSKUData=SKUStockData;
                    const skud_index=allSKUData.findIndex(ci=>ci.ProductId==skuItem.ProductId);
                    const skud=skud_index>=0?(allSKUData[skud_index] || {}) : {};
                    let mfdStocks=skud['mfdStocks'] || [];

                    let stock=skud.Stock!=null?skud.Stock:'';
                    let br_stock=skud.BackRoomStock!=null?skud.BackRoomStock:'';
                    let ex_stock=skud.ExpiryStock!=null?skud.ExpiryStock:'';
                    let damage_stock=skud.DamagedStock!=null?skud.DamagedStock:'';
                    let lost_stock=skud.LostStock!=null?skud.LostStock:'';
                    let isSKUPresent=skud.isSKUPresent!=null?skud.isSKUPresent:0;
                    let NearExpiry_stock1=skud.NearExpiry1!=null?skud.NearExpiry1:'';
                    let NearExpiry_stock2=skud.NearExpiry2!=null?skud.NearExpiry2:'';
                    let NearExpiry_stock3=skud.NearExpiry3!=null?skud.NearExpiry3:'';
                    
                    stock_values+=` ('${seq}','${SKU_UID}','${StoreId}','${d2}','${Category.CategoryId}','${Category.CategoryName}','${SubCategoryId}','${SubCategoryName}','${BrandId}','${BrandName}','${ProductId}','${ProductName}','${MSL}','${stock}','${br_stock}','${damage_stock}','${lost_stock}','${ex_stock}','${isSKUPresent}','${NearExpiry_stock1}','${NearExpiry_stock2}','${NearExpiry_stock3}','${d2}') `;
                    
                    for(let m=0;m<mfdStocks.length;m++){
                        let cstock=mfdStocks[m];
                        let mfd_stock=cstock['stock'];
                        let mfd_mfd=cstock['mfd'];
                        let mfd_lotno=cstock['lotno'];
                        let mfd_date=cstock['date']!=null?moment(cstock['date']).format('MM-DD-YYYY'):'';
                        
                        mfdStockV+=mfdStockV!=''?' , ':'';
                        mfdStockV+=` ('${seq}','${SKU_UID}','${StoreId}','${d2}','${item.CategoryId}','${BrandId}','${ProductId}','${mfd_stock}','${mfd_mfd}','${mfd_lotno}','${mfd_date}','${d2}') `;
                    
                    }
                    
                }
                
              }

              
              let add_StockHdr=`INSERT INTO ${AppTables.STOCKWITHCAT_HDR_DATA} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.STOCKWITHCAT_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,CATEGORY_ID,CATEGORY,SUB_CATEGORY_ID,SUB_CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK,ADDED_DATE) VALUES ${stock_values} `;
              let add_mfd_Stock=`INSERT INTO ${AppTables.STOCKWITHCAT_MFD_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,CATEGORY_ID,BRAND_ID,PRODUCT_ID,STOCK,MFD,LOT_NO,DATE,ADDED_DATE) VALUES ${mfdStockV} `;
                
              await txn.executeSql(add_StockHdr,[],async function (txn2, txnres) { 
                console.log('stock header added');
                await txn.executeSql(add_Stock,[],async function (txn2, txnres) { 
                    console.log('stock added');
                    if(mfdStockV!=null && mfdStockV!=''){
                        await txn.executeSql(add_mfd_Stock,[],async function (txn2, txnres) { 
                            console.log('stock mfd added');
                            notify('Stock updated successfully');
                            setProcessing(false);
                            props.navigation.goBack();
                        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
                    }
                    else{
                        notify('Stock updated successfully');
                        setProcessing(false);
                        props.navigation.goBack();
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
              
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


    async function validate(){
        let isValid=true;
        var i=0,j=0;

        let isHdrImgIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HeaderImageAllow')
        let isHdrImgKPIObj=isHdrImgIndex>=0?KPIFields[isHdrImgIndex]:{};
        let isHdrImgEnable=isHdrImgIndex>=0?isHdrImgKPIObj['KPIFieldEnable']:false;

        let isListedSKUIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ListedSKU');
        let isListedSKUKPIObj=isListedSKUIndex>=0?KPIFields[isListedSKUIndex]:{};
        let isListedSKUEnable=isListedSKUIndex>=0?isListedSKUKPIObj['KPIFieldEnable']:true;

        let isStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Stock')
        let isStockKPIObj=isStockIndex>=0?KPIFields[isStockIndex]:{};
        let isStockEnable=isStockIndex>=0?isStockKPIObj['KPIFieldEnable']:true;
        let isStockDis_Name=isStockIndex>=0?isStockKPIObj['KPIFieldDisplayName']:'Stock';

        let isBRStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='BackRoomStock')
        let isBRStockKPIObj=isBRStockIndex>=0?KPIFields[isBRStockIndex]:{};
        let isBRStockEnable=isBRStockIndex>=0?isBRStockKPIObj['KPIFieldEnable']:true;
        let isBRStockDis_Name=isBRStockIndex>=0?isBRStockKPIObj['KPIFieldDisplayName']:'Stock';

        let isDStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='DamageStock')
        let isDStockKPIObj=isDStockIndex>=0?KPIFields[isDStockIndex]:{};
        let isDStockEnable=isDStockIndex>=0?isDStockKPIObj['KPIFieldEnable']:false;
        let isDStockDis_Name=isDStockIndex>=0?isDStockKPIObj['KPIFieldDisplayName']:'';

        let isLStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='LostStock')
        let isLStockKPIObj=isLStockIndex>=0?KPIFields[isLStockIndex]:{};
        let isLStockEnable=isLStockIndex>=0?isLStockKPIObj['KPIFieldEnable']:false;
        let isLStockDis_Name=isLStockIndex>=0?isLStockKPIObj['KPIFieldDisplayName']:'';

        let isExStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExStockKPIObj=isExStockIndex>=0?KPIFields[isExStockIndex]:{};
        let isExStockEnable=isExStockIndex>=0?isExStockKPIObj['KPIFieldEnable']:false;
        let isExStockDis_Name=isExStockIndex>=0?isExStockKPIObj['KPIFieldDisplayName']:'';

        let isMFDIndex=KPIFields.findIndex(i=>i.KPIFieldName=='MFD')
        let isMFD_KPIObj=isMFDIndex>=0?KPIFields[isMFDIndex]:{};
        let isMFDEnable=isMFDIndex>=0?isMFD_KPIObj['KPIFieldEnable']:false;
        let isMFDDis_Name=isMFDIndex>=0?isMFD_KPIObj['KPIFieldDisplayName']:'';

        let NrExpiry1Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry1')
        let NrExpiry1KPIObj=NrExpiry1Index>=0?KPIFields[NrExpiry1Index]:{};
        let NrExpiry1Enable=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldEnable']:false;
        let NrExpiry1_Dis_Name=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldDisplayName']:'';

        let NrExpiry2Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry2')
        let NrExpiry2KPIObj=NrExpiry2Index>=0?KPIFields[NrExpiry2Index]:{};
        let NrExpiry2Enable=NrExpiry2Index>=0?NrExpiry2KPIObj['KPIFieldEnable']:false;
        let NrExpiry2_Dis_Name=NrExpiry2Index>=0?NrExpiry2KPIObj['KPIFieldDisplayName']:'';

        let NrExpiry3Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry3')
        let NrExpiry3KPIObj=NrExpiry1Index>=0?KPIFields[NrExpiry3Index]:{};
        let NrExpiry3Enable=NrExpiry1Index>=0?NrExpiry3KPIObj['KPIFieldEnable']:false;
        let NrExpiry3_Dis_Name=NrExpiry1Index>=0?NrExpiry3KPIObj['KPIFieldDisplayName']:'';

        let MSLIndex=KPIFields.findIndex(i=>i.KPIFieldName=='MSL');
        let MSLObj=MSLIndex>=0?KPIFields[MSLIndex]:{};
        let isMSLAllow=MSLIndex>=0?MSLObj['KPIFieldEnable']:true;

        let NONMSL_Index=KPIFields.findIndex(i=>i.KPIFieldName=='ChildImageAllow');
        let NONMSL_Obj=NONMSL_Index>=0?KPIFields[NONMSL_Index]:{};
        let isNONMSL_Allow=NONMSL_Index>=0?NONMSL_Obj['KPIFieldEnable']:false;

        let catId=Category.CategoryId;
        if(isHdrImgEnable==true && (catData.ImagePath== null || catData.ImagePath=='')){
            notify('Please click image for '+Category.CategoryName,'SHORT');
            isValid=false;
        }
        else{
        await Promise.all(
            globalSubCatData.map(async (item,index) => {
                let skulist=item.skulist || [];
                if(isValid==true){
                    if(skulist.length>0){
                        await Promise.all(
                            skulist.map(async (skuItem,skuIndex) => {
                                if(isValid==true){
                                let skuData=SKUStockData.find(ci=>ci.ProductId==skuItem.ProductId ) || {};
                                let stock=skuData.Stock!=null?skuData.Stock:'';
                                let ex_stock=skuData.ExpiryStock!=null?skuData.ExpiryStock:'';
                                let damage_stock=skuData.DamagedStock!=null?skuData.DamagedStock:'';
                                let lost_stock=skuData.LostStock!=null?skuData.LostStock:'';
                                let isSKUPresent=skuData.isSKUPresent!=null?skuData.isSKUPresent:0;
                                let br_stock=skuData.BackRoomStock!=null?skuData.BackRoomStock:'';
                                let NearExpiry_stock1=skuData.NearExpiry1!=null?skuData.NearExpiry1:'';
                                let NearExpiry_stock2=skuData.NearExpiry2!=null?skuData.NearExpiry2:'';
                                let NearExpiry_stock3=skuData.NearExpiry3!=null?skuData.NearExpiry3:'';
                                    
                                let isMandatory=((isMSLAllow==1 || isMSLAllow=='true') && (skuItem.MSL==1 || skuItem.MSL=='true') ) || ((isNONMSL_Allow==1 || isNONMSL_Allow=='true') && (skuItem.MSL!=1 && skuItem.MSL!='true') ) 
                                
                                if((isListedSKUEnable==true && isSKUPresent==1) || (!isListedSKUEnable  && (isMandatory)) ){
                                    // let sumOfDamagedStocks=parseInt(ex_stock)+parseInt(damage_stock)+parseInt(lost_stock);
                                    if(isStockEnable==true && stock!==0 && ( stock==null || stock=='')){
                                        notify('Please enter '+isStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(isBRStockEnable==true && br_stock!==0 && ( br_stock==null || br_stock=='')){
                                        notify('Please enter '+isBRStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(isDStockEnable==true && damage_stock!==0 && ( damage_stock==null || damage_stock=='')){
                                        notify('Please enter '+isDStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(isLStockEnable==true && lost_stock!==0 && ( lost_stock==null || lost_stock=='')){
                                        notify('Please enter '+isDStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(isExStockEnable==true && ex_stock!==0 && ( ex_stock==null || ex_stock=='')){
                                        notify('Please enter '+isExStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(NrExpiry1Enable==true && NearExpiry_stock1!==0 && ( NearExpiry_stock1==null || NearExpiry_stock1=='')){
                                        notify('Please enter '+NrExpiry1_Dis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(NrExpiry2Enable==true && NearExpiry_stock2!==0 && ( NearExpiry_stock2==null || NearExpiry_stock2=='')){
                                        notify('Please enter '+NrExpiry2_Dis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    else if(NrExpiry3Enable==true && NearExpiry_stock3!==0 && ( NearExpiry_stock3==null ||NearExpiry_stock3=='')){
                                        notify('Please enter '+NrExpiry3_Dis_Name+' for '+skuItem.ProductName,'LONG');
                                        isValid=false;
                                    }
                                    // else if((isDStockEnable && isLStockEnable && isExStockEnable) && sumOfDamagedStocks>parseInt(stock)){
                                    //     notify('Sum of '+isDStockDis_Name+','+isLStockDis_Name+' and '+isExStockDis_Name+' should be less than or equal to Stock for '+skuItem.ProductName,'LONG');
                                    //     isValid=false;
                                    // }
                                    // else if((isDStockEnable && isLStockEnable) && sumOfDamagedStocks>parseInt(stock)){
                                    //     notify('Sum of '+isDStockDis_Name+' and '+isLStockDis_Name+' should be less than or equal to '+isStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                    //     isValid=false;
                                    // }
                                    // else if((isLStockEnable && isExStockEnable) && sumOfDamagedStocks>parseInt(stock)){
                                    //     notify('Sum of '+isLStockDis_Name+' and '+isExStockDis_Name+' should be less than or equal to '+isStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                    //     isValid=false;
                                    // }
                                    // else if((isDStockEnable && isExStockEnable) && sumOfDamagedStocks>parseInt(stock)){
                                    //     notify('Sum of '+isDStockDis_Name+' and '+isExStockDis_Name+' should be less than or equal to '+isStockDis_Name+' for '+skuItem.ProductName,'LONG');
                                    //     isValid=false;
                                    // }
                                    else{

                                    }
                                
                                }
                                }
                            })
                        );
                    }
                }
            })
        );
        }

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

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

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

        if(key=='isSKUPresent'){
            skud['showAllSKU_Fields']=val==1?true:false;
        }

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    // function checkStockVal(item,skuItem,key,old_key,old_val){
    //     console.log('checkStockVal',old_val,val);
    //     let allSKUData=SKUStockData;
    //     let defData={'ProductId':skuItem.ProductId};
    //     const skud_index=allSKUData.findIndex(i=>i.CategoryId==item.CategoryId && i.ProductId==skuItem.ProductId);
    //     const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
    //     console.log('checkStockVal');
    //     let val=skud[key] || '';
    //     let val1=skud[key] || 0;
    //     let product_total_stock=skud['Stock'];
    //     if(product_total_stock!=''){
    //         product_total_stock=parseInt(product_total_stock);
    //         let product_damage_stock=parseInt(skud['DamagedStock'] || 0);
    //         let product_lost_stock=parseInt(skud['LostStock'] || 0);
    //         let product_ex_stock=parseInt(skud['ExpiryStock'] || 0);
        
    //         let product_stock=product_ex_stock;//product_total_stock-(product_damage_stock+product_lost_stock+product_ex_stock);
    //         val1=parseInt(val1);
    //         if(skud_index>=0){
    //             let mfdStocks=skud['mfdStocks'] || [];
    //             let sumOfAllStocks=0
    //             for(let i in mfdStocks){
    //                 let ds=mfdStocks[i];
    //                 sumOfAllStocks+=parseInt(ds.stock);
    //             }

    //             if(sumOfAllStocks>product_stock){
    //                 notify('Sum of all MFD stock cannot be greater than product stock count!');
    //                 skud[key]=old_val;
    //                 skud[old_key]=old_val;
    //             }
    //             else{
    //                 skud[old_key]=val;
    //             }
    //         }
    //         else{
    //             skud[old_key]=val;
    //         }
        

    //         skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
    //         setSKUStockData(allSKUData);
    //         setHasUnsavedChanges(true);
    //         setrerenderdata(!rerenderdata);
    //     }
    // }

    function openAddStkModal(skuItem){
        setCurrentProduct(skuItem);
        // let allSKUData=SKUStockData;
        // let defData={'ProductId':skuItem.ProductId};
        // const skud_index=allSKUData.findIndex(i=>i.ProductId==skuItem.ProductId);
        // const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;

        setShowStockModal(true);
        // let mfdStocks=skud['mfdStocks'] || [];
        // let product_stock=skud['Stock'];
        // let product_ex_stock=skud['ExpiryStock'];
        
        // if(product_stock==null || product_stock==''){
        //     notify('Please enter sku stock first!');
        // }
        // else if(product_ex_stock==null || product_ex_stock==''){
        //     notify('Please enter expiry stock first!');
        // }
        // else{
            
        // }
        
    }

    function onSaveCancel(){
        setShowAlert(false)
    }

    function setStockDate(date){
        let d1=moment(date).format('DD/MM/YYYY');
        let cstock=currentStock;
        cstock['date']=date;
        cstock['mfd']=d1;
        setCurrentStock(cstock);
        setShowDatePicker(false);
    }

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


        let cstock=currentStock;
        cstock[key]=val;
        setCurrentStock(cstock);
        setrerendermodal(!rerendermodal);
    }

   

    function getAllSum(mfdStocks=[],cstock={}){
        let {mfd,date,stock}=cstock
        let sumOfAllStocks=parseInt(stock);
        return new Promise((resolve,reject)=>{
            if(mfdStocks.length>0){
                for(let i in mfdStocks){
                    let ds=mfdStocks[i];
                    sumOfAllStocks+=parseInt(ds.stock);
                    if(i==mfdStocks.length-1){
                        resolve(sumOfAllStocks)
                    }
                }
            }
            else{
                resolve(sumOfAllStocks)
            }
        }).catch((err)=>{
            console.log(err);
            return 0;
        })
    }

    async function addMFDStock(){
        Keyboard.dismiss();
        let skuItem=currentProduct
        let cstock=currentStock;
        var allSKUData=SKUStockData;
        let defData={'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=> i.ProductId==skuItem.ProductId);
        var skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        let mfdStocks=skud['mfdStocks'] || [];
        let {mfd,date,stock,lotno}=cstock

        if(mfd==null || mfd==''){
            notify('Please select date!');
            return ;
        }
        else if(stock==null || stock==''){
            notify('Please enter stock!');
            return ;
        }
        else if(lotno==null || lotno==''){
            notify('Please enter lot no.!');
            return ;
        }
        else if(mfdStocks.findIndex(i=>i.mfd==mfd)>=0){
            notify('This date is already added! Please select different date');
            return ;
        }
        else {
            console.log('added')
            mfdStocks.push(cstock);
            skud['mfdStocks']=mfdStocks;
            skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
            setSKUStockData(allSKUData);
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
            setCurrentStock({});
            setShowStockModal(false);
        }
    }


    function removeMFDStock(){
        let skuItem=toRemoveSKU;
        let cstockIndex=toRemoveId;
        let allSKUData=SKUStockData;
        let defData={'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.ProductId==skuItem.ProductId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        let mfdStocks=skud['mfdStocks'] || [];
        mfdStocks.splice(cstockIndex,1);
        skud['mfdStocks']=mfdStocks;

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        setShowRemoveConfirm_M(false);
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function showRemoveConfirm(skuItem,cstock,cstockIndex){
        setToRemoveId(cstockIndex);
        setToRemoveSKU(skuItem);
        setShowRemoveConfirm_M(true);
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2={};
        if(searchedQry!=null && searchedQry!=''){
            for(let i=0;i<globalSubCatData.length;i++){
                let item=globalSubCatData[i];
                arr2={ 'SubCategoryId':item.SubCategoryId,'SubCategoryName':item.SubCategoryName,'isSubCatCollapsed':item.isSubCatCollapsed};
                let skulist=item.skulist;
                let newSkulist=[];
                for(let k=0;k<skulist.length;k++){
                    let sku=skulist[k];
                    let {ProductName}=sku;
                    if(ProductName.toLowerCase().includes(searchedQry)){
                        newSkulist.push(sku);
                    }

                    if(k==skulist.length-1){
                        arr2.skulist=newSkulist;
                        if(newSkulist.length>0){
                            arr.push(arr2);
                        }
                    }
                }

                
            }
        }
        else{
          arr=globalSubCatData;
        }

        setSubCatData(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }

    function renderDatePicker(){
        let today=new Date();
        console.log('today:',today);
        let d1=Object.keys(currentStock).length>0 && currentStock.date!=null && currentStock.date!='' ?new Date(currentStock.date):new Date();
        return (
            <DateTimePicker
            testID="dateTimePicker"
            value={d1}
            mode={'date'}
            display="default"  
            // maximumDate={today}
            onChange={(event, selectedDate)=>{setStockDate(selectedDate)}}
            />    
        );
    }

    function _render_StockModal(){
        let mfd=Object.keys(currentStock).length>0 && currentStock.mfd!=null && currentStock.mfd!='' ?currentStock.mfd:'';
        let stock=Object.keys(currentStock).length>0 && currentStock.stock!=null?currentStock.stock:'';
        let lotno=Object.keys(currentStock).length>0 && currentStock.lotno!=null?currentStock.lotno:'';
        
        return (
          <CustomModal2
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Add Near Expiry Stock'}
            showModal={showStockModal}
          >
            <View style={customStyle.AddStockM_View}>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>Expiry Date</Text>
                    <View style={[customStyle.AddStockM_col,customStyle.AddStockM_MFDInputCon]} >
                        <Text style={customStyle.AddStockM_MFDInput}>{mfd}</Text>
                        
                        <TouchableOpacity style={customStyle.AddStockM_DatePicker} onPress={()=>{setShowDatePicker(true);}}>
                            <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                        </TouchableOpacity>
                    </View>
                    {showDatePicker==true && 
                        renderDatePicker()
                    } 
                </View>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>Stock</Text>
                    <View style={customStyle.AddStockM_col} >
                        <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            keyboardType={'number-pad'}
                            value={stock}
                            onChangeText={(val)=>{setCS_Stock('stock',val,'numeric')}}
                        />
                    </View>
                </View>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>Lot No.</Text>
                    <View style={customStyle.AddStockM_col} >
                        <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            // keyboardType={'number-pad'}
                            value={lotno}
                            onChangeText={(val)=>{setCS_Stock('lotno',val,'text')}}
                        />
                    </View>
                </View>
            </View>
            <View style={[customStyle.storelVisitM_options,{justifyContent:'space-between'}]}>
             <TouchableOpacity style={[customStyle.storelVisitM_op_btn,customStyle.AddStockM_cancelBtn]} onPress={()=>{setCurrentStock({});setShowStockModal(false);}}>
                <Text style={[customStyle.storelVisitM_op_btnText,customStyle.AddStockM_cancelBtnText]}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[customStyle.storelVisitM_op_btn,customStyle.AddStockM_Btn]} onPress={()=>{addMFDStock()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Add</Text>
              </TouchableOpacity>
            </View>
            
          </CustomModal2>
        )
     }

    
    function toggleCollapse(subcat={},subcatIndex){
        let allData=subCatData;
        let isSubCatCollapsed=subcat.isSubCatCollapsed;
        subcat['isSubCatCollapsed']=!isSubCatCollapsed;
        allData[subcatIndex]=subcat;
        setSubCatData(allData);
        setGlobalSubCatData(allData);
        setrerenderdata(!rerenderdata);
    }

    function _renderStocks(){

        let isHdrImgIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HeaderImageAllow')
        let isHdrImgKPIObj=isHdrImgIndex>=0?KPIFields[isHdrImgIndex]:{};
        let isHdrImgEnable=isHdrImgIndex>=0?isHdrImgKPIObj['KPIFieldEnable']:false;

        let isListedSKUIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ListedSKU')
        let isListedSKUKPIObj=isListedSKUIndex>=0?KPIFields[isListedSKUIndex]:{};
        let isListedSKUEnable=isListedSKUIndex>=0?isListedSKUKPIObj['KPIFieldEnable']:false;

        let isStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Stock')
        let isStockKPIObj=isStockIndex>=0?KPIFields[isStockIndex]:{};
        let isStockEnable=isStockIndex>=0?isStockKPIObj['KPIFieldEnable']:true;
        let isStockDis_Name=isStockIndex>=0?isStockKPIObj['KPIFieldDisplayName']:'Stock';
        
        let isBRStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='BackRoomStock')
        let isBRStockKPIObj=isBRStockIndex>=0?KPIFields[isBRStockIndex]:{};
        let isBRStockEnable=isBRStockIndex>=0?isBRStockKPIObj['KPIFieldEnable']:false;
        let isBRStockDis_Name=isBRStockIndex>=0?isBRStockKPIObj['KPIFieldDisplayName']:'Back Room Stock';

        let isDStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='DamageStock')
        let isDStockKPIObj=isDStockIndex>=0?KPIFields[isDStockIndex]:{};
        let isDStockEnable=isDStockIndex>=0?isDStockKPIObj['KPIFieldEnable']:false;
        let isDStockDis_Name=isDStockIndex>=0?isDStockKPIObj['KPIFieldDisplayName']:'';
        console.log('isDStockIndex:',isDStockIndex,isDStockEnable,isDStockDis_Name);

        let isLStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='LostStock')
        let isLStockKPIObj=isLStockIndex>=0?KPIFields[isLStockIndex]:{};
        let isLStockEnable=isLStockIndex>=0?isLStockKPIObj['KPIFieldEnable']:false;
        let isLStockDis_Name=isLStockIndex>=0?isLStockKPIObj['KPIFieldDisplayName']:'';

        let isExStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExStockKPIObj=isExStockIndex>=0?KPIFields[isExStockIndex]:{};
        let isExStockEnable=isExStockIndex>=0?isExStockKPIObj['KPIFieldEnable']:false;
        let isExStockDis_Name=isExStockIndex>=0?isExStockKPIObj['KPIFieldDisplayName']:'';

        let isMFDIndex=KPIFields.findIndex(i=>i.KPIFieldName=='MFD')
        let isMFD_KPIObj=isMFDIndex>=0?KPIFields[isMFDIndex]:{};
        let isMFDEnable=isMFDIndex>=0?isMFD_KPIObj['KPIFieldEnable']:true;
        let isMFDDis_Name=isMFDIndex>=0?isMFD_KPIObj['KPIFieldDisplayName']:'';
        
        let NrExpiry1Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry1')
        let NrExpiry1KPIObj=NrExpiry1Index>=0?KPIFields[NrExpiry1Index]:{};
        let NrExpiry1Enable=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldEnable']:false;
        let NrExpiry1_Dis_Name=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldDisplayName']:'';

        let NrExpiry2Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry2')
        let NrExpiry2KPIObj=NrExpiry2Index>=0?KPIFields[NrExpiry2Index]:{};
        let NrExpiry2Enable=NrExpiry2Index>=0?NrExpiry2KPIObj['KPIFieldEnable']:false;
        let NrExpiry2_Dis_Name=NrExpiry2Index>=0?NrExpiry2KPIObj['KPIFieldDisplayName']:'';

        let NrExpiry3Index=KPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry3')
        let NrExpiry3KPIObj=NrExpiry1Index>=0?KPIFields[NrExpiry3Index]:{};
        let NrExpiry3Enable=NrExpiry1Index>=0?NrExpiry3KPIObj['KPIFieldEnable']:false;
        let NrExpiry3_Dis_Name=NrExpiry1Index>=0?NrExpiry3KPIObj['KPIFieldDisplayName']:'';

        let MSLIndex=KPIFields.findIndex(i=>i.KPIFieldName=='MSL');
        let MSLObj=MSLIndex>=0?KPIFields[MSLIndex]:{};
        let isMSLAllow=MSLIndex>=0?MSLObj['KPIFieldEnable']:true;

        let NONMSL_Index=KPIFields.findIndex(i=>i.KPIFieldName=='ChildImageAllow');
        let NONMSL_Obj=NONMSL_Index>=0?KPIFields[NONMSL_Index]:{};
        let isNONMSL_Allow=NONMSL_Index>=0?NONMSL_Obj['KPIFieldEnable']:true;

        const cimgName=catData.ImageName!=null?catData.ImageName:'';
        const cimgPath=catData.ImagePath!=null?catData.ImagePath:'';
        const showIMg=cimgPath!='' && cimgPath!=null;

        

        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-100} >  
            
            <ScrollView 
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            >
                {
                ( isHdrImgEnable==true) && 
                <View  style={customStyle.prdCat_hdImgCon}>
                    <View style={customStyle.prdCat_hdIMgWrap}>
                        { !showIMg && 
                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(item)}}>
                                <CameraImg width={80} height={80} />                                     
                            </TouchableOpacity>
                        }
                        { showIMg && 
                            <View style={customStyle.osCatImageView}>
                                <Image style={customStyle.osCatImage} source={{uri:cimgPath}}/>
                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(Category)}}>
                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                </TouchableOpacity>
                            </View>                                    
                        }                                
                    </View>
                </View>
                }
                { (rerenderdata==rerenderdata) &&
                    subCatData.map((item,index)=>{
                        const subcat=item;
                        const subcat_index=index;
                        let isSubCatCollapsed=subcat.isSubCatCollapsed!=null?subcat.isSubCatCollapsed:false;
                        
                        return(
                            <View style={customStyle.opening_Stock_wrap} key={'subcats_'+index}>
                                <View style={customStyle.opening_Stock_cat}>   
                                    <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr} onPress={()=>{toggleCollapse(subcat,index)}}>                  
                                        <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.SubCategoryName}</Text>
                                        </LinearGradient>
                                        {isSubCatCollapsed==true && <Entypo name={'chevron-down'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_catHdrIcon}/>}
                                        {isSubCatCollapsed==false && <Entypo name={'chevron-up'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_catHdrIcon}/>}
                                    </TouchableOpacity>  
                                </View>
                                { !isSubCatCollapsed &&
                                <View style={customStyle.prodCatsHdr_Stockprds}>
                                {(rerenderdata2==rerenderdata2) &&
                                subcat.skulist.map((item,index)=>{
                                        
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.ProductId==skus.ProductId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let stock=thisCatSkuData.Stock!=null?thisCatSkuData.Stock:'';
                                    let br_stock=thisCatSkuData.BackRoomStock!=null?thisCatSkuData.BackRoomStock:'';
        
                                    // let Old_Stock=thisCatSkuData.Old_Stock!=null?thisCatSkuData.Old_Stock:'';
                                    // let OldDamagedStock=thisCatSkuData.OldDamagedStock!=null?thisCatSkuData.OldDamagedStock:'';
                                    // let OldLostStock=thisCatSkuData.OldLostStock!=null?thisCatSkuData.OldLostStock:'';
                                    // let OldExStock=thisCatSkuData.OldExStock!=null?thisCatSkuData.OldExStock:'';
        
                                    let isSKUPresent=thisCatSkuData.isSKUPresent!=null?thisCatSkuData.isSKUPresent:0;
                                    let showAllSKU_Fields=thisCatSkuData.showAllSKU_Fields!=null?thisCatSkuData.showAllSKU_Fields:false;
                                    let ex_stock=thisCatSkuData.ExpiryStock!=null?thisCatSkuData.ExpiryStock:'';
                                    let damage_stock=thisCatSkuData.DamagedStock!=null?thisCatSkuData.DamagedStock:'';
                                    let lost_stock=thisCatSkuData.LostStock!=null?thisCatSkuData.LostStock:'';
                                    let mfdStocks=thisCatSkuData.mfdStocks || [];
                                    let NearExpiry_stock1=thisCatSkuData.NearExpiry1!=null?thisCatSkuData.NearExpiry1:'';
                                    let NearExpiry_stock2=thisCatSkuData.NearExpiry2!=null?thisCatSkuData.NearExpiry2:'';
                                    let NearExpiry_stock3=thisCatSkuData.NearExpiry3!=null?thisCatSkuData.NearExpiry3:'';
        
                                    let isMandatory=((isMSLAllow==1 || isMSLAllow=='true') && (skus.MSL==1 || skus.MSL=='true') ) || ((isNONMSL_Allow==1 || isNONMSL_Allow=='true') && (skus.MSL!=1 && skus.MSL!='true') ) 
        
                                    
                                    return(
                                        <View style={[customStyle.openStk_prd_Con,(isMandatory?{backgroundColor:PageTheme.$fifth_color}:{})]} key={sku_index}>
                                            {isListedSKUEnable==true && 
                                            <View style={customStyle.openStkP_checkboxWrap}>
                                                <View style={customStyle.openStkP_checkboxCon}>
                                                <CheckBox
                                                boxType='square'
                                                
                                                value={(isSKUPresent==1)}
                                                onValueChange={(val)=>{console.log('valchange:',val); let val1=(val==true)?1:0; onStockValChange(skus,val1,'isSKUPresent') }}
                                                style={[customStyle.openStkP_checkbox,(Platform.OS=='ios'?{height:20,width:20,marginTop:8,marginLeft:8,}:{})]}
                                                
                                                tintColors={{ true:PageTheme.$primary_color, false:PageTheme.$text_color_light }}
                                                />
                                                </View>
                                                <Text style={[customStyle.openStk_prd_name,customStyle.openStkP_checkbox_pName]}>{skus.ProductName}</Text>
                                            </View>
                                            }
        
                                            {isListedSKUEnable!=true && <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text>}
                                            {((isListedSKUEnable==true && showAllSKU_Fields==true) || isListedSKUEnable==false) && 
                                            <View style={customStyle.openStk_prd_form}>
                                                {(isStockEnable==true) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{isStockDis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder="" 
                                                            autoComplete='off'  
                                                            ref={(reff)=>{inputRefs.current['input1_'+item.ProductId]=reff;}}            
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(stock+'' || '')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'1')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'Stock','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(isBRStockEnable==true) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{isBRStockDis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""    
                                                            autoComplete='off'        
                                                            ref={(reff)=>{inputRefs.current['input2_'+item.ProductId]=reff;}}     
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(br_stock+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'2')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'BackRoomStock','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(isDStockEnable==true) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{isDStockDis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""      
                                                            autoComplete='off'      
                                                            ref={(reff)=>{inputRefs.current['input3_'+item.ProductId]=reff;}}
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(damage_stock+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'3')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'DamagedStock','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(isLStockEnable==true) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{isLStockDis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""      
                                                            autoComplete='off'      
                                                            ref={(reff)=>{inputRefs.current['input4_'+item.ProductId]=reff;}}   
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(lost_stock+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'4')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'LostStock','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(isExStockEnable==true ) &&
                                              
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{isExStockDis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""  
                                                            autoComplete='off'      
                                                            ref={(reff)=>{inputRefs.current['input5_'+item.ProductId]=reff;}}       
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(ex_stock+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'5')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'ExpiryStock','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                
                                                {(NrExpiry1Enable==true ) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{NrExpiry1_Dis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""  
                                                            autoComplete='off'  
                                                            ref={(reff)=>{inputRefs.current['input6_'+item.ProductId]=reff;}} 
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(NearExpiry_stock1+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'6')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'NearExpiry1','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(NrExpiry2Enable==true ) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{NrExpiry2_Dis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""   
                                                            autoComplete='off'  
                                                            ref={(reff)=>{inputRefs.current['input7_'+item.ProductId]=reff;}}             
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(NearExpiry_stock2+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onFocus={()=>{setOnFocus(item,'7')}}
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'NearExpiry2','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(NrExpiry3Enable==true ) &&
                                                <View style={[customStyle.openStk_prd_row,customStyle.mb10]}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{NrExpiry3_Dis_Name}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle]}              
                                                            placeholder=""  
                                                            autoComplete='off'          
                                                            ref={(reff)=>{inputRefs.current['input8_'+item.ProductId]=reff;}}     
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(NearExpiry_stock3+'')}
                                                            keyboardType='number-pad'
                                                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                            onSubmitEditing={()=>{focusToNext()}}
                                                            onChangeText={(val)=>{ onStockValChange(skus,val,'NearExpiry3','numeric')}}
                                                        />
                                                    </View>
                                                </View>
                                                }
                                                {(isMFDEnable==true) &&
                                                <View style={[customStyle.stk_mfdView,customStyle.mb10]}>
                                                    <Text style={customStyle.stk_mfdTbl_hd}>{isMFDDis_Name}</Text>
                                                    <TouchableOpacity style={customStyle.stk_addStockBtn} onPress={()=>{openAddStkModal(skus)}}>
                                                        <Text style={customStyle.stk_addStockBtnText}>Add</Text>
                                                    </TouchableOpacity>
                                                    <View style={customStyle.stk_mfdTblHeader}>
                                                        <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox1]}>
                                                        <Text style={customStyle.stk_mfdTblHeaderTxt}>Date</Text>
                                                        </View>
                                                        <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox2]}>
                                                        <Text style={customStyle.stk_mfdTblHeaderTxt}>Stock</Text>
                                                        </View>
                                                        <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox3]}>
                                                        <Text style={customStyle.stk_mfdTblHeaderTxt}>Lot No.</Text>
                                                        </View>
                                                        <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox4]}>
                                                        <Text style={customStyle.stk_mfdTblHeaderTxt}>Actions</Text>
                                                        </View>
                                                    </View>
                                                    
                                                    <View style={customStyle.stk_mfdTblBody}>
                                                        {
                                                            mfdStocks.map((mfd_Item,mfd_index)=>{
                                                                let mfd=mfd_Item.mfd || '';
                                                                let stock=mfd_Item.stock || '';
                                                                let lotno=mfd_Item.lotno || '';
                                                                
                                                                return(
                                                                <View key={'mfd'+mfd_index} style={[customStyle.stk_mfdTblrow,((index==mfdStocks.length-1)?customStyle.stk_mfdTblrow_last:{})]}>
                                                                    <View style={[customStyle.stk_mfdTblCol,customStyle.stk_mfdTblCol1]}>
                                                                        <Text style={customStyle.stk_mfdTblColText}>{mfd}</Text>
                                                                    </View>
                                                                    <View style={[customStyle.stk_mfdTblCol,customStyle.stk_mfdTblCol2]}>
                                                                        <Text style={customStyle.stk_mfdTblColText}>{stock}</Text>
                                                                    </View>
                                                                    <View style={[customStyle.stk_mfdTblCol,customStyle.stk_mfdTblCol3]}>
                                                                        <Text style={customStyle.stk_mfdTblColText}>{lotno}</Text>
                                                                    </View>
                                                                    <View style={[customStyle.stk_mfdTblCol,customStyle.stk_mfdTblCol4]}>
                                                                        <TouchableOpacity style={customStyle.stk_mfdTbl_DeleteBtn} onPress={()=>{showRemoveConfirm(skus,mfd_Item,mfd_index)}}>
                                                                            <Ionicons name='trash' color={PageTheme.$red} size={18} />
                                                                        </TouchableOpacity>
                                                                    </View>
                                                                </View>
                                                                )
                                                            })
                                                        }
                                                    </View>
                                                </View>
                                                }
                                            </View>
                                            }
                                        </View>
                                    )
                                })
                                }
                                </View>
                                }
                            </View>
                        );
                    })
                }
            </ScrollView>
            </KeyboardAvoidingView>   
        )
    }
    
    
   
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setShowRemoveConfirm_M(false)},removeMFDStock,'Do you really want to remove this stock?')}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {rerendermodal==rerendermodal && _render_StockModal()}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        <View style={customStyle.pageHdrWrap}>
            <Text style={customStyle.pageHdrWrapText}>{`Category: ${(Category.CategoryName!=null?(Category.CategoryName.length>40?Category.CategoryName.substring(0,40)+'...':Category.CategoryName):'')}`}</Text>
        </View>
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
            
            <View style={customStyle.storel_searchbar}>
                <TextInput 
                    style={[customStyle.storel_searchInput]}
                    placeholder="Search by Product Name"
                    autoComplete='off'
                    placeholderTextColor={PageTheme.$placeholder_color} 
                    value={searchedItem}
                    onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
                />
                <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                    <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
                </TouchableOpacity>
            </View>
            <View style={customStyle.colorDescriptionWrap}>
                <View style={customStyle.colorBoxCon}>
                    <View style={[customStyle.colorBox,customStyle.colorBox1]}></View>
                    <Text style={customStyle.colorDesc}>MSL (Mandatory)</Text>
                </View>
                <View style={customStyle.colorBoxCon}>
                    <View style={[customStyle.colorBox,customStyle.colorBox2]}></View>
                    <Text style={customStyle.colorDesc}>Non-MSL (Non-Mandatory)</Text>
                </View>
            </View>
            { Object.keys(storeData).length>0 &&     
                _renderStocks()
            }
        
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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