import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, KeyboardAvoidingView, BackHandler, Keyboard, Animated, AppState} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath, HierarchyTbls} 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 { 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 StockQRCode(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(false);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    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 [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [showStockModal, setShowStockModal] = useState(false);
    const [showDatePicker, setShowDatePicker] = useState(false);
    const [rerendermodal, setrerendermodal] = useState(0);
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveCat, setToRemoveCat] = useState({});
    const [toRemoveSKU, setToRemoveSKU] = useState({});
    const [showRemoveConfirm_M, setShowRemoveConfirm_M] = useState(false);
    const [searchedItem, setSearchedItem]= useState('');

    const [AddVisFormData, setAddVisFormData] = useState({});
    const [QREnable, setQREnable] = useState(false);
    const [QRqtnData, setQRqtnData] = useState({});
    const [showQRCamera, setShowQRCamera] = useState(false);
     const [products, setProducts] = useState([]);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [activeSections,setActiveSections]= useState([]);
    const [ShowCatWise,setShowCatWise]= useState(false);
    const [CatData,setCatData]= useState(false);
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");
    const inputRefs = useRef({});
    const outerFlatListRef = useRef(null);
    const middleFlatListRefs = useRef({});
    const innerFlatListRefs = useRef({});

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(SKUStockData);
    const WindowDataImgRef = React.useRef(catImages);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    const PSGroupData=React.useRef(''); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
    const BGPSAllow=React.useRef(false);

    
    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 ShowCatWise1=params.ShowCatWise!=null?params.ShowCatWise:false;
        let CatData1=params.CatData!=null?params.CatData:{};
        let isAdhoc=params.isAdhoc || false;

        console.log('params.ShowCatWise',params.ShowCatWise);

        setIsAdhocScreen(isAdhoc);
        setShowCatWise(ShowCatWise1);
        setCatData(CatData1);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        // getData(storeData1,menu1,ShowCatWise1,CatData1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(SKUStockData,pro)});
            return unsubscribe;
        };
       
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               visiteDate:d2,
               BGPSAllow:BGPSAllow.current,
               PSGroupData:PSGroupData.current,
           }
           let WindowsStr= JSON.stringify(newData)
           console.log("checkwindata:",WindowsStr)
           await set_item('storeData',WindowsStr); 

           let newDataForSubCateory ={
            storeBGDataHdr:WindowDataImgRef.current,
            menuName:ScreenNameRef.current,
            StoreId1:StoreIdRef.current,
            visiteDate:d2,
            BGPSAllow:BGPSAllow.current,
            PSGroupData:PSGroupData.current,
           }
           let WindowsStr2= JSON.stringify(newDataForSubCateory)
           console.log("checkwindatahdr:",WindowsStr2)
           await set_item('storeDataHdr',WindowsStr2); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
        // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
        // AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    }, [hasUnsavedChanges]);  
    
    // useEffect(() => {
    //     AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    //     AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    // }, [SKUStockData]); 
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }

    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val){
        WindowDataRef.current=val
        setSKUStockData(val);
    }

    function BgWindowDataHdr(val){
        WindowDataImgRef.current=val
        setCatImages(val);
    }


    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

   

    async function getData(storeData1,menu1,ShowCatWise1,CatData1={},QRcode){   
        try {  
            console.log("Qrcode---:",QRcode) 
            // let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
            // let allCats=[];
            // let allSKUData=[];
            // let AllKPIFields=await getKPIFields(menu1);
            // setKPIFields(AllKPIFields);

            // // set switch camera flag as defined in mapping menu flag (if exists)
            // let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
            // let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
            // let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
            // setShowSwitchCamera(SwitchingCamera);

            // let {PSAllow,PSTableName}=menu1;
            // PSTableName=PSTableName!=null?PSTableName:'';
            // PSAllow=PSAllow!=null?PSAllow:false;
       

            // //storeBGData check
            // let storeBGData1=[],bgStoreJson={},isBgDataExists=false;
            // let windData = await get_item('storeData')
            // console.log("windowdataaa--",windData)
            // if(windData!=null && windData!=''){
            //     let StoreJson = JSON.parse(windData)
            //     let { storeBGData,menuName,StoreId1,visiteDate }= StoreJson
            //     if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
            //         isBgDataExists=true;
            //         storeBGData1=storeBGData;
            //         bgStoreJson=StoreJson
            //         // setSKUStockData(storeBGData);
            //         BgUnsavedChanges(true)
            //         BgWindowData(storeBGData);
            //     }
            // }

            //  //storeBGData check for SubCategoryImg
            //  let storeBGData2=[],bgStoreJson2={},isBgDataExists2=false;
            //  let windData2 = await get_item('storeDataHdr')
            //  console.log("windowdata--",windData2)
            //  if(windData2!=null && windData2!=''){
            //      let StoreJson2 = JSON.parse(windData2);
            //      let { storeBGDataHdr,menuName,StoreId1,visiteDate }= StoreJson2
            //      if(storeBGData2.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
            //          isBgDataExists2=true;
            //          storeBGData2=storeBGDataHdr;
            //          bgStoreJson2=StoreJson2
            //          // setSKUStockData(storeBGData);
            //          BgUnsavedChanges(true)
            //          BgWindowDataHdr(storeBGDataHdr);
            //      }
            //  }

            // //  call this after storeBGData check
            // if(PSAllow){
            //     // if Partial save is allowed then add the currently active category or group in BG var 
            //     BGPSAllow.current=true;
            //     PSGroupData.current=CatData1;
            // }
          
            // await db.transaction(async function (txn) {  

            //     let orderBy='',idCol='',nameCol='';
                
            //     if(PSTableName.toLowerCase()==HierarchyTbls.Master_Category.toLowerCase()){
            //         idCol='CategoryId',nameCol='CategoryName';
            //         orderBy=' CategorySequence ';
            //     }
            //     else if(PSTableName.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()){
            //         idCol='BrandId',nameCol='BrandName';
            //         orderBy=' BrandSequence ';
            //     }
            //     else {
            //         idCol='SubCategoryId',nameCol='SubCategoryName';
            //         orderBy=' SubCategorySequence ';
            //     }
            //     let IdVal=CatData1[idCol];
            //     let NameVal=CatData1[nameCol];
            //     setColId(idCol);
            //     setColName(nameCol);


               
            //     let COMPStockAllow_Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='COMPStockAllow');
            //     let COMPStockAllow_Obj=COMPStockAllow_Index>=0?AllKPIFields[COMPStockAllow_Index]:{};
            //     let isCOMPStockAllow=COMPStockAllow_Index>=0?COMPStockAllow_Obj['KPIFieldEnable']:false;


            //     let join='',join2='',join3='',q='',q2='';
                
                
            //     // if(ShowCatWise1==true){
            //      console.log("idcolumnnn---",idCol)

            //     join=`  inner join Mapping_ProductAssortment m on p.ProductId=m.ProductId `;
            //     join2=` inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
            //     join3=` Left Outer Join ${AppTables.STOCK2HDR_DATA} st on st.SUB_CATEGORY_ID=p.${idCol} and st.STORE_ID='${StoreId}' and st.VISIT_DATE='${d2}' `;
            //     q=`select distinct p.${idCol} as SubCategoryId,p.${nameCol} as SubCategoryName,st.IMAGE,st.IMAGEPATH from Product_Master p  ${join} ${join2} ${join3} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and p.ProductCode= '${QRcode}' and m.StoreTypeId='${StoreTypeId}' and m.StoreCategoryId='${StoreCategoryId}' and m.StoreClassId='${StoreClassId}' ${(isCOMPStockAllow==true?'':` and p.IsCompetitor='0' `)} `;
            //     if(ShowCatWise1==true){
            //         console.log("showcatewise:",ShowCatWise1)
            //         q+=` and p.${idCol}='${IdVal}' `;
            //     }
            //     q+=` order by p.IsCompetitor,p.${nameCol}`;
                
            //     // q2=` SELECT SUB_CATEGORY_ID as SubCategoryId,SUB_CATEGORY as SubCategoryName,IMAGE,IMAGEPATH FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                
            //     console.log('ShowCatWise1:',ShowCatWise1,q);

            //     await txn.executeSql(q,[],async function (txn2, txnres) { 
            //         console.log('added products subcats:',txnres.rows.length)
            //         if(txnres.rows.length>0){
            //             let arr=[];
            //             for(var i=0;i<txnres.rows.length;i++){
            //                 let data =txnres.rows.item(i);
            //                 console.log("dataaa:",data)
            //                 data['isCollapsed']=false;
                        

            //                 let br_d=await getBrands(storeData1,menu1,data,allSKUData,AllKPIFields,idCol,nameCol,CatData1,ShowCatWise1,QRcode);
            //                 let brands=br_d['brands'];
            //                 let products_data=br_d['products_data'];
                        
            //                 data['brandList']=brands;
            //                 let defData={'SubCategoryId':data.SubCategoryId,'ImageName':data.IMAGE,'ImagePath':data.IMAGEPATH};  

            //                 allCats.push(defData);
            //                 allSKUData.concat(products_data);
                            
            //                 arr.push(data);
            //                 if(i==txnres.rows.length-1){
            //                     if(!isBgDataExists){
            //                         BgWindowData(allSKUData)
            //                     }


            //                     // setCatImages(allCats);
            //                     // setSKUStockData(allSKUData);
            //                     setBrandData(arr);
            //                     setGlobalBrandData(arr);
            //                     setTimeout(()=>{setrerenderdata2(!rerenderdata2);},3000);
            //                     setProcessing(false);
            //                 }
            //             }
            //         }
            //         else{
            //             setProcessing(false);
            //             notify("No Data Found!");
            //         }
            
            //     },function (txnE,txnerr) { console.log('qerr:',txnerr);setProcessing(false); },);
            //     // setProcessing(false);
                
            // });          
        } catch (err) {
          console.log(err);          
        }        
    }

    // async function getBrands(storeData1,menu1,item,allSKUData=[],AllKPIFields,idCol,nameCol,CatData1={},ShowCatWise1=false,QRcode){

    //     console.log("yessssss",QRcode)
      
    //     // If Partial save is allowed  then pick the filter data id else pick the Subcaetgroy Id (default)
    //     let IdVal=ShowCatWise1?CatData1[idCol]:item[idCol];
    //     let NameVal=ShowCatWise1?CatData1[nameCol]:item[nameCol];

    //     let data_to_ret={'brands':[],'products_data':allSKUData}
    //     let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;

    //     let COMPStockAllow_Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='COMPStockAllow');
    //     let COMPStockAllow_Obj=COMPStockAllow_Index>=0?AllKPIFields[COMPStockAllow_Index]:{};
    //     let isCOMPStockAllow=COMPStockAllow_Index>=0?COMPStockAllow_Obj['KPIFieldEnable']:false;
      
    //     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, p.IsCompetitor from Product_Master p  ${join} ${join2} where m.ChainId='${ChainId}' and p.ProductCode='${QRcode}' and m.StateId='${StateId}' and m.StoreCategoryId='${StoreCategoryId}' and m.StoreClassId='${StoreClassId}' and m.StoreTypeId='${StoreTypeId}'  and p.${idCol}='${IdVal}' ${(isCOMPStockAllow==true?'':` and p.IsCompetitor='0' `)}  order by p.IsCompetitor, p.BrandName`;
                
               
    //             await txn.executeSql(brands_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['isBrandCollapsed']=false;
    //                         let pr_d=await getSKU(storeData1,item,data,allSKUData,AllKPIFields,idCol,nameCol,CatData1,ShowCatWise1,QRcode);
    //                         console.log('pr_d:',pr_d['products'].length,data);
    //                         let products=pr_d['products'];
    //                         let products_data=pr_d['products_data'];
    //                         data['skulist']=products

    //                         console.log('products len:',products.length);
    //                         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 (txnE,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=[],AllKPIFields,idCol,nameCol,CatData1={},ShowCatWise1=false,QRcode){

    //     // If Partial save is allowed  then pick the filter data id else pick the Subcaetgroy Id (default)
    //     let IdVal=ShowCatWise1?CatData1[idCol]:cat[idCol];
    //     let NameVal=ShowCatWise1?CatData1[nameCol]:cat[nameCol];
        
    //     let sku_ret={'products':[],'products_data':allSKUData};
    //     let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock,StoreClassId,StoreCategoryId}=storeData1;

    //     let DefaultStockToggleI=AllKPIFields.findIndex(i=>i.KPIFieldName=='DefaultStockToggle')
    //     let DefaultStockToggleObj=DefaultStockToggleI>=0?AllKPIFields[DefaultStockToggleI]:{};
    //     let DefaultStockToggle=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldEnable']:false;
    //     let DefaultStockToggleValue=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldDisplayName']:"2";
    //     let deftogvalue=DefaultStockToggleValue=="3"?"3":(DefaultStockToggle=="1"?"1":"0");
        

    //     let COMPStockAllow_Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='COMPStockAllow');
    //     let COMPStockAllow_Obj=COMPStockAllow_Index>=0?AllKPIFields[COMPStockAllow_Index]:{};
    //     let isCOMPStockAllow=COMPStockAllow_Index>=0?COMPStockAllow_Obj['KPIFieldEnable']:false;

    //     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 join5=`  Left Outer join (select * from ${AppTables.STOCK2_DATA} where SUB_CATEGORY_ID='${cat.SubCategoryId}' and BRAND_ID='${brand.BrandId}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}' ) st on st.PRODUCT_ID=p.ProductId`;
    //             let seletlist=`Distinct st.STOCK_UID,p.ProductName,p.ProductCode,p.ProductId,p.BrandName,p.BrandId,p.IsCompetitor,m.MSL,m.MBQ,st.STOCK,st.BACKROOM_STOCK,st.DAMAGED_STOCK,st.LOST_STOCK,st.EXPIRY_STOCK,st.IS_SKU_STOCK_PRESENT,st.NREXPIRY1_STOCK,st.NREXPIRY2_STOCK,st.NREXPIRY3_STOCK,st.OUT_OF_STOCK,st.LESS_THAN_MBQ`;
    //             let sku_q2=`select ${seletlist} from Product_Master p  ${join} ${join2} ${join5} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreCategoryId='${StoreCategoryId}' and p.ProductCode='${QRcode}' and m.StoreClassId='${StoreClassId}' and m.StoreTypeId='${StoreTypeId}' `;
    //             sku_q2+=idCol!='BrandId'?` and p.${idCol}='${IdVal}' `:'';
    //             sku_q2+=` and p.BrandId='${brand.BrandId}' ${(isCOMPStockAllow==true?'':` and p.IsCompetitor='0' `)} order by p.ProductSequence`;
     
                
    //             console.log("sku_q2:",sku_q2);

    //             await txn.executeSql(sku_q2,[],async function (txn2, txnres) { 
                   
    //                 if(txnres.rows.length>0){
    //                     let arr=[];
    //                     for(var i=0;i<txnres.rows.length;i++){
    //                         let data =txnres.rows.item(i);
    //                         let ancval=data.OUT_OF_STOCK==1?1:0;
    //                         let ancval2=data.LESS_THAN_MBQ==1?1:0;
    //                         let animatedChoice=new Animated.Value(ancval);
    //                         let animatedChoice2=new Animated.Value(ancval2);
    //                         data.animatedChoice=animatedChoice;
    //                         data.animatedChoice2=animatedChoice2;
                            
    //                         setInputRefss(AllKPIFields,cat,brand,data);


    //                         data['Old_Stock']=(data.STOCK || '');
    //                         data['OldDamagedStock']=(data.DAMAGED_STOCK || '');
    //                         data['OldLostStock']=(data.LOST_STOCK || '');
    //                         data['OldExStock']=(data.EXPIRY_STOCK || '');
                            
    //                         let mfdStocks=await getMFDStockData(data);
    //                         let stock =data.STOCK!=null?data.STOCK:(data.STOCK===0?0:'');
    //                         let BACKROOM_STOCK =data.BACKROOM_STOCK!=null?data.BACKROOM_STOCK:(data.BACKROOM_STOCK===0?0:'');
    //                         let EXPIRY_STOCK =data.EXPIRY_STOCK!=null?data.EXPIRY_STOCK:(data.EXPIRY_STOCK===0?0:'');
    //                         let DAMAGED_STOCK =data.DAMAGED_STOCK!=null?data.DAMAGED_STOCK:(data.DAMAGED_STOCK===0?0:'');
    //                         let LOST_STOCK =data.LOST_STOCK!=null?data.LOST_STOCK:(data.LOST_STOCK===0?0:'');
    //                         let NREXPIRY1_STOCK =data.NREXPIRY1_STOCK!=null?data.NREXPIRY1_STOCK:(data.NREXPIRY1_STOCK===0?0:'');
    //                         let NREXPIRY2_STOCK =data.NREXPIRY2_STOCK!=null?data.NREXPIRY2_STOCK:(data.NREXPIRY2_STOCK===0?0:'');
    //                         let NREXPIRY3_STOCK =data.NREXPIRY3_STOCK!=null?data.NREXPIRY3_STOCK:(data.NREXPIRY3_STOCK===0?0:'');

    //                         let defData={'SubCategoryId':cat.SubCategoryId,'ProductId':data.ProductId,'Stock':stock,'BackRoomStock':BACKROOM_STOCK,'ExpiryStock':EXPIRY_STOCK,'DamagedStock':DAMAGED_STOCK,'LostStock':LOST_STOCK,'mfdStocks':(mfdStocks || []),'isSKUPresent':data.IS_SKU_STOCK_PRESENT,'showAllSKU_Fields':(data.IS_SKU_STOCK_PRESENT==1),'NearExpiry1':NREXPIRY1_STOCK,'NearExpiry2':NREXPIRY2_STOCK,'NearExpiry3':NREXPIRY3_STOCK,"OutOfStock":data.OUT_OF_STOCK==1?1:0,"LessThanMBQ":data.LESS_THAN_MBQ==1?1:0};
                          
    //                         allSKUData.push(defData);
    //                         arr.push(data);

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

    function setInputRefss(AllKPIFields,cat,brand,data){
        let isStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='Stock')
        let isStockKPIObj=isStockIndex>=0?AllKPIFields[isStockIndex]:{};
        let isStockEnable=isStockIndex>=0?isStockKPIObj['KPIFieldEnable']:true;
        let isStockDis_Name=isStockIndex>=0?isStockKPIObj['KPIFieldDisplayName']:'';

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

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

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

        let isExStockIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExStockKPIObj=isExStockIndex>=0?AllKPIFields[isExStockIndex]:{};
        let isExStockEnable=isExStockIndex>=0?isExStockKPIObj['KPIFieldEnable']:false;
        let isExStockDis_Name=isExStockIndex>=0?isExStockKPIObj['KPIFieldDisplayName']:'';
        
        let NrExpiry1Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='NrExpiry1')
        let NrExpiry1KPIObj=NrExpiry1Index>=0?AllKPIFields[NrExpiry1Index]:{};
        let NrExpiry1Enable=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldEnable']:false;
        let NrExpiry1_Dis_Name=NrExpiry1Index>=0?NrExpiry1KPIObj['KPIFieldDisplayName']:'';

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

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


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

    }

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

    async function getImage(imgdata){
        let cat=getImageProps.option || '';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
            let picture_clicked_time=moment(picture_clickedd).format('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: '+currentMenu.MenuName+' | Date:'+picture_clicked_time;
           
            
            let picture_clicked_date1=moment(picture_clickedd).format('YYYYMMDD');
            let picture_clicked_time1=moment(picture_clickedd).format('HHmmss');
            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_Stock-'+picture_clicked_date1+'_'+picture_clicked_time1+'.jpg';
            
            let allIMgs=catImages;
            let defData={'SubCategoryId':cat.SubCategoryId};
            const cindex=allIMgs.findIndex(i=>i.SubCategoryId==cat.SubCategoryId);
            const imgData=cindex>=0?(allIMgs[cindex] || defData):defData;
            imgData.ImageName=filename;

            let imagePath='file://'+ImageFolderPath+currentMenu.ScreenName+"/"+filename;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri=imagePath;
                console.log('image marker',uri);
                imgData.ImagePath=uri; 
                cindex>=0?allIMgs[cindex]=imgData:allIMgs.push(imgData);
                setCatImages(allIMgs);
                console.log("catimages--",catImages)
                // setHasUnsavedChanges(true);
                BgWindowDataHdr(allIMgs)
               
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
            })
            .catch(err => {
                console.log(ST.Errorimagefilewritefailed+'!!!');
                console.log(err.message, err.code);
            }); 
            
            // resize file 
            // let resize_res=await resizeImage(imgurl,imgWidth,imgHeight)
           
            
            // if(resize_res.success){
                // file resized now rename file
                 
            // }
            // else{
            //     if(resize_res.error){
            //         notify("Error in image: ",resize_res.error);
            //     }else if (resize_res.imagenotfound){
            //         notify("Cannot find image!");
            //     }else{
            //         notify("Something went wrong while capturing image!");
            //     }
            // }                     
        }        
    }
  
    async function openCamera(option){ 
        setGetImageProps({'option':option}); 
        console.log('openCamera');
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

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

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

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

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

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


              let seq_q=` select seq from sqlite_sequence where name="${AppTables.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 (txnE,txnerr) { console.log(txnerr); insertData(0); },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function insertData(seq=0){
        try {   
            console.log(seq);
            let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData;
            console.log('insertData');
            await db.transaction(async function (txn) {
              var values='',stock_values='',mfdStockV='';
              for(var i=0;i<globalBrandData.length;i++){
                  
                seq++;
                let catIndex=i;
                let item=globalBrandData[catIndex];
                let cimage=catImages.find(ci=>ci.SubCategoryId==item.SubCategoryId) || {};
                values+=values!=''?' , ':'';
                
                
                values+=` ('${StoreId}','${d2}','${item.SubCategoryName}','${item.SubCategoryId}','','${(cimage.ImageName || '')}','${(cimage.ImagePath || '')}','1','${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.SubCategoryId==item.SubCategoryId && 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 OutOfStock=skud.OutOfStock!=null?skud.OutOfStock:'0';
                        let LessThanMBQ=skud.LessThanMBQ!=null?skud.LessThanMBQ:'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.SubCategoryId}','${item.SubCategoryName}','${BrandId}','${BrandName}','${ProductId}','${ProductName}','${MSL}','${stock}','${br_stock}','${damage_stock}','${lost_stock}','${ex_stock}','${isSKUPresent}','${NearExpiry_stock1}','${NearExpiry_stock2}','${NearExpiry_stock3}','${OutOfStock}','${LessThanMBQ}','${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.SubCategoryId}','${BrandId}','${ProductId}','${mfd_stock}','${mfd_mfd}','${mfd_lotno}','${mfd_date}','${d2}') `;
                        
                        }
                        
                    }
                }
                
              }

              
              let add_StockHdr=`INSERT INTO ${AppTables.STOCKQRHDR_DATA} (STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,MSL,IMAGE,IMAGEPATH,IS_UPDATED,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.STOCKQR_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,SUB_CATEGORY_ID,SUB_CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK,OUT_OF_STOCK,LESS_THAN_MBQ,ADDED_DATE) VALUES ${stock_values} `;
            //  let add_mfd_Stock=`INSERT INTO ${AppTables.STOCK2_MFD_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,SUB_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);
                             // clear store data in local storage to avoiding re-set data for the store  
                            clear_item('storeData')
                            props.navigation.goBack();
                        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddstock) },);
                    }
                    else{
                        notify(ST.Stockupdatedsuccessfully);
                        setProcessing(false);
                         // clear store data in local storage to avoiding re-set data for the store  
                         clear_item('storeData')
                        props.navigation.goBack();
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddstock) },);
              },function (txnE,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 StockValidationRequiredI=KPIFields.findIndex(i=>i.KPIFieldName=='StockValidationRequired')
        let StockValidationRequiredObj=StockValidationRequiredI>=0?KPIFields[StockValidationRequiredI]:{};
        let StockValidationRequired=StockValidationRequiredI>=0?StockValidationRequiredObj['KPIFieldEnable']:true;
        console.log('StockValidationRequired:',StockValidationRequired);
        if(StockValidationRequired==false){
            return isValid;
        }

        // validate only if permit

        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=='NONMSL');
        let NONMSL_Obj=NONMSL_Index>=0?KPIFields[NONMSL_Index]:{};
        let isNONMSL_Allow=NONMSL_Index>=0?NONMSL_Obj['KPIFieldEnable']:true;

        // new 
        let OutofStockI=KPIFields.findIndex(i=>i.KPIFieldName=='OutofStock')
        let OutofStockObj=OutofStockI>=0?KPIFields[OutofStockI]:{};
        let OutofStockEnable=OutofStockI>=0?OutofStockObj['KPIFieldEnable']:false;

        let LessThanMBQI=KPIFields.findIndex(i=>i.KPIFieldName=='LessThanMBQ')
        let LessThanMBQObj=LessThanMBQI>=0?KPIFields[LessThanMBQI]:{};
        let LessThanMBQEnable=LessThanMBQI>=0?LessThanMBQObj['KPIFieldEnable']:false;
        
        let DefaultStockToggleI=KPIFields.findIndex(i=>i.KPIFieldName=='DefaultStockToggle')
        let DefaultStockToggleObj=DefaultStockToggleI>=0?KPIFields[DefaultStockToggleI]:{};
        let DefaultStockToggle=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldEnable']:false;
        let DefaultStockToggleValue=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldDisplayName']:"2";
        let deftogvalue=DefaultStockToggleValue=="3"?"3":(DefaultStockToggle=="1"?"1":"0");

        let COMPStockAllow_Index=KPIFields.findIndex(i=>i.KPIFieldName=='COMPStockAllow');
        let COMPStockAllow_Obj=COMPStockAllow_Index>=0?KPIFields[COMPStockAllow_Index]:{};
        let isCOMPStockAllow=COMPStockAllow_Index>=0?COMPStockAllow_Obj['KPIMandatory']:false;


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

                
                // let isCollapsed=item.isCollapsed!=null?item.isCollapsed:true;
                
                if(StoreCameraAllow && isHdrImgEnable==true && (cimgData.ImagePath== null || cimgData.ImagePath=='')){
                    notify(ST.Pleaseclickimagefor+' '+item.SubCategoryName,'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.SubCategoryId==item.SubCategoryId && 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 OutOfStock=skuData.OutOfStock!=null?skuData.OutOfStock:deftogvalue;
                                        let LessThanMBQ=skuData.LessThanMBQ!=null?skuData.LessThanMBQ:deftogvalue;
                                            
                                        // let isMandatory=((isMSLAllow==1 || isMSLAllow=='true') && (skuItem.MSL==1 || skuItem.MSL=='true') ) || ((isNONMSL_Allow==0 || isNONMSL_Allow=='false') && (skuItem.MSL!=1 && skuItem.MSL!='true') ) 
                                        let IsCompetitor=skuItem.IsCompetitor=='1' || skuItem.IsCompetitor==1?true:false;
                                            
                                        let isMSLMandCond=!IsCompetitor && (isMSLAllow==1 || isMSLAllow=='true') && (skuItem.MSL==1 || skuItem.MSL=='true') ;
                                        let isNONMSLMandCond=!IsCompetitor && (isNONMSL_Allow==true || isNONMSL_Allow=='true') && (skuItem.MSL!=1 && skuItem.MSL!='true') 
                                        
                                        let IsCompetitorMand=  (isCOMPStockAllow==1 || isCOMPStockAllow=='true')  && IsCompetitor;
                                        let isMandatory=isMSLMandCond || isNONMSLMandCond || IsCompetitorMand;
                                        
        
                                        
                                        let errorobj = {'EF_cat':item,'EF_brand':brand,'EF_product':skuItem}
                                        let errorcatid = item.SubCategoryId
                                        let error_bid = brand.BrandId
                                        let error_pid = skuItem.ProductId
                                        let show_errorH=false,error_HInputKey='';
                                        console.log("isListedSKUEnable:",isMandatory,isMSLMandCond,isNONMSLMandCond,IsCompetitorMand,IsCompetitor)
                                        if((isListedSKUEnable==true && isSKUPresent==1) || (!isListedSKUEnable  && (isMandatory)) ){
        
                                            // let sumOfDamagedStocks=parseInt(ex_stock)+parseInt(damage_stock)+parseInt(lost_stock);
                                           console.log("isStockEnable:",isStockEnable,stock)
                                            if(LessThanMBQEnable==true && LessThanMBQ=="3"){
                                                notify("Please select required options for "+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(OutofStockEnable==true && OutOfStock=="3"){
                                                notify("Please select required options for "+skuItem.ProductName,'LONG');
                                                isValid=false;
                                            }
                                            else if(isStockEnable==true && stock!==0 && ( stock==null || stock=='')){
                                                notify(ST.Pleaseenter+' '+isStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                                show_errorH=true,error_HInputKey='input1_';
                                            }
                                            // else if(isBRStockEnable==true && br_stock!==0 && ( br_stock==null || br_stock=='')){
                                            //     notify(ST.Pleaseenter+' '+isBRStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                            //     isValid=false;
                                            //     show_errorH=true,error_HInputKey='input2_';
                                            // }
                                            else if(isDStockEnable==true && damage_stock!==0 && ( damage_stock==null || damage_stock=='')){
                                                notify(ST.Pleaseenter+' '+isDStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                                show_errorH=true,error_HInputKey='input3_';
                                            }
                                            else if(isLStockEnable==true && lost_stock!==0 && ( lost_stock==null || lost_stock=='')){
                                                notify(ST.Pleaseenter+' '+isDStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                                show_errorH=true,error_HInputKey='input4_';
                                            }
                                            else if(isExStockEnable==true && ex_stock!==0 && ( ex_stock==null || ex_stock=='')){
                                                notify(ST.Pleaseenter+' '+isExStockDis_Name+' '+ST.for+' '+skuItem.ProductName,'LONG');
                                                isValid=false;
                                                show_errorH=true,error_HInputKey='input5_';
                                            }
                                            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;
                                                show_errorH=true,error_HInputKey='input6_';
                                            }
                                            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;
                                                show_errorH=true,error_HInputKey='input7_';
                                            }
                                            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;
                                                show_errorH=true,error_HInputKey='input8_';
                                            }
                                            // 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{

                                            }

                                            if(show_errorH){
                                                errorobj['EF_InputKey']=error_HInputKey;
                                                setErrorField(errorobj)
                                                setError(true)
                                                let refIn1=inputRefs.current[error_HInputKey+errorcatid+'_'+error_bid+'_'+error_pid]
                                                refIn1.focus();
                                            }
                                          
                                        }
                                        }
                                    })
                                );
                            }
                            }

                        });
                    }
                    
                }
            }
            })
        );

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

    function onStockValChange(item,skuItem,val,key,type=''){
        console.log("keycheck",key, val)
        setError(false)
        setErrorField({})
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && 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);
        BgWindowData(allSKUData)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

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

        setShowStockModal(true);      
    }

    function onSaveCancel(){
        setShowAlert(false)
    }


    async function onQRScanned(imgdata){

        let QR_withValidChars=imgdata!=null && imgdata!=''?imgdata.replace(/["']/g,''):'';
        let value=QR_withValidChars;//imgdata && imgdata[0] && imgdata[0].displayValue ? imgdata[0].displayValue :""
        // setTextValue(value,qtn,window)
        console.log("value------",value)
        onFormDataChange(value,'QRCode','qrtext')
        getData(storeData,currentMenu,"","",value);
    }


    function onFormDataChange(val,key,type="text"){

        // if(val!=''){
        //     let isValid=validateNumber(val,type);
        //     console.log("type:",type,isValid);
        //     if(!isValid){
        //         return;
        //     }r
        // }    
        let data=AddVisFormData;
        data[key]=val;
        setAddVisFormData(data);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);

        console.log("addvisbiltydtaa--",AddVisFormData)
    }



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

    function setCS_Stock(key,val,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        
        let cstock=currentStock;
        cstock[key]=val;
        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={'SubCategoryId':cat.SubCategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==cat.SubCategoryId && 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);
                BgWindowData(allSKUData)
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
                setCurrentStock({});
                setShowStockModal(false);
            // }
            
        }
    }


    function removeMFDStock(){
        let cat=toRemoveCat;
        let skuItem=toRemoveSKU;
        let cstockIndex=toRemoveId;
        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':cat.SubCategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==cat.SubCategoryId && 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);
        BgWindowData(allSKUData)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(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=Object.assign({'test':'1'} , item);
                
                let newBrandList=[];
                for(let j=0;j<brandList.length;j++){
                    let brand=brandList[j];
                    let skulist=brand.skulist || [];
                    newBrand=Object.assign({'test2':'2'} , brand);
                    
                    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)
    }

    async function focusToNext(cat,brand,sku,type='1',outerId, middleId,index){

        let activeKey='';
        let arr=Object.keys(inputRefs.current);


        // const middleFlatListRef = middleFlatListRefs.current[outerId];
        // if (middleFlatListRef) {
        //   const innerFlatListRef = innerFlatListRefs.current[middleId];
        //   if (innerFlatListRef) {
        //     innerFlatListRef.scrollToIndex({ animated: true, index: index });
        //   }
        // }

        activeKey='input'+type+'_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+sku.ProductId;

        let activeIndex=arr.indexOf(activeKey);
        if(activeIndex>=0 && activeIndex<arr.length-1){
            let nextKey = arr[++activeIndex] 
            let nextRef= inputRefs.current[nextKey];
            nextRef.focus();    
        }
        else{
            return
        }
    }

    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=""
                            autoComplete='off'
                            maxLength={6}
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            keyboardType={'number-pad'}
                            value={stock}
                            onChangeText={(val)=>{setCS_Stock('stock',val,'numeric')}}
                        />
                    </View>
                </View>
                <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{ST.LotNo}</Text>
                    <View style={customStyle.AddStockM_col} >
                        <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            // keyboardType={'number-pad'}
                            value={lotno}
                            onChangeText={(val)=>{setCS_Stock('lotno',val,'text')}}
                        />
                    </View>
                </View>
            </View>
            <View style={[customStyle.storelVisitM_options,{justifyContent:'space-between'}]}>
             <TouchableOpacity style={[customStyle.storelVisitM_op_btn,customStyle.AddStockM_cancelBtn]} onPress={()=>{setCurrentStock({});setShowStockModal(false);}}>
                <Text style={[customStyle.storelVisitM_op_btnText,customStyle.AddStockM_cancelBtnText]}>{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 || [];
        
        brand['isBrandCollapsed']=!isBrandCollapsed;
        brandList[brand_index]=brand;
        cat['brandList']=brandList;
        allData[catIndex]=cat;
        setBrandData(allData);
        setGlobalBrandData(allData);
        setrerenderdata(!rerenderdata);
    }

    function onChoiceSelect(item,skuItem,val,key,animatedChoice){
        console.log('onChoiceSelect',animatedChoice)
       
        var val1=0;
        if(val==1){
            val1=1;
        }
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onStockValChange(item,skuItem,val,key,'');
    }
    
    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']:'';

        console.log("istockdispname--",isStockDis_Name)
        
        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;
        

        // yes no fields 
        let OutofStockI=KPIFields.findIndex(i=>i.KPIFieldName=='OutofStock')
        let OutofStockObj=OutofStockI>=0?KPIFields[OutofStockI]:{};
        let OutofStockEnable=OutofStockI>=0?OutofStockObj['KPIFieldEnable']:false;
        let OutofStockDisName=OutofStockI>=0?OutofStockObj['KPIFieldDisplayName']:'';

        let LessThanMBQI=KPIFields.findIndex(i=>i.KPIFieldName=='LessThanMBQ')
        let LessThanMBQObj=LessThanMBQI>=0?KPIFields[LessThanMBQI]:{};
        let LessThanMBQEnable=LessThanMBQI>=0?LessThanMBQObj['KPIFieldEnable']:false;
        let LessThanMBQDisName=LessThanMBQI>=0?LessThanMBQObj['KPIFieldDisplayName']:'';

        let ShowMBQLabelI=KPIFields.findIndex(i=>i.KPIFieldName=='ShowMBQ')
        let ShowMBQLabelObj=ShowMBQLabelI>=0?KPIFields[ShowMBQLabelI]:{};
        let ShowMBQLabel=ShowMBQLabelI>=0?ShowMBQLabelObj['KPIFieldEnable']:false;
        let ShowMBQLabelDisName=ShowMBQLabelI>=0?ShowMBQLabelObj['KPIFieldDisplayName']:'';

        
        let DefaultStockToggleI=KPIFields.findIndex(i=>i.KPIFieldName=='DefaultStockToggle')
        let DefaultStockToggleObj=DefaultStockToggleI>=0?KPIFields[DefaultStockToggleI]:{};
        let DefaultStockToggle=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldEnable']:false;
        let DefaultStockToggleValue=DefaultStockToggleI>=0?DefaultStockToggleObj['KPIFieldDisplayName']:"2";
        let deftogvalue=DefaultStockToggleValue=="3"?"3":(DefaultStockToggle=="1"?"1":"0");
        


        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-150} >  
            
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            ref={outerFlatListRef}
            keyboardDismissMode={Platform.OS === 'ios' ? 'interactive' : 'on-drag'}
            renderItem={({item,index})=>{
                const cat=item;
                const outerId=index
                console.log("cat--outter---",item)
                const cindex=catImages.findIndex(i=>i.SubCategoryId==item.SubCategoryId);
                const cimgName=cindex>=0?(catImages[cindex]?catImages[cindex].ImageName:''):'';
                const cimgPath=cindex>=0?(catImages[cindex]?catImages[cindex].ImagePath:''):'';
                const showIMg=cimgPath!='' && cimgPath!=null;

                let isCollapsed=cat.isCollapsed!=null?item.isCollapsed:false;

                // get error field category id
                let EF_cat= errorfield.EF_cat!=null? errorfield.EF_cat:{};
                let errorcatid = EF_cat.SubCategoryId || '';

               
                // 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.SubCategoryName}</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)}}>
                                        <CameraImg width={80} height={80} />                                     
                                    </TouchableOpacity>
                                }
                                { showIMg && 
                                    <View style={customStyle.osCatImageView}>
                                        <Image style={customStyle.osCatImage} source={{uri:cimgPath}}/>
                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(item)}}>
                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                        </TouchableOpacity>
                                    </View>                                    
                                }                                
                            </View>}
                        </View>
                        { !isCollapsed &&
                            item.brandList!=null && item.brandList.length>0 && 
                                <FlatList 
                                    data={item.brandList}
                                    // keyExtractor={(middleItem) => middleItem.id}
                                    ref={(ref) => {
                                        if (ref) middleFlatListRefs.current[outerId] = ref;
                                      }}

                                    renderItem={({item:brand,index:brand_index})=>{
                                let isBrandCollapsed=brand.isBrandCollapsed!=null?brand.isBrandCollapsed:false;
                                const middleId=brand_index;
                                // get error field brand id
                                let EF_brand= errorfield.EF_brand!=null? errorfield.EF_brand:{};
                                let error_bid = EF_brand.BrandId || '';

                                return (
                                    <View key={brand_index+'_brands_'+'item_'+index}>
                                        <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;}}
                                            // keyExtractor={(innerItem) => innerItem.id}
                                            ref={(ref) => {
                                            if (ref) innerFlatListRefs.current[middleId] = ref;
                                            }}

                                            renderItem={({item,index})=>{
                                                
                                            const skus=item;
                                            const sku_index=index;
        
                          
                                            
                                            let thisCatSkuData_i=SKUStockData.findIndex(i=>i.SubCategoryId==cat.SubCategoryId && i.ProductId==skus.ProductId);
                                            let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                            let stock=thisCatSkuData.Stock!=null?thisCatSkuData.Stock:'';
                                            let QrCode=thisCatSkuData.ProductCode!=null?thisCatSkuData.ProductCode:'';
                                    
                                            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 OutOfStock=thisCatSkuData.OutOfStock!=null?thisCatSkuData.OutOfStock:deftogvalue;
                                            let LessThanMBQ=thisCatSkuData.LessThanMBQ!=null?thisCatSkuData.LessThanMBQ:deftogvalue;

                                            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') )
                                            let IsCompetitor=skus.IsCompetitor=='1' || skus.IsCompetitor==1?true:false;

                                            
                                            let xpos=OutOfStock=="3"?0:(OutOfStock==1?-75:0);
                                            if(skus.animatedChoice!=null ){
                                                xpos=skus.animatedChoice.interpolate({
                                                    inputRange:[0,1],
                                                    outputRange:[0,-75],
                                                });
                                            }

                                            let xpos1=LessThanMBQ=="3"?0:( LessThanMBQ==1?-75:0);
                                            if(skus.animatedChoice2!=null ){
                                                xpos1=skus.animatedChoice2.interpolate({
                                                    inputRange:[0,1],
                                                    outputRange:[0,-75],
                                                });
                                            }

                                            // change color for competitor
                                            let card_bg=(IsCompetitor?{backgroundColor:PageTheme.$card_colorYellowLight}:(isMandatory?{backgroundColor:PageTheme.$fifth_color}:{}));
                                            let card_border=(IsCompetitor?{borderColor:PageTheme.$card_colorYellowDark}:(isMandatory?{borderColor:PageTheme.$primary_color}:{}));

                                            // get error field product id
                                            let EF_product= errorfield.EF_product!=null? errorfield.EF_product:{};
                                            let error_pid = EF_product.ProductId || '';
                                            let EF_InputKey=errorfield.EF_InputKey;
                                            let show_errorhere =errorcatid==cat.SubCategoryId && error_bid==brand.BrandId && error_pid==skus.ProductId;
                                            
                                            let errorStyle_ST=( error && show_errorhere && EF_InputKey=='input1_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_BS=( error && show_errorhere && EF_InputKey=='input2_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_DS=( error && show_errorhere && EF_InputKey=='input3_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_LS=( error && show_errorhere && EF_InputKey=='input4_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_EXS=( error && show_errorhere && EF_InputKey=='input5_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_NEX1=( error && show_errorhere && EF_InputKey=='input6_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_NEX2=( error && show_errorhere && EF_InputKey=='input7_'? customStyle.stk_inptSTyle_error :{});
                                            let errorStyle_NEX3=( error && show_errorhere && EF_InputKey=='input8_'? customStyle.stk_inptSTyle_error :{});



                                            return(
                                                <View style={[customStyle.openStk_prd_Con,card_bg]} 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}>
                                                        {ShowMBQLabel==true &&
                                                        <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                                            <View style={[customStyle.stockPrdInfo]}>
                                                                <Text style={[customStyle.stockPrdInfoLabelHd]}>{'MBQ :'}</Text>
                                                                <Text style={[customStyle.stockPrdInfoLabel]}>{skus.MBQ}</Text>
                                                            </View>
                                                        </View>
                                                        }
                                                        {OutofStockEnable==true && <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                                            <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{OutofStockDisName}</Text>
                                                            <View style={customStyle.openStk_prd_choiceBoxCon}>
                                                                <View style={customStyle.openStk_prd_choiceBox}>
                                                                    <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(OutOfStock=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),((OutOfStock=="3")?{opacity:0,display:'none'}:{}),
                                                                    {   transform: [{   translateX:xpos }],  }]}></Animated.View>
                                                                    <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(cat,skus,1,'OutOfStock',skus.animatedChoice)}}>
                                                                        <Text style={[customStyle.openStkCh_text,(OutOfStock=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                                                    </TouchableOpacity>
                                                                    <TouchableOpacity style={[customStyle.openStkCh_con1,((OutOfStock=="3")?customStyle.openStkCh_con1Grey:{})]} onPress={()=>{onChoiceSelect(cat,skus,0,'OutOfStock',skus.animatedChoice)}}>
                                                                        <Text style={[customStyle.openStkCh_text,(OutOfStock=="3"?{}:(OutOfStock=='0'?customStyle.openStkCh_textactive:{}))]}>{ST.No}</Text>
                                                                    </TouchableOpacity>
                                                                </View>
                                                            </View>
                                                        </View>}

                                                        {LessThanMBQEnable==true && <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                                            <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{LessThanMBQDisName}</Text>
                                                            <View style={customStyle.openStk_prd_choiceBoxCon}>
                                                                <View style={customStyle.openStk_prd_choiceBox}>
                                                                    
                                                                    <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(LessThanMBQ=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),((LessThanMBQ=="3")?{opacity:0,display:'none'}:{}),
                                                                    {   transform: [{   translateX:xpos1 }],  }]}></Animated.View>
                                                                    <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(cat,skus,1,'LessThanMBQ',skus.animatedChoice2)}}>
                                                                        <Text style={[customStyle.openStkCh_text,(LessThanMBQ=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                                                    </TouchableOpacity>
                                                                    <TouchableOpacity style={[customStyle.openStkCh_con1,((LessThanMBQ=="3")?customStyle.openStkCh_con1Grey:{})]} onPress={()=>{onChoiceSelect(cat,skus,0,'LessThanMBQ',skus.animatedChoice2)}}>
                                                                        <Text style={[customStyle.openStkCh_text,(LessThanMBQ=="3"?{}:((LessThanMBQ=='0')?customStyle.openStkCh_textactive:{}))]}>{ST.No}</Text>
                                                                    </TouchableOpacity>
                                                                </View>
                                                            </View>
                                                        </View>}

                                                        {(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> */}
                                                                <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{"QR Code"}</Text>
                                                                <TextInput 
                                                                    ref={(reff)=>{inputRefs.current['input1_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_ST]}              
                                                                    placeholder=""  
                                                                    autoComplete='off'    
                                                                    maxLength={18}      
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(skus.ProductCode+'' || '')}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    // onChangeText={(val)=>{ onStockValChange(cat,skus,val,'QRcode','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'Stock','Old_Stock',Old_Stock)}}
                                                                    // onSubmitEditing={()=>{focusToNext(cat,brand,skus,'1',outerId, middleId,index)}}
                                                                />
                                                            </View>
                                                        </View>
                                                        }

                                                        {(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> */}
                                                                <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{"Stock"}</Text>
                                                                <TextInput 
                                                                    ref={(reff)=>{inputRefs.current['input1_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_ST]}              
                                                                    placeholder=""  
                                                                    autoComplete='off'    
                                                                    maxLength={6}      
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(stock+'' || '')}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'Stock','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'Stock','Old_Stock',Old_Stock)}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'1',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input2_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_BS]}              
                                                                    placeholder=""      
                                                                    autoComplete='off'  
                                                                    maxLength={6}    
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(br_stock+'')}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'BackRoomStock','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'Stock','Old_Stock',Old_Stock)}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'2',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input3_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_DS]}              
                                                                    placeholder=""  
                                                                    autoComplete='off'          
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(damage_stock+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'DamagedStock','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'DamagedStock','OldDamagedStock',OldDamagedStock)}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'3',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input4_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_LS]}              
                                                                    placeholder=""  
                                                                    autoComplete='off'          
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(lost_stock+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'LostStock','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'LostStock','OldLostStock',OldLostStock)}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'4',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input5_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_EXS]}              
                                                                    placeholder="" 
                                                                    autoComplete='off'           
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(ex_stock+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'ExpiryStock','numeric')}}
                                                                    // onEndEditing={(e)=>{ checkStockVal(cat,skus,'ExpiryStock','OldExStock',OldExStock)}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'5',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input6_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_NEX1]}              
                                                                    placeholder=""    
                                                                    autoComplete='off'        
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock1+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry1','numeric')}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'6',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input7_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_NEX2]}              
                                                                    placeholder=""  
                                                                    autoComplete='off'          
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock2+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry2','numeric')}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'7',outerId, middleId,index)}}
                                                                />
                                                            </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 
                                                                    ref={(reff)=>{inputRefs.current['input8_'+cat.SubCategoryId+'_'+brand.BrandId+'_'+skus.ProductId]=reff;}}
                                                                    style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,customStyle.stk_inptSTyle,errorStyle_NEX3]}              
                                                                    placeholder=""     
                                                                    autoComplete='off'       
                                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                                    value={(NearExpiry_stock3+'')}
                                                                    maxLength={6}
                                                                    keyboardType='number-pad'
                                                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                    blurOnSubmit={false}
                                                                    onChangeText={(val)=>{ onStockValChange(cat,skus,val,'NearExpiry3','numeric')}}
                                                                    onSubmitEditing={()=>{focusToNext(cat,brand,skus,'8',outerId, middleId,index)}}
                                                                />
                                                            </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}/>}
        <View style={{zIndex: 10}}>
          <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        </View>
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setShowRemoveConfirm_M(false)},removeMFDStock,ST.Doyoureallywanttoremovethisstock)}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {rerendermodal==rerendermodal && _render_StockModal()}
        <CustomCamera cameraType={'back'} QRCodeEnable={QREnable} onImageCaptured={(imgData)=>{setShowQRCamera(false);onQRScanned(imgData)}} showCamera={showQRCamera} onHideCamera={()=>{setShowQRCamera(false);}}/>   

        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <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}
                autoComplete='off'
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View> */}

          <View style={customStyle.addVisForm}>
                    <View style={customStyle.addVisRow}>                        
                        <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{"QR Code"}</Text>
                                <View>
                                    <TextInput  
                                        style={customStyle.addVisInputStyle} 
                                        value={(AddVisFormData.QRCode || '')}
                                        onChangeText={(val)=>{onFormDataChange(val,'QRCode',"qrtext");}}
                                        autoComplete='off'
                                    />
                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setQREnable(true);setQRqtnData({});setShowQRCamera(true);}}>
                                        <Ionicons name="camera" color={PageTheme.$accent_color} size={24}/>
                                    </TouchableOpacity> 
                                </View>
                            </View>
                        </View>
                        
                        
                        {/* <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{"Asset Code"}</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.AssetCode || '')}
                                onChangeText={(val)=>{onFormDataChange(val,'AssetCode');}}
                                autoComplete='off'
                                />
                            </View>
                        </View> */}
                        {/* <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.Image}</Text>
                                <View style={customStyle.addVisCameras}>
                                    <View style={customStyle.openStkCameraCon}>
                                        { (AddVisFormData.Image1Path=='' || AddVisFormData.Image1Path==null) && 
                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera('1')}}>
                                                <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                            </TouchableOpacity>
                                        }
                                        { (AddVisFormData.Image1Path!='' && AddVisFormData.Image1Path!=null) && 
                                            <View style={customStyle.osCatImageView}>
                                                <Image style={customStyle.osCatImage} source={{uri:AddVisFormData.Image1Path}}/>
                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera('1')}}>
                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                </TouchableOpacity>
                                            </View>                                    
                                        }       
                                    </View>
                                    
                                </View>
                            </View>
                        </View>
                        <View style={customStyle.addVis_btnWrap}>
                            <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{Add_AddVis()}}>
                                <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                            </TouchableOpacity>
                        </View> */}
                    </View>
                </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)(StockQRCode);