import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated} from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, UploadData2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {db, common_ImagePath,ImageFolderPath, URL_IMAGE, VisitorLoginImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import NoDataComponent from '../components/NoDataComponent';
import { getMethodName, METHODS } from '../constants/methodNames';

import CustomCamera from '../components/Camera';



import CameraImg from '../assets/performics/camera_front_image.svg'
import CustomModal from '../components/CustomModal';
import { getImagePOSTData, UploadImagesWithoutWait } from '../constants/uploadData';

function VisitorLogin(props) {
  const route = useRoute();
  const ST=props.StaticText || {};
  // get all theme styles acc to current theme set
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const globalStyle = globalStyles(props.DarkMode, route.name);
  
  
  const [processing, setProcessing] = useState(true);
  const [loaderTitle, setLoaderTitle] = useState();
  const [designation, setDesignation] = useState('');
  const [visitors, setVisitors] = useState([]);
  const [searchedEmployees, setSearchedEmployees] = useState([]);
  const [rerenderdata, setrerenderdata]= useState(0);
  const [employeeCode, setEmployeeCode]= useState('');
  const [EmpData, setEmpData]= useState({});
  const [currentCheckOutItem, setCurrentCheckOutItem]= useState({});
  const [removedVisitor, setRemovedVisitor]= useState({});
  
  const [showCheckOutModal, setShowCheckOutModal]= useState(false);
  const [showRemoveVistor, setShowRemoveVistor]= useState(false);

  const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

  const d1=new Date();
  const d2=moment(d1).format('MM/DD/YYYY');

  useEffect(() => {
    setLoaderTitle(ST.Loading+'...')
    getData();

      const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
    
      return function cleanup() {
        return unsubscribe;
      };
  }, []);

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

  useFocusEffect(
    React.useCallback(() => {
      getData(); 
    }, [])
  );

  function  onBeforeRemove(e){
      if(showCamera==true){
          e.preventDefault();
          setShowCamera(false);
      }
      else{
        return;   
      }
  }

  async function getData(){        
    try {   

      let token=await get_item('loginToken');
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);
      let desg=loginDetails.Designation || '';
      setDesignation(desg);

      await db.transaction(async function (txn) {        

        // let q1=`DELETE from ${AppTables.VISITOR_LOGIN} where EMP_CODE='C000363'`;
        // await txn.executeSql(q1,[],async function (txn2, txnres) { 
        //     console.log('deleted');
        // },function (txnE,txnerr) { console.log(txnerr); },);
        
        let q=`SELECT * from ${AppTables.VISITOR_LOGIN} where VISIT_DATE='${d2}'`;
        await txn.executeSql(q,[],async function (txn2, txnres) { 
            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){
                  setVisitors(arr);
                  setProcessing(false);
                  setrerenderdata(!rerenderdata);
                }
              }
            }
            else{
              setProcessing(false);
            }
        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
        
      });          
    } catch (err) {
      console.log(err);     
      setProcessing(false);     
    }        
  }


  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)}`);
    }else if(currentCheckOutItem?.EMP_ID=='' || currentCheckOutItem?.EMP_ID==null){
      isValid=false;
      notify(`Employe ID is missing`);
    }
    return isValid;
  }

  async function getImage(imgdata){
    setLoaderTitle("Processing Image...");
    setProcessing(true);
    let item=getImageProps.item || '';
    let type=getImageProps.type || '';
    if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
        notify(ST.Cameraunavailable);
    }else if(item?.EmpId=="" && item?.EmpId==null){
      notify("Employee Id is missing.");
    }
    else if(typeof imgdata =='object' && imgdata.uri!=null){
        const img=imgdata;
        const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
        let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
        let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

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

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

             
        let filename=item.EmpId+'_'+(props.UserId || '')+'_VisitorLoginImg-'+calculate_tym_date_for_filename+'.jpg';

        const mark_text1=calculate_tym_date_over_img;
        const mark_text2='User Name:'+props.UserId+' | Employee Code:'+item.LegacyCode+' | Image Type: Visitor Login'+' | Date:'+calculate_tym_date_over_img;
      
        let allData=EmpData;
        
        let image_key=type=='In'?item.EmpId+'In_Image':item.EmpId+'Out_Image';
        let image_path_key=type=='In'?item.EmpId+'In_ImagePath':item.EmpId+'Out_ImagePath';
        allData[image_key]=filename;
        
            
        // let imagePath=common_ImagePath+filename;
        let imagePath=VisitorLoginImageFolderPath+filename;
        
        RNFS.copyFile(imgurl, imagePath)
        .then(async(resn) => {
          // render data with clicked image
          let uri='file://'+imagePath;
          allData[image_path_key]=uri; 
          setEmpData(allData);
          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(ST.Errorimagefilewritefailed+'!!!');
            console.log(err.message, err.code);
            notify(ST.CannotProcessImage);
        });                   
    } 
    setProcessing(false);       
  }

  function getBottomText(){
    let item=getImageProps.item || {};
    return 'User Name:'+props.UserId+' | Employee Code:'+item.LegacyCode+' | Image Type: Visitor Login';
  }

  async function openCamera(item,type='In'){  
    setGetImageProps({'item':item,'type':type}); 
    setShowCamera(true);
    // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
  }

  async function onCheckOut(item){
    setCurrentCheckOutItem(item);
    setShowCheckOutModal(true);
  }

  async function onDelete(item){
   
    if(item.UPLOADSTATUS=='U'){
      setProcessing(false);
      notify(ST.Dataalreadyuploaded+' '+ST.Cannotdeletevisitornow);
    }
    else if(item.OUT_TIME!='' && item.OUT_TIME!=null){
      setProcessing(false);
      notify(ST.Visitoralreadyhadcheckedout+' '+ST.Cannotdeletevisitornow);
    }
    else{
      console.log('delete emp')
      setRemovedVisitor(item);
      setShowRemoveVistor(true);
    }
  }

  async function removeVisitor(){
    let item=removedVisitor;
    setShowRemoveVistor(false)
    setLoaderTitle(ST.RemovingEmployee+'...');
    setProcessing(true);
    try{
      await db.transaction(async function (txn) {        
        let {EMP_CODE,EMP_ID}=item;
        let q2=`DELETE FROM ${AppTables.VISITOR_LOGIN} WHERE VISIT_DATE='${d2}' AND EMP_CODE='${EMP_CODE}'`;
        let q=`SELECT * FROM ${AppTables.VISITOR_LOGIN} WHERE VISIT_DATE='${d2}' `;
        await txn.executeSql(q2,[],async function (txn2, txnres3) { 
          await txn.executeSql(q,[],async function (txn2, txnres2) { 
            console.log('Visitors',txnres2.rows.length);
            let arr=[];
            if(txnres2.rows.length>0){
              
              
              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){
                  let tempData=EmpData;
                  let imageOut_key=EMP_ID+'Out_Image';
                  let imageOut_path_key=EMP_ID+'Out_ImagePath';
                  let imageIn_key=EMP_ID+'In_Image';
                  let imageIn_path_key=EMP_ID+'In_ImagePath';
                  delete tempData[imageOut_key];
                  delete tempData[imageOut_path_key];
                  delete tempData[imageIn_key];
                  delete tempData[imageIn_path_key];
                  setEmpData(tempData);
                  setVisitors(arr);
                  setProcessing(false);
                  notify(ST.Visitorremovedsuccessfully);
                }
              }
            }
            else{
              setVisitors(arr);
              setProcessing(false);
              notify(ST.Visitorremovedsuccessfully);
            }
            
          },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Somethingwentwrong); },);
        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotRemovevisitor); },);
        
      });          
    }
    catch(err){
      console.log('err',err);
      setProcessing(false);
      notify(ST.Errorwhileremovingvisitor);
    }
  }

  async function cancelCehckout(){
    setShowCheckOutModal(false);
  }

  async function checkOutEmpl(item){
    if(validateEmp(item,false)){
      setShowCheckOutModal(false);
      setProcessing(false);
      let {EmpId,EmployeeName,DesignationName,LegacyCode}=item;
      let visitoreData=currentCheckOutItem;
      visitoreData['feedbackData']=[];

      try{
        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+'Out_Image';
          let image_path_key=item.EmpId+'Out_ImagePath';
          let image1=EmpData[image_key] || '';
          visitoreData['OUT_TIME']=currentTime;
          visitoreData['OUT_TIME_IMAGE']=image1;
          let q=`Update ${AppTables.VISITOR_LOGIN} SET OUT_TIME='${currentTime}',OUT_TIME_IMAGE='${image1}' WHERE EMP_CODE='${LegacyCode}' AND VISIT_DATE='${d3}'`;
          // let q2=`SELECT * FROM ${AppTables.VISITOR_LOGIN} WHERE OUT_TIME is not null and OUT_TIME!='' and VISIT_DATE='${d3}'`;   
          
         console.log("q----Update----",q)
          // update visitor checkout status
          await txn.executeSql(q,[],async function (txn2, txnres) { 
            console.log('Visitor Updated');
            
            let questionData=[];
            let selectlist=` DISTINCT T.CategoryId,T.Category,T.Question,T.QuestionId, T2.*`;
            let join2=`Inner Join ${AppTables.VISITOR_LOGIN_FEEDBACK} T2 on T.QuestionId=T2.QUESTION_ID  and T.CategoryId=T2.CATEGORY_ID`;
            let q3=` SELECT ${selectlist} FROM Master_VisitorLoginQuestion T ${join2} where T2.EMP_CODE='${LegacyCode}' and T2.VISIT_DATE='${d2}' `; 

            console.log("get qtns to upload q:",q3)
            await txn.executeSql(q3,[],async function (txn2, txnres) { 
                console.log('get qtns to upload count:',txnres.rows.length);
                if(txnres.rows.length>0){
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        let {CATEGORY_ID,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE2}=data;
                        let obj1= {}; 

                        obj1['CategoryId']=CATEGORY_ID;
                        obj1['QuestionId']=QUESTION_ID;
                        obj1['QuestionType']=QUESTION_TYPE;
                        obj1['Answer']=ANSWER;
                        obj1['AnswerId']=ANSWER_ID;
                        obj1['MultiAnswerId']=MULTI_OPTIONS_IDS!=null && MULTI_OPTIONS_IDS!='undefined'?MULTI_OPTIONS_IDS:'';
                        obj1['AnswerImage1']=IMAGE1;
                        obj1['AnswerImage2']=IMAGE2;
                        obj1['UserId']=props.UserId;

                        questionData.push(obj1)
                        console.log("q----questionData----",questionData)
                        if(i==txnres.rows.length-1){
                          visitoreData['feedbackData']=questionData;
                          uploadVisitorStatus(visitoreData);
                        }
                    }
                }
                else{
                  console.log("q----visitoreData---1-",visitoreData);
                  uploadVisitorStatus(visitoreData);
                }
                
            },function (txnE,txnerr) { console.log(txnerr);console.log("q----visitoreData----",visitoreData); uploadVisitorStatus(visitoreData);},);
          
          
          },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotupdatevisitor); },);
        
          
        });    
        
        
      }
      catch(err){
        console.log('err',err);
        setProcessing(false);
        notify(ST.Errorwhileaddingemployee);
      }
    }
    
  }

  async function uploadVisitorStatus(item){
    const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
    let {IN_TIME_IMAGE,OUT_TIME_IMAGE}=item;
    let obj={
      "MID":0,
      "CreatedBy":props.UserId,
      "EmpId":item.EMP_ID,
      "VisitDate":d2,
      "InTimeImage":item.IN_TIME_IMAGE,
      "OutTimeImage":item.OUT_TIME_IMAGE,
      "InTime":item.IN_TIME,
      "OutTime":item.OUT_TIME,
      "feedbackData":item.feedbackData
    }
    let postData={
      "MID":0,
      "Keys":"Visitor_Login",
      "JsonData":JSON.stringify(obj),
      "UserId":props.UserId,
    };

    console.log("postDAta--------",postData)
    // return
    let INIMAGE='',OUTIMAGE='';
    if(IN_TIME_IMAGE!='' && IN_TIME_IMAGE!=null){
        let imgPath='file://'+VisitorLoginImageFolderPath+IN_TIME_IMAGE;
        
        let file={
            uri: imgPath,
            type: 'image/jpeg',
            name: IN_TIME_IMAGE,
            filetype:'image',
            folderName:'VisitorLogin',
        }
        INIMAGE=file;
    }

    if(OUT_TIME_IMAGE!='' && OUT_TIME_IMAGE!=null){
        let imgPath='file://'+VisitorLoginImageFolderPath+OUT_TIME_IMAGE;
        
        let file={
            uri: imgPath,
            type: 'image/jpeg',
            name: OUT_TIME_IMAGE,
            filetype:'image',
            folderName:'VisitorLogin',
        }
        OUTIMAGE=file;
    }
    await 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);
        let allImageUploaded=true;
        if(INIMAGE!=''){
          let isExists=await RNFS.exists(INIMAGE.uri).then((res)=>{return res;});
          console.log('isExists file',isExists);
          if(isExists==true){
            let fileData=getImagePOSTData(INIMAGE,d2);
            let isImageUploaded=await UploadImagesWithoutWait(fileData,url2);
            if(isImageUploaded==false){
              allImageUploaded=false;
            }
          }
        }
        if(OUTIMAGE!=''){
          let isExists=await RNFS.exists(OUTIMAGE.uri).then((res)=>{return res;});
          console.log('isExists file',isExists);
          if(isExists==true){
            let fileData=getImagePOSTData(OUTIMAGE,d2);
            let isImageUploaded=await UploadImagesWithoutWait(fileData,url2);
            if(isImageUploaded==false){
              allImageUploaded=false;
            }
          }
        }
        if(allImageUploaded==true){
            console.log('all Visitor image uploaded');
            let isupdated=await updateVLUploadStatus(item);
            if(isupdated==true){
              setProcessing(false);
              notify(ST.Visitordatauploaded);
            }
            else{
              setProcessing(false);
              notify(ST.Cannotuploadvisitordata);
            }
            setCurrentCheckOutItem({});

        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploadvisitordata);
          setCurrentCheckOutItem({});
        }
        
      }else{
        setProcessing(false);
        notify(ST.Cannotuploadvisitordata);
        setCurrentCheckOutItem({});
      }
    })
    .catch((err)=>{
        console.log(err);
        setProcessing(false);
        notify(ST.Cannotuploadvisitordata);
        setCurrentCheckOutItem({});
    }); 

  }

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

        let q=`Update ${AppTables.VISITOR_LOGIN} SET UPLOADSTATUS='U' WHERE EMP_CODE='${item.EMP_CODE}' AND VISIT_DATE='${d2}'`;
        await txn.executeSql(q,[],async function (txn2, txnres) { 
          console.log('Visitor Updated');
          let allVisitors=visitors;
          let thisVisIndex=allVisitors.findIndex(i=>i.EMP_CODE==item.EMP_CODE);
          if(thisVisIndex>=0){
            let thisVis=allVisitors[thisVisIndex] || {};
            thisVis['UPLOADSTATUS']='U';
            allVisitors[thisVisIndex]=thisVis;
            setVisitors(allVisitors);
            setrerenderdata(!rerenderdata);
            resolve(true);
          }
          else{
            resolve(false);
          }
        },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
        
      });   
    }).then((val)=>{
      return val;
    }).catch((err)=>{
      console.log(err);
      return false;
    });
  }

  function _render_CheckOutModal(){
    
    let data=currentCheckOutItem;
    let item={"EmpId":data.EMP_ID,"EmployeeName":data.NAME,"DesignationName":data.DESIGNATION,"LegacyCode":data.EMP_CODE};
    let image_key=item.EmpId+'Out_Image';
    let image_path_key=item.EmpId+'Out_ImagePath';
    let Image1=EmpData[image_path_key] || '';
    return (
      <CustomModal 
        style={customStyle.vl_checkoutModal}
        titleStyle={customStyle.vl_checkoutModalTitle}
        title={ST.VisitorCheckOut}
        message={(currentCheckOutItem.NAME || '')}
        messageStyle={customStyle.vl_checkoutModalTitle}
        showModal={showCheckOutModal}
      >
        <View style={customStyle.vl_checkoutM_Con}>
          <View style={customStyle.vl_checkoutM_Camera}>
            <View style={customStyle.vl_checkoutM_CameraCon}>
            { (Image1=='' || Image1==null) && 
              <TouchableOpacity style={[customStyle.vl_checkoutM_openCam]} onPress={()=>{openCamera(item,'Out')}}>
                <CameraImg width={80} height={80} />                                     
              </TouchableOpacity>
            }                                 
            { (Image1!='' && Image1!=null) && 
              <View style={customStyle.vl_checkoutM_ImageView}>
                <Image style={[customStyle.vl_checkoutM_Image,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:Image1}}/>
                <TouchableOpacity style={[customStyle.vl_checkoutM_recap]} onPress={()=>{openCamera(item,'Out')}}>
                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                </TouchableOpacity>
              </View>                                    
            }        
            </View>

            <View style={[customStyle.nonWCapImgModal_btng,customStyle.vl_checkoutM_btng]}>              
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{cancelCehckout()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={()=>{checkOutEmpl(item)}}>
                <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </CustomModal>
    )
  }

  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>
    )
  }
 
  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
      {processing && <CustomLoader title={loaderTitle}/>}
      <CustomHeader {...props} showaddstore={true} title={ST.VisitorLogin}/>
      {_render_CheckOutModal()}
      {_render_RemoveAlert()}
      <CustomCamera cameraType={'front'} BottomText={getBottomText()} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
      <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper,customStyle.vlPageWrapper]}>
        { !props.isDataDownloaded && <NoDataComponent {...props} />}
        { props.isDataDownloaded==true && 
          <ScrollView
            contentContainerStyle={customStyle.vl_scrollViewInner}
            style={customStyle.vl_scrollView}
          >
            <View style={[customStyle.vlUinfo_Card]}>
              <View style={[customStyle.vlUinfo_CardRow,customStyle.vlUinfo_CardBorder]}> 
                <Text style={customStyle.vlUinfo_lbl}>{ST.Username+' :'}</Text>  
                <Text style={customStyle.vlUinfo_text}>{props.UserId}</Text>                
              </View> 
              <View style={customStyle.vlUinfo_CardRow}> 
                <Text style={customStyle.vlUinfo_lbl}>{ST.Designation+' :'}</Text>  
                <Text style={customStyle.vlUinfo_text}>{designation}</Text>                
              </View> 
            </View>

            <View style={customStyle.vl_visitorsList}>
              <View style={{flexDirection:"row",justifyContent:"space-between", alignItems:"center"}}>
                <Text style={customStyle.vl_visitorsListText}>{ST.Visitors}</Text>
                <TouchableOpacity activeOpacity={0.4} style={customStyle.vlEmplSearchBtn2} onPress={()=>props.navigation.navigate('VisitorLoginQA')}>
                    <Text style={customStyle.vlEmplSearchBtnText}>{"Add Visitors"}</Text>
                </TouchableOpacity> 
              </View>
              <View style={customStyle.vl_TblHeader}>
                <View style={[customStyle.vl_TblHeaderBox,customStyle.vl_TblHeaderBox1]}>
                  <Text style={customStyle.vl_TblHeaderTxt}>{ST.Name}</Text>
                </View>
                <View style={[customStyle.vl_TblHeaderBox,customStyle.vl_TblHeaderBox2]}>
                  <Text style={customStyle.vl_TblHeaderTxt}>{ST.Designation}</Text>
                </View>
                <View style={[customStyle.vl_TblHeaderBox,customStyle.vl_TblHeaderBox3]}>
                  <Text style={customStyle.vl_TblHeaderTxt}>{ST.Actions}</Text>
                </View>
              </View>
              <View style={customStyle.vl_TblBody}>
              {
                visitors.length>0 &&
                visitors.map((item,index)=>{
                  return(
                    <View style={[customStyle.vl_visitorsLItem,((index<(visitors.length-1))?customStyle.vl_visitorsLItemB:{})]} key={index}>
                      <View style={[customStyle.vl_visitorsLI_Box,customStyle.vl_visitorsLI_Box1]}>
                        <Text style={customStyle.vl_visitorsLI_Txt}>{item.NAME}</Text>
                      </View>
                      <View style={[customStyle.vl_visitorsLI_Box,customStyle.vl_visitorsLI_Box2]}>
                        <Text style={customStyle.vl_visitorsLI_Txt}>{item.DESIGNATION}</Text>
                      </View>
                      {item.UPLOADSTATUS!='U' && (item.OUT_TIME=='' || item.OUT_TIME==null) &&
                      <View style={[customStyle.vl_visitorsLI_Box,customStyle.vl_visitorsLI_Box3]}>
                        <TouchableOpacity style={customStyle.vl_CheckOutBtn} onPress={()=>{onCheckOut(item)}}>
                          <Text style={customStyle.vl_CheckOutBtnText}>{ST.CheckOut}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={customStyle.vl_DeleteBtn} onPress={()=>{onDelete(item)}}>
                          <Ionicons name='trash' color={PageTheme.$red} size={24} />
                        </TouchableOpacity>
                      </View>
                      }
                      {item.UPLOADSTATUS!='U' &&  (item.OUT_TIME!='' && item.OUT_TIME!=null) &&
                        <View style={[customStyle.vlStatus2]}>
                          <Ionicons name='checkmark-sharp' color='green' size={20}/>
                          <Text style={[customStyle.storel_usText,{color:'green'}]}>{ST.CheckedOut}</Text>
                        </View>
                      }

                      {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>
              
          </ScrollView>
        }
        </View>      
      </LinearGradient>      
    </Container>
  );
}

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