import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme, STATUSBAR_HEIGHT } from "../styles/Global";
import {Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,FlatList, Alert, Dimensions,Animated, Easing} from 'react-native';
import { connect  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {marktext1,marktext2, resizeImage, restore_ImageWithMetaData} from '../controller/functions';
import {db, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, FontAwesome, FontAwesome5, Fontisto, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector';
import MultiSelect from 'react-native-multiple-select';
import { PageTheme } from '../styles/Themes';
import DateTimePicker from '@react-native-community/datetimepicker';
import DraggableFlatList,{ScaleDecorator} from 'react-native-draggable-flatlist'
import AudioRecorderPlayer, { AudioEncoderAndroidType, AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption } from 'react-native-audio-recorder-player';
import CustomCamera from '../components/Camera';

const {height, width} = Dimensions.get('window');
const topbarht=STATUSBAR_HEIGHT+50;
const actualWindowHt=parseInt((height-topbarht)+10);

function QuestionsScreen(props) { 
    const route = useRoute();
    const audioRecorderPlayer = new AudioRecorderPlayer();
    const AudioSet = {
        AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
        AudioSourceAndroid: AudioSourceAndroidType.MIC,
        AVModeIOS: AVModeIOSOption.measurement,
        AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
        AVNumberOfChannelsKeyIOS: 2,
        AVFormatIDKeyIOS: AVEncodingOption.aac,
      };
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);
    const [showRecorder, setShowRecorder] = useState(false);
    const [VRS, setVRS] = useState({});
    const [RecorderTimer, setRecorderTimer] = useState({});
    const [playerTimer, setPlayerTimer] = useState({});
    const [rerenderView, setRerenderView] = useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [VoiceRecorderStatus, setVoiceRecorderStatus] = useState('Press mic to start recording voice');
    const [RecFilePath, setRecFilePath] = useState({});
    const [dateValue, setDateValue] = useState('');
    const [openDatePicker, setOpenDatePicker]= useState(0);
    const [storeData, setStoreData] = useState({});
    const [ShowCat, setShowCat] = useState(false);
    const [ActiveSurvey, setActiveSurvey]= useState({});
    const [ActiveCategory, setActiveCategory]= useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [SurveySubCats, setSurveySubCats]= useState([]);
    const [SurveyQuestions, setSurveyQuestions]= useState([]);
    const [QuestionsData,setQuestionsData]=useState({});
    const [showAlert, setShowAlert] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

    const [isFeedbackView,setIsFeedbackView]= useState(false);
    
    
    const animatedRipple=useRef(new Animated.Value(0)).current;
    const animatedRipple2=useRef(new Animated.Value(0.5)).current;

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
       let params=props.route.params? props.route.params:{};
       let storeData1=params.storeData || {};
       let surveydata=params.surveyData || {};
       let catData=params.catData || {};
       let menu1=params.menu || {};
       let ShowCat1=params.ShowCat || false;
       let isAdhoc=params.isAdhocScreen || false;
       let fbv1=params.FeedbackView || false;
       setIsFeedbackView(fbv1);
       setShowCat(ShowCat1);
       setIsAdhocScreen(isAdhoc);
       setStoreData(storeData1);
       setActiveSurvey(surveydata)
       setCurrentMenu(menu1);
       setActiveCategory(catData)
       
        if(fbv1==true){
            getSurveyData2(storeData1);
        }else{
            getSurveyData(surveydata,catData,storeData1,ShowCat1);
        }
       
       props.navigation.addListener('beforeRemove', onBeforeRemove);
       return (()=>{
            audioRecorderPlayer.removePlayBackListener();
            audioRecorderPlayer.removeRecordBackListener();
            props.navigation.removeListener('beforeRemove', onBeforeRemove);
       });
    }, []);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    

    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    // async function getData(surveydata,catData={},storeData1){    
        
    //     try {   
    //         let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
    //         let surveyQtns=require('../constants/s_qtns.json');
    //         let subcats=[],qtns=[];
    //         for(const i in surveyQtns){
    //             let item=surveyQtns[i]
    //             let {ShowCat,AnswerId,Answer,AnswerSequence,ImageAllow,EnableQuestion,DisableQuestion,SubCategoryId,SubCategory,SubCategorySequence}=item;
    //             let addqtn=false;

    //             // let obj={MaxLength,MinLength,SubCategoryId,SubCategory,LengthValidation,QuestionImageAllow,DateRange,Question,QuestionId,QuestionType,OTP,Answer,AnswerId,ImageAllow,MULTI_OPTIONS_IDS:[]}
    //             if(ShowCat==0 && item.SurveyId==surveydata.SurveyId && qtns.findIndex(a=>a.QuestionId==item.QuestionId)<0)
    //             {    
    //                 qtns.push(item);
    //             }
    //             else if(ShowCat==1 && Object.keys(catData).length>0 && item.SurveyId==surveydata.SurveyId && item.CategoryId==catData.CategoryId  && qtns.findIndex(a=>a.QuestionId==item.QuestionId)<0)
    //             {    
    //                 qtns.push(item);
    //             }

    //             let s_obj={SubCategory,SubCategoryId,SubCategorySequence};
    //             if(ShowCat==0 && item.SurveyId==surveydata.SurveyId && subcats.findIndex(a=>a.SubCategoryId==item.SubCategoryId)<0){
    //                 subcats.push(s_obj);
    //             }
    //             else if(ShowCat==1 && Object.keys(catData).length>0 && item.SurveyId==surveydata.SurveyId && item.CategoryId==catData.CategoryId  && subcats.findIndex(a=>a.SubCategoryId==item.SubCategoryId)<0){
    //                 subcats.push(s_obj);
    //             }

                
    //             let sc_index=subcats.findIndex(a=>a.SubCategoryId==item.SubCategoryId);
    //             if(sc_index>=0){
    //                 let sc=subcats[sc_index];
    //                 let Questions=sc['Questions'] || [];
    //                 if(ShowCat==0 && item.SurveyId==surveydata.SurveyId && Questions.findIndex(a=>a.QuestionId==item.QuestionId)<0)
    //                 {    
    //                     Questions.push(item);
    //                 }
    //                 else if(ShowCat==1 && Object.keys(catData).length>0 && item.SurveyId==surveydata.SurveyId && item.CategoryId==catData.CategoryId  && Questions.findIndex(a=>a.QuestionId==item.QuestionId)<0)
    //                 {    
    //                     Questions.push(item);
    //                 }

    //                 sc['Questions']=Questions;
    //                 subcats[sc_index]=sc;
    //                 let q_index=Questions.findIndex(a=>a.QuestionId==item.QuestionId);
    //                 let q_index2=qtns.findIndex(a=>a.QuestionId==item.QuestionId);
                    
    //                 // if(q_index>=0){
    //                 //     let data=item;
    //                 //     let qn=Questions[q_index];
    //                 //     if(data.QuestionType=='List_Multi_Choice' || data.QuestionType=='List_Single_Choice' || data.QuestionType=='Rating'){
    //                 //         let allanswers=qn['Answers'] || [];
    //                 //         let ansobj={AnswerId,Answer,AnswerSequence,ImageAllow,EnableQuestion,DisableQuestion}
    //                 //         allanswers.push(ansobj);
    //                 //         qn['Answers']=allanswers;
    //                 //     }
    //                 //     else if(data.QuestionType=='Date'){
    //                 //         qn.showDatePicker=false;
    //                 //     }
    //                 //     Questions[q_index]=qn;
    //                 // }


    //                 if(q_index2>=0){
    //                     let data=item;
    //                     let qn=qtns[q_index2];
    //                     if(data.QuestionType=='List_Multi_Choice' || data.QuestionType=='List_Single_Choice' || data.QuestionType=='Rating'){
    //                         let allanswers=qn['Answers'] || [];
    //                         let ansobj={AnswerId,Answer,AnswerSequence,ImageAllow,EnableQuestion,DisableQuestion}
    //                         if(allanswers.findIndex(a=>a.AnswerId==data.AnswerId)<0)
    //                             allanswers.push(ansobj);

    //                         console.log('allanswers:',allanswers.length)
    //                         qn['Answers']=allanswers;
    //                     }
    //                     else if(data.QuestionType=='Date'){
    //                         qn.showDatePicker=false;
    //                     }
    //                     qtns[q_index]=qn;
    //                 }
                    
    //             }
    //         }
    //         setSurveySubCats(subcats);
    //         setSurveyQuestions(qtns);
    //         setProcessing(false);
   
    //     } catch (err) {
    //       console.log(err);          
    //     }        
    // }

    async function getSurveyData(item,catData={},storeData1,ShowCat1){ 
        try {   
            let {StoreId}=storeData1;
            let {CategoryId}=catData;
            let {SurveyId}= item;
            
            await db.transaction(async function (txn) { 


              let q2=`SELECT DISTINCT T.SubCategory,T.SubCategoryId,T.SubCategorySequence FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${SurveyId}' `;
              if(ShowCat1==true){
                q2+=` and T.CategoryId='${CategoryId}' `;
              } 
              q2+=` order by T.CategorySequence`;


              await txn.executeSql(q2,[],async function (txn2, txnres) { 
                  console.log('survey subcats:',txnres.rows.length);
                  if(txnres.rows.length>0){
                      let arr=[],allQtns=[];
                      for(var i=0;i<txnres.rows.length;i++){
                          let data =txnres.rows.item(i);
                          let all_scat_qtns=await getSurveyQtns(item,catData,storeData1,ShowCat1,data,false,menu1)
                          console.log('all_scat_qtns:',all_scat_qtns.length)
                          data['Questions']=all_scat_qtns;
                          allQtns=allQtns.concat(all_scat_qtns);
                          arr.push(data);
                          if(i==txnres.rows.length-1){
                              setSurveySubCats(arr);
                              setSurveyQuestions(allQtns);
                              setProcessing(false);
                          }
                      }
                  }
                  
              },function (txnE,txnerr) { console.log(txnerr); },);
             
            });          
          } catch (err) {
            console.log(err);          
          } 
    }

    async function getSurveyData2(storeData1){ 
        try {   
            let {StoreId}=storeData1;
            await db.transaction(async function (txn) { 
                let q2=`SELECT DISTINCT T.SubCategory,T.SubCategoryId,T.SubCategorySequence FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}'  order by T.CategorySequence`;
                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                    console.log('survey subcats:',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[],allQtns=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            let all_scat_qtns=await getSurveyQtns({},{},storeData1,false,data,true,menu1)
                           
                            data['Questions']=all_scat_qtns;
                            allQtns=allQtns.concat(all_scat_qtns);
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                setSurveySubCats(arr);
                                console.log('allsubcats:',arr.length,allQtns.length)
                                setSurveyQuestions(allQtns);
                                setProcessing(false);
                            }
                        }
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr); },);
               
            });  
          } catch (err) {
            console.log(err);          
          } 
    }


    async function getSurveyQtns(item,catData,storeData1,ShowCat1,subCat,fbv1=false,menu1){
        return new Promise((resolve,reject)=>{
            try {   
                let {StoreId}=storeData1;
                let {CategoryId}=catData;
                let {SurveyId}= item;
                let {SubCategoryId}=subCat;
                
                db.transaction(async function (txn) {  
                    let q2='';
                  if(fbv1==true){
                    // get inserted audit
                    let selectlist=` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                    let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                    let join2=` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID and T.SubCategoryId=T1.SUB_CATEGORY_ID And T.QuestionId=T1.QUESTION_ID`;
                    q2=`Select ${selectlist} FROM Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}' AND  T1.SUB_CATEGORY_ID='${SubCategoryId}'  `;
                    q2+=` ORDER BY T.SubCategorySequence `;
                  }
                  else{
                    // get inserted audit
                    let selectlist=` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                    let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                    let join2=` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID and T.SubCategoryId=T1.SUB_CATEGORY_ID And T.QuestionId=T1.QUESTION_ID`;
                    q2=`Select ${selectlist} FROM Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}' AND T1.SURVEY_ID=${SurveyId} AND T1.SUB_CATEGORY_ID='${SubCategoryId}'  `;
                    if(ShowCat1==true){
                    q2+=` AND  T1.CATEGORY_ID=${CategoryId} `;
                    }
                    q2+=` ORDER BY T.SubCategorySequence `;
                  }


                  
      
                  await txn.executeSql(q2,[],async function (txn2, txnres) { 
                     
                      if(txnres.rows.length>0){
                          let arr=[];
                          var QD=QuestionsData;
                          for(var i=0;i<txnres.rows.length;i++){
                              let data =txnres.rows.item(i);
                              let answers=[];
                              let qtn=data;
                              qtn.isDisabled=qtn.isDisabled==1 || qtn.isDisabled=='1'?true:false
                             
                              if(data.QuestionType=='List_Multi_Choice' || data.QuestionType=='List_Single_Choice' || data.QuestionType=='Rating'){
                                  let allanswers=await getAnswers(data,item.SurveyId,storeData1,true);
                                
                                  answers=allanswers.Answers || [];
                                  if(data.QuestionType=='Rating'){
                                      data.showRating=false;
                                  }
                              }
                              else if(data.QuestionType=='Date'){
                                  data.showDatePicker=false;
                              }
                              data.Answers=answers;
      
                              let id_key=qtn.QuestionId+'_AnswerId'; 
                              let ans_key=qtn.QuestionId+'_Answer'; 
                              let multi_key=qtn.QuestionId+'_MultiOption';
                              let date_key=qtn.QuestionId+'_Date';
                              let img_key=qtn.QuestionId+'_ImagePath1';
                              let imgname_key=qtn.QuestionId+'_ImageName1';
                              let img_key2=qtn.QuestionId+'_ImagePath2';
                              let imgname_key2=qtn.QuestionId+'_ImageName2';
                              let rating_key=qtn.QuestionId+'_Rating'; 
                              let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
      
                              let showImageTag=(data.QuestionImageAllow==true || data.QuestionImageAllow=='true' || data.QuestionImageAllow==1) ;
                              let showImageTag2=false;
      
                              QD[id_key]=data.AnswerId;
                              QD[ans_key]=data.Answer;

                              
                              let selansid=data.AnswerId;
                              if(qtn.QuestionType=='List_Multi_Choice'){
                                  selansid=data.multi_op_ids?data.multi_op_ids.split(','):[];
                                  QD[multi_key]=data.multi_op_ids;
                              }
      
                              if((qtn.QuestionType=='List_Single_Choice' || qtn.QuestionType=='List_Multi_Choice' )){
                                  if (qtn.Answers && qtn.Answers.length>0){
                                      for(var k=0;k<qtn.Answers.length;k++){
                                          let ansss=qtn.Answers[k];
                                          let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                                          let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                                          if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl && ansss.AnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                              showImageTag=true;
                                          }

                                            if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                                showImageTag2=true;
                                            }
                                            else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                                showImageTag2=true;
                                            }

                                      }
                                  }
                              }
      
                              if(showImageTag){
                                  let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image1;
                                  QD[imgname_key]=data.Image1;
                                  QD[img_key]=imgPath;
                              }

                              if(showImageTag2){
                                let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image2;
                                QD[imgname_key2]=data.Image2;
                                QD[img_key2]=imgPath;
                              }

                              
      
                              if(qtn.QuestionType=='Audio'){
                                  let voicefile_path=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+'/Recordings/'+data.Answer;
                                  QD[voiceClip_key]={'path':voicefile_path,'filename':data.Answer};
                              }
      
                              if(qtn.QuestionType=='Date'){
                                  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;
                                  QD[date_key]=fulldate;
                                  
                              }
                              arr.push(data);  
                              if(i==txnres.rows.length-1){
                                  setQuestionsData(QD);
                                  resolve(arr);
                                //   setSurveyQuestions(arr);
                                //   setProcessing(false);
                              }
                          }
                      }
                      else{
                        let q='';
                        if(fbv1==true){
                            let sl=` DISTINCT T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.MaxLength,T.MinLength,T.LengthValidation,T.Question,T.QuestionId,T.QuestionType,T.OTP,T.QuestionImageAllow,T.DateRange`;
                            q=` SELECT ${sl} FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SubCategoryId='${SubCategoryId}'  `; 
                            q+=` order by T.SubCategorySequence `;
                        }
                        else{
                            let sl=` DISTINCT T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.MaxLength,T.MinLength,T.LengthValidation,T.Question,T.QuestionId,T.QuestionType,T.OTP,T.QuestionImageAllow,T.DateRange`;
                            q=` SELECT ${sl} FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${SurveyId}' and T.SubCategoryId='${SubCategoryId}'  `; 
                            if(ShowCat1==true){
                              q+=` and T.CategoryId='${CategoryId}'  `;
                            }
                            q+=` order by T.SubCategorySequence `;
                        }
                          
                        
                          
                           await txn.executeSql(q,[],async function (txn2, txnres2) { 
                              
                              let arr=[];
                              if(txnres2.rows.length>0){
                                  for(var i=0;i<txnres2.rows.length;i++){
                                      let data =txnres2.rows.item(i);
                                      let answers=[];
                                      if(data.QuestionType=='List_Multi_Choice' || data.QuestionType=='List_Single_Choice' || data.QuestionType=='Rating'){
                                          let allanswers=await getAnswers(data,item.SurveyId,storeData1,false,fbv1);
                                          answers=allanswers.Answers || [];
                                          if(data.QuestionType=='Rating'){
                                              data.showRating=false;
                                          }
                                      }
                                      else if(data.QuestionType=='Date'){
                                          data.showDatePicker=false;
                                      }
                                      
                                      data.Answers=answers;
                                      arr.push(data);
                                      
                                      if(i==txnres2.rows.length-1){
                                          resolve(arr);
                                      }
                                  }
                              }
                              else{
                                resolve([]);
                              }
      
                          },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
                      }
                      
                  },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
                 
                });          
              } catch (err) {
                console.log(err);          
              }  
        })
    }

    async function getAnswers(qtn,SurveyId,storeData1,isInserted,fbv1){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                // get inserted audit
                let q2='';
                if(fbv1==true){
                    let selectlist=` DISTINCT T.Answer,T.AnswerId,T.ImageAllow1,T.ImageAllow2,T.EnableQuestion,T.DisableQuestion`;
                    let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                    q2=`Select ${selectlist} FROM Master_SurveyQuestion T ${join} WHERE T.QuestionId='${qtn.QuestionId}' AND M.StoreId = '${StoreId}' AND T.SubCategoryId='${qtn.SubCategoryId}' ORDER BY T.AnswerSequence `;
                }
                else{
                    let selectlist=` DISTINCT T.Answer,T.AnswerId,T.ImageAllow1,T.ImageAllow2,T.EnableQuestion,T.DisableQuestion`;
                    let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                    q2=`Select ${selectlist} FROM Master_SurveyQuestion T ${join} WHERE T.QuestionId='${qtn.QuestionId}' AND M.StoreId = '${StoreId}' AND T.SurveyId==${SurveyId} AND T.SubCategoryId='${qtn.SubCategoryId}' ORDER BY T.AnswerSequence `;
                }
                
                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                    // console.log('answers len',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                setSurveyQuestions(arr);
                                resolve(arr);
                            }
                        }
                    }
                    else{
                        resolve([]);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
               
              });    
        }).then((val)=>{
            return {'Answers':val,'Success':true};
        }).catch((err)=>{
            console.log(err);
            return {'Success':false,'Error':err}
        });
    }

    async function getImage(imgdata){
        let qtn=getImageProps.qtn || '';
        let type=getImageProps.type || '1';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

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

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

             let filename=storeData.StoreId+'_'+ActiveSurvey.SurveyId+'_'+qtn.QuestionId+'_SurveyImg_'+calculate_tym_date_for_filename+'.jpg';
    
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | Survey Id:'+ActiveSurvey.SurveyId+' | Question Id :'+qtn.QuestionId+' | Image Type: Survey'+' | Date:'+calculate_tym_date_over_img;
                            
        
            
            let qd=QuestionsData;
            let img_key=type=='1'?qtn.QuestionId+'_ImagePath1':qtn.QuestionId+'_ImagePath2';
            let imgname_key=type=='1'?qtn.QuestionId+'_ImageName1':qtn.QuestionId+'_ImageName2';
            qd[imgname_key]=filename;
            
        
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                console.log('image marker',uri);
                qd[img_key]=uri; 

                setQuestionsData(qd);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);

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

    async function disableQtns(sqtns,DQtns,data,isreturn=false){
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                    let s_qtn=sqtns[s_qtnindex];
                    if(s_qtn!=null){
                        s_qtn['isDisabled']=true
                        sqtns[s_qtnindex]=s_qtn;
                        let id_key=s_qtn.QuestionId+'_AnswerId'; 
                        let ans_key=s_qtn.QuestionId+'_Answer'; 
                        data[id_key]=0;
                        data[ans_key]='';
                        return false
                    }else{
                        return false
                    }
                })
            ).then(async (val)=>{
                setSurveyQuestions(sqtns);
                setQuestionsData(data);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                let s_qtn=sqtns[s_qtnindex];
                if(s_qtn!=null){
                    s_qtn['isDisabled']=false
                    sqtns[s_qtnindex]=s_qtn;
                    return false
                }else{
                    return false
                }
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                disableQtns(sqtns,DQtns,data)
            }
            else{
                setSurveyQuestions(sqtns);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
            }
        })
    }
   
    function onselectionChange(option,qtn){
        let data=QuestionsData;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        data[id_key]=option.value;
        data[ans_key]=option.label;

        setQuestionsData(data);

        let aq_ans=qtn.Answers!=null?qtn.Answers:[];
        let ans_obj=aq_ans.find(i=>i.AnswerId==option.value) || {};
        let EQtns=ans_obj.EnableQuestion!=null && ans_obj.EnableQuestion!=''?ans_obj.EnableQuestion.replace(' ','').split(','):[];
        let DQtns=ans_obj.DisableQuestion!=null && ans_obj.DisableQuestion!=''?ans_obj.DisableQuestion.replace(' ','').split(','):[];
      
        let sqtns=SurveyQuestions
        if(EQtns.length>0){
            enableQtns(sqtns,EQtns,DQtns,data)
        }
        else if(DQtns.length>0){
            disableQtns(sqtns,DQtns,data)
        }
        else{
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
        }
       
        
        
    }

    function setTextValue(value,qtn) {        
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        
        let obj=QuestionsData;
        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.QuestionId+'_Date'; 
            let d=value!=null?new Date(value):new Date();
            let mfdate=moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn,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);
        setQuestionsData(obj);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function setRatingValue(data){
        // let ids=[];
        // data.map((item,index)=>{
        //     ids.push(item.AnswerId);
        // })
        setRatingOrder(data);
    }


    async function setMultiSelectValue(selectedItems=[],qtn) {  
        console.log('setMultiSelectValue',selectedItems);      
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let multi_key=qtn.QuestionId+'_MultiOption';
        let obj=QuestionsData;
        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);
        setQuestionsData(obj);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }


    function showQtnDatePicker(qtn,show=false){
        let newqtnIndex=SurveyQuestions.findIndex(q=>q.QuestionId==qtn.QuestionId);
        console.log('showQtnDatePicker:',newqtnIndex);
        if(newqtnIndex>=0){
            let sq=SurveyQuestions;
            let newqtn=sq[newqtnIndex];
            newqtn.showDatePicker=show;
            sq[newqtnIndex]=newqtn;
            setSurveyQuestions(sq);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    
    function setShowQtnKey(qtn,key,show=false){
        if(key!=null && key!=''){
            let newqtnIndex=SurveyQuestions.findIndex(q=>q.QuestionId==qtn.QuestionId);
            console.log('setShowQtnKey:',newqtnIndex);
            if(newqtnIndex>=0){
                let sq=SurveyQuestions;
                let newqtn=sq[newqtnIndex];
                newqtn[key]=show;
                sq[newqtnIndex]=newqtn;
                setSurveyQuestions(sq);
                if(show==true) setrerenderdata(!rerenderdata);
            }
        }
    }

    function onRatingCancel(){ 
        setShowRating(false);
        
    }

    function onRatingSave(){
        setShowRating(false);

        let qtn=RatingQtn;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let rating_key=qtn.QuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })
        let obj=QuestionsData;
        obj[rating_key]=ids.join(',');
        obj[id_key]=0;
        obj[ans_key]=anss.join(',');
        
        console.log(obj);
        setQuestionsData(obj);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onRecordCancel(){
        setShowRecorder(false);
    }
    
    function onRecordSave(){

        let isRecorderPlaying=VRS.RecorderPlayStatus!=null && VRS.RecorderPlayStatus==true;
        let isPlayerPlaying=VRS.PlayerPlayStatus!=null && VRS.PlayerPlayStatus==true;

        if(isRecorderPlaying){
            notify('Please stop recording first');
            return;
        }
        else if(isPlayerPlaying){
            stopPlayer(VRS);
            // notify('Please stop playing audio first');
            // return;
        }

        setShowRecorder(false);
        let qtn=RatingQtn;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
       
        let obj=QuestionsData;
        obj[ans_key]=RecFilePath.filename || '';
        obj[id_key]=0;
        obj[voiceClip_key]=RecFilePath;
       
        setQuestionsData(obj);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    const RippleAnimation = (value,minValue,maxValue,delay) =>
    Animated.loop(
        Animated.sequence([
            Animated.timing(value, {
                toValue: maxValue,
                duration: 1000,
                delay:delay,
                useNativeDriver:(Platform.OS=='ios'?false:true),
            }),
            Animated.timing(value, {
                toValue: minValue,
                duration: 1000,
                delay:delay,
                useNativeDriver:(Platform.OS=='ios'?false:true),
            }),
        ]),
        
    ).start();

    const startRecorder = React.useCallback(async (storeData1,qtn,ActiveSurvey1,vrStatus) => {
        try{
            console.log('startRecorder')
            if(audioRecorderPlayer!=null){

                if(vrStatus['RecorderPlayStatus']==true){
                    notify('Already Recording...')
                    return;
                }
                else if(vrStatus['PlayerPlayStatus']==true){
                    notify('Please stop player first!')
                    return;
                }

                stopPlayer(vrStatus);

                let picture_clickedd=new Date();
                let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                let commname=storeData1.StoreId+'_'+ActiveSurvey1.SurveyId+'_'+qtn.QuestionId+'_SurveyRecording_'+picture_clicked_date+'_'+picture_clicked_time;
                let filename=Platform.OS=='ios'?commname+'.m4a':commname+'.mp3';
                            
                const url=Platform.OS=='ios'?'file://'+ImageFolderPath+currentMenu.ScreenName+"/"+'Recordings/'+filename:ImageFolderPath+currentMenu.ScreenName+"/"+'Recordings/'+filename;
                const url_dir=ImageFolderPath+currentMenu.ScreenName+"/"+'Recordings/';
                console.log('write file url:',url);
                RNFS.mkdir(url_dir).then((res)=>{
                   
                    RNFS.writeFile(url, '')
                    .then(async (success) => {
                        // if(success!=null){
                            const path = Platform.select({
                                ios: url,
                                android: url,
                            });
        
                            const result = await audioRecorderPlayer.startRecorder(path,AudioSet);
                        
                            if(result!=null && result!=''){
                                console.log('start recording now');
                                vrStatus['RecorderPlayStatus']=true;
                                setVRS(vrStatus);
                                setRecFilePath({'path':url,'filename':filename});
                                // animate
                                RippleAnimation(animatedRipple,0,1,0);
                                RippleAnimation(animatedRipple2,0,1,100);
                                
                                audioRecorderPlayer.addRecordBackListener((e) => {
                                    let recordsec=e.currentPosition;
                                    let data={'recordSecs':recordsec,'recordTime':audioRecorderPlayer.mmssss(Math.floor(recordsec))};
                                    if(vrStatus['RecorderPlayStatus']==true)
                                    {
                                        setRecorderTimer(data);
                                        setHasUnsavedChanges(true);
                                        setVoiceRecorderStatus('Recording... ! Press mic to stop recording');
                                    }
                                    
                                    console.log('recordsec:',recordsec);
                                    if(recordsec>=60*1000){
                                        stopRecorder(vrStatus);
                                        notify('Maximum record time limit reached.','LONG');
                                    }
                                    return;
                                });
                            }
                            console.log('start recorder:',result);
                        // }
                        // else{
                        //     notify('Something Went Wrong! Cannot open file for recording!');
                        // }
                        
                    })
                    .catch((err) => {
                        console.log('eerriur1',err.message);
                        notify('Something Went Wrong! Cannot open file for recording!');
                    });
                })
                .catch((err) => {
                    console.log('eerriur2',err.message);
                    notify('Something Went Wrong! Cannot open file for recording!');
                });   
                
            }
        }
        catch(e){
            console.log('error:',e);
        }

    },[]);
    

    

    
    
    const stopRecorder = React.useCallback(async (vrStatus) => {
        try{
            console.log('stopRecorder');
            if(audioRecorderPlayer!=null){
                
                animatedRipple.setValue(0);
                animatedRipple2.setValue(0.5);
                const uri = await audioRecorderPlayer.stopRecorder();
                audioRecorderPlayer.removeRecordBackListener();
                    
                vrStatus['RecorderPlayStatus']=false;
                vrStatus['PlayerPlayStatus']=false;
                setPlayerTimer({});
                setVRS({...VRS,vrStatus});
                setVoiceRecorderStatus('Press mic to start recording voice');
            }
        }
        catch(e){
            console.log('error:',e);
        }

    },[]);

    const startPlayer = React.useCallback(async (url,vrStatus1,type='0') => {
        try{
            let vrStatus=VRS;
            let qtn=RatingQtn;
            if(audioRecorderPlayer!=null){
                console.log('startPlayer1',url);
                if(vrStatus['PlayerPlayStatus']==true){
                    notify('Already Playing...')
                    return;
                }
                else if(vrStatus['RecorderPlayStatus']==true){
                    notify('Please stop recording first!')
                    return;
                }
                else if(url=='' || url==null){
                    notify('File not found!')
                    return;
                }

                const result = await audioRecorderPlayer.startPlayer(url);
                if(result!=null){
                    vrStatus['PlayerPlayStatus']=true;
                    setVRS(vrStatus);
                    
                    audioRecorderPlayer.addPlayBackListener((e) => {
                        let playDuration=audioRecorderPlayer.mmssss(Math.floor(e.duration));
                        let vrs=VRS;
                        let data={'playerSecs':e.currentPosition,'totalDuration':e.duration,'playDuration':playDuration,'playTime':audioRecorderPlayer.mmssss(Math.floor(e.currentPosition),)};
                        let data2={'playerSecs':'0000','totalDuration':e.duration,'playDuration':playDuration,'playTime':"00:00:00"};
                        if(vrs['PlayerPlayStatus']==true)
                        {   
                            setPlayerTimer(e.currentPosition<0?data2:data);
                        }
                        if(e.currentPosition<0){
                            return ;
                        }
                        let wp=e.duration!=null?Math.floor((e.currentPosition/e.duration)* 100):0;
                        console.log('wp:',wp);
                        if(wp>=100 || isNaN(wp)){
                            stopPlayer(vrs);
                        }
                        else if(type=='1' && wp<1){
                            pausePlayer();
                        }
                        setProcessing(false);
                        return;
                    });
                }
                else{
                    setProcessing(false);
                }
            }
        }
        catch(e){
            console.log('error:',e);
            setProcessing(false);
        }

    },[]);

    const resumePlayer = React.useCallback(async (url)=>{
       console.log('resume player')
       let vrStatus=VRS;
        const res=await audioRecorderPlayer.resumePlayer();
        console.log('res:',res);
        if(res=='No audio playing'){
            startPlayer(url,vrStatus);
        }
        vrStatus['PlayerPlayStatus']=true;
        setVRS({...VRS,vrStatus});
    },[]);

    
    const pausePlayer = React.useCallback(()=>{
        console.log('pause player')
        let vrStatus=VRS;
        audioRecorderPlayer.pausePlayer();
        vrStatus['PlayerPlayStatus']=false;
        setVRS({...VRS,vrStatus});
    },[]);

    const stopPlayer = React.useCallback(async (vrStatus) => {
        try{
           console.log('stop player now');
            
            if(audioRecorderPlayer!=null){
                const uri = await audioRecorderPlayer.stopPlayer();
                audioRecorderPlayer.removePlayBackListener();
                vrStatus['PlayerPlayStatus']=false;
                setVRS({...VRS,vrStatus});
            }
        }
        catch(e){
            console.log('error:',e);
        }

    },[]);

    async function show_recorder(qtn){
        let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
        let url=QuestionsData[voiceClip_key]?QuestionsData[voiceClip_key].path :'';
        setRatingQtn(qtn);
        if((RecorderTimer==null || Object.keys(RecorderTimer).length<=0) && (playerTimer==null || Object.keys(playerTimer).length<=0) && url!=null && url!=''){
            setLoaderTitle('Loading...');
            setProcessing(true);
            await startPlayer(url,VRS,'1');
        }
        setRecFilePath((QuestionsData[voiceClip_key] || {}));
        setShowRecorder(true);
    }

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

    function onSaveCancel(){
        setShowAlert(false);
    }

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   
            
                
              let q=`DELETE FROM ${AppTables.SURVEY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SURVEY_ID='${ActiveSurvey.SurveyId}' `;
              if(ShowCat==true){
                  q+=` and CATEGORY_ID='${ActiveCategory.CategoryId}' `;
              }

              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('survey data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              
              var values='';
              let {SurveyId,SurveyName} = ActiveSurvey;
              for(var i=0;i<SurveyQuestions.length;i++){
                values+=values!=''?' , ':'';

                let qtn=SurveyQuestions[i];
                
                let id_key=qtn.QuestionId+'_AnswerId'; 
                let ans_key=qtn.QuestionId+'_Answer'; 
                let multi_key=qtn.QuestionId+'_MultiOption';
                let date_key=qtn.QuestionId+'_Date';
                let img_key1=qtn.QuestionId+'_ImagePath1';
                let imgname_key1=qtn.QuestionId+'_ImageName1';
                let img_key2=qtn.QuestionId+'_ImagePath2';
                let imgname_key2=qtn.QuestionId+'_ImageName2';
                let rating_key=qtn.QuestionId+'_Rating'; 
                let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 

                let {CategoryId,Category,SubCategory,SubCategoryId,DateRange,LengthValidation,MaxLength,MinLength,OTP,Question,QuestionId,QuestionImageAllow,QuestionType}=qtn;
                
                let selansid=QuestionsData[id_key] || 0;
                let selans=QuestionsData[ans_key] || '';
                let imgName1=QuestionsData[imgname_key1] || '';
                let imgName2=QuestionsData[imgname_key2] || '';
                let multiops=QuestionsData[multi_key] || '';
                let isQtnDisabled=qtn.isDisabled!=null && qtn.isDisabled!=''?qtn.isDisabled?1:0:0;
                let allanss=qtn.Answers || {};
                let ans_obj=allanss.find(i=>i.AnswerId==selansid)
                let imgallow1=ans_obj!=null && ans_obj['ImageAllow1']!=null?ans_obj.ImageAllow1:false;
                let imgallow2=ans_obj!=null && ans_obj['ImageAllow2']!=null?ans_obj.ImageAllow2:false;
                let f_imgalloq1=(QuestionImageAllow=='true' || QuestionImageAllow==1) || (imgallow1=='true' || imgallow1==1)
                
                values+=` ('${StoreId}','${d2}','${SurveyId}','${CategoryId}','${SubCategoryId}','${Question}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${imgName1}','${imgallow2}','${imgName2}','${multiops}','${isQtnDisabled}','${d2}') `;
               }
              
              let add_data=`INSERT INTO ${AppTables.SURVEY} (STORE_ID,VISIT_DATE,SURVEY_ID,CATEGORY_ID,SUB_CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,IMAGE_ALLOW2,IMAGE2,MULTI_OPTIONS_IDS,IS_DISABLED,ADDED_DATE) VALUES ${values} `;
             
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('surveys added');
                notify('Survey updated successfully','SHORT');
                setProcessing(false);
                props.navigation.goBack();
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot update survey') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function validate(){  
        var isvalid=true;
        const QD=QuestionsData;
        console.log(SurveyQuestions.length);
        for(var i=0;i<SurveyQuestions.length;i++){
            let qtn=SurveyQuestions[i];
            let selansid='',selanswer='',selimg='',showImageTag=false,showImageTag2=false;
            let id_key=qtn.QuestionId+'_AnswerId'; 
            let ans_key=qtn.QuestionId+'_Answer'; 
            let multi_key=qtn.QuestionId+'_MultiOption';
            let date_key=qtn.QuestionId+'_Date';
            let img_key=qtn.QuestionId+'_ImagePath1';
            let imgname_key=qtn.QuestionId+'_ImageName1';
            let img_key2=qtn.QuestionId+'_ImagePath2';
            let imgname_key2=qtn.QuestionId+'_ImageName2';
            let rating_key=qtn.QuestionId+'_Rating'; 
            let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
            let list_mcdata=[];
           
            let isImgAllowed=(qtn.QuestionImageAllow==true || qtn.QuestionImageAllow=='true' || qtn.QuestionImageAllow==1);
            let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating') ;
            if(qtn.QuestionType=='List_Single_Choice')
            {
                selansid=QD[id_key];
            }
            else if(qtn.QuestionType=='List_Multi_Choice')
            {
                selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
            }
              
           
            if(qtn.QuestionType=='List_Multi_Choice' && selansid.length<=0){
                isvalid=false;
                notify('Please select options for the required field','SHORT');
                break;
            }
            else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                isvalid=false;
                let msg=( qtn.QuestionType=='Date'?'Please pick a date':(qtn.QuestionType=='Rating'?'Please select rating':'Please fill all details'));
                notify(msg,'SHORT');
                break;
            }
            else if( qtn.QuestionType=='Audio' && (Object.keys(QD).indexOf(voiceClip_key)<0 || (Object.keys(QD).indexOf(voiceClip_key)>=0 && (QD[voiceClip_key]==null || QD[voiceClip_key].filename==null || QD[voiceClip_key].filename=='')))){
                isvalid=false;
                notify('Please record audio clip for the required field','SHORT');
                break;
            }
            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) ))){
                isvalid=false;
                notify('Please fill all details','SHORT');
                break;
            }
            else if(isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                isvalid=false;
                notify('Please add images','SHORT');
                break;
            }else{
                console.log('no condition found');
            }

            if((qtn.QuestionType=='List_Single_Choice' || qtn.QuestionType=='List_Multi_Choice' )){
                if (qtn.Answers && qtn.Answers.length>0){
                    for(var j=0;j<qtn.Answers.length;j++){
                        let ansss=qtn.Answers[j];
                        let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                        if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl && ansss.AnswerId==selansid)){
                            showImageTag=true;
                        }
                        else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                            showImageTag=true;
                        }
                        
                        let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                        if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl2 && ansss.AnswerId==selansid)){
                            showImageTag2=true;
                        }
                        else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                            showImageTag2=true;
                        }
                    }
                }
            }

            if(showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                isvalid=false;
                notify('Please add images','SHORT');
                break;
            }

            
            if(showImageTag2 && (Object.keys(QD).indexOf(img_key2)<0 || (Object.keys(QD).indexOf(img_key2)>=0 && QD[img_key2]===''))){
                isvalid=false;
                notify('Please add images','SHORT');
                break;
            }

            
        } 
        
        return isvalid;
    }
   
    function render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        let isQtnDisabled=qtn.isDisabled!=null && qtn.isDisabled!=''?qtn.isDisabled:false;
        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) }}
            overlayStyle={customStyle.addVisPickerOverlay}
            cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            optionStyle={customStyle.addvis_opStyle}
            optionTextStyle={customStyle.addvis_opTextStyle}
            optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            selectedKey={'1'}
            disabled={isQtnDisabled}
            >
            <Text style={[customStyle.addVisPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-select-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn){
        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)}}
            maximumDate={new Date(maxDate)}
            minimumDate={new Date(minDate)}
            />    
        );
    }

    function renderItem({ item, drag, isActive }){
        return (
          <ScaleDecorator>
            <TouchableOpacity
              
              onLongPress={drag}
              disabled={isActive}
              style={[customStyle.RModal_listItem,{ backgroundColor: isActive ? PageTheme.$primary_color : PageTheme.$secondary_color_light },]}
            >
              <Text style={[customStyle.RModal_listItemText,(isActive?{color:PageTheme.$accent_color}:{})]}>{item.Answer}</Text>
            </TouchableOpacity>
          </ScaleDecorator>
        );
    };

    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let rating_key=qtn.QuestionId+'_Rating'; 
        // let ratings=QuestionsData[rating_key]!=null?QuestionsData[rating_key].split(','):[];
        
        let newarr=RatingOrder;
        if(RatingOrder.length<=0){
            newarr=Answers;
        }

        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>Drag Items In Order</Text>
                <Text style={customStyle.VRSubHeding}>Press and hold to drag</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}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRatingSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>Save</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        )
    }

    function renderRecorderView(){
        
        let qtn=RatingQtn;
        let isRecorderPlaying=VRS.RecorderPlayStatus!=null && VRS.RecorderPlayStatus==true;
        let isPlayerPlaying=VRS.PlayerPlayStatus!=null && VRS.PlayerPlayStatus==true;
        const scale=animatedRipple.interpolate({
            inputRange:[0,1],
            outputRange:[1,1.3],
        });

        const borderColor=animatedRipple.interpolate({
            inputRange:[0,1],
            outputRange:['#f5acb4c2','#fce6e9e3'],
        });

        const scale2=animatedRipple2.interpolate({
            inputRange:[0,1],
            outputRange:[1,1.5],
        });

        const borderColor2=animatedRipple2.interpolate({
            inputRange:[0,1],
            outputRange:['#f5acb4c2','#fce6e9e3'],
        });

        let totalDuration=RecorderTimer.recordSecs!=null?RecorderTimer.recordSecs:playerTimer.totalDuration;
        let wp=totalDuration!=null?Math.floor((playerTimer.playerSecs/totalDuration)* 100):0;
        let width1=wp<=100?(wp>0?wp+'%':'0%'):'100%';
        if(isNaN(wp)) width1='0%';

        return (
        <View style={customStyle.RatingModal}>
            {rerenderView==rerenderView && 
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>Record Voice Clip</Text>
                <Text style={customStyle.VRSubHeding2}>You can record max for 60 secs</Text>
                <Text style={customStyle.VRSubHeding}>{VoiceRecorderStatus}</Text>
                
                <View style={customStyle.VoiceRecorder}>
                    <View style={customStyle.VoiceRecorderMic}>
                        <Animated.View style={[customStyle.VRMicBgRipple2,{
                            transform:[
                                {scale:scale2},
                            ],
                            borderColor:('#fce6e9e3'),
                        }]}></Animated.View>
                        <Animated.View style={[customStyle.VRMicBgRipple1,{
                            transform:[
                                {scale:scale},
                            ],
                            borderColor:('#f5acb4c2'),
                        }]}></Animated.View>
                        <TouchableOpacity activeOpacity={1} style={customStyle.VoiceRecorderMicBtn} onPress={()=>{startRecorder(storeData,qtn,ActiveSurvey,VRS);  }}>
                            <FontAwesome size={30} color={PageTheme.$accent_color} name="microphone"/>
                        </TouchableOpacity>
                        {isRecorderPlaying && 
                        <TouchableOpacity activeOpacity={1} style={customStyle.VoiceRecorderStopBtn} onPress={()=>{stopRecorder(VRS);  }}>
                            <FontAwesome5 size={30} color={PageTheme.$accent_color} name="microphone-alt"/>
                        </TouchableOpacity>
                        }
                        
                    </View>
                    <View style={customStyle.VoiceRecordedView}>
                            <Text style={customStyle.VoiceRecorderTimer}>{RecorderTimer.recordTime}</Text>
                            {
                                (!isRecorderPlaying && RecFilePath.filename!=null && RecFilePath.filename!='') &&
                                <View style={customStyle.VRPlayBack}>
                                    <View style={customStyle.VRPlayBackBarView}>
                                        <View style={customStyle.VRPlayBackBar}>
                                            <View style={customStyle.VRPlayBackBarBg}></View>
                                            <View style={[customStyle.VRPlayBackBarFilled,{width:width1}]}></View>
                                        </View>
                                        <Text style={customStyle.VRPlayBackTimer}>{`${(playerTimer.playTime || '00:00:00')} / ${playerTimer.playDuration || RecorderTimer.recordTime}`}</Text>
                                    </View>
                                    
                                    <View style={customStyle.VRPlayBackControls}>
                                        <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Play} onPress={()=>{let url=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+currentMenu.ScreenName+"/"+'Recordings/'+RecFilePath.filename; (wp<100 && wp>0)? resumePlayer(url):startPlayer(url,VRS); }}>
                                            <Entypo size={24} color={PageTheme.$accent_color} name="controller-play"/>
                                        </TouchableOpacity>
                                        {isPlayerPlaying && <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Pause} onPress={()=>{ wp<100?pausePlayer():stopPlayer(VRS); }}>
                                            <Entypo size={24} color={PageTheme.$accent_color} name="controller-paus"/>
                                        </TouchableOpacity>}
                                    </View>
                                </View>
                            }
                        </View>
                </View>
                <View style={customStyle.RModal_Btns}>
                    <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={()=>{onRecordCancel()}}>
                        <Text style={customStyle.RModal_BtnTextCancel}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRecordSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>Save</Text>
                    </TouchableOpacity>
                </View>
            </View>}
        </View>
        )
    }
    
    function _renderSurveyQtns(subcat){
        const SurveyQuestions=subcat.Questions;
        return (
        <View style={customStyle.SVn_GroupViewList}>
            {
                SurveyQuestions.length>0 && 
                SurveyQuestions.map((item,index)=>{
                    
                    let qtn=item;  
                    let selansid='',selanswer='',selimg='',selimg2='',showImageTag=false,showImageTag2=false;
                    let id_key=qtn.QuestionId+'_AnswerId'; 
                    let ans_key=qtn.QuestionId+'_Answer'; 
                    let multi_key=qtn.QuestionId+'_MultiOption';
                    let date_key=qtn.QuestionId+'_Date';
                    let img_key=qtn.QuestionId+'_ImagePath1';
                    let imgname_key=qtn.QuestionId+'_ImageName1';
                    let img_key2=qtn.QuestionId+'_ImagePath2';
                    let imgname_key2=qtn.QuestionId+'_ImageName2';
                    let rating_key=qtn.QuestionId+'_Rating'; 
                    let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
                    let list_mcdata=[];

                    if(qtn.QuestionType=='List_Single_Choice')
                    {
                        selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                        selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                    }
                    else if(qtn.QuestionType=='List_Multi_Choice')
                    {
                        
                        if(qtn.Answers!=null){
                            console.log('qtn.Answers:',qtn.Answers.length);
                            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.QuestionImageAllow==true || qtn.QuestionImageAllow=='true' || qtn.QuestionImageAllow==1);
                        showImageTag2=false;
                    }
                    else if(qtn.QuestionType=='Rating'){
                        selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                    }
                    else if(qtn.QuestionType=='Audio'){
                        selansid=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                        selanswer=QuestionsData[voiceClip_key]?(QuestionsData[voiceClip_key].filename || ''):'';
                    }

                    if((qtn.QuestionType=='List_Single_Choice' || qtn.QuestionType=='List_Multi_Choice' )){
                        if (qtn.Answers && qtn.Answers.length>0){
                            for(var i=0;i<qtn.Answers.length;i++){
                                let ansss=qtn.Answers[i];
                                
                                let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                                let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                                
                                if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl && ansss.AnswerId==selansid)){
                                    showImageTag=true;
                                }
                                else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                    showImageTag=true;
                                }

                                if(qtn.QuestionType=='List_Single_Choice' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                    showImageTag2=true;
                                }
                                else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                    showImageTag2=true;
                                }
                            }
                        }
                    }
                    
                    if(showImageTag){
                        selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                    }

                    if(showImageTag2){
                        selimg2=QuestionsData[img_key2]!=null && QuestionsData[img_key2]!=''?'file://'+QuestionsData[img_key2]:'';                    
                    }
                    
                  
                    
                    return(
                    <View style={[customStyle.sform_group2,]} key={index}>
                        <Text style={[customStyle.sform_label3]}>{qtn.Question}</Text>                     
                        {qtn.QuestionType=='List_Single_Choice' && qtn.Answers && 
                            render_Picker('Answer','AnswerId',onselectionChange,{value:selanswer,qtn:qtn})
                        }
                        {qtn.QuestionType=='List_Multi_Choice' && qtn.Answers &&
                            <MultiSelect
                                items={list_mcdata}
                                uniqueKey="AnswerId"
                                onSelectedItemsChange={(selectedItems)=>{console.log('onSelectedItemsChange'); }} //setMultiSelectValue(selectedItems,qtn)
                                selectedItems={selansid}
                                selectText="Pick Items"
                                searchInputPlaceholderText="Search Items..."
                                // onChangeInput={ (text)=> console.log(text)}
                                tagRemoveIconColor={PageTheme.$primary_color}
                                tagBorderColor={PageTheme.$primary_color}
                                tagTextColor={PageTheme.$primary_color}
                                selectedItemTextColor={PageTheme.$primary_color}
                                selectedItemIconColor={PageTheme.$primary_color}
                                itemTextColor={PageTheme.$text_color}
                                displayKey="Answer"
                                searchInputStyle={{ color: '#CCC' }}
                                submitButtonColor={PageTheme.$primary_color}
                                submitButtonText="Submit"
                            />
                        }
                        { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text') &&  
                            <TextInput 
                                style={[customStyle.surveyQtn_InputStyle]}
                                placeholder=""
                                autoComplete='off'
                                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)}}
                            />
                        }
                        {
                            (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,true)}}>
                                    <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                </TouchableOpacity> 
                            </View>     
                        }
                        {   ((qtn.showDatePicker==true || qtn.showDatePicker=='true') && (qtn.QuestionType=='Date') ) && 
                            renderDatePicker(qtn)
                        }  
                        {
                            (qtn.QuestionType=='Rating') && 
                            <View style={customStyle.surveyQtn_datePicker_con}>
                                <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{setRatingQtn(qtn);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(qtn,'1')}}>
                                    <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                </TouchableOpacity>
                            </View>
                        }
                        {
                            showImageTag2 &&
                            <View style={[customStyle.store_audit_img_con,]}>                    
                                <Image source={(selimg2!='' && selimg2!=null )?{uri:selimg2}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg2!='' && selimg2!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(qtn,'2')}}>
                                    <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                </TouchableOpacity>
                            </View>
                        }
                    </View> 
                    )
                })
            }
        </View>
                  
        );
    }

    // function _renderSurveyQtns(subcatItem){
    //     return (
    //         <FlatList
    //                 data={SurveyQuestions}
    //                 extraData={rerenderdata}
    //                 style={[customStyle.SVn_QtnScroll]}
    //                 nestedScrollEnabled={true}
    //                 removeClippedSubviews={false}
    //                 showsVerticalScrollIndicator={false}      
    //                 contentContainerStyle={customStyle.SVn_QtnScrollInner}
    //                 renderItem={({ item, index, separators }) =>{  
                           
    //                 }}
    //         /> 
    //     )
    // }

    function _renderSurveyView(){
        return (
            <View style={customStyle.SVn_ContentCon}>
            <FlatList 
            style={customStyle.SVn_ContentOuter} 
            extraData={rerenderdata}
            nestedScrollEnabled={true}
            removeClippedSubviews={false}
            showsVerticalScrollIndicator={false}     
            contentContainerStyle={(isFeedbackView!=true ?customStyle.SVn_ContentInner:{paddingHorizontal:10})}
            data={SurveySubCats}
            renderItem={({ item, index, separators }) =>{  
                let subcat=item,s_index=index;
                
                return (
                    <View style={[customStyle.SVn_GroupView,(isFeedbackView==true && index==0?{paddingTop:0}:{})]} key={s_index}>
                        <LinearGradient colors={[PageTheme.$bg_color,PageTheme.$primary_color,PageTheme.$bg_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}  style={customStyle.SVn_GroupView_hdr}>
                            <Text style={customStyle.SVn_GroupView_hdrText}>{subcat.SubCategory}</Text>
                        </LinearGradient>
                        { _renderSurveyQtns(subcat)}
                    </View>
                )
            }}
            >
                
            </FlatList>
            </View>
        );
    }

    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} 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.roundScrollZIndex]}>
            <View style={[customStyle.pageContentWrapper,(isFeedbackView!=true ? customStyle.SVn_PageWrapper:{})]}>
               {isFeedbackView!=true && <View style={customStyle.SVn_activeSurvey}>
                    <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$gradient1]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.SVn_activeSurvey_tile}>
                        {/* <Text style={customStyle.SV_activeSurvey_name}>{(ActiveSurvey.SurveyName!=null?(ActiveSurvey.SurveyName.length>26?ActiveSurvey.SurveyName.substring(0,26)+'...':ActiveSurvey.SurveyName) : '')}</Text> */}
                        <Text style={customStyle.SV_activeSurvey_name}>{('Survey Id : '+(ActiveSurvey.SurveyId || '')+(ShowCat==true?'  |  '+'Category Id : '+(ActiveCategory.CategoryId || ''):''))}</Text>
                    </LinearGradient>
                </View>}
                { 
                // Object.keys(ActiveSurvey).length>0 &&            
                    _renderSurveyView()
                }
                <View style={[customStyle.SVn_SubmitBtn]}>
                    <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
                </View> 
            </View>  
        </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
        { showRecorder==true && 
            renderRecorderView()
        }
      </Container>   
    ); 
  }
  

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