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} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, 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 { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
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 cameraImg from '../assets/performics/camera_front_image.svg'
import MultiSelect from 'react-native-multiple-select';

function 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 [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 d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

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

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

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

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);

          await db.transaction(async function (txn) {        
            

            let q3=`Select POSMReasonId as ReasonId,POSMReason as Reason From Master_POSMReason`;
            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);
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            setReasons_list(arr);
                        }                                
                    }
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
            
            

            // check if data exists
            let selectlist=` w.STORE_ID as StoreId,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,wd.POSMNotExistCamera,w.POSM_NA_IMAGE as POSMNAImage,w.POSM_IMAGE1 as Image1,w.POSM_IMAGE2 as Image2,wd.POSMExistReasonEnable,wd.POSMNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,wd.POSMImage1,wd.POSMImage2,wd.POSMImage1Lable,wd.POSMImage2Lable,wd.POSMImage1CameraGrid,wd.POSMImage2CameraGrid`;
            let join=` inner join Master_POSMDefinition wd on w.POSM_DEFINITION_ID=wd.POSMDefinitionId `;
            let q=` Select ${selectlist} from ${AppTables.POSM_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;

            // else pick data from masters
            let selectlist2=` s.StoreId,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,w.POSMNotExistCamera,'' as POSMNAImage,w.POSMExistReasonEnable,w.POSMNotExistReasonEnable,'' as ReasonId,'' as Reason,w.POSMImage1,w.POSMImage2,w.POSMImage1Lable,w.POSMImage2Lable,w.POSMImage1CameraGrid,w.POSMImage2CameraGrid`;
            let join2=` inner join Mapping_StorePOSM s on w.POSMDefinitionId=s.POSMDefinitionId  `;
            let q2=` Select ${selectlist2} from Master_POSMDefinition w  ${join2} where s.StoreId='${StoreId}'  `;
            

            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                
                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: {}}
                        
                        let WQr =  await getWindowQuestions(data,storeData1,isPresent);
                        let WindowQuestions = WQr['WindowQuestions'] || [];
                        let WindowQA= WQr['WindowQA'] || {};
                        

                        let isNAImageAvl=data.POSMNotExistCamera=='true' || data.POSMNotExistCamera==1?1:0;
                        let NAImage1=isNAImageAvl==1 && data.POSMNAImage!=null?data.POSMNAImage:'';
                        let NAImage1Path=NAImage1!=''?'file://'+common_ImagePath+NAImage1:'';

                        let isImage1= data.POSMImage1=='true' || data.POSMImage1==1?1:0;
                        let Image1Name=isImage1==1 && data.Image1!=null?data.Image1:'';
                        let Image1=Image1Name!=''?'file://'+common_ImagePath+Image1Name:'';

                        let isImage2= data.POSMImage2=='true' || data.POSMImage2==1?1:0;
                        let Image2Name=isImage1==1 && data.Image2!=null?data.Image2:'';
                        let Image2=Image2Name!=''?'file://'+common_ImagePath+Image2Name:'';
                        
                        let windowDataObj={'PosmId':data.PosmId,'POSMDefinitionId':data.POSMDefinitionId,'WindowQA':WindowQA,'NAImage1':NAImage1,'NAImage1Path':NAImage1Path,'ReasonId':data.ReasonId,'Reason':data.Reason,'isPresent':isPresent,'Image1Name':Image1Name,'Image1':Image1,'Image2Name':Image2Name,'Image2':Image2};
                        data['WindowQuestions']=WindowQuestions;
                        arr.push(data);
                        
                        allWindowsData.push(windowDataObj);
                        if(i==txnres2.rows.length-1){
                            setWindowData(allWindowsData);
                            setWindows(arr);
                            setGlobalWindows(arr);
                            images.push(imgObj);
                            setZoomImageUrl(images);
                            setProcessing(false);
                        }                                
                    }
                }
                else{
                    await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                        
                        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: {}}
                                let WQr =  await getWindowQuestions(data,storeData1,false);
                                let WindowQuestions = WQr['WindowQuestions'] || [];
                                let WindowQA= WQr['WindowQA'] || {};

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

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

    async function getWindowQuestions(window,storeData1,isInserted=false){
        let obj={'WindowQA':{},'WindowQuestions':[]}
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                var q='',selectlist='',join='',join2='';
                if(isInserted==true){
                    selectlist=` DISTINCT  q.QUESTION_ID as POSMQuestionId,q.QUESTION_CODE as POSMQuestionCode,wq.POSMQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PAShowCamera,q.IMAGE1 as Image1  `;
                    join2=` inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId `;
                    join=` inner join Master_POSMQuestion wq on wq.POSMQuestionId=q.QUESTION_ID `;
                    q=`select ${selectlist} from ${AppTables.POSM_CHILD_DATA} q ${join} ${join2} where q.STORE_ID='${storeData1.StoreId}' and q.POSM_DEFINITION_ID='${window.POSMDefinitionId}' and q.POSM_ID='${window.PosmId}' order by wq.POSMQuestionSequence  `;
                }
                else{
                    selectlist=` DISTINCT  wq.POSMQuestionId,wq.POSMQuestionCode,wq.POSMQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable `;
                    join=` inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId `;
                    q=`select ${selectlist} from Master_POSMQuestion wq ${join} where mq.POSMDefinitionId='${window.POSMDefinitionId}' order by wq.POSMQuestionSequence  `;
                }
               
                await txn.executeSql(q,[],async function (txn2, txnres2) { 

                    if(txnres2.rows.length>0){
                        let arr=[];
                        let wqa_obj={};
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let answers=[];
                            data.PQDefaultQuestionEnable=data.PQDefaultQuestionEnable==1 || data.PQDefaultQuestionEnable=='true'?true:false;
                             
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  answers=await getWindowAnswers(data);
                                  if(data.QuestionType=='Rating'){
                                      data.showRating=false;
                                  }
                              }
                              else if(data.QuestionType=='Date'){
                                  data.showDatePicker=false;
                              }
                              data['Answers']=answers;
      
                              let id_key=data.POSMQuestionId+'_AnswerId'; 
                              let ans_key=data.POSMQuestionId+'_Answer'; 
                              let multi_key=data.POSMQuestionId+'_MultiOption';
                              let date_key=data.POSMQuestionId+'_Date';
                              let img_key=data.POSMQuestionId+'_ImagePath1';
                              let imgname_key=data.POSMQuestionId+'_ImageName1';
                              let rating_key=data.POSMQuestionId+'_Rating'; 
                              
      
                              let showImageTag=(data.PQShowCamera=='true' || data.PQShowCamera==1) ;
      
                              data.AnswerId!=null?wqa_obj[id_key]=data.AnswerId:'';
                              data.Answer!=null?wqa_obj[ans_key]=data.Answer:'';

                              
                              let selansid=data.AnswerId!=null?data.AnswerId:'';
                              if(data.QuestionType=='Multi choice list' && selansid!='' && data.multi_op_ids!=null){
                                  selansid=data.multi_op_ids?data.multi_op_ids.split(','):[];
                                  wqa_obj[multi_key]=data.multi_op_ids;
                              }
      
                              if((data.QuestionType=='Single choice list' || data.QuestionType=='Multi choice list' ) && selansid!='' && selansid!=null){
                                  if (data.Answers && data.Answers.length>0){
                                      for(var k=0;k<data.Answers.length;k++){
                                          let ansss=data.Answers[k];
                                          let isandImgAl=(ansss.PAShowCamera==1 || ansss.PAShowCamera=='true');
                                          if(data.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(data.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                              showImageTag=true;
                                          }
                                      }
                                  }
                              }
      
                              if(showImageTag && data.Answer!=null){
                                  console.log('Image1 qa',data);
                                  let imgPath=(Platform.OS=='ios'?'file://':'')+common_ImagePath+data.Image1;
                                  wqa_obj[imgname_key]=data.Image1;
                                  wqa_obj[img_key]=imgPath;
                              }

                             
      
                              if(data.QuestionType=='Date' && data.Answer!=null){
                                  let dayonly=moment().format('DD');
                                  let actual_date=data.Answer?data.Answer.split('/'):[];
                                  let month=actual_date[0],year=actual_date[1];
                                  let fulldate=month+'/'+dayonly+'/'+year;
                                  wqa_obj[date_key]=fulldate;
                                  
                              }

                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                obj['WindowQuestions']=arr;
                                obj['WindowQA']=wqa_obj;
                                resolve(obj)
                            }                                
                        }
                    }
                    else{
                        resolve(obj)
                    }
                },function (txn2, txnerr) { console.log(txnerr); resolve(obj) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return obj;
        });
    }


    async function getWindowAnswers(qtn){
        
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='';
                selectlist=` DISTINCT  POSMAnswerId as AnswerId,POSMAnswerName as Answer,PAShowCamera,PACameraMandatory,PAQuestionEnable,PAQuestionDisable `;
                q=`select ${selectlist} from  Master_POSMQuestion  where POSMQuestionId='${qtn.POSMQuestionId}'  order by PASequence  `;

                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                resolve(arr)
                            }                                
                        }
                    }
                    else{
                        resolve([])
                    }
                },function (txn2, txnerr) { console.log(txnerr); resolve([]) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return [];
        });
    }



    async function getImage(imgdata){
        let type=getImageProps.type || '';
        let window=getImageProps.window || {};
        let qtn=getImageProps.qtn || {};
        let cameraType=getImageProps.cameraType!=null?getImageProps.cameraType:'1';

        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 picture_clicked_time=new Date();
            picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
            
            
            const mark_text1=picture_clicked_time;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: POSM'+' | Date:'+picture_clicked_time;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let picture_clickedd=new Date();
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+window.POSMDefinitionId+'_'+window.PosmId+'_'+(props.UserId || '')+'_POSMImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            
                            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;
                           
                            if(cameraType=='2'){
                              
                                var QD=wind.WindowQA || {};
                                var image_key=qtn.POSMQuestionId+'_ImageName1';
                                var image_key_path=qtn.POSMQuestionId+'_ImagePath1';
                                QD[image_key]=filename;
                                
                            }
                            else if(cameraType=='3'){
                                var image_key='NAImage1';
                                var image_key_path='NAImage1Path';
                                wind[image_key]=filename;
                            }
                            else{
                                var image_key=type=='1'?'Image1Name':'Image2Name';
                                var image_key_path=type=='1'?'Image1':'Image2';
                                wind[image_key]=filename;
                            }
                            
                            
                            
                            // renamefile
                            let imagePath=`${common_ImagePath}${filename}`;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                                console.log('image marker',uri);
                                
                                if(cameraType=='2'){
                                    QD[image_key_path]=uri;
                                    wind.WindowQA=QD;
                                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                                    setWindowData(allData);
                                    setHasUnsavedChanges(true);
                                    setrerenderdata3(!rerenderdata3);
                                }
                                else{
                                    wind[image_key_path]=uri;
                                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                                    setWindowData(allData);
                                    setHasUnsavedChanges(true);
                                    setrerenderdata(!rerenderdata);
                                }
                                
                                
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(window,type='1',cameraType='1',qtn={}){  
        setGetImageProps({'window':window,'type':type,'cameraType':cameraType,'qtn':qtn}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

   
    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){
           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.POSM_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                  console.log('window hdr data deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);
              await txn.executeSql(`DELETE FROM ${AppTables.POSM_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                  console.log('window child data deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);

              
             
                // add data
                var values='',childV='';
              
                for (const wi in Windows){
                    const window=Windows[wi];
                    let isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                    let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                    let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                    let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                    let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                    let WindowQuestions=window.WindowQuestions || [];
                    
                   
                    const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                    let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                    let ReasonId=wind.ReasonId!=null?wind.ReasonId:0;
                    let Reason=wind.Reason!=null?wind.Reason:'';
                    let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                    let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                    let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                    let Image1=wind.Image1!=null?wind.Image1:'';
                    let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                    let Image2=wind.Image2!=null?wind.Image2:'';
                   
                    let QD=wind.WindowQA || {};

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

                    values+=values!=''?' , ':'';
                    values+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMName}','${PosmTypeId}','${POSMTypeName}','${POSMTable}','${POSMField}','${POSMValue}','${ChildName}','${isPresent}','${NAImage1}','${Image1Name}','${Image2Name}','${ReasonId}','${Reason}','${d3}') `;
                    
                    if(isPresent==1){
                        for(const qtnIndex in WindowQuestions){
                            const qtn=WindowQuestions[qtnIndex];
                            
                            let selansid='',selanswer='',selimg='',showImageTag=false;
                            let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                            let ans_key=qtn.POSMQuestionId+'_Answer'; 
                            let multi_key=qtn.POSMQuestionId+'_MultiOption';
                            let date_key=qtn.POSMQuestionId+'_Date';
                            let img_key=qtn.POSMQuestionId+'_ImagePath1';
                            let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                            let rating_key=qtn.POSMQuestionId+'_Rating'; 
                          

                            let {POSMQuestionId,POSMQuestionCode,QuestionType,PAShowCamera}=qtn
                            let answer=QD[ans_key] || '';
                            let answerId=QD[id_key] || 0;
                            let multi_options_ids=QD[multi_key] || '';
                            
                            if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                            {
                                showImageTag=(qtn.PQShowCamera==1 || qtn.PQShowCamera=='true');
                            }
                            else if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                if (qtn.Answers && qtn.Answers.length>0){
                                    for(var i=0;i<qtn.Answers.length;i++){
                                        let ansss=qtn.Answers[i];
                                        let isandImgAl=(ansss.PAShowCamera=='true' || ansss.PAShowCamera==1);
                                        console.log('isandImgAl',isandImgAl,ansss.AnswerId,'selandidhsj',answerId);
                                        if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==answerId)){
                                            showImageTag=true;
                                        }
                                        else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && answerId.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag=true;
                                        }
                                        
                                    }
                                }
                            }

                            let Image1=showImageTag==1?QD[imgname_key]:'';
                            console.log('Image1',showImageTag,Image1);

                            childV+=childV!=''?' , ':'';
                            childV+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMQuestionId}','${POSMQuestionCode}','${QuestionType}','${answer}','${answerId}','${multi_options_ids}','${Image1}','${(PAShowCamera=='true' || PAShowCamera==true?1:0)}','${d3}') `;
                        }
                    }
                }
              
                console.log('childV:',childV);
                
                let add_hdr_data=`INSERT INTO ${AppTables.POSM_HDR_DATA} (POSM_HEADER_ID,STORE_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_NA_IMAGE,POSM_IMAGE1,POSM_IMAGE2,REASON_ID,REASON,ADDED_DATE) VALUES ${values} `;
                let add_child_data=`INSERT INTO ${AppTables.POSM_CHILD_DATA} (POSM_HEADER_ID,STORE_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE) VALUES ${childV} `;
                
                await txn.executeSql(add_hdr_data,[],async function (txn2, txnres) { 
                    console.log('posm header data added');
                    var isChildAdded=true;
                   
                    if(childV!=''){
                        isChildAdded=await executeQuery(add_child_data);
                    }

                    if(!isChildAdded){
                        setProcessing(false);notify(ST.Cannotaddposmquestionsdata);
                    }
                    else{
                        setProcessing(false);notify(ST.POSMdataupdatedsuccessfully);
                        props.navigation.goBack();
                    }
                       
                },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotaddPOSMdata); },);
            });          
        } 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(txn2,txnerr){console.log(txnerr);resolve(false) });
          }); 
        }).then((val)=>{
          return val;
        }).catch((err)=>{
            console.log(err);
          return false;
        })
    }
    


    async function validate(){
        let isValid=true;
       
        return new Promise((resolve,reject)=>{
            for (const wi in Windows){
                const window=Windows[wi];
                let isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                let WindowQuestions=window.WindowQuestions || [];
                
               
                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                let Image2=wind.Image2!=null?wind.Image2:'';
                let QD=wind.WindowQA || {};

                if(isPresent=='1'){
                    if(isReasonEnable==true && ReasonId=='' ){
                        notify(`${ST.Pleaseselectreasonfor} ${window.POSMName} `,'LONG');
                        resolve(false);return;
                    }
                    else{
                        if(isImage1==1 && Image1Name==''){
                            notify(`${ST.Pleaseclickallimagesfor} ${window.POSMName}`,'LONG');
                            resolve(false);return;
                        }
                        else if(isImage2==1 && Image2Name==''){
                            notify(`${ST.Pleaseclickallimagesfor} ${window.POSMName}`,'LONG');
                            resolve(false);return;
                        }
                        else if(WindowQuestions.length>0){
                            for(const qtnIndex in WindowQuestions){
                                const qtn=WindowQuestions[qtnIndex];
                                
                                let selansid='',selanswer='',selimg='',showImageTag=false;
                                let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                                let ans_key=qtn.POSMQuestionId+'_Answer'; 
                                let multi_key=qtn.POSMQuestionId+'_MultiOption';
                                let date_key=qtn.POSMQuestionId+'_Date';
                                let img_key=qtn.POSMQuestionId+'_ImagePath1';
                                let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                                let rating_key=qtn.POSMQuestionId+'_Rating'; 
                                let list_mcdata=[];

                                let isImgAllowed=(qtn.PQShowCamera=='true' || qtn.PQShowCamera==1);
                                let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating') ;
                                if(qtn.QuestionType=='Single choice list')
                                {
                                    selansid=QD[id_key];
                                }
                                else if(qtn.QuestionType=='Multi choice list')
                                {
                                    selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
                                }
                                
                            
                                if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                                    notify(`${ST.Pleaseselectoptionsfortherequiredfield} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }
                                else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                                    console.log('jhg')
                                    let msg=( qtn.QuestionType=='Date'?`${ST.Pleasepickadatefortherequiredfield} ${ST.In} ${window.POSMName}`:(qtn.QuestionType=='Rating'?`${ST.Pleaseselectratingfortherequiredfield} ${ST.In} ${window.POSMName}`:`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.POSMName}`));
                                    notify(msg,'SHORT');
                                    resolve(false);return;
                                }
                                else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]==='' || (QD[id_key]===0 && qtn.isDisabled===false) ))){
                                    console.log('test',QD[id_key],id_key,QD)
                                    notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }
                                else if(isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                    notify(`${ST.Pleaseaddimages} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }else{
                                    console.log('no condition found');
                                }

                                if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                    if (qtn.Answers && qtn.Answers.length>0){
                                        for(var j=0;j<qtn.Answers.length;j++){
                                            let ansss=qtn.Answers[j];
                                            let isandImgAl=(ansss.PAShowCamera=='true' || ansss.PAShowCamera==1);
                                            if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                                showImageTag=true;
                                            }
                                            else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                                showImageTag=true;
                                            }
                                        }
                                    }
                                }

                                if(showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                    notify(`${ST.Pleaseaddimages} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }
                            }
                        }
                    }
                }
                else{
                    if(isNAReasonEnable==true && ReasonId=='' ){
                        notify(`${ST.Pleaseselectreasonfor} ${window.POSMName} `,'LONG');
                        resolve(false);return;
                    }
                    else if(isNAImageAvl==true && NAImage1=='' ){
                        notify(`${ST.Pleaseclickimagefor} ${window.POSMName}`,'LONG');
                        resolve(false);return;
                    }
                }

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


    function onselectionChange(option,keyLbl,keyVal,otherData){
        let item=otherData.window;
        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[keyVal]=option.value;
        wind[keyLbl]=option.label;

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

    function onselectionChange2(option,qtn,window){
        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 data=wind.WindowQA || {};
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        data[id_key]=option.value;
        data[ans_key]=option.label;
        

        wind['WindowQA']=data;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
      
        setWindowData(allData);

        let aq_ans=qtn.Answers!=null?qtn.Answers:[];
        let ans_obj=aq_ans.find(i=>i.AnswerId==option.value) || {};
        let EQtns=ans_obj.WAQuestionEnable!=null && ans_obj.WAQuestionEnable!=''?ans_obj.WAQuestionEnable.replace(' ','').split(','):[];
        let DQtns=ans_obj.WAQuestionDisable!=null && ans_obj.WAQuestionDisable!=''?ans_obj.WAQuestionDisable.replace(' ','').split(','):[];
      
        let sqtns=window.WindowQuestions || []

        if(EQtns.length>0){
            enableQtns(sqtns,EQtns,DQtns,data,wind,wind_index,allData,window)
        }
        else if(DQtns.length>0){
            disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
        }
        else{
            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.POSMQuestionId==qid) || {};
                    let s_qtn=sqtns[s_qtnindex];
                    s_qtn['isDisabled']=true
                    sqtns[s_qtnindex]=s_qtn;
                    let id_key=s_qtn.POSMQuestionId+'_AnswerId'; 
                    let ans_key=s_qtn.POSMQuestionId+'_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.POSMDefinitionId==window.POSMDefinitionId && i.PosmId==window.PosmId)
                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.POSMQuestionId==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){
                disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            }
            else{
                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.POSMDefinitionId==window.POSMDefinitionId && i.PosmId==window.PosmId)
                if(windowIndex>0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    setHasUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                }
            }
        })
    }

    async function setMultiSelectValue(selectedItems=[],qtn={},window={}) {  
        console.log('setMultiSelectValue',selectedItems);      
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let multi_key=qtn.POSMQuestionId+'_MultiOption';
       
        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 obj=wind.WindowQA || {};
        obj[id_key]=0;
        obj[multi_key]=selectedItems.join(',');
        let anss=[];
        selectedItems.map((itemValue)=>{
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue); 
            if(ans.Answer){anss.push(ans.Answer)}
        });
        obj[ans_key]=anss.join(',');
        console.log('obj:',obj);
        
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value,qtn,window) {        
        
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        
        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 obj=wind.WindowQA || {};

        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.POSMQuestionId+'_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);

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

    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.POSMQuestionId==qtn.POSMQuestionId);
       
        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.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId) || {};
            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.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let rating_key=qtn.POSMQuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })

        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 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);

        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }
    
   
    function onChoiceSelect(item,val,key,animatedChoice){
        console.log('onChoiceSelect',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){
        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 setWindowStockVal(val,window,stockProd){
        let allData=WindowData;
        let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
        const win_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        let sdIndex=WStocksData.findIndex(i=> i.ProductId==stockProd.WindowStockValue);
        let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.WindowStockValue,'Stock':''};
        sd['Stock']=val;
        sdIndex>=0?WStocksData[sdIndex]=sd:WStocksData.push(sd);
        wind['WStocksData']=WStocksData;
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata4(!rerenderdata4);
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

  

    function openImageRefView(RefImage=''){
        setShow_zoomImage(true);
    }

    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let rating_key=qtn.POSMQuestionId+'_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}
            cancelText={ST.Cancel}
            >
            <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 _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 isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                let POSMTitleEnable=window.POSMDefinitionTitleEnable=='true' || window.POSMDefinitionTitleEnable==1? 1:0;
                let POSMTitle=window.POSMDefinitionTitle!=null && window.POSMDefinitionTitle!='undefined'? window.POSMDefinitionTitle:"";
                let RefImage=window.POSMRefImage;
                let camera1Label=window.POSMImage1Lable || '';
                let camera2Label=window.POSMImage2Lable || '';
                let WindowQuestions=window.WindowQuestions || [];

                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let QuestionsData=wind.WindowQA || {};
                let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                let Image2=wind.Image2!=null?wind.Image2:'';

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

                console.log(window);
                return(
                    <View style={customStyle.WItem_wrap} key={'window_'+index}>
                        <View style={customStyle.WItem_Hdr}>                            
                            {/* <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.WItem_Hdrbg}> */}
                            <View style={customStyle.WItem_Hdrbg}>
                                <Text style={customStyle.WItem_HdrText}>{window.POSMName}</Text>
                                {(POSMTitleEnable==1 && POSMTitle!=null && POSMTitle!='') && <Text style={customStyle.WItem_HdrSubTitleText}>{POSMTitle}</Text>}
                                <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={()=>{openImageRefView(RefImage)}}>
                                    <Entypo name='image-inverted' size={24} color={PageTheme.$accent_color} />    
                                </TouchableOpacity>
                            </View>
                            {/* </LinearGradient> */}
                        </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' && isNAReasonEnable==true) || (isPresent=='1' && isReasonEnable==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={onselectionChange} selected_data={{value:Reason,otherData:{window:window}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                                    </View>
                                }


                                {(isPresent!='1' && isNAImageAvl==true) && 
                                <View>
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$bg_color,PageTheme.$fourth_color,PageTheme.$bg_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]}>
                                        { (NAImage1Path=='' || NAImage1Path==null) && 
                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(window,'1','3')}}>
                                                <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                            </TouchableOpacity>
                                        }
                                        { (NAImage1Path!='' && NAImage1Path!=null) && 
                                            <View style={customStyle.osCatImageView}>
                                                <Image style={customStyle.osCatImage} source={{uri:NAImage1Path}}/>
                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window,'1','3')}}>
                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                </TouchableOpacity>
                                            </View>                                    
                                        }   
                                        </View>
                                    </View>
                                    </View>
                                </View>
                                }



                                {(isPresent=='1') && 
                                <View>
                                    {(isImage1==1 || isImage2==1)&& 
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$bg_color,PageTheme.$fourth_color,PageTheme.$bg_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]}>
                                        {isImage1==1 && 
                                            <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                            { (Image1=='' || Image1==null) && 
                                                <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(window,'1','1')}}>
                                                    <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                                </TouchableOpacity>
                                            }
                                            { (Image1!='' && Image1!=null) && 
                                                <View style={customStyle.osCatImageView}>
                                                    <Image style={customStyle.osCatImage} source={{uri:Image1}}/>
                                                    <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window,'1','1')}}>
                                                        <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                    </TouchableOpacity>
                                                </View>                                    
                                            }       
                                            <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text>
                                            </View>
                                        }
                                        {isImage2==1 && 
                                            <View style={customStyle.openStkCameraCon}>
                                            { (Image2=='' || Image2==null) && 
                                                <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(window,'2','1')}}>
                                                    <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                                </TouchableOpacity>
                                            }
                                            { (Image2!='' && Image2!=null)  && 
                                                <View style={customStyle.osCatImageView}>
                                                    <Image style={customStyle.osCatImage} source={{uri:Image2}}/>
                                                    <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window,'2','1')}}>
                                                        <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                    </TouchableOpacity>
                                                </View>                                    
                                            }      
                                            <Text style={customStyle.WSCameraLabel}>{camera2Label}</Text> 
                                            </View>  
                                        }          
                                        </View>
                                    </View>
                                    }
                                    
                                    {(WindowQuestions.length>0) && 
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$bg_color,PageTheme.$fourth_color,PageTheme.$bg_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{ST.POSMQuestions}</Text>
                                    </LinearGradient>
                                    {WindowQuestions.map((item,index)=>{
                                        
                                        let qtn=item;  
                                        let qtnIndex=index;
                                        let selansid='',selanswer='',selimg='',showImageTag=false;
                                        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                                        let ans_key=qtn.POSMQuestionId+'_Answer'; 
                                        let multi_key=qtn.POSMQuestionId+'_MultiOption';
                                        let date_key=qtn.POSMQuestionId+'_Date';
                                        let img_key=qtn.POSMQuestionId+'_ImagePath1';
                                        let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                                        let rating_key=qtn.POSMQuestionId+'_Rating'; 
                                        
                                        let list_mcdata=[];
                                        
                                        if(qtn.QuestionType=='Single choice list')
                                        {
                                            selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                                            selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                                        }
                                        else if(qtn.QuestionType=='Multi choice list')
                                        {
                                            if(qtn.Answers!=null){
                                                for(var i=0;i<qtn.Answers.length;i++){
                                                    let obj={'AnswerId':parseInt(qtn.Answers[i].AnswerId),'Answer':qtn.Answers[i].Answer};
                                                    list_mcdata.push(obj);
                                                }
                                            }
                                            selansid=QuestionsData[multi_key]!=null && QuestionsData[multi_key]!=''?QuestionsData[multi_key].split(','):[];
                                            // if(selansid!=null && selansid.length>0){
                                            //     let arr=[];
                                            //     for(var i=0;i<selansid.length;i++){
                                            //         arr.push(parseInt(selansid[i]));
                                            //     }
                                            //     selansid=arr;
                                            // }
                                        }
                                        else if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                                        {
                                            selansid=QuestionsData[ans_key];
                                            selanswer=(qtn.QuestionType=='Date'  )?(QuestionsData[date_key] || moment().format('MM/DD/YYYY')):'';
                                            showImageTag=(qtn.PQShowCamera==1 || qtn.PQShowCamera=='true');
                                        }
                                        else if(qtn.QuestionType=='Rating'){
                                            selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                                        }
                                        

                                        if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                            if (qtn.Answers && qtn.Answers.length>0){
                                                for(var i=0;i<qtn.Answers.length;i++){
                                                    let ansss=qtn.Answers[i];
                                                    let isandImgAl=(ansss.PAShowCamera=='true' || ansss.PAShowCamera==1);
                                                    
                                                    if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                                        showImageTag=true;
                                                    }
                                                    else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                                        showImageTag=true;
                                                    }
                                                    
                                                }
                                            }
                                        }
                                        
                                        if(showImageTag){
                                            selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                                        }

                                        
                                        return(
                                        <View style={[customStyle.sform_group2,]} key={'Qtn_'+qtnIndex} >
                                            <Text style={[customStyle.sform_label3]}>{qtn.POSMQuestionName}</Text>                     
                                            {qtn.QuestionType=='Single choice list' && qtn.Answers && 
                                                render_Picker('Answer','AnswerId',onselectionChange2,{value:selanswer,qtn:qtn,window:window})
                                            }
                                            {qtn.QuestionType=='Multi choice list' && qtn.Answers &&
                                                <MultiSelect
                                                    items={list_mcdata}
                                                    uniqueKey="AnswerId"
                                                    onSelectedItemsChange={(selectedItems)=>{ setMultiSelectValue(selectedItems,qtn,window) }} //setMultiSelectValue(selectedItems,qtn)
                                                    selectedItems={selansid}
                                                    selectText="Pick Items"
                                                    searchInputPlaceholderText={ST.SearchItems+"..."}
                                                    // onChangeInput={ (text)=> console.log(text)}
                                                    tagRemoveIconColor={PrimaryTheme.$primary_color}
                                                    tagBorderColor={PrimaryTheme.$primary_color}
                                                    tagTextColor={PrimaryTheme.$primary_color}
                                                    selectedItemTextColor={PrimaryTheme.$primary_color}
                                                    selectedItemIconColor={PrimaryTheme.$primary_color}
                                                    itemTextColor={PrimaryTheme.$text_color}
                                                    displayKey="Answer"
                                                    searchInputStyle={{ color: '#CCC' }}
                                                    submitButtonColor={PrimaryTheme.$primary_color}
                                                    
                                                    submitButtonText={ST.Submit}
                                                />
                                            }
                                            { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text') &&  
                                                <TextInput 
                                                    style={[customStyle.WQ_InputStyle]}
                                                    placeholder=""
                                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                                    // keyboardType={'ascii-capable'}
                                                    keyboardType={(qtn.QuestionType=='Decimal'?'decimal-pad':(qtn.QuestionType=='Text'?'default':'number-pad'))}
                                                    value={selansid}
                                                    onChangeText={(val)=>{setTextValue(val,qtn,window)}}
                                                    autoComplete='off'
                                                />
                                                
                                            }
                                           
                                            {
                                                (qtn.QuestionType=='Date') && 
                                                <View style={customStyle.surveyQtn_datePicker_con}>
                                                    <Text style={customStyle.surveyQtn_datePicker_text}>{selansid!=''?selansid:'MM/YYYY'}</Text>
                                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setDateValue(selanswer);showQtnDatePicker(qtn,window,true)}}>
                                                        <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                                    </TouchableOpacity> 
                                                </View>     
                                            }
                                            {   ((qtn.showDatePicker==true || qtn.showDatePicker=='true') && (qtn.QuestionType=='Date') ) && 
                                                renderDatePicker(qtn,window)
                                            }  
                                            {
                                                (qtn.QuestionType=='Rating') && 
                                                <View style={customStyle.surveyQtn_datePicker_con}>
                                                    <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                    <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{setRatingQtn(qtn);setRatingWindow(window);setShowRating(true);}}>
                                                        <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag"/>
                                                    </TouchableOpacity> 
                                                </View>    
                                            }

                                            {
                                                // (qtn.QuestionType=='Audio') && 
                                                // <View style={customStyle.surveyQtn_datePicker_con}>
                                                //     <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                //     <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{show_recorder(qtn);}}>
                                                //         <FontAwesome size={25} color={PageTheme.$accent_color} name="microphone"/>
                                                //     </TouchableOpacity> 
                                                // </View>    
                                            }
                                            
                                            {
                                                showImageTag &&
                                                <View style={[customStyle.store_audit_img_con,]}>                    
                                                    <Image source={(selimg!='' && selimg!=null )?{uri:selimg}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg!='' && selimg!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                                    <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(window,'1','2',qtn)}}>
                                                        <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                                    </TouchableOpacity>
                                                </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={()=>{console.log('tsth');setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#000'} 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+' POSM'}
                    placeholderTextColor={PageTheme.$placeholder_color} 
                    value={searchedItem}
                    onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
                    autoComplete='off'
                  />
                  <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                    <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
                  </TouchableOpacity>
              </View>
            )
        }
        else{
            return(
                <View></View>
            )
        }
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,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> 
        {   showRating==true && 
            renderRatingView()
        }
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} 
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }  
      </Container>   
    ); 
}
  
  

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