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

import Container from '../components/container';
import CustomLoader from '../components/CustomLoader';
import DrawerHeader from '../components/drawerHeader';
import { db, common_ImagePath, ImageFolderPath, URL_IMAGE, VisitorImageFolderPath } from '../constants/constants';
import { getAllFolderImages, getDownloadJson, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, UploadData2, validateNumber } from '../controller/functions';
import LinearGradient from 'react-native-linear-gradient';
import { SvgXml } from 'react-native-svg';
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 '../screens/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 { Props } from 'react-native-image-zoom-viewer/built/image-viewer.type';
import CustomModal from '../components/CustomModal';
// import AudioRecorderPlayer, { AudioEncoderAndroidType, AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption } from 'react-native-audio-recorder-player';


function VisitorFeedback(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 [visitorFeedbackdata, setvisitorFeedbackdata] = useState([]);
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [getImageProps, setGetImageProps] = useState({});
    const [getEditData, setEditData] = 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 [ShowCat, setShowCat] = useState(false);
    const [removedVisitor, setRemovedVisitor] = useState({});
    const [showRemoveVistor, setShowRemoveVistor] = useState(false);
    const [starCalQtns, setstarCalQtns] = useState([]);

    // const [visitors, setVisitors] = useState([]);



    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        console.log('params', params)
        getSurveyData();
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log('getSurveyData onfocus');
            getSurveyData();
        });

        return willFocusSubscription;
    }, []);

    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 getSurveyData() {
        console.log('getSurveyData')
        try {

            await db.transaction(async function (txn) {


                let q2 = `SELECT DISTINCT NAME,DESIGNATION,UPLOADSTATUS,IMAGE FROM ${AppTables.VISITOR_FEEDBACK} where VISIT_DATE='${d2}'`;

                console.log('q2', q2)
                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);

                            let all_scat_objet = await getSurveyQtns();

                            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 : []

                            data['Questions'] = all_scat_qtns;
                            allQtns = allQtns.concat(all_scat_qtns);
                            allavgquest = allavgquest.concat(all_scat_qtnsavg);

                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                setSurveySubCats(arr);
                                setSurveyQuestions(allQtns);
                                setstarCalQtns(allavgquest);

                                setProcessing(false);
                            }
                        }
                    }

                }, function (txnE, txnerr) { console.log(txnerr); },);

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



    async function removeVisitor() {
        let item = removedVisitor;
        setShowRemoveVistor(false)
        setLoaderTitle(ST.RemovingEmployee + '...');
        setProcessing(true);

        try {
            await db.transaction(async function (txn) {
                let data = visitorFeedbackdata;
                var values = '';
                console.log('visitdata', data)
                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_VisitorFeedbackQuestion T on T1.QUESTION_ID=T.QuestionId`;
                let q = ` DELETE FROM ${AppTables.VISITOR_FEEDBACK}  where NAME='${item.NAME}' and DESIGNATION='${item.DESIGNATION}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    let feedbackData = [];
                    let AllVisitorImages = [];
                    let questionData = [];

                    if (txnres.rows.length > 0) {
                        feedbackData['Name'] = item.NAME;
                        feedbackData['Designation'] = item.DESIGNATION;
                        feedbackData['Image'] = item.IMAGE;
                        feedbackData['Date'] = d2;
                        feedbackData['UserId'] = props.UserId;
                        for (var i = 0; i < txnres.rows.length; i++) {

                            let data = txnres.rows.item(i);
                            console.log('dataqtn', data)
                            // feedbackData.push(data)

                            let id_key = data.QuestionId + '_AnswerId';
                            let ans_key = data.QuestionId + '_Answer';
                            let multi_key = data.QuestionId + '_MultiOption';
                            let img_key1 = data.QuestionId + '_ImagePath1';
                            let imgname_key1 = data.QuestionId + '_ImageName1';
                            let img_key2 = data.QuestionId + '_ImagePath2';
                            let imgname_key2 = data.QuestionId + '_ImageName2';

                            let { CategoryId, Category, DateRange, LengthValidation, MaxLength, MinLength, OTP, Question, QuestionId, QuestionImageAllow, QuestionType, imgallow1, imgallow2, imgName1, imgName2 } = data;
                            console.log('qtncategorys', data)

                            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=data.isDisabled!=null && data.isDisabled!=''?data.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}','${item.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} = ''
                            let obj1 = {};

                            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;


                            if (((QuestionImageAllow == 1 || QuestionImageAllow == 'true') || (imgallow1 == 1 | imgallow1 == 'true')) && imgName1 != '') {
                                let imgPath = VisitorImageFolderPath + imgName1;
                                let file = {
                                    uri: imgPath,
                                    type: 'image/jpeg',
                                    name: imgName1,
                                    filetype: 'image',
                                    folderName: 'VisitorFeedbackImages',
                                }
                                AllVisitorImages.push(file);
                            }

                            if ((imgallow2 == 1 || imgallow2 == 'true') && imgName2 != '') {
                                let imgPath = VisitorImageFolderPath + imgName2;
                                let file = {
                                    uri: imgPath,
                                    type: 'image/jpeg',
                                    name: imgName2,
                                    filetype: 'image',
                                    folderName: 'VisitorFeedbackImages',
                                }
                                AllVisitorImages.push(file);
                            }
                            console.log('obj', feedbackData.push(obj))
                            console.log('image', AllVisitorImages.push(obj))

                            questionData.push(obj1)

                            if (i == txnres.rows.length - 1) {
                                feedbackData['feedbackData'] = questionData;
                                let tempData = visitorFeedbackdata;
                                let imgData = AllVisitorImages;
                                delete tempData.length;
                                delete imgData.length;
                            }

                        }


                    }

                    getSurveyData();




                }, function (txnE, txnerr) { console.log(txnerr); },);



            });
        }
        catch (err) {
            console.log('err', err);
            setProcessing(false);
            notify(ST.Errorwhileaddingemployee);
        }
    }


    async function getSurveyQtns() {
        let obj = { 'qtns': [], 'avgqtns': [] };
        // let {CategoryId}= catData;
        // let {NAME,DESIGNATION}=vfData;

        return new Promise((resolve, reject) => {
            try {

                db.transaction(async function (txn) {

                    let sl = ` DISTINCT MaxLength,MinLength,LengthValidation,CategoryId,Category,Question,QuestionId,QuestionType,OTP,QuestionImageAllow,DateRange,QuestionCalculate`;
                    let q = ` SELECT ${sl} FROM Master_VisitorFeedbackQuestion `;
                    // console.log('catData',catData.CategoryId)
                    await txn.executeSql(q, [], async function (txn2, txnres2) {

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

                                let answers = [];
                                if (data.QuestionType == 'List_Multi_Choice' || data.QuestionType == 'List_Single_Choice' || data.QuestionType == 'Rating') {
                                    let allanswers = await getAnswers(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;
            }
        })
    }
    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_VisitorFeedbackQuestion 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;
            let mark_text2 = '';
            if (imagetype == 1) {
                mark_text2 = 'User Name:' + props.UserId + ' | Employee Code:' + visitorFeedback.EMP_CODE + ' | Image Type: Visitor Logout' + ' | Date:' + calculate_tym_date_over_img;
            }
            else {
                mark_text2 = 'User Name:' + props.UserId + ' | Employee Code:' + visitorFeedback.EMP_CODE + ' | Image Type: Visitor Feedback' + ' | Date:' + calculate_tym_date_over_img;
            }


            let filename = '';
            let image_key = '';
            let image_path_key = '';
            let allData = '';
            let qd = '';

            if (imagetype == 1) {
                filename = (props.UserId || '') + '_' + visitorFeedback.EMP_ID + '_VisitorLogoutImg-' + calculate_tym_date_for_filename + '.jpg';
                allData = image;
                image_key = 'Visitor_Image';
                image_path_key = 'Visitor_ImagePath';
                allData[image_key] = filename;

            }
            else {
                qd = QuestionsData;
                filename = (props.UserId || '') + '_' + visitorFeedback.EMP_ID + '_' + 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 = 'file://' + VisitorImageFolderPath + filename;

            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = imagePath;
                    console.log('image marker', uri);
                    if (imagetype == 1) {
                        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);
                });

        }

    }


    function getBottomText() {
        let imagetype = getImageProps.imagetype || '1';
        if (imagetype == 1) {
            return 'User Name:' + props.UserId + ' | Employee Code:' + visitorFeedback.EMP_CODE + ' | Image Type: Visitor Logout';
        }
        else {
            return 'User Name:' + props.UserId + ' | Employee Code:' + visitorFeedback.EMP_CODE + ' | Image Type: Visitor Feedback';
        }
    }

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

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

    function openVisitorFeedback() {
        props.navigation.navigate('VisitorFeedbackQA');
    }

    function openVisitorFeedbackedit(item) {
        console.log('itemvisitor', item)
        props.navigation.navigate('VisitorFeedbackQA', { 'EditMode': true, 'visitoreditdata': item });
        setEditData({ 'visitoreditdata': item })
    }



    async function uploadVisitorFeedback(feedbackData, AllVisitorImages = []) {
        const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
        console.log('pdurl', url)


        let postData = {
            'MID': 0,
            'Keys': 'VisitorFeedbackQA',
            '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);

                    if (allImageUploaded == true) {
                        console.log('all Visitor image uploaded');

                        let isUpdated = await updateVLUploadStatus();
                        if (isUpdated) {
                            notify('Uploaded successully');
                        }
                        getSurveyData();
                        setProcessing(false);

                    }
                    else {
                        setProcessing(false);
                        notify('CannotuploadvisitorfeedbackQAdata');
                    }

                } else {
                    setProcessing(false);
                    notify('CannotuploadvisitorfeedbackQAdata');
                }
            })
            .catch((err) => {
                console.log(err);
                setProcessing(false);
                notify('CannotuploadvisitorfeedbackQAdata');
            });

    }



    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 uploadData(item) {
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);

        try {
            let AllVisitorImages = await getAllFolderImages();
            await db.transaction(async function (txn) {
                let data = visitorFeedbackdata;
                var values = '';
                console.log('visitdata', item.NAME)
                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_VisitorFeedbackQuestion T on T1.QUESTION_ID=T.QuestionId`;
                let q = ` SELECT ${selectlist} FROM ${AppTables.VISITOR_FEEDBACK} T1 ${join} where T1.NAME='${item.NAME}' and T1.DESIGNATION='${item.DESIGNATION}' and T1.VISIT_DATE='${d2}' `;

                await txn.executeSql(q, [], async function (txn2, txnres) {
                    var values = '';
                    let feedbackData = {};
                    let questionData = [];


                    if (txnres.rows.length > 0) {
                        feedbackData['Name'] = item.NAME;
                        feedbackData['Designation'] = item.DESIGNATION;
                        feedbackData['Image'] = item.IMAGE;
                        feedbackData['VisitDate'] = d2;
                        feedbackData['UserId'] = props.UserId;
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let obj1 = {};
                            let data = txnres.rows.item(i);
                            console.log('dataqtn', data)
                            // feedbackData.push(data)


                            let id_key = data.QuestionId + '_AnswerId';
                            let ans_key = data.QuestionId + '_Answer';
                            let multi_key = data.QuestionId + '_MultiOption';
                            let img_key1 = data.QuestionId + '_ImagePath1';
                            let imgname_key1 = data.QuestionId + '_ImageName1';
                            let img_key2 = data.QuestionId + '_ImagePath2';
                            let imgname_key2 = data.QuestionId + '_ImageName2';

                            let { CategoryId, Category, DateRange, LengthValidation, MaxLength, MinLength, OTP, Question, QuestionId, QuestionImageAllow, QuestionType, imgallow1, imgallow2, imgName1, imgName2 } = data;
                            console.log('qtncategorys', data)

                            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=data.isDisabled!=null && data.isDisabled!=''?data.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}','${item.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'] = item.ANSWER;
                            obj1['AnswerId'] = selansid;
                            obj1['MultiAnswerId'] = multiops != null && multiops != 'undefined' ? multiops : '';
                            obj1['AnswerImage1'] = imgName1;
                            obj1['AnswerImage2'] = imgName2;
                            obj1['UserId'] = props.UserId;

                            // if(((QuestionImageAllow==1 || QuestionImageAllow=='true') || (imgallow1==1 | imgallow1=='true')) && imgName1!=''){
                            //     let imgPath=VisitorImageFolderPath+imgName1;
                            //     let file={
                            //         uri: imgPath,
                            //         type: 'image/jpeg',
                            //         name: imgName1,
                            //         filetype:'image',
                            //         folderName:'VisitorFeedbackImages',
                            //     }
                            //     AllVisitorImages.push(file);
                            // }

                            // if((imgallow2==1 || imgallow2=='true') && imgName2!='' ){
                            //     let imgPath=VisitorImageFolderPath+imgName2;
                            //     let file={
                            //         uri: imgPath,
                            //         type: 'image/jpeg',
                            //         name: imgName2,
                            //         filetype:'image',
                            //         folderName:'VisitorFeedbackImages',
                            //     }
                            //     AllVisitorImages.push(file);
                            // }
                            // console.log('obj',feedbackData.push(obj))
                            // console.log('image',AllVisitorImages.push(obj))

                            questionData.push(obj1)

                            if (i == txnres.rows.length - 1) {
                                feedbackData['feedbackData'] = questionData;
                                uploadVisitorFeedback(feedbackData, AllVisitorImages);
                                notify('visitor feedback updated successfully');
                                notify('Data and Images Uploaded')
                                // props.set_autoback({'AutoGoToPrev':true});
                                setProcessing(true);
                            }

                        }

                    }




                }, function (txnE, txnerr) { console.log(txnerr); },);

            });
        }
        catch (err) {
            console.log('err', err);
            setProcessing(false);
            notify(ST.Errorwhileaddingemployee);
        }

    }





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

                let q = `Update ${AppTables.VISITOR_FEEDBACK} SET UPLOADSTATUS='U' WHERE VISIT_DATE='${d2}'`;
                console.log('q', q)
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('Visitor Updated');
                    let allVisitors = SurveySubCats;
                    // let thisVisIndex=SurveySubCats.findIndex(i=>i.NAME==item.NAME);
                    // if(thisVisIndex>=0){
                    let thisVis = allVisitors || {};
                    thisVis['UPLOADSTATUS'] = 'U';
                    //   allVisitors[thisVisIndex]=thisVis;
                    setSurveySubCats(allVisitors);
                    setrerenderdata(!rerenderdata);
                    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;

        if (image.Visitor_ImagePath == '' && image.Visitor_ImagePath == null) {
            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 == 'Rating' ? ST.Pleaseselectrating : 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 _render_RemoveAlert() {
        let data = removedVisitor;
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={[customStyle.vl_removeModalTitle]}
                title={ST.DoyoureallywanttoremoveVisitor}
                message={(data.NAME || '')}
                messageStyle={customStyle.vl_removeModalSubTitle}
                showModal={showRemoveVistor}
            >
                <View style={customStyle.storelVisitM_options}>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowRemoveVistor(false) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { removeVisitor(removedVisitor) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>{ST.Yes}</Text>
                    </TouchableOpacity>
                </View>
            </CustomModal>
        )
    }

    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(','):[];

        let newarr = RatingOrder;
        if (RatingOrder.length <= 0) {
            newarr = Answers;
        }

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

    function _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('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 = [];

                        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] : '';
                        }

                        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 == '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', '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://' : '') + VisitorImageFolderPath + '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>
        )
    }

    async function onDelete(item) {

        if (item.UPLOADSTATUS == 'U') {
            setProcessing(false);
            notify(ST.Dataalreadyuploaded + ' ' + ST.Cannotdeletevisitornow);
        }

        else {
            console.log('delete emp')
            setRemovedVisitor(item);
            setShowRemoveVistor(true);
        }
    }


    function _renderSurveyView() {
        return (
            <View style={customStyle.SVn_ContentCon}>
                <FlatList
                    style={customStyle.SVn_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>
        );
    }

    return (


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

            <CustomHeader {...props} showaddstore={true} title={'Visitor Feedback'} />
            {_render_RemoveAlert()}

            <CustomCamera cameraType={'front'} BottomText={getBottomText()} 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]}>
                    {/* <View style={[customStyle.vlUinfo_Card]}> */}
                    <View style={[customStyle.vlUinfo_CardRow, customStyle.vlUinfo_CardBorder]}>
                        <Text style={customStyle.vl_Feedback}>{'Feedback'}</Text>
                        {/* <TouchableOpacity style={customStyle.vl_EditBtn} onPress={()=>{openVisitorFeedback(item)}}>
                <Text style={customStyle.RModal_BtnTextsave}>{'Edit'}</Text>
                </TouchableOpacity>  */}
                        <TouchableOpacity style={customStyle.vl_AddBtn} onPress={() => { openVisitorFeedback() }}>
                            <Text style={customStyle.RModal_BtnTextsave}>{'Add'}</Text>
                        </TouchableOpacity>
                        {/* <Text style={customStyle.vlUinfo_text}>{visitorFeedback.NAME}</Text>                 */}
                    </View>


                    <View style={customStyle.vlf_TblHeader}>
                        <View style={[customStyle.vl_TblHeaderBox, customStyle.vlf_TblHeaderBox1]}>
                            <Text style={customStyle.vlf_TblHeaderTxt}>{ST.Name}</Text>
                        </View>
                        <View style={[customStyle.vl_TblHeaderBox, customStyle.vlf_TblHeaderBox2]}>
                            <Text style={customStyle.vlf_TblHeaderTxt}>{ST.Designation}</Text>
                        </View>
                        <View style={[customStyle.vl_TblHeaderBox, customStyle.vlf_TblHeaderBox3]}>
                            <Text style={customStyle.vlf_TblHeaderTxt}>{ST.Actions}</Text>
                        </View>
                    </View>
                    <View style={customStyle.vl_TblBody}>
                        {
                            SurveySubCats.length > 0 &&
                            SurveySubCats.map((item, index) => {
                                // console.log('visiteor item:',item)
                                return (
                                    <View style={[customStyle.vl_visitorsLItem, ((index < (visitorFeedbackdata.length - 1)) ? customStyle.vl_visitorsLItemB : {})]} key={index}>
                                        <View style={[customStyle.vl_visitorsLI_Box, customStyle.vlf_visitorsLI_Box1]}>
                                            <Text style={customStyle.vl_visitorsLI_Txt}>{item.NAME}</Text>
                                        </View>
                                        <View style={[customStyle.vl_visitorsLI_Box, customStyle.vlf_visitorsLI_Box2]}>
                                            <Text style={customStyle.vl_visitorsLI_Txt}>{item.DESIGNATION}</Text>
                                        </View>

                                        {item.UPLOADSTATUS == 'I' &&
                                            //    <TouchableOpacity style={customStyle.vl_EditBtn} onPress={()=>{openVisitorFeedbackedit(item)}}>
                                            //    <Text style={customStyle.RModal_BtnTextsave}>{'Edit'}</Text>
                                            //    </TouchableOpacity> 

                                            <TouchableOpacity style={customStyle.vl_DeleteBtn} onPress={() => { onDelete(item) }}>
                                                <Ionicons name='trash' color={PageTheme.$red} size={24} />
                                            </TouchableOpacity>
                                        }

                                        {item.UPLOADSTATUS == 'I' &&
                                            <TouchableOpacity style={customStyle.vl_UploadBtn} onPress={() => { uploadData(item) }}>
                                                <Text style={customStyle.RModal_BtnTextsave}>{'Upload'}</Text>
                                            </TouchableOpacity>



                                        }

                                        {item.UPLOADSTATUS == 'U' &&
                                            <View style={[customStyle.vlStatus]}>
                                                <Ionicons name='checkmark-done-sharp' color='green' size={20} />
                                                <Text style={[customStyle.storel_usText, { color: 'green' }]}>{ST.Uploaded}</Text>
                                            </View>
                                        }


                                    </View>
                                )
                            })
                        }
                    </View>

                </View>

            </LinearGradient>

        </Container>
    )

}
export default connect(mapStateToProps, mapDispatchToProps)(VisitorFeedback);