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, Animated, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, Fontisto, 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 * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import CameraImg from '../assets/performics/camera_front_image.svg'


function DB_POSM(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 animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [rerenderdata3, setrerenderdata3]= useState(0);
    const [rerenderdata4, setrerenderdata4]= useState(0);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const [dateValue, setDateValue] = useState('');
    const [WindowData, setWindowData] = useState([]);
    const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);
    const [globalWindows, setGlobalWindows] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const zoomView=useRef(null);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingWindow, setRatingWindow] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);
    const [searchedItem, setSearchedItem]= useState('');
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(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 || {};
        
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

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

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

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);
          // set switch camera flag as defined in mapping menu flag (if exists)
          let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
          let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
          let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
          setShowSwitchCamera(SwitchingCamera);
          await db.transaction(async function (txn) {        
            // check if data exists
            let selectlist=` w.DISTRIBUTOR_ID as DistributorId,w.POSM_HEADER_ID as posmHeaderId,wd.POSMDefinitionId,wd.PosmId,wd.POSMName,wd.PosmTypeId,wd.POSMTypeName,wd.POSMDefinitionTitle,wd.POSMDefinitionTitleEnable,wd.POSMTable,wd.POSMField,wd.POSMValue,wd.ChildName,wd.POSMRefImage,w.IS_PRESENT as IsPresent,w.POSM_IMAGE as POSMImage,w.STOCK_QTY as StockQty`;
            let join=` inner join Master_POSMDefinition wd on w.POSM_DEFINITION_ID=wd.POSMDefinitionId `;
            let q=` Select ${selectlist} from ${AppTables.DBPOSM_HDR_DATA} w  ${join} where w.DISTRIBUTOR_ID='${StoreId}'  `;

            // else pick data from masters
            let selectlist2=` db.DistributorId,w.POSMDefinitionId,w.PosmId,w.POSMName,w.PosmTypeId,w.POSMTypeName,w.POSMDefinitionTitle,w.POSMDefinitionTitleEnable,w.POSMTable,w.POSMField,w.POSMValue,w.ChildName,w.POSMRefImage,'' as IsPresent,'' as POSMImage,'' as StockQty`;
            let q2=`Select * from (select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN Mapping_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId  
                
                UNION

                select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN Adhoc_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId 

                `+(props.ShowNonMerList==true?`
                UNION

                select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN NonMerchandising_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId 

                
                `:'')
                +(props.ShowNonProgram==true?`
                UNION

                select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN NonProgram_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId 

                  `:'')
                +(props.ShowStoreSearch==true?`
                UNION

                select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN StoreSearch_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId 

                
                `:'')
                +(props.ShowBeatPlanList==true?`
                UNION

                select Distinct ${selectlist2} from Master_Distributor db
                INNER JOIN JourneyPlan_RouteWise jcp on db.DistributorId=jcp.DistributorId
                INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
                INNER JOIN Master_POSMDefinition w on w.POSMDefinitionId=MW.POSMDefinitionId   

                
                `:'')
                +` order by db.DistributorId,w.POSMDefinitionId)as db Where db.DistributorId=${StoreId} `
                ;
            
            
            
            
            console.log("dbposm q:",q)
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log("added rows",txnres2.rows.length)
                if(txnres2.rows.length>0){
                    let arr=[];let images=[],allWindowsData=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data=txnres2.rows.item(i);
                      
                        let animatedChoice=new Animated.Value((data.IsPresent=='1' || data.IsPresent==1?1:0));
                        data.animatedChoice=animatedChoice;
                    
                        let isPresent=data.IsPresent=='1' || data.IsPresent==1?1:0;
                        let imgObj={imgIndex:(i+1),url: data.POSMRefImage, props: {}}
                        images.push(imgObj);

                        let Image1=data.POSMImage!=null?data.POSMImage:'';
                        let Image1Path=Image1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+Image1:'';

                        let windowDataObj={'PosmId':data.PosmId,'POSMDefinitionId':data.POSMDefinitionId,'Image1':Image1,'Image1Path':Image1Path,'isPresent':isPresent,'StockQty':(data.StockQty || '')};
                        
                        arr.push(data);
                        
                        allWindowsData.push(windowDataObj);
                        if(i==txnres2.rows.length-1){
                            setWindowData(allWindowsData);
                            setWindows(arr);
                            setGlobalWindows(arr);
                            setZoomImageUrl(images);
                            setProcessing(false);
                        }                                
                    }
                }
                else{
                    console.log("dbposm q2:",q2)
                    await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                        console.log("default rows",txnres2.rows.length)
                        if(txnres2.rows.length>0){
                            let arr=[],images=[],allWindowsData=[];
                            for(var i=0;i<txnres2.rows.length;i++){
                                let data=txnres2.rows.item(i);
                                let animatedChoice=new Animated.Value(0);
                                data.animatedChoice=animatedChoice;
                               
                                let imgObj={imgIndex:(i+1),url: data.POSMRefImage, props: {}}
                                images.push(imgObj);

                                let windowDataObj={'PosmId':data.PosmId,'POSMDefinitionId':data.POSMDefinitionId};
                                
                                arr.push(data);
                                allWindowsData.push(windowDataObj);
                                if(i==txnres2.rows.length-1){
                                    setWindowData(allWindowsData);
                                    setWindows(arr);
                                    setGlobalWindows(arr);
                                    setZoomImageUrl(images);
                                    setProcessing(false);
                                }                                
                            }
                        }
                        else{
                            setProcessing(false);
                        }
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
                }
            },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);

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




    async function getImage(imgdata){
        let window=getImageProps.window || {};

        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();
            //jevanp changes
            let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

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

            let filename=storeData.StoreId+'_'+window.POSMDefinitionId+'_'+window.PosmId+'_'+(props.UserId || '')+'_DBPOSMImg-'+calculate_tym_date_for_filename+'.jpg';
            
            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Distributor Name:'+storeData.StoreName+' | Distributor Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName+' | Date:'+calculate_tym_date_over_img;

            
            let allData=WindowData;
            let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
            const wind_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId) ;
            let wind=wind_index>=0?allData[wind_index]:defData;
            
            let image_key='Image1';
            let image_key_path='Image1Path';
            wind[image_key]=filename;
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                console.log('image marker',uri);
                
                wind[image_key_path]=uri;
                wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                setWindowData(allData);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);

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

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

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        let d1n=new Date();
        let d3=moment(d1n).format('MM/DD/YYYY');
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   
              //  remove old data
              await txn.executeSql(`DELETE FROM ${AppTables.DBPOSM_HDR_DATA} WHERE DISTRIBUTOR_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                  console.log('window hdr data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);
                // add data
                var values='',childV='';
                for (const wi in Windows){
                    const window=Windows[wi];

                    const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                    let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                    let Image1=wind.Image1!=null?wind.Image1:'';
                    let Image1Path=wind.Image1Path!=null?wind.Image1Path:'';
                    

                    let POSM_HEADER_ID='POSM'+wi+(Math.floor(Math.random()*1000)+1);
                    let {POSMDefinitionId,PosmId,POSMName,PosmTypeId,POSMTypeName,POSMTable,POSMField,POSMValue,ChildName}=window;
                    let StockQty=wind.StockQty!=null?wind.StockQty:'';

                    values+=values!=''?' , ':'';
                    values+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMName}','${PosmTypeId}','${POSMTypeName}','${POSMTable}','${POSMField}','${POSMValue}','${ChildName}','${isPresent}','${Image1}','${StockQty}','${d3}') `;
                }
                
                let add_hdr_data=`INSERT INTO ${AppTables.DBPOSM_HDR_DATA}(POSM_HEADER_ID,DISTRIBUTOR_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,POSM_NAME,POSM_TYPE_ID,POSM_TYPE_NAME,POSM_TABLE,POSM_FIELD,POSM_VALUE,CHILD_NAME,IS_PRESENT,POSM_IMAGE,STOCK_QTY,ADDED_DATE) VALUES ${values} `;
                await txn.executeSql(add_hdr_data,[],async function (txn2, txnres) { 
                    console.log('posm header data added');
                    setProcessing(false);notify(ST.POSMdataupdatedsuccessfully);
                    props.navigation.goBack();
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotaddPOSMdata); },);
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function validate(){
        let isValid=true;
        return new Promise((resolve,reject)=>{
            for (const wi in Windows){
                const window=Windows[wi];
                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image1Path=wind.Image1Path!=null?wind.Image1Path:'';
                let StockQty=wind.StockQty!=null?wind.StockQty:'';

                if(isPresent=='1'){
                    if(StockQty==''){
                        notify(`Please enter stock for ${window.POSMName}`,'LONG');
                        resolve(false);return;
                    }
                    else if(Image1==''){
                        notify(`${ST.Pleaseclickallimagesfor} ${window.POSMName}`,'LONG');
                        resolve(false);return;
                    }
                }
                else{
                   
                }

                if(wi==(Windows.length-1)){
                    resolve(true);return;
                }
                
            }
            
        }).then((val)=>{return val})
        .catch((err)=>{console.log(err); return false});
    
    }


   
    function onChoiceSelect(item,val,key,animatedChoice){
        var val1=0;
        val==1?val1=1:'';
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onWindowDataChange(item,val,key)
    }

    function onWindowDataChange(item,val,key,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        let allData=WindowData;
        let defData={'PosmId':item.PosmId,'POSMDefinitionId':item.POSMDefinitionId};
        const win_index=allData.findIndex(i=>i.PosmId==item.PosmId && i.POSMDefinitionId==item.POSMDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

        if(key=='ReasonId'){
            let rsn=reasons_list.find(r=>r.ReasonId==val) || {};
            wind['Reason']=rsn.Reason || '';
        }

        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

   

    function onSaveCancel(){
        setShowAlert(false);
    }

  

    function openImageRefView(windowIndex=0){
        setrefImageIndex(windowIndex);
        setShow_zoomImage(true);
    }


    function _renderWindow(){
        return (
            <FlatList 
            data={Windows}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.Win_scroll} 
            style={customStyle.Win_scrollO}
            listKey={(item, index) => `posm_${index.toString()}`}
            renderItem={({item,index})=>{
                const window=item;
                
                let RefImage=window.POSMRefImage;

                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                
                let StockQty=wind.StockQty!=null?wind.StockQty+'':'';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image1Path=wind.Image1Path!=null?wind.Image1Path:'';
                

                var xpos=isPresent=='1'?-75:0;
                if(window.animatedChoice!=null ){
                    xpos=window.animatedChoice.interpolate({
                        inputRange:[0,1],
                        outputRange:[0,-75],
                    });
                }

             
                return(
                    <View style={customStyle.WItem_wrap} key={'window_'+index}>
                        <View style={customStyle.WItem_Hdr}>                            
                            <View style={customStyle.WItem_Hdrbg}>
                                <Text style={customStyle.WItem_HdrText}>{window.POSMName}</Text>
                                <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={()=>{openImageRefView(index)}}>
                                    <Entypo name='image-inverted' size={24} color={PageTheme.$accent_color} />    
                                </TouchableOpacity>
                            </View>
                        </View>
                        
                        <View style={customStyle.WForm}>
                            <View style={[customStyle.openStk_prd_cols,customStyle.mt10]}>
                                <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                    <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                                    <View style={customStyle.openStk_prd_choiceBoxCon}>
                                        <View style={customStyle.openStk_prd_choiceBox}>
                                            <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isPresent=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                            {   transform: [{   translateX:xpos }],  }]}></Animated.View>
                                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(window,1,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,(isPresent=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                            </TouchableOpacity>
                                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(window,0,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,(isPresent=='0'?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                                

                                {(isPresent=='1') && 
                                <View>
                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.pb10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{'Stock'}</Text>
                                        <TextInput 
                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                            placeholder=""    
                                            autoComplete='off'        
                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                            value={StockQty}
                                            keyboardType='number-pad'
                                            onChangeText={(val)=>{onWindowDataChange(window,val,'StockQty','numeric')}}
                                        />
                                    </View>
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{ST.CaptureImage}</Text>
                                    </LinearGradient>
                                    <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]}>
                                        <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                        { (Image1Path=='' || Image1Path==null) && 
                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(window)}}>
                                                <CameraImg width={80} height={80} />                                     
                                            </TouchableOpacity>
                                        }
                                        { (Image1Path!='' && Image1Path!=null) && 
                                            <View style={customStyle.osCatImageView}>
                                                <Image style={customStyle.osCatImage} source={{uri:Image1Path}}/>
                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window)}}>
                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                </TouchableOpacity>
                                            </View>                                    
                                        }   
                                        </View>
                                    </View>
                                    </View>
                                </View>
                                }
                                                    
                            </View>
                        </View>
                    </View>
                );
            }}
            />
        )
    }

    function _renderHeader(currentIndex){        
        return(
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2={};
        if(searchedQry!=null && searchedQry!=''){
            for(let i=0;i<globalWindows.length;i++){
                let item=globalWindows[i];
                arr2=Object.assign({'test':'1'} , item);
                if(item.POSMName.toLowerCase().includes(searchedQry)){
                    arr.push(arr2);
                }
            }
        }
        else{
          arr=globalWindows;
        }

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

    function getSearchBar(){
        let isSearchEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='SearchEnable')
        let isSearchEnableKPIObj=isSearchEnableIndex>=0?KPIFields[isSearchEnableIndex]:{};
        let isSearchEnable=isSearchEnableIndex>=0?isSearchEnableKPIObj['KPIFieldEnable']:false;
        if(isSearchEnable==true){
            return (
                <View style={customStyle.storel_searchbar}>
                  <TextInput 
                    style={[customStyle.storel_searchInput]}
                    placeholder={ST.Searchby+' '+currentMenu.MenuName}
                    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>
            )
        }
        else{
            return(
                <View></View>
            )
        }
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <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,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          {getSearchBar()}
          { Object.keys(storeData).length>0 && 
            <View style={customStyle.Windows_Wrap}>
                {_renderWindow()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
       
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} index={refImageIndex}
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }  
      </Container>   
    ); 
}
  
  

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