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, 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, FontAwesome, Fontisto, MaterialCommunityIcons} from '../components/icons';

import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';

import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import DateTimePicker from '@react-native-community/datetimepicker';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import AstrickCamera from '../assets/icons/astrickcamera.svg';


function POSSale(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};

    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    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 [getImageProps,setGetImageProps]= useState({});
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const [WindowData, setWindowData] = useState([]);
    const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [zoomImageIndex, setzoomImageIndex] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showCamera, setShowCamera] = useState(false);
    const zoomView=useRef(null);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingWindow, setRatingWindow] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);

    const [AllImagesData, setAllImagesData] = useState([]);
    const [globalWindows, setGlobalWindows] = useState([]);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [Image1, setImage1] = useState('');
    const [Image2, setImage2] = useState('');
    const [imageCapture, setimageCapture] = useState('');
    const [imageCapture2, setimageCapture2] = useState('');
    
   
    
    const [DataCleanModal, setDataCleanModal] = useState(false);
    const [DataCleanAnim, setDataCleanAnim] = useState("");
    const [DataCleanItem, setDataCleanItem] = useState({});
    const [isPresentClean, setIsPresentClean] = useState(0);
    const [data, setData] = useState({});
    const [POSDef, setPOSDef] = useState({});
    const [Months, setMonths] = useState([]);
    const [posSData, setPosSData] = useState({});
    const [posSImgArr, setPosSImgArr] = useState([]);

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);


    const [InputChange, setInputChange] = useState([]);
    const DefPOSWind={"WindowId":"0","WindowName":"POS Sale"};

    const inputRefs = useRef({});    
    
    
    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 cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
       
        
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        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,StoreCategoryId,StoreClassId}=storeData1;
          let arrobj=[];
          
          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 c_month=moment().format("MMM YYYY"),p_month=moment().subtract(1,"months").format("MMM YYYY"),ptp_month=moment().subtract(2,"months").format("MMM YYYY");
          let monthsArr=[{"MonthId":c_month,"MonthName":c_month},{"MonthId":p_month,"MonthName":p_month},{"MonthId":ptp_month,"MonthName":ptp_month}];
          setMonths(monthsArr);

          
         
       

          await db.transaction(async function (txn) {   

            let q3=`Select PosReasonId as ReasonId,PosReason as Reason From Master_PosSaleReason`;
            await txn.executeSql(q3,[],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);
                        console.log('data',data)
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            setReasons_list(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);

            // check if data exists
            let q5=` Select * from ${AppTables.HEADER_POSSALE_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            await txn.executeSql(q5,[],async function (txn5, txnres5) { 
                if(txnres5.rows.length>0){
                    let pos_d=txnres5.rows.item(0);
                    let {MONTH,IMAGE1,IMAGE2,TOTAL_POS_VALUE}=pos_d;
                    // let image1Path=IMAGE1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+IMAGE1:'';
                    // let image2Path=IMAGE2!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+IMAGE2:'';
                    let posdata_obj={"MonthName":MONTH,"TotalPosValue":TOTAL_POS_VALUE};//,"Image1Name":IMAGE1,"Image1":image1Path,"Image2Name":IMAGE2,"Image2":image2Path
                    setPosSData(posdata_obj);
                }
            },function (txnE,txnerr) { console.log(txnerr); });  
            
            let q=` Select * from Master_PosSaleDefinition p INNER join Mapping_StorePosSaleDefinition mps on p.PosDefinitionId=mps.PosDefinitionId where mps.StoreId='${StoreId}'  `;
            let possaledata ={},defposData=[],inputChangeFlag=[];
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log('q dicide',txnres2.rows.length)
                if(txnres2.rows.length>0){
                    let data=txnres2.rows.item(0);
                    let PosOverall=data.PosOverall==true || data.PosOverall=='true'?1:0;
                    let poscheckAssortment = data.PosCheckAssortment
                    console.log('PSA',poscheckAssortment)
                    possaledata = data;

                    let HeaderImageRequired=data.HeaderImageRequired==1 || data.HeaderImageRequired=='1' ?true:false;
                    let HeaderImageCount=data.HeaderImageCount!=null?data.HeaderImageCount:2;
                    let HeaderImageMandatory=data.HeaderImageMandatory!=null?data.HeaderImageMandatory:2;

                    setPOSDef(possaledata);
                    
                    let q2=` Select * from ${AppTables.POSSALE_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                
                    await txn.executeSql(q2,[],async function (txn2, txnres3) { 
                        console.log('added data:',txnres2.rows.length);
                        if(txnres3.rows.length>0){
                            let allWindowsData=[];
                            
                            for(var i=0;i<txnres3.rows.length;i++){
                                let data=txnres3.rows.item(i);
                                console.log('dataloading:',data)
                                let obj={"WindowId":data.WINDOW_ID,"WindowName":data.WINDOW_NAME,"PosValue":data.POS_VALUE,"PosVolume":data.POS_VOLUME,"ReasonId":data.REASONID,"Reason":data.REASON,"isPresent":data.ISPRESENT}
                                let animatedChoice=new Animated.Value((data.IsPresent=='1' || data.IsPresent==1?1:0));
                                data.animatedChoice=animatedChoice;
                                let changesFlag = {WindowId:data.WINDOW_ID, WindowName:data.WINDOW_NAME, Flag:false}
                                console.log('changesFlag',changesFlag)
                                inputChangeFlag.push(changesFlag)
                                allWindowsData.push(obj);
                                
                                if(i==txnres3.rows.length-1)
                                {
                                    setInputChange(inputChangeFlag)
                                    setWindowData(allWindowsData);
                                    let PosSaleImages= HeaderImageRequired==true?await getPosSaleImages(HeaderImageCount,HeaderImageMandatory,possaledata,storeData1,menu1):[];
                                    setPosSImgArr(PosSaleImages);
                                    setProcessing(false);    
                                }
                            }          
                        }
                        else{
                            
                            if(PosOverall==1){
                                let obj={"WindowId":DefPOSWind.WindowId,"WindowName":DefPOSWind.WindowName,"PosValue":"","PosVolume":"","ReasonId":"","Reason":"","isPresent":"0"}
                                let changesFlag = {WindowId:DefPOSWind.WindowId, WindowName:DefPOSWind.WindowName, Flag:false}
                                inputChangeFlag.push(changesFlag)
                                defposData.push(obj);
                                
                                setInputChange(inputChangeFlag)
                                setWindowData(defposData);
                                let PosSaleImages= HeaderImageRequired==true?await getPosSaleImages(HeaderImageCount,HeaderImageMandatory,possaledata,storeData1,menu1):[];
                                setPosSImgArr(PosSaleImages);
                                setProcessing(false); 
                            }  
                            else
                            {
                                let q4='';
                                let join3=` INNER join Mapping_PosSaleDefinition mps on p.${data.PosField}=mps.PosSaleValue `;
                                let join2 = data.PosCheckAssortment==true?` INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId ` :'';
                                let assortmentCond=data.PosCheckAssortment==true? ` where mp.StoreId='${StoreId}' `:'';
                                data.PosTable=data.PosTable!=null?data.PosTable:'';
                                if(data.PosTable.toLowerCase() == HierarchyTbls.Master_Category.toLowerCase()){
                                    q4=`SELECT DISTINCT p.CategoryId as WindowId,p.CategoryName as WindowName  from Product_Master p  ${join2}  ${join3} ${assortmentCond} order by p.CategorySequence`;
                                }
                                else if(data.PosTable.toLowerCase() == HierarchyTbls.Master_Brand.toLowerCase()){
                                    q4=`SELECT DISTINCT p.BrandId as WindowId,p.BrandName as WindowName  from Product_Master p  ${join2} ${join3}  ${assortmentCond} order by p.BrandSequence`;
                                }
                                else if(data.PosTable.toLowerCase() == HierarchyTbls.Master_SubCategory.toLowerCase()){
                                    q4=`SELECT DISTINCT p.SubCategoryId as WindowId,p.SubCategoryName as WindowName from Product_Master p  ${join2} ${join3}  ${assortmentCond} order by p.SubCategorySequence`;
                                }
                                else if(data.PosTable.toLowerCase() == HierarchyTbls.Master_Product.toLowerCase()){
                                    q4=`SELECT DISTINCT p.ProductId as WindowId,p.ProductName as WindowName  from Product_Master p  ${join2} ${join3} ${assortmentCond} order by p.ProductSequence`;
                                }

                                await txn.executeSql(q4,[],async function (txn4, txnres4) { 
                                    
                                    let datapossale=[], posassdata=[],inputChangeFlag=[];
                                    if(txnres4.rows.length>0){
            
                                        let arr=[];
                                        for(var i=0;i<txnres4.rows.length;i++){
                                            let data =txnres4.rows.item(i);
                                            arr.push(data);
                                            
                                            let obj={"WindowId":data.WindowId,"WindowName":data.WindowName,"PosValue":'',"PosVolume":'',"ReasonId":'',"Reason":'',"isPresent":0}
                                            let animatedChoice=new Animated.Value((data.IsPresent=='1' || data.IsPresent==1?1:0));
                                            data.animatedChoice=animatedChoice;
                                            let changesFlag = {WindowId:data.WindowId, WindowName: data.WindowName, Flag:false}
                                            inputChangeFlag.push(changesFlag)
                                            datapossale.push(obj);
                        
                                            if(i==txnres4.rows.length-1){
                                                setInputChange(inputChangeFlag)
                                                setWindowData(datapossale);
                                                let PosSaleImages= HeaderImageRequired==true?await getPosSaleImages(HeaderImageCount,HeaderImageMandatory,possaledata,storeData1,menu1):[];
                                                setPosSImgArr(PosSaleImages);
                                                setPOSDef(possaledata);
                                                setProcessing(false);    
                                            }
                                        }
                                    }
                                    else{
                                        let PosSaleImages= HeaderImageRequired==true?await getPosSaleImages(HeaderImageCount,HeaderImageMandatory,possaledata,storeData1,menu1):[];
                                        setPosSImgArr(PosSaleImages);
                                        setProcessing(false);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr);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 getPosSaleImages(ImageCount,MandCount,data,storeData1,menu1){
        let WindowSplits_def=  [];
        for(var s=0;s<ImageCount;s++){
            let isMandatory=false;
            if(s<MandCount){
                isMandatory=true;  
            }
            let obj={'Image1Name':'','Image1':'',img1Required:isMandatory};
            WindowSplits_def.push(obj);
        }
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {

                let q=`select * from ${AppTables.POSSALE_IMAGES} where POSDEFINITIONID='${data.PosDefinitionId}' and STORE_ID='${storeData1.StoreId}' and VISIT_DATE='${d2}' `;
               
                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);
                           
                            let isMandatory=false;
                            if(i<MandCount){
                                isMandatory=true;  
                            }
                            let Image1= data.IMAGE1!=null && data.IMAGE1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE1:'';
                            let obj={'Image1Name':data.IMAGE1,'Image1':Image1,img1Required:isMandatory};
                            arr.push(obj);

                            if(i==txnres2.rows.length-1){
                                resolve(arr)
                            }                                
                        }
                    }
                    else{
                        resolve(WindowSplits_def)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(WindowSplits_def) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return WindowSplits_def;
        });
    }


    async function onSubmitData(){
        let isvalid = '';
        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.HEADER_POSSALE_DATA} WHERE STORE_ID='${StoreId}'and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                    console.log('Possale hdr data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);

                await txn.executeSql(`DELETE FROM ${AppTables.POSSALE_DATA} WHERE STORE_ID='${StoreId}'and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                    console.log('Possale data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);


                await txn.executeSql(`DELETE FROM ${AppTables.POSSALE_IMAGES} WHERE STORE_ID='${StoreId}'and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                    console.log('Possale images data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);

                

                var values='',values1='',img_values='';
                let {MonthName,Image1Name,Image2Name,TotalPosValue}=posSData;
                values1+=` ('${StoreId}','${d3}','${MonthName}','${Image1Name || ''}','${Image2Name || ''}','${TotalPosValue}','${d3}') `;

                let PosOverall=POSDef.PosOverall==true || POSDef.PosOverall=='true'?1:0;
                let HeaderImageRequired=POSDef.HeaderImageRequired==1 || POSDef.HeaderImageRequired=='1'?true:false;
                let HeaderImageCount=POSDef.HeaderImageCount!=null?POSDef.HeaderImageCount:2;
                let HeaderImageMandatory=POSDef.HeaderImageMandatory!=null?POSDef.HeaderImageMandatory:2;
                
                for (const wi in WindowData){
                    const window=WindowData[wi];
                    
                    let wind=window;
                    let isPresent = '', ReasonId='', Reason='', PosValue='',PosVolume='',WindowId='',WindowName='';
                    WindowId = wind.WindowId;
                    WindowName = wind.WindowName;
                    isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                    ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                    Reason=wind.Reason!=null?wind.Reason:'';
                    PosValue=wind.PosValue!=null?wind.PosValue:'';
                    PosVolume=wind.PosVolume!=null?wind.PosVolume:'';           

                    values+=values!=''?' , ':'';
                
                    values+=` ('${StoreId}','${d3}','${WindowId}','${WindowName}','${POSDef.PosDefinitionId}','${PosValue}','${PosVolume}','${isPresent}','${ReasonId}','${Reason}','${d3}') `;
                    
                }

                for (const imgI in posSImgArr){
                    let item=posSImgArr[imgI];
                    let Image1=item.Image1!=null?item.Image1:'';
                    let Image1Name=item.Image1Name!=null?item.Image1Name:'';
                    img_values+=img_values!=''?' , ':'';
                
                    img_values+=` ('${StoreId}','${d3}','${POSDef.PosDefinitionId}','${Image1Name}','${d3}') `;
                }

                console.log('values:',values);
                let header_add_possale_data=`INSERT INTO ${AppTables.HEADER_POSSALE_DATA} (STORE_ID,VISIT_DATE,MONTH,IMAGE1,IMAGE2,TOTAL_POS_VALUE,ADDED_DATE) VALUES ${values1} `;
                console.log('add_possale_data',header_add_possale_data)

                let add_possale_data=`INSERT INTO ${AppTables.POSSALE_DATA} (STORE_ID,VISIT_DATE,WINDOW_ID,WINDOW_NAME,POSDEFINITIONID,POS_VALUE,POS_VOLUME,ISPRESENT,REASONID,REASON,ADDED_DATE) VALUES ${values} `;
                let add_possale_Images=`INSERT INTO ${AppTables.POSSALE_IMAGES} (STORE_ID,VISIT_DATE,POSDEFINITIONID,IMAGE1,ADDED_DATE) VALUES ${img_values} `;
                
                await txn.executeSql(header_add_possale_data,[],async function (txn2, txnres) { 
                    console.log('POSSALE header data added');
                    await txn.executeSql(add_possale_data,[],async function (txn2, txnres) { 
                        console.log('POSSALE data added');
                        if(HeaderImageRequired==true && HeaderImageMandatory>=0){
                        await txn.executeSql(add_possale_Images,[],async function (txn2, txnres) { 
                            console.log('POSSALE header images added');
                            props.navigation.goBack();
                        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot save possale data'); },);
                    }else{
                        props.navigation.goBack();
                    }
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot save possale data'); },);
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot save headerpossale data'); },);
                
            
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function executeQuery(q){
        return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
            await txn.executeSql(q,[],async function (txn2, txnres2) {           
              resolve(true);
            },function(Etxn,txnerr){console.log(txnerr);resolve(false) });
          }); 
        }).then((val)=>{
          return val;
        }).catch((err)=>{
            console.log(err);
          return false;
        })
    }




    async function validate(){
        console.log('validate')
        let isValid=true;
        let isReasonEnable=POSDef.PosNotExistReasonEnable=='true' || POSDef.PosNotExistReasonEnable==1? 1:0;
        let isshowPosValue=POSDef.ShowPosValue=='true' || POSDef.ShowPosValue==1?1:0;
        let isshowPosVolume=POSDef.ShowPosVolume=='true' || POSDef.ShowPosVolume==1?1:0;

        let ShowHdrPosSaleI=KPIFields.findIndex(i=>i.KPIFieldName=='ShowTotalPosSaleHeade');
        let ShowHdrPosSaleObj=ShowHdrPosSaleI>=0?KPIFields[ShowHdrPosSaleI]:{};
        let ShowHdrPosSale=ShowHdrPosSaleI>=0?ShowHdrPosSaleObj['KPIFieldEnable']:false;
        let ShowHdrPosSaleDN=ShowHdrPosSaleObj['KPIFieldDisplayName']!='' && ShowHdrPosSaleObj['KPIFieldDisplayName']!=null ? ShowHdrPosSaleObj['KPIFieldDisplayName'] :"Total POS Value";

        // let posCAValue=KPIFields.findIndex(i=>i.KPIFieldName=='PosSaleCameraAllow')
        // let posCAValueObj=posCAValue>=0?KPIFields[posCAValue]:{};
        // let posCAValueEnable=posCAValue>=0?posCAValueObj['KPIFieldEnable']:true;

        let HeaderImageRequired=POSDef.HeaderImageRequired==1 || POSDef.HeaderImageRequired=='1'?true:false;
        let HeaderImageCount=POSDef.HeaderImageCount!=null?POSDef.HeaderImageCount:2;
        let HeaderImageMandatory=POSDef.HeaderImageMandatory!=null?POSDef.HeaderImageMandatory:2;
       
        

        
        return new Promise(async(resolve,reject)=>{
            let {Image1,Image1Name,Image2,Image2Name,MonthName,TotalPosValue}=posSData;
            if(MonthName==null || MonthName==''){
                notify(`Please select month`,'SHORT');
                resolve(false);return;
            }
            else if(ShowHdrPosSale==true && TotalPosValue!==0 && (TotalPosValue=='' || TotalPosValue==null)){
                notify(`Please enter ${ShowHdrPosSaleDN} value`,'SHORT');
                resolve(false);return;
            }
            // else if(posCAValueEnable && (Image1==null || Image1=='')){
            //     notify(`Please click image`,'SHORT');
            //     resolve(false);return;
            // }
            else{
                
                if(HeaderImageRequired==true && HeaderImageMandatory>=0){
                    let res=await new Promise((resolve1,reject1)=>{
                        posSImgArr.map((item,index)=>{
                            if(StoreCameraAllow && item.img1Required==true && (item.Image1=='' || item.Image1==null)){
                                notify(`Please click image`,'SHORT');
                                resolve1(false);
                            }
                            if(index==posSImgArr.length-1){
                                resolve1(true);
                            }
                        })
                    }).catch((err)=>{
                        console.log("error:",err);
                        return false;
                    })
                    console.log("HeaderImageRequired validate res:",res)
                    if(res==false){
                        isValid=false;return false;
                    }
                }
                if(isValid){
                    for (const wi in WindowData){
                        const window=WindowData[wi];
                        const wind=window;
                        let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                        let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                        let PosValue=wind.PosValue!=null?wind.PosValue:'';
                        let PosVolume=wind.PosVolume!=null?wind.PosVolume:'';
                        if(isPresent=='1'){
                            if(isshowPosValue==true && ( PosValue==null || PosValue=='')){
                                notify(`Please Enter ${POSDef.PosValueLabel} `,'SHORT');
                                resolve(false);return;
                            }
                            else if(isshowPosVolume==true && (PosVolume==null || PosVolume=='')){
                                notify(`Please Enter ${POSDef.PosVolumeLabel}`,'SHORT');
                                resolve(false);return;
                            }
                        }
                        else {
                            if(isReasonEnable==true && ReasonId=='' ){
                                notify(`${'Please Select Reason'}`,'SHORT');
                                resolve(false);return;
                            }
                        }

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

    function onselectionChange3(option,keyLbl,keyVal,otherData){
        let item=otherData.window;
        let index=otherData.index;

        let allData=WindowData;
        let wind = item; 
        wind[keyVal]=option.value;
        wind[keyLbl]=option.label;
       
        let objIndex = InputChange.findIndex(i=>i.WindowId==item.WindowId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        setInputChange(winArr);


        index>=0?allData[index]=wind:'';
        console.log('windowallData',allData)

        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
       
    }
   

    async function disableQtns(sqtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
       
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.VisibilityQuestionId==qid) || {};
                    let s_qtn=sqtns[s_qtnindex];
                    s_qtn['isDisabled']=true
                    sqtns[s_qtnindex]=s_qtn;
                    let id_key=s_qtn.VisibilityQuestionId+'_AnswerId'; 
                    let ans_key=s_qtn.VisibilityQuestionId+'_Answer'; 
                    data[id_key]=0;
                    data[ans_key]='';

                    wind['WindowQA']=data;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    
                    return false
                })
            ).then(async (val)=>{

                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.VisibilityDefinitionId==window.VisibilityDefinitionId && i.VisibilityId==window.VisibilityId)
                if(windowIndex>=0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    setWindowData(allData);
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    setHasUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                }
                
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.VisibilityQuestionId==qid) || {};
                let s_qtn=sqtns[s_qtnindex];
                s_qtn['isDisabled']=false
                sqtns[s_qtnindex]=s_qtn;
                return false
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                await disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            }
            else{
                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.VisibilityDefinitionId==window.VisibilityDefinitionId && i.VisibilityId==window.VisibilityId)
                if(windowIndex>0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    setHasUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                }
            }
        })
    }

   
    function setTextValue(value,qtn,window) {        
        let id_key=qtn.VisibilityQuestionId+'_AnswerId'; 
        let ans_key=qtn.VisibilityQuestionId+'_Answer'; 
        
        let allData=WindowData;
        let defData={'PosDefinitionId':window.PosDefinitionId};
        const wind_index=allData.findIndex(i=> i.PosDefinitionId==window.PosDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};

        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.VisibilityQuestionId+'_Date'; 
            let d=value!=null?new Date(value):new Date();
            let mfdate=moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn,window,false);
            obj[id_key]=0;
            obj[ans_key]=mfdate;
            obj[date_key]=moment(d).format('MM/DD/YYYY');
        }
        else{
            obj[id_key]=0;
            obj[ans_key]=value;
        }
        
        console.log(value,obj);
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.VisibilityQuestionId==qtn.VisibilityQuestionId);
       
        if(newqtnIndex>=0){
            let newqtn=allQtns[newqtnIndex];
            newqtn.showDatePicker=show;
            allQtns[newqtnIndex]=newqtn;
            window['WindowQuestions']=allQtns;
            let allWindows=Windows;
            const winIndex=allWindows.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId) || {};
            allWindows[winIndex]=window;
            setWindows(allWindows);
            setGlobalWindows(allwindows);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    function setRatingValue(data){
        setRatingOrder(data);
    }

    function onRatingCancel(){ 
        setShowRating(false);
    }

    function onRatingSave(){
        setShowRating(false);
        let qtn=RatingQtn;
        let window=RatingWindow;
        let id_key=qtn.VisibilityQuestionId+'_AnswerId'; 
        let ans_key=qtn.VisibilityQuestionId+'_Answer'; 
        let rating_key=qtn.VisibilityQuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })

        let allData=WindowData;
        let defData={'PosDefinitionId':window.PosDefinitionId};
        const wind_index=allData.findIndex(i=>i.PosDefinitionId==window.PosDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};

        obj[rating_key]=ids.join(',');
        obj[id_key]=0;
        obj[ans_key]=anss.join(',');
        
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------7",winArr)

        setInputChange(winArr)
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }
    
   
    function onChoiceSelect(item,index,val,key,animatedChoice){

        let win_index=InputChange.find(i=>i.WindowId==item.WindowId)
        console.log('win_index123',win_index)
        let changeValue=win_index.Flag>=0?win_index.Flag:false;
        console.log("win_index--------",win_index)
        console.log("changeValue--------",changeValue)
        console.log("InputChange--------",InputChange)

        
        if(true){
            setIsPresentClean(val)
            setDataCleanAnim(animatedChoice)
            setDataCleanItem(item)
            setDataCleanModal(true)
            return
        }
        
        var val1=0;
        val==1?val1=1:'';
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onWindowDataChange(item,index,val,key)
    }

    function onWindowDataChange(item,index,val,key,type=''){
        
        let allData=WindowData;
        
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        let wind = item;
      
        let PosOverall=POSDef.PosOverall==true || POSDef.PosOverall=='true'?1:0;
        wind[key]=val;
        // if(key=='ReasonId'){
        //     let rsn=reasons_list.find(r=>r.ReasonId==val) || {};
        //     wind['Reason']=rsn.Reason || '';
        // }

        index>=0?allData[index]=wind:'';


        let objIndex = InputChange.findIndex(i=>i.WindowId==item.WindowId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)
      
        console.log('windowallData',allData)

        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

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

        let alldata=posSData;
        alldata[key]=val;
        setPosSData(alldata);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option,keyLbl,keyVal,otherData){
        let allData=posSData;
        allData[keyLbl]=option.label;
        allData[keyVal]=option.value;
 
        setPosSData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
      }

    
    async function setWindowStockVal(val,window,stockProd,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify(ST.Pleaseenterwholenumbersonly,'SHORT');
                return;
            }
        }
        
        let allData=WindowData;
        let defData={'VisibilityId':window.VisibilityId,'VisibilityDefinitionId':window.VisibilityDefinitionId};
        const win_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        let sdIndex=WStocksData.findIndex(i=> i.ProductId==stockProd.VisibilityStockValue);
        let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.VisibilityStockValue,'Stock':''};
        sd[key]=val;
        sdIndex>=0?WStocksData[sdIndex]=sd:WStocksData.push(sd);
        wind['WStocksData']=WStocksData;
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        if(key=='isPVisPresent'){
            let isAllChecked = await verifyAllChecked(val,window,stockProd,key);
            wind['isAllSKUChecked']=isAllChecked;
        }
        
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata4(!rerenderdata4);
    }

    
    

    async function onCatTextChange(window,key,val){
        let item=window;
        let allData=WindowData;
        let defData={'VisibilityId':item.VisibilityId,'VisibilityDefinitionId':item.VisibilityDefinitionId};
        const win_index=allData.findIndex(i=>i.VisibilityId==item.VisibilityId && i.VisibilityDefinitionId==item.VisibilityDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

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


    async function verifyAllChecked(val,window,stockProd,key){
        return await new Promise((resolve,reject)=>{
            let WindowStocks=window.WindowStocks || [];
            let allData=WindowData;
            const win_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
            let wind=win_index>=0?(allData[win_index] || defData) : defData;
            let WStocksData=wind['WStocksData'] || [];
            if(WindowStocks.length>0){
                let isAllChecked=1;
                for(var i=0;i<WindowStocks.length;i++){
                    let stockProd=WindowStocks[i];
                    
                    let sdIndex1=WStocksData.findIndex(a=> a.ProductId==stockProd.VisibilityStockValue);
                    let sd1=sdIndex1>=0?WStocksData[sdIndex1]:{};
                    let isPVisPresent=sd1.isPVisPresent;
                    if(isPVisPresent==null || isPVisPresent=='' || isPVisPresent==0 || isPVisPresent=='0'){
                        isAllChecked=0
                    }

                    if(i==WindowStocks.length-1){
                        resolve(isAllChecked);
                    }
                }
            }
            else{
                resolve(0);
            }
            
        }).catch((err)=>{
            console.log(err);
            return 0;
        });
    }

    async function getImage(imgdata){
        let type=getImageProps.type || '';
        let ImageIndex=getImageProps.ImageIndex;
        console.log('getImage ImageIndex:',type,ImageIndex)
        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.height;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

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

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

      let filename=(props.UserId || '')+'_PossaleImg-'+calculate_tym_date_for_filename+'.jpg';
            
            let allData=posSImgArr;//posSData;
            let image_key,image_key_path;
            let imgObj={};
            if(ImageIndex>=0){
                imgObj=allData[ImageIndex];
            }
            if(type=='1'){
                image_key='Image1Name';
                image_key_path="Image1";
            }
            // else{
            //     image_key='Image2Name';
            //     image_key_path="Image2";
            // }

            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+'  | Image Type: '+currentMenu.MenuName+' | Date:'+calculate_tym_date_over_img;
            
            
            // renamefile
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            
            console.log('imagePath',imagePath,imgObj)
            RNFS.copyFile(imgurl,imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                imgObj[image_key]=filename;
                imgObj[image_key_path]=uri;
                
                ImageIndex>=0?allData[ImageIndex]=imgObj:allData.push(imgObj);
                console.log("allData:",allData);
                setPosSImgArr(allData);
                setSelectedImg(uri);
                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 removeImage(){
        let index=toRemoveIndex;
        let allData=AllImagesData;
        let imgData=allData[index];
        let imgPath=imgData.ImagePath || '';
        if(imgPath!=''){
            let imgPath1='file://'+imgPath;
            RNFS.unlink(imgPath1);
        }
        allData.splice(index,1);
        setAllImagesData(allData);
    }

    async function  onRemoveImage(imgName,index){
        setToRemoveIndex(index);
    }

  
    async function openCamera(type='1',index=''){  
        setGetImageProps({'type':type,"ImageIndex":index}); 
        setShowCamera(true);
    }
  

    function onWindowDataClean(){
        if(DataCleanAnim!=null){
            console.log("anim---")
            let anim=isPresentClean==1?1:'';
            Animated.timing(DataCleanAnim, {
                toValue:anim,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        let allData=WindowData;
        let WindowSplits =  [];
        for(var s=0;s<DataCleanItem.NoOfSplit;s++){
            let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':''};
            WindowSplits.push(obj);
        }

        console.log("isPresentClean-------",isPresentClean,"----",isPresentClean==1?0:1)
        // i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId
        let defData={'WindowId':DataCleanItem.WindowId,isPresent:isPresentClean};
        const win_index=allData.findIndex(i=>i.WindowId==DataCleanItem.WindowId);
        allData[win_index]=defData

        let objIndex = InputChange.findIndex((obj => obj.WindowId == DataCleanItem.WindowId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=false
        console.log("changeValue---------7",winArr)
        setInputChange(winArr)
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setDataCleanModal(false)
        setrerenderdata(!rerenderdata);
    }

    function checkAllSKUs(val,window){
        
        let WindowStocks=window.WindowStocks || [];
        let allData=WindowData;
        let defData={'VisibilityId':window.VisibilityId,'VisibilityDefinitionId':window.VisibilityDefinitionId};
        const win_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        console.log('WStocksData before:',WStocksData)
        for(var i=0;i<WindowStocks.length;i++){
            let stockProd=WindowStocks[i];
            
            let sdIndex=WStocksData.findIndex(a=> a.ProductId==stockProd.VisibilityStockValue);
            let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.VisibilityStockValue,'Stock':''};
            let isPVisPresent=(val==1 || val=='1')?1:0;
            sd['isPVisPresent']=isPVisPresent;
            
            sdIndex>=0?(WStocksData[sdIndex]=sd):(WStocksData.push(sd));
        }

        
        wind['WStocksData']=WStocksData;
        wind['isAllSKUChecked']=val==1?1:0;
        console.log('wind updated');
        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 FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        let newWindows=[];
        if(searchedQry!=null && searchedQry!=''){
            
            for(let i=0;i<globalWindows.length;i++){
                let item=globalWindows[i];
                let {VisibilityName}=item;
                if(VisibilityName.toLowerCase().includes(searchedQry)){
                    newWindows.push(item);
                }

                if(i==globalWindows.length-1){
                    arr=newWindows;
                }
            }
        }
        else{
          arr=globalWindows;
        }

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

    
    async function OpenImgModal(imgPath,type='1',ImageIndex=''){
      
        setSelectedImg(imgPath)
        setShowModal(true);
        if((imgPath!='' && imgPath!=null)){
            setShowImageSaveOp(false);
        }
        else{
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({type,ImageIndex});
    }

    function cancelImage(){
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
    }
   


    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.VisibilityQuestionId+'_AnswerId'; 
        let ans_key=qtn.VisibilityQuestionId+'_Answer'; 
        let rating_key=qtn.VisibilityQuestionId+'_Rating'; 
        
        let newarr=RatingOrder;
        if(RatingOrder.length<=0){
            newarr=Answers;
        }

        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>{ST.DragItemsInOrder}</Text>
                <Text style={customStyle.VRSubHeding}>{ST.Pressandholdtodrag}</Text>
                <DraggableFlatList
                    data={newarr}
                    style={customStyle.RModal_list}
                    contentContainerStyle={customStyle.RModal_listInner}
                    onDragEnd={({ data }) =>{setRatingValue(data)}}
                    keyExtractor={(item) => item.AnswerId}
                    renderItem={renderItem}
                />
                <View style={customStyle.RModal_Btns}>
                    <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={()=>{onRatingCancel()}}>
                        <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRatingSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        )
    }

    function render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        let window=selected_data.window || {};
        let isQtnDisabled=qtn.isDisabled!=null || qtn.isDisabled!=''?false:true;
        let allAnswers=qtn.Answers || [];
        
        allAnswers.map((item,index)=>{
            let obj={ key: index, label: item[label_key],value:item[value_key] };
            if(selected_data.value==item[label_key])
                obj['component']= <View style={customStyle.addvis_selectedOpStyle}><Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text></View>;
            data.push(obj);
        });
        
        return (
            <ModalSelector
            data={data}
            
            touchableActiveOpacity={0.8}
            
            style={customStyle.addVisPickerStyle}
            onChange={(option)=>{onChange(option,qtn,window) }}
            overlayStyle={customStyle.addVisPickerOverlay}
            cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            optionStyle={customStyle.addvis_opStyle}
            optionTextStyle={customStyle.addvis_opTextStyle}
            optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            selectedKey={'1'}
            disabled={isQtnDisabled}
            >
            <Text style={[customStyle.WQPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-'+ST.select+'-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn,window){
        let qtnn=qtn;
        let DateRange=qtn.DateRange;
        let maxDate=moment().add(10,'years').format('MM/DD/YYYY');
        let minDate=moment().subtract(10,'years').format('MM/DD/YYYY');
        if(DateRange=='RFD'){
            maxDate=moment().format('MM/DD/YYYY');
        }
        else if(DateRange=='RPD'){
            minDate=moment().format('MM/DD/YYYY');
        }
        
        return (
            <DateTimePicker
            testID="dateTimePicker"
            value={(dateValue!=null && dateValue!=''?new Date(dateValue):new Date())}
            mode={'date'}
            display="default"  
            onChange={(event, selectedDate)=>{setTextValue(selectedDate,qtnn,window)}}
            maximumDate={new Date(maxDate)}
            minimumDate={new Date(minDate)}
            />    
        );
    }


    function _renderItem(item,index){

        const window=item;
        const windowIndex=index;
        
        let isNAReasonEnable=POSDef.PosNotExistReasonEnable=='true' || POSDef.PosNotExistReasonEnable==1?1:0;
        let isshowPosValue=POSDef.ShowPosValue=='true' || POSDef.ShowPosValue==1?1:0;
        let isshowPosVolume=POSDef.ShowPosVolume=='true' || POSDef.ShowPosVolume==1?1:0;
        let wind = item;
        
        
        let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
        let Reason=wind.Reason!=null?wind.Reason:'';
        let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
        let PosValue=wind.PosValue!=null?wind.PosValue:'';
        let PosVolume=wind.PosVolume!=null?wind.PosVolume:'';
        
        var xpos=isPresent=='1'?-75:0;
        if(wind.animatedChoice!=null ){
            xpos=wind.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}>{item.WindowName}</Text>
                    </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,index,1,'isPresent',wind.animatedChoice)}}>
                                        <Text style={[customStyle.openStkCh_text,(isPresent=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(window,index,0,'isPresent',wind.animatedChoice)}}>
                                        <Text style={[customStyle.openStkCh_text,(isPresent=='0'?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                       
                        { ((isPresent=='1'&& isshowPosValue==true)) &&
                            <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{POSDef.PosValueLabel}</Text>
                                <TextInput 
                                    style={[customStyle.posS_flex_inputStyle2]}
                                    placeholder=""
                                    autoComplete='off'
                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                    keyboardType={'numeric'}
                                    value ={(PosValue+'')}
                                    onChangeText={(val)=>{onWindowDataChange(item,index,val,'PosValue','numeric')}}
                                    
                                   />
                              
                                </View>
                        }
                        { ((isPresent=='1'&& isshowPosVolume==true) ) &&
                            <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{POSDef.PosVolumeLabel}</Text>
                                <TextInput 
                                    style={[customStyle.posS_flex_inputStyle2]}
                                    // ref={(reff)=>{inputRefs.current['input1_'+stockProd.VisibilityDefinitionId+'_'+stockProd.VisibilityStockDefinitionId]=reff;}} 
                                    placeholder=""
                                    autoComplete='off'
                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                    keyboardType={'numeric'}
                                    value ={(PosVolume+'')}
                                    onChangeText={(val)=>{onWindowDataChange(item,index,val,'PosVolume','numeric')}}
                                    />
                                </View>
                        }

                        {
                        (isPresent=='0' && isNAReasonEnable==true) && 
                        <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange3} selected_data={{value:Reason,otherData:{window:window,index:index}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                         </View>
                        }
                   
                    </View>
                </View>
            </View>
        );

    }

    function _renderWindow(){
        
        
        let PosOverall=POSDef.PosOverall==true || POSDef.PosOverall=='true'?1:0;
        if(PosOverall==1){
            return (
            <>
            {_renderPOSSHeader()}
            {_renderItem(DefPOSWind,0)}
            </>
            )
        }
        else{
            return (
                <FlatList 
                data={WindowData}
                extraData={rerenderdata}
                contentContainerStyle={customStyle.Win_scroll} 
                style={customStyle.Win_scrollO}
                initialNumToRender={5}
                ListHeaderComponent={_renderPOSSHeader}
                listKey={(item, index) => `window_${index.toString()}`}
                renderItem={({item,index})=>{
                    return _renderItem(item,index);
                    
                }}
                />
            )
        }
    }

   
    
    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 _renderPOSSHeader(){
        
        let {TotalPosValue}=posSData;//Image1,Image1Name,Image2,Image2Name

        let HeaderImageRequired=POSDef.HeaderImageRequired==1 || POSDef.HeaderImageRequired=='1'?true:false;
        let HeaderImageCount=POSDef.HeaderImageCount!=null?POSDef.HeaderImageCount:2;
        // let HeaderImageMandatory=POSDef.HeaderImageMandatory!=null?POSDef.HeaderImageMandatory:2;
       
        let ShowHdrPosSaleI=KPIFields.findIndex(i=>i.KPIFieldName=='ShowTotalPosSaleHeade');
        let ShowHdrPosSaleObj=ShowHdrPosSaleI>=0?KPIFields[ShowHdrPosSaleI]:{};
        let ShowHdrPosSale=ShowHdrPosSaleI>=0?ShowHdrPosSaleObj['KPIFieldEnable']:false;
        let ShowHdrPosSaleDN=ShowHdrPosSaleObj['KPIFieldDisplayName']!='' && ShowHdrPosSaleObj['KPIFieldDisplayName']!=null ? ShowHdrPosSaleObj['KPIFieldDisplayName'] :"Total POS Value";
        return (
            <View style={[customStyle.possale_headerview]}>
                <View style={[customStyle.openStk_prd_colflex,customStyle.posS_hdrWrap]}>
                    <Text style={[customStyle.openStk_prd_label,customStyle.posS_flex_label]}>{'Month'}</Text>
                    <View style={customStyle.picker_design} >
                    {CustomPicker(props,Months,'MonthId','MonthName','MonthId','MonthName',onselectionChange,{value:posSData.MonthName})}
                    </View>
                </View>
                {ShowHdrPosSale==true && 
                <View style={[customStyle.openStk_prd_row,customStyle.posS_field,customStyle.posS_fieldBorder]}>
                    <View style={[customStyle.openStk_prd_colflex]}>
                        <Text style={[customStyle.openStk_prd_label,customStyle.posS_flex_label]}>{ShowHdrPosSaleDN}</Text>
                        <TextInput 
                            style={[customStyle.openStk_prd_inputStyle,customStyle.posS_flex_inputStyle]}              
                            placeholder=""  
                            autoComplete='off'          
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            value={TotalPosValue}
                            keyboardType={'numeric'}
                            onChangeText={(val)=>{onHdrDataChange(val,"TotalPosValue","numeric")}}
                        />
                    </View>
                </View>}
                <View style={[customStyle.openStk_prdCameras,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10,customStyle.WSCameraWrap]}>
                    
                    {HeaderImageRequired && HeaderImageCount>0 && 
                    posSImgArr.map((item,index)=>{

                        let Image1=item.Image1!=null?item.Image1:'';
                        let img1Required=item.img1Required!=null?item.img1Required:false;
                        return (
                        <View key={index} style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                            { (Image1=='' || Image1==null) ?
                            (img1Required?
                            <TouchableOpacity onPress={()=>{openCamera('1',index)}}>
                                <AstrickCamera width={50} height={50}  />
                            </TouchableOpacity>:
                            <TouchableOpacity onPress={()=>{openCamera('1',index)}}>
                                <CameraImg2 width={50} height={50} />
                            </TouchableOpacity>
                            ) : 
                            
                            ((Image1!='' && Image1!=null)  ?
                            <TouchableOpacity onPress={()=>{OpenImgModal(Image1,'1',index)}}>
                                <CameraImg3 width={50} height={50}  />
                            </TouchableOpacity> : null)
                            }
                        </View>
                        )
                    })
                    }
                    
                    {/* <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                    
                    { (Image1=='' || Image1==null) ?
                        <TouchableOpacity onPress={()=>{openCamera('1')}}>
                            <Image style={customStyle.osCatImage2} source={CameraImg5}/>
                        </TouchableOpacity> : (Image1!='' && Image1!=null)  ?
                        <TouchableOpacity onPress={()=>{OpenImgModal(Image1,'1')}}>
                            <SvgXml width={50} height={50} xml={CameraImg3} />
                        </TouchableOpacity> : null
                    }
                    </View> */}
                    
                    
                    {/* <View style={customStyle.openStkCameraCon}>
                    
                    { (Image2=='' || Image2==null) ?
                        <TouchableOpacity onPress={()=>{openCamera('2')}}>
                            <SvgXml width={50} height={50} xml={CameraImg2} />
                        </TouchableOpacity> : (Image2!='' && Image2!=null)  ?
                        <TouchableOpacity onPress={()=>{OpenImgModal(Image2,'2')}}>
                            <SvgXml width={50} height={50} xml={CameraImg3} />
                        </TouchableOpacity> : null
                    }
                    </View>   */}
                            
                </View>
            </View>
        );
    }

    const onCancelClean = () =>{
        setDataCleanModal(false)
    }
    const onclear = () => {
        console.log("onclear---------",DataCleanItem)
        onWindowDataClean(DataCleanItem)
    }
   
    function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        
        let {type,ImageIndex}=reCapImgModalObj
        return (
          <CustomModal
            style={customStyle.PromoImgModal}
            title={currentMenu.MenuName+" Image"}
            message={""}
            titleStyle={customStyle.PromoImgModal_title}
            messageStyle={customStyle.PromoImgModal_subtitle}
            showModal={showModal}
          >
            { 
            isImageCap && 
            <View style={customStyle.PromoImgModalCon}>
              <View style={customStyle.PromoImgModal_ImgWrap}>
              
                <Image  style={[customStyle.PromoImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:SelectedImg}} />
              </View>
              <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={()=>{openCamera(type,ImageIndex)}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage(false)}}>
                
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }
   
    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}`}/> 
        {_OpenCaptureImage_Modal()}           
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,DataCleanModal,onCancelClean,onclear,'Your data will be clean',)}
        {/* <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(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,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
            
          { Object.keys(storeData).length>0 && 
            <View style={customStyle.POS_Wrap}>
                {_renderWindow()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
       {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)(POSSale);