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} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';

function OpeningStock(props) { 
    const route = useRoute();
  
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [KPIFields, setKPIFields] = useState([]);
    
    const [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

    const inputRefs = useRef({});

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

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

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

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

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          let allCats=[];

          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);

          await db.transaction(async function (txn) {        
            
            let join=' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
            let join2=' INNER join Mapping_ProductAssortment mp on p.ProductId=mp.ProductId ';
            let q=`SELECT DISTINCT c.CategoryId,c.CategoryName,mp.MSL from Master_Category c ${join} ${join2}  where mp.StateId='${StateId}' and mp.ChainId='${ChainId}' and mp.StoreTypeId='${StoreTypeId}' order by p.CategorySequence`;
            
            let q2=` SELECT CATEGORY_ID as CategoryId,CATEGORY as CategoryName,MSL,IMAGE,IMAGEPATH FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    
                    let arr=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        arr.push(data);

                        let defData={'CategoryId':data.CategoryId,'ImageName':data.IMAGE,'ImagePath':data.IMAGEPATH};
                        allCats.push(defData);
                        if(i==txnres.rows.length-1){
                            // setBrandData(arr);
                            setCatImages(allCats);
                            getSKU(arr,storeData1);
                        }
                    }
                }
                else{
                    await txn.executeSql(q,[],async function (txn2, txnres2) { 
                        if(txnres2.rows.length>0){
                            let arr=[];
                            for(var i=0;i<txnres2.rows.length;i++){
                                let data =txnres2.rows.item(i);
                                arr.push(data);
                                if(i==txnres2.rows.length-1){
                                    // setBrandData(arr);
                                    getSKU(arr,storeData1);
                                }                                
                            }
                            
                        }
                    },function (txn2, txnerr) { console.log(txnerr); },);
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
            // setProcessing(false);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getSKU(brands=[],storeData1={}){
        
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData1;     
        
          await db.transaction(async function (txn) { 
            var allSKUData=[];
            await Promise.all(
                brands.map(async (item,index) => {
                    let seletlist=`PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK`;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and  CATEGORY_ID='${item.CategoryId}' `;
     
                    let join=`  inner join Mapping_ProductAssortment m on p.ProductId=m.ProductId `;
                    let join2=`  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                    let sku_q2=`select distinct p.ProductName,p.ProductId,p.BrandName,p.BrandId,m.MSL from Product_Master p  ${join} ${join2} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' and p.CategoryId='${item.CategoryId}' and CompanyId='1' order by p.ProductSequence`;
                    

                    return await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                        if(txnres.rows.length>0){
                          
                            let arr=[];
                            for(var i=0;i<txnres.rows.length;i++){
                                let data =txnres.rows.item(i);
                                inputRefs.current['input1_'+item.CategoryId+'_'+data.ProductId]='';
                                inputRefs.current['input2_'+item.CategoryId+'_'+data.ProductId]='';
                                arr.push(data);
                                
                                let defData={'CategoryId':item.CategoryId,'ProductId':data.ProductId,'Stock':data.OPENING_STOCK,'ExpiryStock':data.EXPIRY_STK};
                                
                                allSKUData.push(defData);

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

                                        // let defData={'CategoryId':item.CategoryId,'ProductId':data.ProductId,'Stock':1,'ExpiryStock':0};
                                       
                                        // allSKUData.push(defData);


                                        if(i==(txnres2.rows.length-1)){                                        
                                            item['skulist']=arr;
                                            brands[index]=item;
                                            if(index==brands.length-1){
                                                console.log('setBrands:',brands);
                                                // setSKUStockData(allSKUData);
                                                setBrandData(brands);
                                                setProcessing(false);
                                            }
                                            return item;
                                        }               
                                    }
                                }
                                else{
                                    return item;
                                }
                                
                            },function (txn2, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        }
                    },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); return item; },);
                  return item;
                })
            ) .then((res)=>{
                
            });          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function focusToNext(cat,index,sku,sku_index,inputType='1'){
        console.log('focusToNext',index,sku_index,inputType);
        let data=brandData;

        let isExpStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExpStockPIObj=isExpStockIndex>=0?KPIFields[isExpStockIndex]:{};
        let isExpStockEnable=isExpStockIndex>=0?isExpStockPIObj['KPIFieldEnable']:true;
        let key=isExpStockEnable?'input1_':'input2_';
        
        if(inputType=='1'){
            console.log('next 1 call')
            let refIn2=inputRefs.current['input2_'+cat.CategoryId+'_'+sku.ProductId];
            refIn2.focus();
        }
        else{
            let ccat_index=index;
            let skulist=cat.skulist || [];
            console.log('skulist.length:',skulist.length)
            if(sku_index==skulist.length-1){ // if last subcategory element
                //then move to next category
                console.log('move to next cat',ccat_index,data.length)
                if(ccat_index==data.length-1){
                    return;
                }
                else{
                    ccat_index+=1;
                    console.log('move to next cat n:',ccat_index)
                    let cat1=data[ccat_index];
                    let skulist1=cat1.skulist || [];
                    if(skulist1.length>0){
                        let sku1=skulist1[0];
                        
                        let refIn1=inputRefs.current[key+cat1.CategoryId+'_'+sku1.ProductId];
                        console.log('move to next cat refIn1:',key+cat1.CategoryId+'_'+sku1.ProductId)
                        refIn1.focus();
                    }
                }
            }
            else{
                // move to next subcategory
                let sku1=skulist[sku_index+1];
                let refIn1=inputRefs.current[key+cat.CategoryId+'_'+sku1.ProductId];
                refIn1.focus();
            }
            
            
            
        }

    }

    async function getImage(imgdata){
        let cat=getImageProps.option || '';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl='file://'+img.uri, imgWidth=img.width, imgHeight=img.height;
           
            
            let picture_clicked_time=new Date();
            picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
            
            
            const mark_text1=picture_clicked_time;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Opening Stock'+' | Date:'+picture_clicked_time;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let picture_clickedd=new Date();
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_OpeningStk-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            
                            let allIMgs=catImages;
                            let defData={'CategoryId':cat.CategoryId};
                            const cindex=allIMgs.findIndex(i=>i.CategoryId==cat.CategoryId);
                            const imgData=cindex>=0?(allIMgs[cindex] || defData):defData;
                            imgData.ImageName=filename;
                            
                            // renamefile
                            let imagePath='file://'+`${common_ImagePath}${filename}`;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri=imagePath;
                                console.log('image marker',uri);
                                imgData.ImagePath=uri; 
                                cindex>=0?allIMgs[cindex]=imgData:allIMgs.push(imgData);
                                setCatImages(allIMgs);
                                setHasUnsavedChanges(true);
                                setrerenderdata(!rerenderdata);
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify('Please capture a image');
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify('Please capture a image');
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(option){ 
        setGetImageProps({'option':option}); 
        console.log('openCamera');
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'});
        setShowCamera(true);
    }

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

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

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

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

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

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

            let isExpStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
            let isExpStockPIObj=isExpStockIndex>=0?KPIFields[isExpStockIndex]:{};
            let isExpStockEnable=isExpStockIndex>=0?isExpStockPIObj['KPIFieldEnable']:true;

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

              let add_StockHdr=`INSERT INTO ${AppTables.INSERT_OPENINGHEADER_DATA} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.STOCK_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,CATEGORY_ID,CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK,ADDED_DATE) VALUES ${stock_values} `;
                
             
            
              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');
                    notify('Stock updated successfully');
                    setProcessing(false);
                    props.navigation.goBack();
                },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


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

        let isExpMandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStockMandatory')
        let isExpMandKPIObj=isExpMandIndex>=0?KPIFields[isExpMandIndex]:{};
        let isExpMandEnable=isExpMandIndex>=0?isExpMandKPIObj['KPIFieldEnable']:true;

        let isExpStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExpStockPIObj=isExpStockIndex>=0?KPIFields[isExpStockIndex]:{};
        let isExpStockEnable=isExpStockIndex>=0?isExpStockPIObj['KPIFieldEnable']:true;

       
        await Promise.all(
            brandData.map(async (item,index) => {
            if(isValid){
                let catId=item.CategoryId;
                let cimgData=catImages.find(ci=>ci.CategoryId==catId) || {};
                if(cimgData.ImagePath== null || cimgData.ImagePath==''){
                    notify('Please click image for '+item.CategoryName,'SHORT');
                    isValid=false;
                }
                else{
                    let skulist=item.skulist || [];
                    if(skulist.length>0){
                        await Promise.all(
                            skulist.map(async (skuItem,skuIndex) => {
                                if(isValid){
                                    let skuData=SKUStockData.find(ci=>ci.CategoryId==item.CategoryId && ci.ProductId==skuItem.ProductId ) || {};
                                    
                                    if(skuData.Stock!==0 && ( skuData.Stock==null || skuData.Stock=='')){
                                        notify('Please enter stock for '+skuItem.ProductName,'SHORT');
                                        isValid=false;
                                    }
                                    else if((isExpMandEnable==1 && isExpStockEnable==true) && skuData.ExpiryStock!==0 && (skuData.ExpiryStock==null || skuData.ExpiryStock=='')){
                                        notify('Please enter expiry stock for '+skuItem.ProductName,'SHORT');
                                        isValid=false;
                                    }
                                    else if(isExpStockEnable==true &&(parseInt(skuData.ExpiryStock)>parseInt(skuData.Stock))){
                                        notify('Expiry Stock value should be less than or equal to Stock for '+skuItem.ProductName,'SHORT');
                                        isValid=false;
                                    }else{
                                       
                                    }
                                }
                            })
                        );
                    }
                }
            }
            })
        );

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

    function onStockValChange(item,skuItem,val,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify('Please enter whole numbers only','SHORT');
                return;
            }
        }
        
        let allSKUData=SKUStockData;
        let defData={'CategoryId':item.CategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==item.CategoryId && i.ProductId==skuItem.ProductId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;

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

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

    function _renderStocks(){
        let isExpStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
        let isExpStockPIObj=isExpStockIndex>=0?KPIFields[isExpStockIndex]:{};
        let isExpStockEnable=isExpStockIndex>=0?isExpStockPIObj['KPIFieldEnable']:true;

        return (
        <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={(Platform.OS=='ios'?10:-100)} >  
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                const catIndex=index;
                const cindex=catImages.findIndex(i=>i.CategoryId==item.CategoryId);
                const cimgName=cindex>=0?(catImages[cindex]?catImages[cindex].ImageName:''):'';
                const cimgPath=cindex>=0?(catImages[cindex]?catImages[cindex].ImagePath:''):'';
                const showIMg=cimgPath!='' && cimgPath!=null;
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={customStyle.opening_Stock_catText}>{item.CategoryName}</Text>
                            </LinearGradient>
                            <View style={customStyle.osCat_actions}>
                                {/* <TouchableOpacity style={[customStyle.osCat_action_add_image,customStyle.osCat_actn_margin]}>
                                    <SvgXml width={50} height={50} xml={addImg} /> 
                                </TouchableOpacity> */}
                                { !showIMg && 
                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(item)}}>
                                        <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                    </TouchableOpacity>
                                }
                                { showIMg && 
                                    <View style={customStyle.osCatImageView}>
                                        <Image style={customStyle.osCatImage} source={{uri:cimgPath}}/>
                                        {/* <Image style={customStyle.osCatImage} source={require('../assets/performics/add_image.svg')}/> */}
                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(item)}}>
                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                        </TouchableOpacity>
                                    </View>                                    
                                }                                
                            </View>
                        </View>
                        <View style={customStyle.opening_Stock_prds}>
                            {
                                
                                <FlatList 
                                data={item.skulist}
                                extraData={rerenderdata2}
                                renderItem={({item,index})=>{
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.CategoryId==cat.CategoryId && i.ProductId==skus.ProductId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let stock=thisCatSkuData.Stock!=null?thisCatSkuData.Stock:'';
                                    let ex_stock=thisCatSkuData.ExpiryStock!=null?thisCatSkuData.ExpiryStock:'';
                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text>
                                            <View style={customStyle.openStk_prd_form}>
                                            {isExpStockEnable==true &&
                                                <View style={customStyle.openStk_prd_row}>
                                                    <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_1]}>
                                                        <Text style={customStyle.openStk_prd_label}>Stock</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input1_'+cat.CategoryId+'_'+skus.ProductId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle]}              
                                                            placeholder=""            
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(stock!=null?stock+'':'0')}
                                                            keyboardType='number-pad'
                                                            onSubmitEditing={()=>{focusToNext(cat,catIndex,skus,sku_index,'1')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'Stock','numeric')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                    <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_2]}>
                                                        <Text style={customStyle.openStk_prd_label}>Expiry Stock</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input2_'+cat.CategoryId+'_'+skus.ProductId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle]}              
                                                            placeholder=""            
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(ex_stock+'' || '')}
                                                            keyboardType='number-pad'
                                                            onSubmitEditing={()=>{focusToNext(cat,catIndex,skus,sku_index,'2')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'ExpiryStock','numeric')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                </View>
                                            }
                                            {isExpStockEnable==false &&
                                                <View style={customStyle.openStk_prd_row}>
                                                     <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>Stock</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input2_'+cat.CategoryId+'_'+skus.ProductId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                                            placeholder=""            
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(stock+'' || '')}
                                                            keyboardType='number-pad'
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'Stock','numeric')}}
                                                            onSubmitEditing={()=>{focusToNext(cat,catIndex,skus,sku_index,'2')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                </View>
                                            }
                                            </View>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView> 
        );
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_render_Alert()}
        <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&     
            _renderStocks()
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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