import { View, Text,TouchableOpacity,Image,FlatList,TextInput,Alert, ScrollView, Keyboard} from 'react-native'
import React,{useState,useEffect} from 'react';
import {useRoute} from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import moment from 'moment';
import {AntDesign, Entypo, FontAwesome, FontAwesome5, Fontisto, MaterialCommunityIcons} from '../components/icons';

import Container from '../components/container';
import CustomLoader from '../components/CustomLoader';
import {db, ImageFolderPath, URL_IMAGE, VisitorLoginImageFolderPath} from '../constants/constants';
import {getAllFileForAFolder, getAllFolderImages, getDownloadJson,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, UploadData2, validateNumber} from '../controller/functions';
import LinearGradient from 'react-native-linear-gradient';
import CameraImg from '../assets/performics/camera_front_image.svg'
import * as RNFS from 'react-native-fs';
import {notify} from '../components/notify';
import { connect } from 'react-redux';
import CustomCamera from '../components/Camera';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {empdata} from './VisitorLogin'
import CustomHeader from '../components/customHeader';
import { AppTables } from '../constants/tableConstants';
import { ConfirmSaveAlert } from '../components/alert';
import GradientButton from '../components/gradientButton';
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 { getMethodName, METHODS } from '../constants/methodNames';
import { getImagePOSTData, uploadAll_VisImages, UploadImagesWithoutWait } from '../constants/uploadData';
// import AudioRecorderPlayer, { AudioEncoderAndroidType, AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption } from 'react-native-audio-recorder-player';


function VisitorLoginQA(props){
    const route = useRoute();
   
    const ST=props.StaticText || {};
    const projectCode=props.projectCode;
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    const [visitorFeedback, setvisitorFeedback] = useState([]);
    const [processing, setProcessing] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState();
    const [getImageProps,setGetImageProps]= useState({});
    const [showCamera, setShowCamera] = useState(false);
    const [image, setImage]= useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [SurveyQuestions, setSurveyQuestions]= useState([]);

    const [SurveySubCats, setSurveySubCats]= useState([]);
    const [QuestionsData,setQuestionsData]=useState({});
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [EditMode, setEditMode] = useState(false);
    const [vfQuestion, setvfQuestion] = useState({});
    const [defaultRating, setDefaultRating] = useState(2);
    const [starCalQtns, setstarCalQtns] = useState([]);

    const StartCount= 5;
    const [maxRating, setMaxRating] = useState([]);
    const [employeeCode, setEmployeeCode]= useState('');
    const [searchedEmployees, setSearchedEmployees] = useState([]);

    const [EmpData, setEmpData]= useState({});
// const [visitors, setVisitors] = useState([]);

useEffect(()=>{
    console.log("vfQuestion---------",vfQuestion)
},[vfQuestion])
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        console.log('params',params)
        let visitorfeedbackData=params.visitoreditdata || {};
        let editMode1=params.EditMode || false;
        setEditMode(editMode1);
        console.log('visitorfeedbackData',visitorfeedbackData.NAME)
        setvisitorFeedback(visitorfeedbackData);
        getData(editMode1,visitorfeedbackData);
        console.log('props',props.UserId)
        // addEmpl();
        return function cleanup() {
            props.navigation.removeListener('beforeRemove', onBeforeRemove);
          };
    
    },[]);   

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
  }, [hasUnsavedChanges]);   

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

    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }


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

    function onSaveCancel(){
        setShowAlert(false);
    }
    

    async function getData(editMode1=false,vfData={}){ 
      try {   
        console.log("editMode1",editMode1);
        let arr=[];
        for(let sIndex=1;sIndex<=StartCount;sIndex++){
            arr.push(sIndex);
            if(sIndex==StartCount){
                setMaxRating(arr);
            }
        }

        if(editMode1){
            // designation
            let obj = {'name':vfData.NAME,'designation':vfData.DESIGNATION}
            setvfQuestion(obj);

            let imagePath='file://'+VisitorLoginImageFolderPath+vfData.IMAGE;

            let objimg = {'Visitor_Image':vfData.IMAGE,'Visitor_ImagePath':imagePath}
            setImage(objimg);

        }
          
          await db.transaction(async function (txn) { 


            let q2='SELECT Distinct CategoryId,Category,CategorySequence FROM Master_VisitorLoginQuestion';
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                console.log('feedback survey:',txnres.rows.length);
                if(txnres.rows.length>0){
                    let arr=[],allQtns=[],allavgquest=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        console.log('9datacat',data)
                        console.log('datadded',data.CategoryId)
                        let all_scat_objet=await getSurveyQtns(data,editMode1,vfData);
                        console.log('all_scat_objet',all_scat_objet)
                        let all_scat_qtns = all_scat_objet.qtns!=null ?all_scat_objet.qtns:[]
                        let all_scat_qtnsavg = all_scat_objet.avgqtns!=null ?all_scat_objet.avgqtns:[]
                        console.log('all_scat_qtns:',all_scat_qtns)
                        data['Questions']=all_scat_qtns;
                        allQtns=allQtns.concat(all_scat_qtns);
                        allavgquest = allavgquest.concat(all_scat_qtnsavg);
                        console.log('allQtns',allQtns)
                        arr.push(data);
                        if(i==txnres.rows.length-1){
                            setSurveySubCats(arr);
                            setSurveyQuestions(allQtns);
                            setstarCalQtns(allavgquest);
                            console.log('allQtns1222',allQtns)
                            setProcessing(false);
                        }
                    }
                }
                else{
                    setProcessing(false);
                }
                
            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);
           
          });          
        } catch (err) {
          console.log(err);          
        } 
  }


  async function getSurveyQtns(catData={},editMode1=false,vfData={}){
    let obj = {'qtns':[],'avgqtns':[]};
    let {CategoryId}= catData;
    let {NAME,DESIGNATION}=vfData;
 
    return new Promise((resolve,reject)=>{
        try {   
            
            db.transaction(async function (txn) {  
                
                if(editMode1){
                    let selectlist=` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,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 sl=` DISTINCT mvf.MaxLength,mvf.MinLength,mvf.LengthValidation,Question,QuestionId,QuestionType,OTP,QuestionImageAllow,DateRange,QuestionCalculate`;
                    let join=`Inner join Master_VisitorLoginQuestion T on T1.QUESTION_ID=T.QuestionId and T1.CATEGORY_ID=T.CategoryId`;
                    let q=` SELECT ${selectlist} FROM ${AppTables.VISITOR_LOGIN_FEEDBACK} T1 ${join} where T1.CATEGORY_ID='${catData.CategoryId}' and T1.NAME='${NAME}' and T1.DESIGNATION='${DESIGNATION}' and T1.VISIT_DATE='${d2}' `; 
                    // let q3=` SELECT * FROM ${AppTables.VISITOR_LOGIN_FEEDBACK} T1 where T1.CATEGORY_ID='${catData.CategoryId}' and T1.VISIT_DATE='${d2}' `;
                    
                    console.log('querydata',catData.CategoryId)
                    await txn.executeSql(q,[],async function (txn2, txnres2) { 
                        console.log('Surveys:',txnres2.rows.length)
                        let arr=[];
                        let arr2=[];
                        var QD=QuestionsData;
                        if(txnres2.rows.length>0){
                            for(var i=0;i<txnres2.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);
                                    console.log('allanswers',allanswers)
                                    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=data.Image1!=''?((Platform.OS=='ios'?'file://':'')+VisitorLoginImageFolderPath+data.Image1):'';
                                    QD[imgname_key]=data.Image1;
                                    QD[img_key]=imgPath;
                                }

                                if(showImageTag2){
                                    let imgPath=data.Image2!=''?((Platform.OS=='ios'?'file://':'')+VisitorLoginImageFolderPath+data.Image2):'';
                                    QD[imgname_key2]=data.Image2;
                                    QD[img_key2]=imgPath;
                                }
        
                                if(qtn.QuestionType=='Audio'){
                                    let voicefile_path=(Platform.OS=='ios'?'file://':'')+VisitorLoginImageFolderPath+'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(data.QuestionType=='RatingStarCal'){
                                    arr2.push(data)
                                }
                                if(i==txnres2.rows.length-1){
                                    obj['qtns']= arr;
                                    obj['avgqtns']= arr2;
                                    setQuestionsData(arr);
                                    resolve(obj);
                                }
                            }
                        }
                        else{
                            resolve(obj);
                        }
                    },function (txnE,txnerr) { console.log(txnerr);resolve(obj); },);
                }
                else{
                    let sl=` DISTINCT MaxLength,MinLength,LengthValidation,CategoryId,Category,Question,QuestionId,QuestionType,OTP,QuestionImageAllow,DateRange,QuestionCalculate`;
                    let q=` SELECT ${sl} FROM Master_VisitorLoginQuestion where CategoryId='${catData.CategoryId}' `; 
                    console.log('catData',catData.CategoryId)
                    await txn.executeSql(q,[],async function (txn2, txnres2) { 
                        console.log('Surveys:',txnres2.rows.length)
                        let arr=[];
                        let arr2=[];
                        var QD=QuestionsData;
                        if(txnres2.rows.length>0){
                            for(var i=0;i<txnres2.rows.length;i++){
                                let data =txnres2.rows.item(i);
                                console.log('datafeedbacj',data)
                                let answers=[];
                                if(data.QuestionType=='List_Multi_Choice' || data.QuestionType=='List_Single_Choice' || data.QuestionType=='Rating'){
                                    let allanswers=await getAnswers(data);
                                    console.log('datarender',data)
                                    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(data.QuestionType=='RatingStarCal'){
                                arr2.push(data)
                                }
                                if(i==txnres2.rows.length-1){
                                obj['qtns']= arr;
                                obj['avgqtns']= arr2;
                                setQuestionsData(arr);
                                resolve(obj);
                              }
                            }
                        }
                        else{
                            resolve(obj);
                        }

                    },function (txnE,txnerr) { console.log(txnerr);resolve(obj); },);
                }
             
            });          
          } catch (err) {
            console.log(err);  
            return obj;        
          }  
    })
}

function validateEmp(item,checkin){
    let isValid=true;
    let image_key=checkin==true?item.EmpId+'In_Image':item.EmpId+'Out_Image';
    let image_path_key=checkin==true?item.EmpId+'In_ImagePath':item.EmpId+'Out_ImagePath';
    let image1=EmpData[image_key] || '';
    if(image1=='' || image1==null){
      isValid=false;
      notify(`${(checkin==true?ST.PleaseclickCheckInImage:ST.PleaseclickCheckOutImage)}`);
    }
    return isValid;
  }

async function addEmpl(item){
    // if(validateEmp(item,true)){
      console.log('addEmp')
      setLoaderTitle(ST.AddingEmployee+'...');
      setProcessing(true);

      try{
        let {EmpId,EmployeeName,DesignationName,LegacyCode}=item;
        if(!Boolean(EmpId)){
            notify("Employee ID is missing..");
            return true
        }

        return new Promise(async (resolve) => {
        let isAlreadyExist=false;

        await db.transaction(async function (txn) {        
          let currentTime=moment().format('HH:mm:ss');
          let d3=moment().format('MM/DD/YYYY');
          let image_key=item.EmpId+'In_Image';
          let image_path_key=item.EmpId+'In_ImagePath';
          let image1=EmpData[image_key] || '';
          let values=`('${EmpId}','${LegacyCode}','${EmployeeName}','${DesignationName}','I','${d3}','${currentTime}','','${image.Visitor_Image}','','${d3}')`;
          let q=`INSERT INTO ${AppTables.VISITOR_LOGIN}(EMP_ID,EMP_CODE,NAME,DESIGNATION,UPLOADSTATUS,VISIT_DATE,IN_TIME,OUT_TIME,IN_TIME_IMAGE,OUT_TIME_IMAGE,ADDED_DATE) VALUES ${values}`;
          let q2=`SELECT * FROM ${AppTables.VISITOR_LOGIN} WHERE  VISIT_DATE='${d3}'`;
          
          let q3=`SELECT * FROM ${AppTables.VISITOR_LOGIN} WHERE  VISIT_DATE='${d3}' and EMP_CODE='${LegacyCode}'`;
          await txn.executeSql(q3,[],async function (txn2, txnres3) { 
            if(txnres3.rows.length>0){
              setProcessing(false);
              notify(ST.Visitor+' '+LegacyCode+' '+ST.Alreadyexists);
              console.log("isAlreadyExist-----",true)
              isAlreadyExist=true;
              resolve(true);
            //   return true
            }
            else{
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                console.log('Visitor added');
                
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                  console.log('Visitors',txnres2.rows.length);
                  if(txnres2.rows.length>0){
                    
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                      
                      let index=i;
                      let data=txnres2.rows.item(i);
                      
                      arr.push(data);
                      if(index==txnres2.rows.length-1){
                        resolve(false);
                        // setEmployeeCode('');
                        // setSearchedEmployees([]);
                        // setVisitors(arr);
                        setProcessing(false);
                        notify(ST.Visitoraddedsuccessfully);
                      }
                    }
                  }
                  else{
                    resolve(false);
                    setProcessing(false);
                    notify(ST.Somethingwentwrong+'! '+ST.Cannotaddvisitor);
                  }
                },function (txnE,txnerr) { resolve(true); console.log(txnerr);setProcessing(false);notify(ST.Somethingwentwrong); },);
                
              },function (txnE,txnerr) {resolve(true); console.log(txnerr);setProcessing(false);notify(ST.Cannotaddvisitor); },);
            
            }
          },function (txnE,txnerr) { resolve(true); console.log(txnerr);setProcessing(false);notify(ST.Cannotaddvisitor); },);
          
        });  
    });
        
        // return isAlreadyExist;
      }
      catch(err){
        console.log('err',err);
        setProcessing(false);
        notify(ST.Errorwhileaddingvisitor);
      }

    // }
  }

async function getAnswers(qtn){
   
    return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {   
            // get inserted audits
            let selectlist=` DISTINCT Answer,AnswerId,ImageAllow1,ImageAllow2,EnableQuestion,DisableQuestion`;
            // let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
            let q2=`Select ${selectlist} FROM Master_VisitorLoginQuestion WHERE QuestionId='${qtn.QuestionId}' ORDER BY AnswerSequence `;
            // console.log('q',q2)
            
            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';
      let imagetype = getImageProps.imagetype|| '1';
      console.log('qtnGetImage in getImage',qtn)
      console.log('typeGetImage',type)
      console.log('imagetypeGetImage',imagetype)
      if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
          notify(ST.Cameraunavailable);
      }
      else if(typeof imgdata =='object' && imgdata.uri!=null){
        const img=imgdata;
        const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
        let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
        let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

        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;
        
        const mark_text1=calculate_tym_date_over_img;
        const mark_text2='User Name:'+props.UserId+' | Image Type: Visitor Login QA'+' | Date:'+calculate_tym_date_over_img;
        
        const removespace = vfQuestion.EmpId
                          
        let filename = '';
        let image_key = '';
        let image_path_key = '';
        let allData = '';
        let qd = '';
        
        if(imagetype==1){
            filename=(props.UserId || '')+'_'+removespace+'_'+vfQuestion.designation+'_VisitorImg-'+calculate_tym_date_for_filename+'.jpg';
            allData=image;
            console.log('allData',allData=image)
            image_key='Visitor_Image';
            image_path_key='Visitor_ImagePath';
            allData[image_key]=filename;
            console.log('image_key',allData[image_key]=filename)
        
        }
        else{
            qd=QuestionsData;
            filename=(props.UserId || '')+'_'+removespace+'_'+vfQuestion.designation+'_'+qtn.QuestionId+'_VisitorFeedbackImg_'+calculate_tym_date_for_filename+'.jpg';
            
            image_key=type=='1'?qtn.QuestionId+'_ImageName1':qtn.QuestionId+'_ImageName2';
            image_path_key=type=='1'?qtn.QuestionId+'_ImagePath1':qtn.QuestionId+'_ImagePath2';
            
            qd[image_key]=filename;
            console.log('questiondata',qd)
        
        }

            
        let imagePath=VisitorLoginImageFolderPath+filename;
        RNFS.copyFile(imgurl, imagePath)
        .then(async(resn) => {
            // render data with clicked image
            let uri='file://'+imagePath;
            if(imagetype==1){
                console.log('image_path_key',allData[image_path_key]=uri)
                allData[image_path_key]=uri; 
                console.log('allDatavisitor',allData)
                setImage(allData);
            }
            else{
                qd[image_path_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 disableQtns(){
       
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                    console.log('sqtns qid',qid,s_qtnindex)
                    let s_qtn=sqtns[s_qtnindex];
                    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
                })
            ).then(async (val)=>{
                setSurveyQuestions(sqtns);
                setQuestionsData(data);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
            })
        }
    }

    async function enableQtns(){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==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()
            }
            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(','):[];
      
        console.log('EQtns:',EQtns,DQtns);
        let sqtns=SurveyQuestions
        if(EQtns.length>0){
            enableQtns()
        }
        else if(DQtns.length>0){
            disableQtns()
        }
        else{
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
        }    
    }

    async function setTextValue(value,qtn,type='') {   
        if(value!=''){
            let isValid=validateNumber(value,type);
            if(!isValid){
                return;
            }
         
        }     

        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 if(qtn.QuestionType=='RatingStar'){
            obj[id_key]=0;
            obj[ans_key]=value;
        

            let averagequestions = starCalQtns;
            console.log('averagequestions',averagequestions)
            

            for(let i=0;i<averagequestions.length;i++){
                let questobj = averagequestions[i]
                console.log('questobj',questobj)
                let alldependencyid = questobj.QuestionCalculate.split(',')
                console.log('alldependencyid',alldependencyid)
                if(alldependencyid.indexOf(qtn.QuestionId)){
                let uobj=await refreshAvgQtnRating(questobj,alldependencyid,obj);
                obj=uobj;
                }
            }

        }
        else{
            obj[id_key]=0;
            obj[ans_key]=value;
        }
        console.log('valuequestion',value,obj);
        setQuestionsData(obj);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    //async fumction
    async function refreshAvgQtnRating(qtn, depids,obj){

        let sum = 0;
        obj=QuestionsData;

        //promise
        return new Promise((resolve,reject)=>{

        for (let i = 0; i<depids.length;i++)
        {
            let questionid = depids[i]
            // let id_key=questionid+'_AnswerId'; 
            let ans_key=questionid+'_Answer'; 

            let cv = obj[ans_key]
            sum+=parseInt(cv); 

           if(i==depids.length-1){

                let cv_id_key=qtn.QuestionId+'_AnswerId'; 
                let cv_ans_key=qtn.QuestionId+'_Answer'; 
                let avg = sum/depids.length
                obj[cv_id_key]=0;
                obj[cv_ans_key]=avg;
                resolve(obj);

            }
        }
        resolve(obj);
        });
             
    };          
       

    

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


    async function openCamera(qtn,type,imagetype){  
       console.log('qtnsetImage',qtn)
       console.log('typesetImage',type)
       console.log('imagetypesetImage',imagetype)
       setGetImageProps({'qtn':qtn,'type':type,'imagetype':imagetype}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
      }

      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}
            cancelText={ST.Cancel}
            >
            <Text style={[customStyle.addVisPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-select-')}</Text>
            </ModalSelector>
        )
    }

  
    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        if(SurveyQuestions.length>0){
        if(!Boolean(searchedEmployees && searchedEmployees[0])){
            notify('Employee data is missing..');
            return
        }
        let userAlreadyexists=await addEmpl(searchedEmployees[0]);
        if(userAlreadyexists){
            return 
        }
        let currentTime=moment().format('HH:mm:ss');
        let d3=moment().format('MM/DD/YYYY');
        let image_key='Visitor_Image';
        let image_path_key='Visitor_ImagePath';
        let image1=image[image_key] || '';
        let AllVisitorImages=await getAllFileForAFolder(VisitorLoginImageFolderPath,"VisitorLoginFeedbackImages","VisitorLoginFeedback");
        console.log("AllVisitorImages:",AllVisitorImages.length);
        
    
        try{
          await db.transaction(async function (txn) {        
            
            let q=`select * from ${AppTables.VISITOR_LOGIN_FEEDBACK} WHERE NAME='${vfQuestion.name}'and DESIGNATION='${vfQuestion.designation}' AND VISIT_DATE='${d3}'`;
            console.log('query:',q)
            await txn.executeSql(q,[],async function (txn2, txnres) { 
              console.log('query count:',txnres.rows.length);
            //   if(txnres.rows.length>0){
            //     notify('Visitor Feedback Data with this name and designation already exists!')
            //     setProcessing(false);
            //   }
            //   else{

                let q=`DELETE FROM ${AppTables.VISITOR_LOGIN_FEEDBACK} WHERE NAME='${vfQuestion.name}'and DESIGNATION='${vfQuestion.designation}' AND VISIT_DATE='${d3}'`;
                //  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 feedbackData = {};
                let questionData=[];
               
                

                feedbackData['Name']=vfQuestion.name;
                feedbackData['Designation']= vfQuestion.designation;
                feedbackData['Image']=image.Visitor_Image;
                feedbackData['UserId']=props.UserId;
                feedbackData['VisitDate']=d2;
                

                for(var i=0;i<SurveyQuestions.length;i++){
                    let obj1= {}; 
                    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 img_key1=qtn.QuestionId+'_ImagePath1';
                    let imgname_key1=qtn.QuestionId+'_ImageName1';
                    let img_key2=qtn.QuestionId+'_ImagePath2';
                    let imgname_key2=qtn.QuestionId+'_ImageName2';

                    let {CategoryId,Category,DateRange,LengthValidation,MaxLength,MinLength,OTP,Question,QuestionId,QuestionImageAllow,QuestionType,imgallow1,imgallow2,imgName1,imgName2}=qtn;
                    console.log('qtncategorys',qtn)
                    
                    let selansid=QuestionsData[id_key] || 0;
                    let selans=QuestionsData[ans_key] || '';
                    imgName1=QuestionsData[imgname_key1] || '';
                    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)
                    imgallow1=ans_obj!=null && ans_obj['ImageAllow1']!=null?ans_obj.ImageAllow1:false;
                    imgallow2=ans_obj!=null && ans_obj['ImageAllow2']!=null?ans_obj.ImageAllow2:false;
                    let f_imgalloq1=(QuestionImageAllow=='true' || QuestionImageAllow==1) || (imgallow1=='true' || imgallow1==1)
                    
                    values+=` ('${d2}','${vfQuestion.legacyCode}','${vfQuestion.name}','${vfQuestion.designation}','${image.Visitor_Image}','${'I'}','${CategoryId}','${Question}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${(imgName1 || '')}','${imgallow2}','${(imgName2 || '')}','${multiops}','${isQtnDisabled}') `;


                    // let {EmpId, UserId,Answer,AnswerId,ImageAllow1,Image1,ImageAllow2,Image2,MultiOptionsIds} = ''
                   
                    obj1['CategoryId']=CategoryId;
                    obj1['QuestionId']=QuestionId;
                    obj1['QuestionType']=QuestionType;
                    obj1['Answer']=selans;
                    obj1['AnswerId']=selansid;
                    obj1['MultiAnswerId']=multiops!=null && multiops!='undefined'?multiops:'';
                    obj1['AnswerImage1']=imgName1;
                    obj1['AnswerImage2']=imgName2;
                    obj1['UserId']=props.UserId;

                    
                 
                 
                    questionData.push(obj1)
                
                    // console.log('feedbackdata data:',obj1);
                }

                feedbackData['feedbackData']=questionData;
                
                let add_data=`INSERT INTO ${AppTables.VISITOR_LOGIN_FEEDBACK} (VISIT_DATE,EMP_CODE,NAME,DESIGNATION,IMAGE,UPLOADSTATUS,CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,IMAGE_ALLOW2,IMAGE2,MULTI_OPTIONS_IDS,IS_DISABLED) VALUES ${values} `;

                await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                    console.log('visitor feedback added');
                    notify('visitor feedback added successfully');
                    setLoaderTitle("Uploading Data...")
                    // uploadVisitorFeedback(feedbackData,AllVisitorImages);
                    setProcessing(false);
                    props.navigation.goBack();
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot update feedback') },);

            //   }
            },function (txnE,txnerr) { 
                console.log("error:",txnE,txnerr);
                console.log(txnerr);setProcessing(false);notify(ST.Cannotupdatevisitor);
            });
          });          
        }
        catch(err){
          console.log('err',err);
          setProcessing(false);
        }

    }else{
        // await addEmpl(searchedEmployees[0]);
        let userAlreadyexists=await addEmpl(searchedEmployees[0]);
        console.log("userAlreadyexists---",userAlreadyexists)
        if(userAlreadyexists){
            return 
        }
        props.navigation.goBack();
        setProcessing(false);
    }
        
    }

    async function updateVLUploadStatus(){
        return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) {        
    
            let q=`Update ${AppTables.VISITOR_LOGIN_FEEDBACK} SET UPLOADSTATUS='U' WHERE NAME='${vfQuestion.name}' AND DESIGNATION='${vfQuestion.designation}' AND VISIT_DATE='${d2}'`;
            await txn.executeSql(q,[],async function (txn2, txnres) { 
              resolve(true);
              
            },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
            
          });   
        }).then((val)=>{
          return val;
        }).catch((err)=>{
          console.log(err);
          return false;
        });
      }
    


  async function uploadVisitorFeedback(feedbackData,AllVisitorImages=[]){
    const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
    console.log('pdurl',url)
    
    
    let postData={
    'MID':0,
    'Keys':'VisitorLoginFeedbackQA',
    'JsonData':JSON.stringify(feedbackData),
    'UserId':props.UserId,};

    console.log('postData',postData)
     UploadData2(url,postData)
    .then(async(res)=>{
      console.log('res:',res);
      if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
        const url2=(props.imageUploadUrl || URL_IMAGE)+getMethodName(METHODS.UPLOADIMAGES_METHOD);
        console.log('url2',url2)
        let allImageUploaded=await uploadAll_VisImages(props,AllVisitorImages);
        console.log('allImageUploaded',allImageUploaded)
        if(allImageUploaded==true){
            console.log('all Visitor image uploaded');
            let isUpdated=await updateVLUploadStatus();
            if(isUpdated){
                notify('Uploaded successully');
            }
            setProcessing(false);
            props.navigation.goBack();
        }
        else{
            notify(ST.CannotuploadvisitorfeedbackQAdata);
            setProcessing(false);
            props.navigation.goBack();
        }
        
      }else{
        notify(ST.CannotuploadvisitorfeedbackQAdata);
        setProcessing(false);
        props.navigation.goBack();
      }
    })
    .catch((err)=>{
        console.log(err);
        notify(ST.CannotuploadvisitorfeedbackQAdata);
        setProcessing(false);
        props.navigation.goBack();
    }); 

  }

//   async function updateVLUploadStatus(){
//     return new Promise((resolve,reject)=>{
//       db.transaction(async function (txn) {        

//         let q=`Update ${AppTables.VISITOR_LOGIN} SET UPLOADSTATUS='U' WHERE EMP_CODE='${visitorFeedback.EMP_CODE}' AND VISIT_DATE='${d2}'`;
//         await txn.executeSql(q,[],async function (txn2, txnres) { 
//           resolve(true);
          
//         },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
        
//       });   
//     }).then((val)=>{
//       return val;
//     }).catch((err)=>{
//       console.log(err);
//       return false;
//     });
//   }





  async function validate(){  
    // let Image1MandIndex='Image1Mandatory';
    // let Image1MandObj=Image1MandIndex>=0?KPIFields[Image1MandIndex]:{};
     let isImage1Mand=true;

    // let Image2MandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Image2Mandatory');
    // let Image2MandObj=Image2MandIndex>=0?KPIFields[Image2MandIndex]:{};
     let isImage2Mand=false;

     

    var isvalid=true;
    const QD=QuestionsData;
    console.log('image.Visitor_ImagePath',image.Visitor_ImagePath)

 
    
    if (!vfQuestion.name) {
        // alert('Please enter Name');
        notify("Please search employee",'SHORT');
        isvalid=false;
      }
      else if (!vfQuestion.designation) {
        // alert('Please enter Designation');
        notify("Please search employee",'SHORT');
        isvalid=false;
      }
     else
      if(!image.Visitor_ImagePath){
        isvalid=false;
        notify(ST.Pleaseaddimages,'SHORT');
      }

    else{
    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';
        // console.log('imgname_key',imgname_key)
        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 isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
        // let img_keyfeedback=qtn.QuestionId+'_ImagePath1':qtn.QuestionId+'_ImagePath2';
        // let imgname_keyfeedback=qtn.QuestionId+'_ImageName1':qtn.QuestionId+'_ImageName2';

        //  let Image1=image[image_path_key] || '';
        //  let Image2=QD[imgname_keyfeedback] || '';
       
        if(isDisabled==true){

        }
        else{
            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(ST.Pleaseselectoptionsfortherequiredfield,'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'?ST.Pleasepickadate:(qtn.QuestionType=='RatingStar'?'Please select rating':ST.Pleasefillalldetails));
                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(ST.Pleaserecordaudioclipfortherequiredfield,'SHORT');
                break;
            }
            else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))){
                isvalid=false;
                notify(ST.Pleasefillalldetails,'SHORT');
                console.log(QD[id_key],QD,id_key)
                break;
            }
            else if(isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                isvalid=false;
                notify(ST.Pleaseaddimages,'SHORT');
                break;
            }
            
            // else if(imgname_key=='' || imgname_key==null){
            //   isvalid=false;
            //   notify(ST.Pleaseaddimages,'SHORT');
            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((isImage1Mand=='1' || isImage1Mand==true) && showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
              isvalid=false;
              notify(ST.Pleaseaddimages,'SHORT');
              break;
          }
          
          if((isImage2Mand=='1' || isImage2Mand==true) &&  showImageTag2 && (Object.keys(QD).indexOf(img_key2)<0 || (Object.keys(QD).indexOf(img_key2)>=0 && QD[img_key2]===''))){
              isvalid=false;
              notify(ST.Pleaseaddimages,'SHORT');
              break;
          }

        }

    } 
  }
    
    return isvalid;
}

  function onTextChange(key, val,type=''){
            
    let data=vfQuestion;
    data[key]=val;
    // setHasUnsavedChanges(true);
    setvfQuestion(data);
    setrerenderdata(!rerenderdata);
    
}



    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({ }){
        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(','):[];
        
       
        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
            <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{console.log('tsth');setShow_zoomImage(false) }}>
                <Entypo name='star' color={'#000'} size={24}/>
            </TouchableOpacity> 
            </View>
        </View>
        )
    }

    function _renderSurveyQtns(subcat){
      const SurveyQuestions=subcat.Questions;
      console.log('SurveyQuestions123',SurveyQuestions)
      return (
      <View style={customStyle.SVn_GroupViewList}>
          {
             
              SurveyQuestions.map((item,index)=>{
                  
                  let qtn=item;  
                  console.log('questionsfeedback',qtn)
                  console.log('rendersurveyqtn',qtn)
                  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=[];

                   showImageTag=(qtn.QuestionImageAllow==true || qtn.QuestionImageAllow=='true' || qtn.QuestionImageAllow==1) ;
                   
                  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 || ''):'';
                  }
                  else if(qtn.QuestionType=='RatingStar')
                  {
                      selansid=QuestionsData[ans_key];
                  }
                  else if(qtn.QuestionType=='RatingStarCal')
                  {
                      selansid=QuestionsData[ans_key];
                  }

                  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]:'';                    
                  }
                  
                  let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
                  console.log('isDisabled',qtn.QuestionId,qtn.isDisabled,isDisabled)
                  if(isDisabled==true){
                      return (
                          <View></View> 
                      )
                  }
                  else{
                      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}
                                  tagContainerStyle={{height:30,width:'100%',paddingVertical:5}}
                                  styleTextTag={{fontSize:14}}
                                  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=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':'numeric')))}}
                              />
                          }
                          {
                              (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=='RatingStar') && 
                            <View style={[customStyle.vfcustomRatingBarStyle]}> 
                             {  maxRating.map((item,index)=>{
                                let isStarSelected=parseInt(item)<=parseInt(selansid);
                                        
                                return (
                                <TouchableOpacity
                                key={item}
                                onPress={() => {setTextValue(item,qtn,'numeric')}}>
                                   {!isStarSelected && <Entypo size={28} color={PageTheme.$star_color} name="star-outlined"/>}
                                   {isStarSelected && <Entypo size={28} color={PageTheme.$star_color} name="star"/>}
                                </TouchableOpacity>
                                )
                            })
                        }
                          </View>
                        }
                        {
                            (qtn.QuestionType=='RatingStarCal') && 
                            <View style={[customStyle.vfcustomRatingBarStyle,customStyle.surveyQtnRatingConAvg]}> 
                             {  maxRating.map((item,index)=>{
                                let isStarSelected=parseInt(item)<=parseInt(selansid);
                                        
                                return (
                                <View >
                                   {!isStarSelected && <AntDesign size={25} color={PageTheme.$star_color} name="staro"/>}
                                   {isStarSelected && <AntDesign size={25} color={PageTheme.$star_color} name="star"/>}
                                </View>
                                )
                            })
                            }
                            </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','2')}}>
                                      <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','2')}}>
                                      <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                  </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}>{ST.RecordVoiceClip}</Text>
                <Text style={customStyle.VRSubHeding2}>{ST.Youcanrecordmaxfor60secs}</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://':'')+VisitorLoginImageFolderPath+'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}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRecordSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                    </TouchableOpacity>
                </View>
            </View>}
        </View>
        )
    }
     
       
    function _renderSurveyView(){
      return (
          <View style={customStyle.SVn_ContentCon}>
          <FlatList 
          style={customStyle.VLoginQA_ContentOuter} 
          extraData={rerenderdata}
          nestedScrollEnabled={true}
          removeClippedSubviews={false}
          showsVerticalScrollIndicator={false}     
          contentContainerStyle={customStyle.SVn_ContentInner}
         data={SurveySubCats}
          renderItem={({ item, index}) =>{  
              let subcat=item,s_index=index;
              console.log('subcat',subcat)
              
              return (
                  <View style={customStyle.SVn_GroupView} 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.Category}</Text>

                      </LinearGradient>
                      { _renderSurveyQtns(subcat)}
                      
                      
                  </View>
              )
          }}
          >
              
          </FlatList>
          </View>
      );
  }
 

  async function getEmplDetails(){
    if(employeeCode=='' || employeeCode==null){
      notify(ST.Pleaseenteremployeecode,'SHORT');
    }
    else{
      setLoaderTitle(ST.GettingEmployeeDetails+'...');
      setProcessing(true);
      // download employee details
      const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
      
      
      let data={'Downloadtype':'Visitor_Search','username':props.UserId,'empid':employeeCode}
      console.log(url,data); 
      await getDownloadJson(url, data)
      .then(async(res) => {       
        console.log('Visitor_Search:',res);
        let emp=[];
        if(res.Visitor_Search!=null){
          emp=res.Visitor_Search || [];
          console.log("name-------1",res?.Visitor_Search[0])
          if(res?.Visitor_Search?.length>0){
            let name=res?.Visitor_Search[0]?.EmployeeName
            let designationName=res?.Visitor_Search[0]?.DesignationName
            let LegacyCode=res?.Visitor_Search[0]?.LegacyCode
            let EmpId=res?.Visitor_Search[0]?.EmpId
            
            console.log("name-------2",name,designationName)
            setvfQuestion({...vfQuestion,designation:designationName,name:name,legacyCode:LegacyCode,EmpId:EmpId})
          }
        }
        else{
          notify(ST.Nodatafound);
        }
        setSearchedEmployees(emp);
        setProcessing(false);
      })
      .catch(err => {
        console.log('onPage Team error', err);
        setProcessing(false);
      });
    }
  }

    return ( 
      
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)} > 
          {/* {processing && <CustomLoader fullHeight={false} />}      */}
          {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}

          <CustomHeader {...props} showaddstore={true} title={'Visitor Feedback'}/>
          {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
          <CustomCamera cameraType={'front'} BottomText={'User Name:'+props.UserId+' | Name:'+(vfQuestion.name!=null?vfQuestion.name.replace(/ /g, ''):'')+'_'+vfQuestion.designation+' | Image Type: Visitor Image'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   

          {/* <DrawerHeader {...props} drawer_title={ST.NoticeBoard} projectCode={projectCode} /> */}
          <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
            <View style={[customStyle.pageContentWrapper,customStyle.datavisitorloginPageWrapper]}>
                <View style={[customStyle.vlEmplForm]}>
                    <View style={customStyle.vlEmplFormRow}> 
                        <View style={customStyle.vlEmplForm_field} > 
                            {/* <Text style={customStyle.vlEmplForm_lbl}>{'Employee Code'}</Text>   */}
                            <TextInput 
                                style={[customStyle.vlEmplForm_InputStyle]}              
                                placeholder={ST.Employeecode}    
                                autoComplete='off'        
                                placeholderTextColor={PageTheme.$text_color_light} 
                                value={employeeCode}
                                // onFocus={()=>props.navigation.navigate('VisitorLoginQA')}
                                onChangeText={(val)=>{setEmployeeCode(val)}}
                            />                               
                        </View>      
                        <TouchableOpacity activeOpacity={0.4} style={customStyle.vlEmplSearchBtn} onPress={()=>{getEmplDetails()}}>
                            <Text style={customStyle.vlEmplSearchBtnText}>{ST.Go}</Text>
                        </TouchableOpacity>         
                    </View> 
                </View>
            {
                Object.keys(vfQuestion).length>0 && 
                <ScrollView>
                    <View style={[customStyle.vlUinfo_Card]}>
                        <View style={customStyle.vlEmplList}>
                        {
                        searchedEmployees.length>0 &&
                        searchedEmployees.map((item,index)=>{
                            let image_key=item.EmpId+'In_Image';
                            let image_path_key=item.EmpId+'In_ImagePath';
                            let Image1=EmpData[image_path_key] || '';
                            
                            return(
                            <View style={customStyle.vlEmplLDtl} key={index}>
                                <View style={[customStyle.vlEmplLDtlRow,customStyle.vlEmplLDtlRow_Border]}>
                                <Text style={customStyle.vlEmplLDtlRow_Lbl}>{ST.Name+':'}</Text>
                                <Text style={customStyle.vlEmplLDtlRow_Text}>{(item.EmployeeName || '')}</Text>
                                </View>
                                <View style={[customStyle.vlEmplLDtlRow]}>
                                <Text style={customStyle.vlEmplLDtlRow_Lbl}>{ST.Designation+':'}</Text>
                                <Text style={customStyle.vlEmplLDtlRow_Text}>{(item.DesignationName || '')}</Text>
                                </View>
                                
                            </View>
                            )
                        })
                        }
                        </View>
                        {/* <Text style={customStyle.addVisLabel}>Name</Text>
                        <TextInput  
                            style={customStyle.addVisInputStyle} 
                            value={(vfQuestion.name!=null?vfQuestion.name:'')}
                            keyboardType={'text'}
                            autoComplete='off'
                            onChangeText={(val)=>{onTextChange('name',val)}}
                        /> */}

                        {/* <Text style={customStyle.addVisLabel}>Designation</Text>
                        <TextInput  
                            style={customStyle.addVisInputStyle} 
                            value ={(vfQuestion.designation!=null?vfQuestion.designation:'')}
                            keyboardType={'text'}
                            autoComplete='off'
                            onChangeText={(val)=>{onTextChange('designation',val)}}
                        /> */}

                        <Text style={customStyle.addVisLabel}>Click Selfie Image</Text>
                        { (image.Visitor_ImagePath==null || image.Visitor_ImagePath=='') && 
                        <TouchableOpacity onPress={()=>{openCamera('','','1')}}>
                            <CameraImg style = {[customStyle.cameravd]} width={80} height={80}  />                                     
                        </TouchableOpacity>
                        }     
                        { (image.Visitor_ImagePath!='' && image.Visitor_ImagePath!=null) && 
                            <View style={customStyle.cameravd}>
                            <Image style={[customStyle.vl_checkoutM_Image,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:image.Visitor_ImagePath}}/>
                            <TouchableOpacity style={[customStyle.vl_checkoutM_recap]} onPress={()=>{openCamera('','','1')}}>
                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                            </TouchableOpacity>
                            </View>                         
                        }   

                        <View  style={[customStyle.visitorfeedback_text]}>
                        <Text style={customStyle.trainingHdrText}>Feedback Questions</Text>
                        </View>
                        { SurveySubCats?.length>0 && _renderSurveyView() } 
                    </View>
                </ScrollView>
            }
            </View>
          </LinearGradient> 

          <View style={[customStyle.SVn_SubmitBtn]}>
          <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
          </View> 

          </Container>   
    )
        
}
export default connect(mapStateToProps, mapDispatchToProps)(VisitorLoginQA);