import React,{useState,useEffect} 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,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import CheckBox from '@react-native-community/checkbox';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert, ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import Accordion from 'react-native-collapsible/Accordion';
import DateTimePicker from '@react-native-community/datetimepicker';
import { createFalse } from 'typescript';
import CustomModal2 from '../components/CustomModal2';

function Stock(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [globalBrandData, setGlobalBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [currentStock, setCurrentStock] = useState({});
    const [currentBrand, setCurrentBrand] = useState({});
    const [currentProduct, setCurrentProduct] = useState({});
    const [KPIFields, setKPIFields] = useState([]);
    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 [toRemoveCat, setToRemoveCat] = 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 d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

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

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

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    async function getKPIFields(menu1){
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                let q=`select * from Mapping_MenuConfiguration where ScreenName='${menu1.ScreenName}'`;
                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 isenable=data.KPIFieldEnable=='true' || data.KPIFieldEnable==1?true:false;
                            data['KPIFieldEnable']=isenable;
                            
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                console.log('ALl KPIs Fields:',arr);
                                setKPIFields(arr);
                                resolve(true)
                            }
                        }
                    }
                    else{
                        resolve(true)
                    }
                },function (txn2, txnerr) { console.log(txnerr);resolve(false) },);
            });
        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log(err);
            return false;
        });
    }

    async function getData(storeData1,menu1){   
          
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          let allCats=[];
          let allSKUData=[];
          await getKPIFields(menu1);
          await db.transaction(async function (txn) {  

            // let dq=`DELETE FROM ${AppTables.STOCK2_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            // let dq2=`DELETE FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            // let dq3=`DELETE FROM ${AppTables.STOCK2_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');
            // },function (txn2, txnerr) { console.log(txnerr); },);

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

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


            
            let join=' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
            let join2=' INNER join Mapping_ProductAssortment mp on p.ProductId=mp.ProductId ';
            let q=`SELECT DISTINCT c.CategoryId,c.CategoryName from Master_Category c ${join} ${join2}  where mp.StateId='${StateId}' and mp.ChainId='${ChainId}' and mp.StoreTypeId='${StoreTypeId}' order by p.CategorySequence`;
            
            let q2=` SELECT CATEGORY_ID as CategoryId,CATEGORY as CategoryName,IMAGE,IMAGEPATH FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' 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 arr=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        data['isCollapsed']=false;
                        let br_d=await getBrands(storeData1,menu1,data,allSKUData);
                        let brands=br_d['brands'];
                        let products_data=br_d['products_data'];
                      
                        data['brandList']=brands;
                        let defData={'CategoryId':data.CategoryId,'ImageName':data.IMAGE,'ImagePath':data.IMAGEPATH};
                        
                        allCats.push(defData);
                        allSKUData.concat(products_data);
                        arr.push(data);
                        if(i==txnres.rows.length-1){
                            setCatImages(allCats);
                            setSKUStockData(allSKUData);
                            setBrandData(arr);
                            setGlobalBrandData(arr);
                            setTimeout(()=>{setrerenderdata2(!rerenderdata2);},3000);
                            setProcessing(false);
                        }
                    }
                }
                else{
                    await txn.executeSql(q,[],async function (txn2, txnres2) { 
                        console.log('cats len:',txnres2.rows.length)
                        if(txnres2.rows.length>0){
                            let arr=[];
                            for(var i=0;i<txnres2.rows.length;i++){
                                let data =txnres2.rows.item(i);
                                data['isCollapsed']=false;
                                let br_d=await getBrands(storeData1,menu1,data);
                                let brands=br_d['brands'];
                                let products_data=br_d['products_data'];
                               
                                data['brandList']=brands;

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

                                if(i==txnres2.rows.length-1){
                                    setSKUStockData(allSKUData);
                                   
                                    setBrandData(arr);
                                    setGlobalBrandData(arr);
                                    setTimeout(()=>{setrerenderdata2(!rerenderdata2);},3000);
                                    setProcessing(false);
                                    
                                }                                
                            }
                            
                        }
                    },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); },);
                }
            },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); },);
            // setProcessing(false);
            
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getBrands(storeData1,menu1,item,allSKUData=[]){
        let data_to_ret={'brands':[],'products_data':allSKUData}
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;

      
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
            
                let join=`  inner join Mapping_ProductAssortment m on p.ProductId=m.ProductId `;
                let join2=` inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                let brands_q=`select distinct p.BrandName,p.BrandId from Product_Master p  ${join} ${join2} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}'  and p.CategoryId='${item.CategoryId}' and CompanyId='1' order by p.ProductSequence`;
                
                
                await txn.executeSql(brands_q,[],async function (txn2, txnres) { 
                    console.log('brands 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['isBrandCollapsed']=false;
                            let pr_d=await getSKU(storeData1,item,data,allSKUData);
                            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){
                                data_to_ret['brands']=arr;
                                data_to_ret['products_data']=allSKUData;
                                resolve(data_to_ret);
                            }
                        }
                    }
                    else{
                        resolve(data_to_ret)
                    }
                },function (txn2, txnerr) { console.log(txnerr); resolve(data_to_ret) },);
                // setProcessing(false);
                
              });  
        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log(err);
            return data_to_ret;
        })
    }

    async function getSKU(storeData1,cat,brand,allSKUData=[]){
        let sku_ret={'products':[],'products_data':allSKUData};
        let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData1;     
        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,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.STOCK2_DATA} WHERE STORE_ID='${StoreId}' and  CATEGORY_ID='${cat.CategoryId}' and BRAND_ID='${brand.BrandId}'  `;
         
                // else get products from masters
                let join=`  inner join Mapping_ProductAssortment 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,m.MSL from Product_Master p  ${join} ${join2} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' and p.CategoryId='${cat.CategoryId}' and p.BrandId='${brand.BrandId}' and CompanyId='1' order by p.ProductSequence`;
                     
                
              
                await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                    
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            
                            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={'CategoryId':cat.CategoryId,'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};
                            
                            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);
                                    let defData={'CategoryId':cat.CategoryId,'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 (txn2, txnerr) { console.log(txnerr); setProcessing(false); resolve(sku_ret); },);
                    }
                },function (txn2, 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 (txn2, 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(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl='file://'+img.uri, imgWidth=img.width, imgHeight=img.height;
           
            
            let picture_clicked_time=new Date();
            picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
            
            
            const mark_text1=picture_clicked_time;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Stock'+' | Date:'+picture_clicked_time;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let picture_clickedd=new Date();
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_Stock-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            
                            let allIMgs=catImages;
                            let defData={'CategoryId':cat.CategoryId};
                            const cindex=allIMgs.findIndex(i=>i.CategoryId==cat.CategoryId);
                            const imgData=cindex>=0?(allIMgs[cindex] || defData):defData;
                            imgData.ImageName=filename;
                            
                            // renamefile
                            let imagePath='file://'+`${common_ImagePath}${filename}`;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri=imagePath;
                                console.log('image marker',uri);
                                imgData.ImagePath=uri; 
                                cindex>=0?allIMgs[cindex]=imgData:allIMgs.push(imgData);
                                setCatImages(allIMgs);
                                setHasUnsavedChanges(true);
                                setrerenderdata(!rerenderdata);
                            })
                            .catch(err => {
                                console.log(ST.Errorimagefilewritefailed+'!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(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){
           setShowAlert(true);
        }
    }

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   

              let q=`DELETE FROM ${AppTables.STOCK2_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q2=`DELETE FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q3=`DELETE FROM ${AppTables.STOCK2_MFD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('stock data deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);

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

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


              let seq_q=` select seq from sqlite_sequence where name="${AppTables.STOCK2HDR_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 (txn2, 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='';
              for(var i=0;i<globalBrandData.length;i++){
                  
                seq++;
                let catIndex=i;
                let item=globalBrandData[catIndex];
                let cimage=catImages.find(ci=>ci.CategoryId==item.CategoryId) || {};
                values+=values!=''?' , ':'';
                
                
                values+=` ('${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','','${(cimage.ImageName || '')}','${(cimage.ImagePath || '')}','${d2}') `;
                console.log('stock hdr values added');

                let brandList=item.brandList || [];
                for(var j=0;j<brandList.length;j++){
                    let brand=brandList[j];

                    let skulist=brand['skulist'] || [];
               
                    for(var k=0;k<skulist.length;k++){
                        let skuItem=skulist[k];
                        let SKU_UID='SKU'+seq+j+k+(Math.floor(Math.random()*1000)+1);
                        let {BrandId, BrandName,MSL,ProductId,ProductName}=skuItem;
                        stock_values+=stock_values!=''?' , ':'';
                        let allSKUData=SKUStockData;
                        const skud_index=allSKUData.findIndex(ci=>ci.CategoryId==item.CategoryId && 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}','${item.CategoryId}','${item.CategoryName}','${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.STOCK2HDR_DATA} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.STOCK2_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,CATEGORY_ID,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.STOCK2_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(ST.Stockupdatedsuccessfully);
                            setProcessing(false);
                            props.navigation.goBack();
                        },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddstock) },);
                    }
                    else{
                        notify(ST.Stockupdatedsuccessfully);
                        setProcessing(false);
                        props.navigation.goBack();
                    }
                    
                },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddstock) },);
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddstock) },);
              
            });          
        } 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']:'';

        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;

        

        await Promise.all(
            globalBrandData.map(async (item,index) => {
            if(isValid){
                let catId=item.CategoryId;
                
                let cimgData=catImages.find(ci=>ci.CategoryId==catId) || {};

                
                // let isCollapsed=item.isCollapsed!=null?item.isCollapsed:true;
                
                if(isHdrImgEnable==true && (cimgData.ImagePath== null || cimgData.ImagePath=='')){
                    notify(ST.Pleaseclickimagefor+' '+item.CategoryName,'SHORT');
                    isValid=false;
                }
                else{
                    let brandList=item.brandList || [];
                    
                    if(brandList.length>0){
                        brandList.map(async (brand,brand_index) => {
                            let skulist=brand.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.CategoryId==item.CategoryId && 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(ST.Pleaseenter+' '+isStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(isBRStockEnable==true && br_stock!==0 && ( br_stock==null || br_stock=='')){
                                                notify(ST.Pleaseenter+' '+isBRStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(isDStockEnable==true && damage_stock!==0 && ( damage_stock==null || damage_stock=='')){
                                                notify(ST.Pleaseenter+' '+isDStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(isLStockEnable==true && lost_stock!==0 && ( lost_stock==null || lost_stock=='')){
                                                notify(ST.Pleaseenter+' '+isDStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(isExStockEnable==true && ex_stock!==0 && ( ex_stock==null || ex_stock=='')){
                                                notify(ST.Pleaseenter+' '+isExStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(NrExpiry1Enable==true && NearExpiry_stock1!==0 && ( NearExpiry_stock1==null || NearExpiry_stock1=='')){
                                                notify(ST.Pleaseenter+' '+NrExpiry1_Dis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(NrExpiry2Enable==true && NearExpiry_stock2!==0 && ( NearExpiry_stock2==null || NearExpiry_stock2=='')){
                                                notify(ST.Pleaseenter+' '+NrExpiry2_Dis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(NrExpiry3Enable==true && NearExpiry_stock3!==0 && ( NearExpiry_stock3==null ||NearExpiry_stock3=='')){
                                                notify(ST.Pleaseenter+' '+NrExpiry3_Dis_Name+' '+ST.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+' '+ST.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+' '+ST.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+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                            //     isValid=false;
                                            // }
                                            else{

                                            }
                                          
                                        }
                                        }
                                    })
                                );
                            }
                            }

                        });
                    }
                    
                }
            }
            })
        );

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

    function onStockValChange(item,skuItem,val,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify(ST.Pleaseenterwholenumbersonly,'SHORT');
                return;
            }
        }

        let allSKUData=SKUStockData;
        let defData={'CategoryId':item.CategoryId,'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;
        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={'CategoryId':item.CategoryId,'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(cat,skuItem){
        setCurrentBrand(cat);
        setCurrentProduct(skuItem);
        let allSKUData=SKUStockData;
        let defData={'CategoryId':cat.CategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==cat.CategoryId && 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(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify(ST.Pleaseenterwholenumbersonly,'SHORT');
                return;
            }
        }
        
        let cstock=currentStock;
        cstock[key]=val;
        console.log(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 cat=currentBrand
        let skuItem=currentProduct
        let cstock=currentStock;
        var allSKUData=SKUStockData;
        let defData={'CategoryId':cat.CategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==cat.CategoryId && i.ProductId==skuItem.ProductId);
        var skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        let mfdStocks=skud['mfdStocks'] || [];
        let product_total_stock=skud['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);
        let {mfd,date,stock,lotno}=cstock


        

        if(mfd==null || mfd==''){
            notify(ST.Pleaseselectdate);
            return ;
        }
        else if(stock==null || stock==''){
            notify(ST.Pleaseenterstock);
            return ;
        }
        else if(lotno==null || lotno==''){
            notify(ST.Pleaseenterlotno);
            return ;
        }
        else if(mfdStocks.findIndex(i=>i.mfd==mfd)>=0){
            notify(ST.ThisdateisalreadyaddedPleaseselectdifferentdate);
            return ;
        }
        else {
            // let sumOfAllStocks=await getAllSum(mfdStocks,cstock);
            // console.log('product_stock',product_stock,',sum:',sumOfAllStocks,JSON.stringify(SKUStockData))
            // if(product_stock!==0 && (product_stock==null || product_stock=='')){
            //     notify('Please enter sku stock');
            //     return ;
            // }
            // else if(sumOfAllStocks>product_stock){
            //     notify('Sum of all MFD stock cannot be greater than product stock count!');
            //     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 cat=toRemoveCat;
        let skuItem=toRemoveSKU;
        let cstockIndex=toRemoveId;
        let allSKUData=SKUStockData;
        let defData={'CategoryId':cat.CategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==cat.CategoryId && 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(cat,skuItem,cstock,cstockIndex){
        setToRemoveId(cstockIndex);
        setToRemoveCat(cat);
        setToRemoveSKU(skuItem);
        setShowRemoveConfirm_M(true);
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2={};
        var newBrand={};
        if(searchedQry!=null && searchedQry!=''){
            // globalBrandData.map((item,index)=>{
            for(let i=0;i<globalBrandData.length;i++){
                let item=globalBrandData[i];
                let brandList=item.brandList || [];
                arr2={ 'CategoryId':item.CategoryId,'CategoryName':item.CategoryName,"MSL":item.MSL,"IMAGE":(item.IMAGE || ''),'IMAGEPATH':(item.IMAGEPATH || ''),'isCollapsed':item.isCollapsed};
                
                let newBrandList=[];
                for(let j=0;j<brandList.length;j++){
                    let brand=brandList[j];
                    let skulist=brand.skulist || [];
                    newBrand={'BrandName':brand.BrandName,'BrandId':brand.BrandId,'isCollapsed':brand.isBrandCollapsed };

                    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){
                            newBrand.skulist=newSkulist;
                            
                            if(newBrand.skulist.length>0){
                                newBrandList.push(newBrand);
                                if(j==brandList.length-1){
                                    arr2.brandList=newBrandList;
                                    arr.push(arr2);
                                }
                            }

                        }
                    }
                }

                
            }
        }
        else{
          arr=globalBrandData;
        }

        console.log('globalBrandData:',globalBrandData)
        setBrandData(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={ST.AddNearExpiryStock}
            showModal={showStockModal}
          >
            <View style={customStyle.AddStockM_View}>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{ST.ExpiryDate}</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}>{ST.Stock}</Text>
                    <View style={customStyle.AddStockM_col} >
                        <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            keyboardType={'number-pad'}
                            value={stock}
                            onChangeText={(val)=>{setCS_Stock('stock',val,'numeric')}}
                            autoComplete='off'
                        />
                    </View>
                </View>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{ST.LotNo}</Text>
                    <View style={customStyle.AddStockM_col} >
                        <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            // keyboardType={'number-pad'}
                            value={lotno}
                            onChangeText={(val)=>{setCS_Stock('lotno',val,'')}}
                            autoComplete='off'
                        />
                    </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]}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[customStyle.storelVisitM_op_btn,customStyle.AddStockM_Btn]} onPress={()=>{addMFDStock()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>{ST.Add}</Text>
              </TouchableOpacity>
            </View>
            
          </CustomModal2>
        )
     }

    
    function toggleCollapse(cat={},catIndex){
        let allData=brandData;
        let isCollapsed=cat.isCollapsed;
        cat['isCollapsed']=!isCollapsed;
        allData[catIndex]=cat;
        setBrandData(allData);
        setGlobalBrandData(allData);
        setrerenderdata(!rerenderdata);
    }


    function toggleCollapse2(cat={},catIndex,brand={},brand_index){
        let allData=brandData;
        let isBrandCollapsed=brand.isBrandCollapsed;
        let brandList=cat.brandList || [];
        console.log('already brandList len:',brandList.length);
        brand['isBrandCollapsed']=!isBrandCollapsed;
        brandList[brand_index]=brand;
        cat['brandList']=brandList;
        allData[catIndex]=cat;
        setBrandData(allData);
        setGlobalBrandData(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']: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']:'';
        
        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']:'';

        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']:true;

        

        // isMandatory=true;


        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-100} >  
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                const cindex=catImages.findIndex(i=>i.CategoryId==item.CategoryId);
                const cimgName=cindex>=0?(catImages[cindex]?catImages[cindex].ImageName:''):'';
                const cimgPath=cindex>=0?(catImages[cindex]?catImages[cindex].ImagePath:''):'';
                const showIMg=cimgPath!='' && cimgPath!=null;

                console.log('brand render:',item.brandList.length);

                let isCollapsed=cat.isCollapsed!=null?item.isCollapsed:false;
               
                // let isHdrImgDis_Name=isHdrImgIndex>=0?isHdrImgKPIObj['KPIFieldDisplayName']:'';
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>   
                            <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr} onPress={()=>{toggleCollapse(cat,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.CategoryName}</Text>
                                </LinearGradient>
                                {isCollapsed==true && <Entypo name={'chevron-down'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_catHdrIcon}/>}
                                {isCollapsed==false && <Entypo name={'chevron-up'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_catHdrIcon}/>}
                            </TouchableOpacity>       
                            {( !isCollapsed && isHdrImgEnable==true) && 
                            <View style={customStyle.osCat_actions}>
                                
                                { !showIMg && 
                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(item)}}>
                                        <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                    </TouchableOpacity>
                                }
                                { showIMg && 
                                    <View style={customStyle.osCatImageView}>
                                        <Image style={customStyle.osCatImage} source={{uri:cimgPath}}/>
                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(item)}}>
                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                        </TouchableOpacity>
                                    </View>                                    
                                }                                
                            </View>}
                        </View>
                        { !isCollapsed &&
                            item.brandList!=null && item.brandList.length>0 && 
                            item.brandList.map((brand,brand_index)=>{
                                let isBrandCollapsed=brand.isBrandCollapsed!=null?brand.isBrandCollapsed:false;
                                console.log('brand render:',brand.BrandName,', cat:',item.CategoryName);

                                return (
                                    <View key={brand_index+'_brands'}>
                                        <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_SubCatHdr} onPress={()=>{toggleCollapse2(cat,index,brand,brand_index)}}>                  
                                            <LinearGradient colors={[PageTheme.$bg_color,PageTheme.$fourth_color,PageTheme.$bg_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_SubCatInner}>
                                                <Text style={customStyle.opening_Stock_SubCatText}>{brand.BrandName}</Text>
                                            </LinearGradient>
                                            {isBrandCollapsed==true && <Entypo name={'chevron-down'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_SubCatIcon}/>}
                                            {isBrandCollapsed==false && <Entypo name={'chevron-up'} color={PageTheme.$text_color} size={20} style={customStyle.opening_Stock_SubCatIcon}/>}
                                        </TouchableOpacity>
                                       
                                        <View style={customStyle.opening_Stock_prds}>
                                        { !isBrandCollapsed &&
                                            
                                            <FlatList 
                                            data={brand.skulist}
                                            extraData={rerenderdata2}
                                            listKey={(i,skuIndex)=>{ return skuIndex;}}
                                            renderItem={({item,index})=>{
                                                
                                            const skus=item;
                                            const sku_index=index;
                                            let thisCatSkuData_i=SKUStockData.findIndex(i=>i.CategoryId==cat.CategoryId && 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') ) 

                                            // console.log('skus.MSL:',skus.MSL);

                                            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(cat,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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(stock+'' || '')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'Stock','numeric')}}
                                                                    autoComplete='off'
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'Stock','Old_Stock',Old_Stock)}}
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(br_stock+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'BackRoomStock','numeric')}}
                                                                    autoComplete='off'
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'Stock','Old_Stock',Old_Stock)}}
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(damage_stock+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'DamagedStock','numeric')}}
                                                                    autoComplete='off'
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'DamagedStock','OldDamagedStock',OldDamagedStock)}}
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(lost_stock+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'LostStock','numeric')}}
                                                                    autoComplete='off'
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'LostStock','OldLostStock',OldLostStock)}}
                                                                />
                                                            </View>
                                                        </View>
                                                        }
                                                        {(isExStockEnable==true ) &&
                                                        // && !isMFDEnable
                                                        <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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(ex_stock+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'ExpiryStock','numeric')}}
                                                                    autoComplete='off'
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'ExpiryStock','OldExStock',OldExStock)}}
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock1+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry1','numeric')}}
                                                                    autoComplete='off'
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock2+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry2','numeric')}}
                                                                    autoComplete='off'
                                                                />
                                                            </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=""            
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock3+'')}
                                                                    keyboardType='number-pad'
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry3','numeric')}}
                                                                    autoComplete='off'
                                                                />
                                                            </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(cat,skus)}}>
                                                                <Text style={customStyle.stk_addStockBtnText}>{ST.Add}</Text>
                                                            </TouchableOpacity>
                                                            <View style={customStyle.stk_mfdTblHeader}>
                                                                <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox1]}>
                                                                <Text style={customStyle.stk_mfdTblHeaderTxt}>{ST.Date}</Text>
                                                                </View>
                                                                <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox2]}>
                                                                <Text style={customStyle.stk_mfdTblHeaderTxt}>{ST.Stock}</Text>
                                                                </View>
                                                                <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox3]}>
                                                                <Text style={customStyle.stk_mfdTblHeaderTxt}>{ST.LotNo}</Text>
                                                                </View>
                                                                <View style={[customStyle.stk_mfdTblHeaderBox,customStyle.stk_mfdTblHeaderBox4]}>
                                                                <Text style={customStyle.stk_mfdTblHeaderTxt}>{ST.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(cat,skus,mfd_Item,mfd_index)}}>
                                                                                    <Ionicons name='trash' color={PageTheme.$red} size={18} />
                                                                                </TouchableOpacity>
                                                                            </View>
                                                                        </View>
                                                                        )
                                                                    })
                                                                }
                                                            </View>
                                                        </View>
                                                        }
                                                    </View>
                                                    }
                                                </View>
                                            )
                                            }}/>
                                        }
                                    </View>
                                    </View>
                                )
                            })
                        }
                        
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>   
        )
    }
    
    
   
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setShowRemoveConfirm_M(false)},removeMFDStock,ST.Doyoureallywanttoremovethisstock)}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {rerendermodal==rerendermodal && _render_StockModal()}
        <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                placeholder={ST.SearchByProductName}
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
                autoComplete='off'
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View>
          { Object.keys(storeData).length>0 &&     
              _renderStocks()
          }
        
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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