import React,{useState,useEffect, memo} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,TouchableHighlight,Platform,PermissionsAndroid,FlatList} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,AddStore, checkRange, UploadData2, UploadData, UpdateStoreStatus} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, AppVersion} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign, Entypo, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import {SvgXml} from 'react-native-svg';
import MapIcon from '../assets/performics/map_icon.svg';
import CustomModal from '../components/CustomModal';
import { AppTables } from '../constants/tableConstants';
import { _checkLocationPermission } from '../components/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getMethodName, METHODS } from '../constants/methodNames';
import { uploadAllData, uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import { PrimaryTheme } from '../styles/Themes';
// import JSON from '../constants/storeList_definition.json';
import * as RNFS from 'react-native-fs';

const StoreItem=memo((props)=>{
  const route = useRoute();
  const PageTheme=GetPageTheme(props.DarkMode,route.name);
  const customStyle=customStyles(props.DarkMode,route.name);
  const item=props.item;
  const item_index=props.index;
  const JSONView=props.JSONView;
  const storeList_def=JSONView.storeList_def || {};
  // (storeList_def!=null && typeof storeList_def=='object' && Object.keys(storeList_def).length>0)
  let showInCard=storeList_def.showInCard;
  showInCard=showInCard==0 || (showInCard!=null && showInCard!='')?showInCard:1;
  let showCardDefaultColor=storeList_def.showCardDefaultColor || PageTheme.$bg_color ;
  let rowData=storeList_def.rowData || [] ;

  async function get_to_store_details(data){
    
      if(data.UploadStatus=='U'){
        notify('All Data already uploaded for this store!');
      }
      else if(data.UploadStatus=='L'){
        notify('Already marked as not working status for this store!');
      }
      else if(data.UploadStatus=='I'){
        let isChcekedIn=await checkIfCheckInAvlbl();
        let menuList=data.MenuList;
        console.log('menuList length:',menuList.length);
        if(isChcekedIn==true){
          menuList.length>0?props.navigation.navigate('StoreDailyMenu',{storeData:data,'isAdhoc':props.isAdhocScreen}):'';
        }
        else{
          let isrestored=await restoreCheckIn(data);
          props.setProcessing(false);
          console.log('isrestored:',isrestored);
          if(isrestored==true){
            menuList.length>0?props.navigation.navigate('StoreDailyMenu',{storeData:data,'isAdhoc':props.isAdhocScreen}):'';
          }
          else{
            notify('Check-In data not available!');
          }
          
        }
        
      }
      else if(data.UploadStatus=='C'){
        notify('Already checked out!');
      }
      else if(data.UploadStatus=='D'){
        notify('Data already uploaded!');
      }
      else if(data.UploadStatus=='P'){
        notify('Data partially uploaded!');
      }
      else if(data.UploadStatus=='N' || data.UploadStatus==''){
        let isChcekedIn=await checkIfAlreadyCheckdIn();
        console.log('isChcekedIn',isChcekedIn);   
        if(isChcekedIn==true){
          notify('You are already checked in to the other store!','LONG');
        }
        else{
          props.setShowStoreVisitModal(true);
          props.setCurrentStore(data); 
        }    
      }
      
  }

  

  async function checkIfCheckInAvlbl(){
    let d1=new Date();
    let d2=moment(d1).format('MM/DD/YYYY');
    return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 

          let join=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
          let q=`Select t1.* from Mapping_JourneyPlan t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
          
          let join2=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Adhoc_JourneyPlan' `;
          let q2=`Select t1.* from Adhoc_JourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
          
          await txn.executeSql(q,[],async function (txn2, txnres2) {           
              if(txnres2.rows.length>0){ 
                // show from local
                resolve(true);      
              }
              else{            
                await txn.executeSql(q2,[],async function (txn2, txnres3) {           
                  if(txnres3.rows.length>0){ 
                    // show from local
                    resolve(true);      
                  }
                  else{            
                    resolve(false);
                  }
                },function(Etxn,txnerr){console.log(txnerr);resolve(false);  });
              }
          },function(Etxn,txnerr){console.log(txnerr);resolve(false); });

        }); 

    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return false;
    });
  }


  async function AskForCancelCheckin(data){
    props.setCancelCheckOutStore(data);
    props.setShowCancelCIModal(true);
  }
  

  async function restoreCheckIn(item){
    props.setLoaderTitle('You have cleared the App-Data! Restoring Checkin Info...');
    props.setProcessing(true);
    let d1=new Date();
    let d2=moment(d1).format('MM/DD/YYYY');
    return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 

          let {StoreId,VisitDate,MID,Latitude, Longitude,UploadStatus,InTime,OutTime}=item;
          let JcpType=props.isAdhocScreen==true?'Adhoc_JourneyPlan':'Mapping_JourneyPlan';

          let In_Time=(InTime!='' && InTime!=null && InTime!='00:00:00' && InTime!='00:00')?moment(d2+' '+InTime).format('MM/DD/YYYY HH:mm:ss'):''; 
          let Out_Time=(OutTime!='' && OutTime!=null && OutTime!='00:00:00' && OutTime!='00:00')?moment(d2+' '+OutTime).format('MM/DD/YYYY HH:mm:ss'):''; 
          let CHECKOUT_TIME=(Out_Time!='' && Out_Time!=null)?Out_Time:In_Time; 
          

          // add store Coverage data
          let q=`delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${VisitDate}' `; 
          let values=` ('${StoreId}','${VisitDate}','${Latitude}','${Longitude}','','${CHECKOUT_TIME}','','0','','','','${MID}','${JcpType}','${d2}')`; 
          let insert_q=` insert into ${AppTables.COVERAGE_DATA}(STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) values ${values}`;
          await txn.executeSql(q,[],async function (txn2, txnres2) {
            console.log('store coverage deleted'); 
            await txn.executeSql(insert_q,[],async function (txn2, txnres3) {
              console.log('InsertCoverageData done');


              // add storeCheckin data
              let q2=`delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${VisitDate}' `; 
              let values2=` ('${StoreId}','${VisitDate}','${Latitude}','${Longitude}','${In_Time}','','${Out_Time}','','','${JcpType}','${d2}')`; 
              let insert_q2=` INSERT INTO ${AppTables.CHECKIN_DATA}(STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
              await txn.executeSql(q2,[],async function (txn2, txnres4) {
                console.log('removed'); 
                await txn.executeSql(insert_q2,[],async function (txn2, txnres5) {
                  console.log('checkin data added'); 
                  resolve(true);  
                },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
              },function(Etxn,txnerr){console.log(txnerr);resolve(false);});


            },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
          },function(Etxn,txnerr){console.log(txnerr);resolve(false);});

        }); 

    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return false;
    });
  }

  async function checkIfAlreadyCheckdIn(){
    let d1=new Date();
    let d2=moment(d1).format('MM/DD/YYYY');
    return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 

          let join=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
          let q=`Select t1.* from Mapping_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
          
          let join2=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Adhoc_JourneyPlan' `;
          let q2=`Select t1.* from Adhoc_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
          
          await txn.executeSql(q,[],async function (txn2, txnres2) {           
              if(txnres2.rows.length>0){ 
                // show from local
                resolve(true);      
              }
              else{            
                await txn.executeSql(q2,[],async function (txn2, txnres3) {           
                  if(txnres3.rows.length>0){ 
                    // show from local
                    resolve(true);      
                  }
                  else{   
                    resolve(false);
                  }
                },function(Etxn,txnerr){console.log(txnerr);resolve(false);  });
              }
          },function(Etxn,txnerr){console.log(txnerr);resolve(false); });

        }); 

    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return false;
    });
  }

  

  function renderRow(rd,rd_index){
    let cols=rd.ShowString || [];
    return (
      <View style={[customStyle.dstorel_row,(rd_index==rowData.length-1?customStyle.dstorel_row_last:{})]} key={rd_index}>
          {
            cols.length>0 && 
            cols.map((col,col_index)=>{
              let sep=(col.fieldNameValueSeparator!=null &&  col.fieldNameValueSeparator!='')?' '+col.fieldNameValueSeparator:'';
              let col_sep=col.afterConcatChar!=null && col.afterConcatChar!='' ? col.afterConcatChar:'';
              let col_style={fontSize:(col.fontSize || 12),fontWeight:(col.fontWeight!=null && col.fontWeight!=''?col.fontWeight : '400')} //fontFamily:(col.fontName || 'sans-serif')
             
              return(
              <View style={[customStyle.dstorel_codeCon]} key={col_index}>
                <Text style={customStyle.dstorel_codeLbl}>{col.labelName+sep}</Text>
                <Text style={[customStyle.dstorel_codeText,col_style]}>{item[col.fieldName]}</Text>
                <Text style={customStyle.dstorel_codeSep}>{col_sep}</Text>
              </View>  
              )
            })
          }
      </View>
    )
  }

  return(
      
      <TouchableOpacity style={[((showInCard=='1'  || showInCard==1) ?customStyle.storel:customStyle.storelR),(showInCard!=1 && showInCard!='1' && item_index==(props.storeList.length-1)?customStyle.storelR_last:{}),(showInCard=='1'  || showInCard==1)?{backgroundColor:showCardDefaultColor}:{}]} key={props.index} onPress={() => {get_to_store_details(item)}}> 
       <View style={customStyle.dstorel_card_outer}>
          {rowData.length>0 && 
            rowData.map((rd,rd_index)=>{
              return renderRow(rd,rd_index);
            })
          }
       </View>
      </TouchableOpacity>
    
  );

    return(
      <View style={customStyle.storel_card_outer}> 
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item.StoreName}</Text>
          </View>                  
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
              <Text style={customStyle.storel_codeLbl}>Store Id:</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
            </View>                    
            <View style={[customStyle.storel_codeCon]}>
              <Text style={customStyle.storel_codeLbl}>Store Type:</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreType}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>                    
            <View style={[customStyle.storel_codeCon]}>
              <Text style={customStyle.storel_codeLbl}>Store Code:</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreCode}</Text>
            </View>
          </View>

          <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
            <View style={[customStyle.storel_codeCon]}>
              <Text style={customStyle.storel_codeLbl}>Address:</Text>
              <Text style={customStyle.storel_codeText}>{item.Address}</Text>
            </View>
          </View>
          {(item.CheckInTime!=null && item.CheckInTime!='') && 
            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>
              <Fontisto style={customStyle.storel_codeIcon} color={PageTheme.$secondary_color_dark} name='clock'/>
              <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                <Text style={customStyle.storel_codeText}>Check In:</Text>
                <Text style={customStyle.storel_codeText}>{item.CheckInTime}</Text>
              </View>
              {(item.CheckOutTime!=null && item.CheckOutTime!='') && 
                <View style={[customStyle.storel_codeCon]}>
                  <Text style={customStyle.storel_codeText}>Check Out:</Text>
                  <Text style={customStyle.storel_codeText}>{item.CheckOutTime}</Text>
                </View>
              }
            </View>
          }
          { (item.UploadStatus!=null && item.UploadStatus!='' && item.UploadStatus!='N') &&
            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
              <View style={[customStyle.storel_usWrap]}>
            
              {item.UploadStatus!=null && (item.UploadStatus=='I' || item.UploadStatus=='L') &&
              <TouchableOpacity style={[customStyle.storel_usCon,customStyle.storel_usConBtn,(item.UploadStatus=='L'?customStyle.storel_usConBtn2:{})]} onPress={()=>{AskForCancelCheckin(item)}}>
                {item.UploadStatus=='L' ? <MaterialCommunityIcons name='exclamation' color='red' size={20}/>:<MaterialCommunityIcons name='login' color='#1f7dbc' size={20}/>}
                {item.UploadStatus=='L' ? <Text style={[customStyle.storel_usText,{color:'red'},customStyle.storel_usBtnText]}>Not Working</Text>:<Text style={[customStyle.storel_usText,{color:'#1f7dbc'},customStyle.storel_usBtnText]}>Checked In</Text>}
                
                <View style={[customStyle.storel_usBtnRemoveIcon]}>
                  <FontAwesome name='trash' size={20} color={'red'} />
                </View>
              </TouchableOpacity>} 
              {/* {item.UploadStatus!=null && item.UploadStatus=='I' &&
              <View style={[customStyle.storel_usCon]}>
                    <MaterialCommunityIcons name='login' color='#1f7dbc' size={20}/>
                  <Text style={[customStyle.storel_usText,{color:'#1f7dbc'}]}>Checked In</Text>
              </View>}  */}
              {item.UploadStatus!=null && item.UploadStatus=='C' &&
              <View style={[customStyle.storel_usCon]}>
                <MaterialCommunityIcons name='logout' color='#ffd667' size={20}/>
                <Text style={[customStyle.storel_usText,{color:'#ffd667'}]}>Checked Out</Text>
              </View>} 
              {item.UploadStatus!=null && item.UploadStatus=='P' &&
              <View style={[customStyle.storel_usCon]}>
                <AntDesign name='cloudupload' color='red' size={20}/>
                <Text style={[customStyle.storel_usText,{color:'red'}]}>Partially Uploaded</Text>
              </View>} 
              {item.UploadStatus!=null && item.UploadStatus=='D' &&
              <View style={[customStyle.storel_usCon]}>
                <Ionicons name='checkmark-sharp' color='green' size={20}/>
                <Text style={[customStyle.storel_usText,{color:'green'}]}>Data Uploaded</Text>
              </View>} 
              {item.UploadStatus!=null && item.UploadStatus=='U' &&
              <View style={[customStyle.storel_usCon]}>
                <Ionicons name='checkmark-done-sharp' color='green' size={20}/>
                <Text style={[customStyle.storel_usText,{color:'green'}]}>Uploaded</Text>
              </View> }  
              {/* {item.UploadStatus!=null && item.UploadStatus=='L' &&
                        <View style={[customStyle.storel_usCon]}>
                          <MaterialCommunityIcons name='exclamation' color='red' size={20}/>
                          <Text style={[customStyle.storel_usText,{color:'red'}]}>Not Working</Text>
              </View> }   */}
              { item.allDone==true && (item.UploadStatus=='I') && 
                <TouchableOpacity  style={customStyle.storel_CheckOutBtn} onPress={()=>{props.onCheckOut?props.onCheckOut(item):'';}}>
                  <Text style={customStyle.storel_CheckOutBtnText}>Check Out</Text>
                </TouchableOpacity> 
              }                 
                      </View>
          </View>}
        </View>
        { item.GeoTag=='Y' && 
          <TouchableOpacity activeOpacity={0.5} style={customStyle.storel_geotag_btn} onPress={()=>{props.navigation.navigate('ShowMap',{storeData:item})}} >
            <SvgXml width={30} height={30} xml={MapIcon}/>    
          </TouchableOpacity>
        }
        { item.GeoTag=='N' && 
          <TouchableOpacity activeOpacity={1} style={customStyle.storel_geotag_btn} onPress={()=>{}} >
            <Entypo name='location-pin' size={30} color={'#b4b4b4'}/>   
          </TouchableOpacity>
        }
       </View>  
    )
  
  
});

function DynamicStoreList(props) { 
    const route = useRoute();
  
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [processing, setProcessing] = useState((props.isDataDownloaded?true:false));
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [nodataFound, setNodataFound] = useState(false);
    const [showStoreVisitModal, setShowStoreVisitModal] = useState(false);
    const [showGeoTagModal, setShowGeoTagModal] = useState(false);
    const [showDistanceModal, setShowDistanceModal] = useState(false);
    const [currentStore, setCurrentStore] = useState({});
    const [storeDistance, setStoreDistance] = useState('0 M');
    const [showAlert, setShowAlert] = useState(false);
    const [checkOutStore,setCheckOutStore]=useState({});
    const [rerenderdata, setrerenderdata]= useState(false);
    let [state, setState] = useState({storeList:[]});
    const [cancelCheckOutStore,setCancelCheckOutStore]=useState({});
    const [showCancelCIModal, setShowCancelCIModal]= useState(false);
    const [JSONView, setJSONView]= useState({});
  
    useEffect(() => { 
      
      getData();
      const willFocusSubscription = props.navigation.addListener('focus', () => {
        checkLocalData();
      });

      return willFocusSubscription
    }, []);


    async function getData(){
      // let json_ex1=JSON;
      // setJSONView(json_ex1);
      // return;

      let json_ex=require('../constants/storeList_definition.json');
      // let path =`file://${RNFS.ExternalStorageDirectoryPath}/Documents/test.json`;
      // console.log('path:',path);
      // let json_ex=await RNFS.readFile(path).then((val)=>{
      //   return val;
      // })
      setJSONView(json_ex);
      checkLocalData();
    }
    

    async function calLocatDistance(){
      if(currentStore.Latitude !='' && currentStore.Latitude!=null){
        const hasPermission=await _checkLocationPermission();
        if(hasPermission==true)
        {    
          Geolocation.getCurrentPosition(
            async (position) => {
                let loc={lat:position.coords.latitude,lng:position.coords.longitude};
                
                var distance = checkRange(loc.lat,loc.lng,currentStore.Latitude,currentStore.Longitude);
                console.log('distance:',distance);
                let dinKM=(distance / 1000);
                let distanceinM=(distance=='' || distance==null || isNaN(distance))?' 0 m':( dinKM > 1 ? dinKM.toFixed(1) + ' Km' : distance + ' m');
                setStoreDistance(distanceinM);
                if(distance>500){
                  setShowDistanceModal(true); 
                }
                else{
                  props.navigation.navigate('StoreCheckin',{storeData:currentStore,'isAdhoc':isAdhocScreen});
                }          
            },
            (error) => {
                notify('Cannot get user position');
            },
            { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
          );
        }
        else{
          notify('Please allow location permission');
        }
      }
      else{
        notify('Store location not available');
      }
      
    }

    
  
    async function checkLocalData(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');

      let token=await get_item('loginToken');
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);
      let params=props.route.params? props.route.params:{};
      let isAdhoc=params.isAdhoc || false;
      setIsAdhocScreen(isAdhoc);

      var q='',tb1='Mapping_JourneyPlan',tb2=AppTables.CHECKIN_DATA,tb3='Adhoc_JourneyPlan';

      var join_tbl=isAdhoc==true?tb3:tb1;
      var join =` left join ${tb2} on ${tb2}.STORE_ID=${join_tbl}.StoreId and ${tb2}.JCP_TYPE='${join_tbl}' and ${tb2}.VISIT_DATE='${d2}' and ${join_tbl}.UploadStatus in ('I','C','D','U','L')  `;
      var orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;
      
      if(isAdhoc==true){
        q=`Select ${tb3}.*,${tb2}.CHECKIN_TIME as CheckInTime ,${tb2}.CHECKOUT_TIME as CheckOutTime from ${tb3} ${join}  where ${tb3}.VisitDate='${d2}' ${orderby} `;
      }
      else{
        q=`Select ${tb1}.*,${tb2}.CHECKIN_TIME as CheckInTime ,${tb2}.CHECKOUT_TIME as CheckOutTime from ${tb1} ${join}  where ${tb1}.VisitDate='${d2}' ${orderby} `;
      }
      
      await db.transaction(async function (txn) {   
        await txn.executeSql(q,[],async function (txn2, txnres2) {           
          if(txnres2.rows.length>0){ 
            // show from local
            var storeArr=[];
            for(var i=0;i<txnres2.rows.length;i++){
              let sdata=txnres2.rows.item(i); 
              let {InTime,OutTime,UploadStatus,StoreId,MID}=sdata;
              let time=sdata.CheckInTime!=null && sdata.CheckInTime!=''?moment(new Date(sdata.CheckInTime)).format('HH:mm:ss'):''; 
              let time2=sdata.CheckOutTime!=null && sdata.CheckOutTime!=''?moment(new Date(sdata.CheckOutTime)).format('HH:mm:ss'):''; 
              let In_Time=(time=='' && UploadStatus!='' && UploadStatus!='N')?InTime:time;
              let Out_Time=(time2==''  && UploadStatus!='' && UploadStatus!='N' && UploadStatus!='I')?OutTime:time2;
              sdata.CheckInTime=In_Time;
              sdata.CheckOutTime=Out_Time;
              
              let MenuList=await getMenuList(sdata);
              let allDone=MenuList.length>0?await getDailyMenu(sdata):true;
              sdata.allDone=allDone;
              sdata.MenuList=MenuList || [];
              storeArr.push(sdata);
              
              if(i==(txnres2.rows.length-1)){
                // console.log(storeArr);
                setState({storeList:storeArr});
                setProcessing(false);
              }
            }            
          }
          else{            
            setProcessing(false); notify('No data found');setNodataFound(true);
          }
        },function(Etxn,txnerr){console.log(txnerr);});
      });      
    }

    async function getDailyMenu(storeData1){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let {StoreId,ChannelId,RegionId}=storeData1;
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {        
             
          let q=Q_MenuList(storeData1); 
          await txn.executeSql(q,[],async function (txn2, txnres) { 
            
            if(txnres.rows.length>0){     
              let allDone=true;   
              for(var i=0;i<txnres.rows.length;i++){
                let data =txnres.rows.item(i);
                let isAvlbl=await checkAvailability(storeData1,data);
                let isDone=await updateStatus(storeData1,data,isAvlbl);
                
                if(isAvlbl && !isDone){
                  allDone=false;
                  resolve(allDone);
                  break;
                }
                if(i==(txnres.rows.length-1)){
                  resolve(allDone);
                }
              }
            }
            else{
              resolve(true);
            }
          },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);

        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });
           
    }

    async function getMenuList(storeData1){
      let {StoreId,ChannelId,RegionId}=storeData1;
      return new Promise((resolve,reject)=>{
  
        db.transaction(async function (txn) {   
          let q=Q_MenuList(storeData1);  
          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)){
                  resolve(arr);
                }
              }
            }
            else{
              resolve([])
            }
          },function (txnE,txnerr) { console.log(txnerr); resolve([]); },);
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log('')
        return []
      })
    }

    async function getKPIS(MenuList){
      let allKpis=[];
              
      return Promise.all(
        MenuList.map((item,index)=>{
          let MenuId=item.MenuId || '';
          MenuId=MenuId+'';
          switch(MenuId){
            case '1':allKpis.push('Stocks'); return 'Stocks';
            case '2':allKpis.push('BRS'); return 'BRS';
            case '3':allKpis.indexOf('Stocks')<0?allKpis.push('Stocks'):''; return 'Stocks';
            case '4':allKpis.indexOf('Stocks')<0?allKpis.push('Stocks'):''; return 'Stocks';
            case '5':allKpis.push('SOS'); return 'SOS';
            case '6':allKpis.push('PaidVis'); return 'PaidVis';
            case '7':allKpis.push('AddVis'); return 'AddVis';
            case '8':allKpis.push('CompVis'); return 'CompVis';
            case '9':allKpis.push('Promotion'); return 'Promotion';
            case '14':allKpis.push('CompPromo'); return 'CompPromo';
            case '15':allKpis.push('Contacts'); return 'Contacts';
            case '16':allKpis.push('Sale'); return 'Sale';
            case '17':allKpis.push('Survey'); return 'Survey';
            default: return '';
          }
        })
      ).then((val)=>{
        console.log('allKPIs:',val,allKpis);
        return allKpis;
      })
    }


    async function checkAvailability(storeData1,data){
      
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          let q2=getAvailblQuery(data.MenuId,storeData1);
          if(q2!='' && q2!=null){
            await txn.executeSql(q2,[],async function (txn2, txnres2) {                     
              let isAvlbl=getIfAvlbl(data.MenuId,txnres2,storeData1);
              resolve(isAvlbl);
            },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);
          }
          else{
            let isAvlbl=getIfAvlbl(data.MenuId,{},storeData1);
            resolve(isAvlbl);
          }
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });     
    }


    async function updateStatus(storeData1,data,isAvlbl){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          let q2=getQuery(data.MenuId,storeData1);
          if(q2!='' && q2!=null && isAvlbl==true){
              await txn.executeSql(q2,[],async function (txn2, txnres2) {                     
                let isDone=await getIfKPIDone(data.MenuId,txnres2,storeData1);
                resolve(isDone);
               
              },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);
          }
          else{
              resolve(false);
          }
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      }); 
             
    }

    async function onCheckOut(storeData1){
      // let isAlldone=await getDailyMenu(storeData1);
      // if(isAlldone==true){
        setCheckOutStore(storeData1);
        setShowAlert(true);
      // }
      // else{
      //   notify('Please fill all KPI ',false);
      // }
    }

    function onSaveCancel(){
      setShowAlert(false);
    }

    async function getLocOnCheckout(){
      setShowAlert(false);
      setLoaderTitle('Updating Checkout Status...');
      setProcessing(true);
      Geolocation.getCurrentPosition(
        async (position) => {
          let {latitude,longitude} = position.coords;
          let loc={lat:latitude,lng:longitude};
          UpdateCheckOutStatus(loc)
        },
        (error) => {
            notify('Cannot get user position');
            setProcessing(false);
        },
        { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
      );
    }

    async function UpdateCheckOutStatus(loc){  
      let {StoreId,MID}=checkOutStore;
      let d=new Date();
      let d2=moment(d).format('MM/DD/YYYY');
      let d3=moment(d).format('MM/DD/YYYY HH:mm:ss'); 
      
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);
       
      let data1={
          "UserId": loginDetails.UserId,
          "StoreId": StoreId,
          "Latitude": loc.lat,
          "Longitude": loc.lng,
          "Checkout_Date": d2,
      }

      const url=props.baseurl+getMethodName(METHODS.CHECKOUTDETAIL_METHOD);
      
      console.log(url,data1);
      await UploadData2(url,data1)
      .then(async(res)=>{ 
          console.log('StoreCheckOutSup1:',res,'MID:',MID);
          if(!res.error){
            if(res==1){
              //Check out completed
              
              let data={checkout_image:''} ;
              const isCheckOutUpdated=await UpdateStoreCheckOut(data);
              
              if(isCheckOutUpdated==true){
                let datan={StoreId:StoreId,UploadStatus:'C',tbname:(isAdhocScreen==true?'Adhoc_JourneyPlan':'Mapping_JourneyPlan')} ;            
                const isUpdated=await UpdateStoreStatus(props,datan);
                if(isUpdated==true){
                  let outtime=moment(d).format('HH:mm:ss'); ;
                  await updateStoreStatuslocal('C',checkOutStore,false,true,outtime);
                  setLoaderTitle('Uploading Data...');
                  UploadOnCheckOut(loc);
                }
                else{
                  setProcessing(false);notify('Error occur while checkout','LONG');
                } 
              }
              else{
                notify('Error occur while checkout','LONG');
              }
              
            }
            else{
              notify('Something went wrong!','SHORT');setProcessing(false);
            }
          }
          else{
            notify('Something went wrong!','SHORT');setProcessing(false);
          }
      })
      .catch((err)=>{
        console.log('onPage Team error',err);
        notify('Something went wrong!','SHORT');setProcessing(false);
      }); 
        
      
    }

    async function updateStoreStatuslocal(status,storeData1,updateCheckin=false,uCOut=false,cout_time=''){
      
      let storeArr=state.storeList;
      let sdata_index=storeArr.findIndex(i=>i.StoreId==storeData1.StoreId);
      if(sdata_index>=0){
        let sdata=storeArr[sdata_index];
        sdata['UploadStatus']=status;
        if(updateCheckin==true){
          sdata['CheckInTime']='';
        }
        if(uCOut==true){
          sdata['CheckOutTime']=cout_time;
        }
        storeArr[sdata_index]=sdata;
        setState({...state,storeArr});
        setrerenderdata(!rerenderdata);
      }
    }

    async function UpdateStoreCheckOut(data) {    
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let now=moment(d1).format('MM/DD/YYYY HH:mm:ss');
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {    
          let q2=`UPDATE ${AppTables.COVERAGE_DATA} SET CHECKOUT_TIME='${now}', CHECKOUT_IMAGE='' WHERE STORE_ID='${checkOutStore.StoreId}' and VISIT_DATE='${d2}' `;
          
          await txn.executeSql(q2,[],async function (txn2, txnres2) { 
            console.log('store coverage updated');
          },function(Etxn,txnerr){console.log(txnerr);resolve(false);}); 

          let q=`UPDATE ${AppTables.CHECKIN_DATA} SET CHECKOUT_TIME='${now}', CHECKOUT_IMAGE='' WHERE STORE_ID='${checkOutStore.StoreId}' and VISIT_DATE='${d2}' `;
          await txn.executeSql(q,[],async function (txn2, txnres2) { 
            console.log('store checkout updated');
            resolve(true);
          },function(Etxn,txnerr){console.log(txnerr);resolve(false);}); 
        
        });
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });
        
      
    }
    

    async function UploadOnCheckOut(loc){
      try {   
        console.log('UploadOnCheckOut');
        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');
        let token = await get_item('loginToken');
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
       
        let PJPStores=await getPJPStoresData('Mapping_JourneyPlan',[],d2);
        let AllStores=await getPJPStoresData('Adhoc_JourneyPlan',PJPStores,d2);

        

        await db.transaction(async function (txn) { 
          console.log('stores to upload:',AllStores.length);  
          if(AllStores.length>0){  
            for (var i=0;i<AllStores.length;i++){
              let data=AllStores[i];
              const index=i;
              let {StoreId,StoreName,EmpId,MID,UploadStatus,Status,VisitDate,REASON_ID,IMAGE,JCP_TYPE}=data;

              let MenuList=await getMenuList(data);
              let allKPIs=await getKPIS(MenuList);
              // get all checkout ids data
              // let allKPIs=['Stocks','BRS','SOS','PaidVis','AddVis','CompVis','Promotion','CompPromo','Contacts','Sale','Survey'];
                  
              if(UploadStatus=='C'){
                let pdata={
                  "Mid":MID,
                  "StoreId":StoreId,
                  "VisitDate":d2,
                  "Latitude":loc.lat,
                  "Longitude":loc.lng,
                  "ReasonId":REASON_ID!=''?REASON_ID:0,
                  "Remark":"",
                  "ImageName":IMAGE,
                  "Appversion":AppVersion,
                  "UploadStatus":'P',
                  "CheckoutImage":IMAGE,
                  "UserName":loginDetails.UserId,
                };
                
                const url2=props.baseurl+getMethodName(METHODS.GETCOVERAGE_METHOD);
                console.log(url2,pdata)
                await UploadData2(url2,pdata)
                .then(async(res)=>{ 
                  console.log('status uploadres:',res,'MID:',MID);
                 
                  if(!res.error){
                    let tbname=JCP_TYPE;
                    let datan={StoreId:StoreId,UploadStatus:'P',tbname:tbname} ;            
                    const isUpdated=await UpdateStoreStatus(props,datan);
                    if(isUpdated==true){
                      
                      await updateStoreStatuslocal('P',data);
                      await uploadAfter_P_status(index,AllStores,data,MenuList,allKPIs,JCP_TYPE);
                     
                    }
                    else{
                      if(index==AllStores.length-1){
                        setProcessing(false);notify('Error occur while uploading data','LONG');
                      }
                    }
                  }
                  else{
                    if(index==AllStores.length-1){
                      setProcessing(false);notify('Error occur while uploading data','LONG');
                    }
                  }
                  
                })
                .catch((err)=>{
                  console.log(err);
                  if(index==AllStores.length-1){
                    setProcessing(false);notify('Error occur while uploading data','LONG');
                  }
                });
              }
              else if (UploadStatus=='D'){
                //  this never be called if there is no KPI
                let allFilesToUpload=await uploadAllData(props,data,allKPIs,props.UserId,JCP_TYPE,false);
                if(allFilesToUpload.length>0){
                  await UploadDataWithImages(index,AllStores,data,MenuList,allKPIs,JCP_TYPE,allFilesToUpload);
                }
                else{
                  notify('All data uploaded for '+StoreName,'SHORT');
                  if(index==AllStores.length-1){
                    setProcessing(false);
                  }
                }
              }
              else if(UploadStatus=='P'){
                await uploadAfter_P_status(index,AllStores,data,MenuList,allKPIs,JCP_TYPE);
              }
              else if(UploadStatus=='L'){
                let isAllUploaded_S=await uploadStoreStatus(props,data,'U',JCP_TYPE);
                if(isAllUploaded_S==true){
                  await updateStoreStatuslocal('U',data);
                  notify('All data uploaded for '+StoreName,'SHORT');
                  if(index==AllStores.length-1){
                    setProcessing(false);
                  }
                }
                else{
                  if(index==AllStores.length-1){
                    setProcessing(false);notify('Error occur while uploading data','LONG');
                  }
                }
              }
            }
                
          } 
        });  

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

    async function uploadAfter_P_status(index,AllStores,data,MenuList,allKPIs,JCP_TYPE){
      let {StoreName}=data;
      if(MenuList.length>0){ 
        // Upload data with Images
        let allFilesToUpload=await uploadAllData(props,data,allKPIs,props.UserId,JCP_TYPE);
        await updateStoreStatuslocal('D',data);
        UploadDataWithImages(index,AllStores,data,MenuList,allKPIs,JCP_TYPE,allFilesToUpload);
      }
      else{
        //  Upload statua u if no data exists
        let isAllUploaded_S=await uploadStoreStatus(props,data,'U',JCP_TYPE);
        if(isAllUploaded_S==true){
          await updateStoreStatuslocal('U',data);
          notify('All data uploaded for '+StoreName,'SHORT');
          if(index==AllStores.length-1){
            setProcessing(false);
          }
        }
        else{
          if(index==AllStores.length-1){
            setProcessing(false);notify('Error occur while uploading data','LONG');
          }
        }
      }
    }

    async function UploadDataWithImages(index,AllStores,data,MenuList,allKPIs,JCP_TYPE,allFilesToUpload){
      let {StoreName}=data;
      if(allFilesToUpload.length>0){
        setLoaderTitle('Uploading Images...');
        console.log('set loader title');
        let isAllUploaded=await uploadAllImages(props,data,allFilesToUpload,JCP_TYPE);

        if(isAllUploaded==true){
          await updateStoreStatuslocal('U',data);
          notify('All data and images uploaded for '+StoreName,'SHORT');
          if(index==AllStores.length-1){
            setProcessing(false);
          }
        }else{
          notify('Cannot upload images for '+StoreName,'SHORT');
          if(index==AllStores.length-1){
            setProcessing(false);
          }
        }
      }
      else{
        notify('All data uploaded for '+StoreName,'SHORT');
        if(index==AllStores.length-1){
          setProcessing(false);
        }
      }
    }

    

    async function getPJPStoresData(tbname,Stores=[],d2){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {
          
          let join=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='${tbname}' `;
          await txn.executeSql(`Select t1.*,t2.REASON_ID,t2.IMAGE,t2.JCP_TYPE from ${tbname} t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus in ('C','P','D','L')`,[],async function (txn2, txnres2) { 
            if(txnres2.rows.length>0){ 
              
              for(var i=0;i<txnres2.rows.length;i++){
                let data=txnres2.rows.item(i);
                Stores.push(data);
              }
              resolve(Stores);
            }
            else{
              resolve(Stores);
            }
          },function (txnE,txnerr) { console.log(txnerr);resolve(Stores)},);

        });
      }).then((val)=>{
        return val;
      })
      .catch((err)=>{
        console.log(err);
        return Stores;
      })
    }

   
    

    async function storeVisited(){
      console.log('isgeotag:',currentStore.GeoTag);
      setShowStoreVisitModal(false);
      if(currentStore.GeoTag=='N'){
        setShowGeoTagModal(true);
      }
      else if(currentStore.UploadStatus=='N' || currentStore.UploadStatus==''){
        calLocatDistance();
      }
      else{
            
      }
    }

    async function storeNotVisited(){
      setShowStoreVisitModal(false);
      props.navigation.navigate('StoreNonWorkingReasons',{storeData:currentStore,'isAdhoc':isAdhocScreen});
    }

    async function onVisitCancel(){
      setLoaderTitle('Deleting Check-In Data...')
      setShowCancelCIModal(false);
      setProcessing(true);
      let {MID,StoreId}=cancelCheckOutStore;
      let postdata={'Mid':MID,"UserName":props.UserId,}
     
      const url=props.baseurl+getMethodName(METHODS.DELETECOVERAGE_METHOD);
      console.log(url,postdata);
      await UploadData2(url,postdata)
      .then(async(res)=>{ 
        console.log('delete coverage res:',res); 
        if(res=='1'){
          let isdeleted=await deleteStore(cancelCheckOutStore);
          if(isdeleted==true){
            let data={"StoreId":StoreId,UploadStatus:"N",tbname:(isAdhocScreen==true?'Adhoc_JourneyPlan':'Mapping_JourneyPlan')};
            let isUpdated=await UpdateStoreStatus(props,data);
            if(isUpdated==true){
              await updateStoreStatuslocal('N',cancelCheckOutStore,true);
              setProcessing(false);
              notify('Check-In Removed');
            }
            else{
              setProcessing(false);
              notify('Check-In removed successfully, but cannot update status!');
            }
          }
          else{
            setProcessing(false);
            notify('Check-In removed successfully, but cannot update status!');
          }
        }
        else{
          setProcessing(false);
          notify('Cannot Remove Check-In!');
        }
        
      }).catch(err => {
        console.log('onPage Team error', err);
        setProcessing(false);
        notify('Cannot Remove Check-In!');
      }); 
     
    }

    async function deleteStore(storeData1){
      let {StoreId}=storeData1;
      let allQueries=[
        `Delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.GEOTAG} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.HEADER_BACK_OF_STORE} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.CHILD_BACK_OF_STORE} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.SALES} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.INSERT_OPENINGHEADER_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.STOCK_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.SHARE_OF_SHELF_IMAGE} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.SHARE_OF_SHELF_FACING_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.INSERT_SAMPLED_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.CONTACT_CONVERSION} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.INSERT_ERROR_TRACKING} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.GROOMING_IMAGE_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.ADDITIONAL_VISIBILITY} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.ADDITIONAL_VISIBILITY_STOCK} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.COMPETITION_VISIBILITY} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.COMPETITION_PROMOTION} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.PROMOTION_HEADER_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.PROMOTION_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.PAID_VISIBILITY_HEADER_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.PAID_VISIBILITY_CHILD_DATA} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.PAID_VIS_CHECKLIST} where STORE_ID='${StoreId}' `,
        `Delete from ${AppTables.SURVEY} where STORE_ID='${StoreId}' `,
      ]
      
      return await Promise.all(
        allQueries.map(async (q,index) => {
          let isDeleted= await executeQuery(q);
          return isDeleted==true;
        })
      )
      .then((val)=>{
        // if(val.indexOf(false)<0){}
        return true;
      }).catch((err)=>{
        console.log(err);
        return false;
      })
    }

    async function executeQuery(q,type='1'){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
          await txn.executeSql(q,[],async function (txn2, txnres2) {           
            if(type=='1'){
              resolve(true);
            }
            else{
              let arr=[];
              if(txnres2.rows.length>0){
                for(var i=0;i<txnres2.rows.length;i++){
                  let data=txnres2.rows.item(i);
                  arr.push(data);
                }
                resolve(arr);
              }
              else{
                resolve([]);
              }
            }
          },function(Etxn,txnerr){console.log(txnerr);type=='1'?resolve(false):resolve([]); });
        }); 
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        let d=type=='1'?false:[];
        return d;
      })
    }

    function _render_StoreVisitModal(){
      return (
        <CustomModal 
          style={customStyle.storelVisitM_Style}
          title={'Store Visited'}
          titleStyle={customStyle.storelVisitM_titleStyle}
          showModal={showStoreVisitModal}
        >
          <View style={customStyle.storelVisitM_options}>
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{storeVisited()}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
            </TouchableOpacity>
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{storeNotVisited()}}>
              <Text style={customStyle.storelVisitM_op_btnText}>No</Text>
            </TouchableOpacity>
          </View>
        </CustomModal>
      )
    }

    function _render_GeoTagModal(){
      return (
        <CustomModal 
          style={customStyle.storelVisitM_Style}
          title={'You need to geotag store'}
          titleStyle={customStyle.storelVisitM_titleStyle}
          showModal={showGeoTagModal}
        >
          <View style={customStyle.storelVisitM_options}>            
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowGeoTagModal(false)}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowGeoTagModal(false);props.navigation.navigate('GeoTag',{storeData:currentStore,'isAdhoc':isAdhocScreen});}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Ok</Text>
            </TouchableOpacity>
          </View>
        </CustomModal>
      )
      
    }

    function _render_CancelCheckinModal(){
      let storename=cancelCheckOutStore.StoreName || '';
      return (
        <CustomModal 
          style={customStyle.storelVisitM_Style}
          title={'Do you really want to Cancel Check-In?'}
          titleStyle={customStyle.storelCancelM_titleStyle}
          messageStyle={customStyle.storelCancelM_subtitleStyle}
          message={storename}
          showModal={showCancelCIModal}
        >
          <View style={customStyle.storelCM_alertCon}>
            <Feather name='alert-triangle' size={20} color={'#ff0000'}/>
            <Text style={customStyle.storelCM_alert}>Your all check-in data will be lost!</Text>
          </View>
            
          <View style={customStyle.storelVisitM_options}>
            
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowCancelCIModal(false);}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{onVisitCancel()}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Ok</Text>
            </TouchableOpacity>
          </View>
        </CustomModal>
      )
    }

    function _render_DistanceModal(){
      return (
        <CustomModal 
          style={customStyle.storeDistance_Modal}
          title={'Performics'}
          titleStyle={customStyle.storeDistanceM_title}
          showModal={showDistanceModal}
        >
          <View style={customStyle.storeDistanceM_Con}>            
            <Text style={customStyle.storeDistanceM_message}>You need to be in the store</Text>
            <Text style={[customStyle.storeDistanceM_message,customStyle.mb20]}>to CheckIn/CheckOut</Text>
            <Text style={customStyle.storeDistanceM_submessage}>{`Allowed distance from store: 500 m`}</Text>
            <Text style={customStyle.storeDistanceM_submessage}>{`Your distance from store: ${storeDistance}`}</Text>
            <TouchableOpacity style={customStyle.storeDistanceM_btn} onPress={()=>{setShowDistanceModal(false);props.navigation.navigate('StoreCheckin',{storeData:currentStore,'isAdhoc':isAdhocScreen});}}>
              <Text style={customStyle.storeDistanceM_btnText}>Ok</Text>
            </TouchableOpacity>
          </View>
        </CustomModal>
      )
      
    }

    function _renderList(){
      const storeList_def=JSONView.storeList_def || {};
      let showInCard=storeList_def.showInCard;
      showInCard=showInCard==0 || (showInCard!=null && showInCard!='')?showInCard:1;

      return (
        <ScrollView
          style={[customStyle.listcon,((showInCard=='1' || showInCard==1 )?{}:customStyle.storeR_listcon)]}
          contentContainerStyle={[customStyle.iteml_con,((showInCard=='1' || showInCard==1 )?{}:customStyle.iteml_conR)]}
        >
          <View style={[((showInCard=='1' || showInCard==1 )?{}:customStyle.iteml_conR2)]}>
          {
            state.storeList.map((item,index)=>{
              return(
                <StoreItem  {...props} item={item} index={index} isAdhocScreen={isAdhocScreen} setShowStoreVisitModal={setShowStoreVisitModal} setCurrentStore={setCurrentStore} onCheckOut={onCheckOut} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing} setShowCancelCIModal={setShowCancelCIModal} setCancelCheckOutStore={setCancelCheckOutStore} JSONView={JSONView}/>
              );
            })
          }
          </View>
          
        </ScrollView> 
      )
    }
  
    
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true} title={(isAdhocScreen==true?'Dynamic Adhoc Store List':'Dynamic Store List')} />
        {_render_StoreVisitModal()}
        {_render_GeoTagModal()}
        {_render_DistanceModal()}
        {_render_CancelCheckinModal()}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,getLocOnCheckout,'Do you really want to checkout?')}
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={customStyle.pageContentWrapper}>
          { !props.isDataDownloaded && <NoDataComponent  {...props}/>}
          
         
          <View style={customStyle.storelist_parentwrap}>
          <ScrollView style={customStyle.storeTab_MenuCon} contentContainerStyle={customStyle.storeTab_Menu} horizontal={true}>
            <TouchableOpacity style={[customStyle.storeTab_pill,(!isAdhocScreen?customStyle.storeTab_pillActive:{})]} key={1} onPress={()=>{props.navigation.pop();props.navigation.push('DynamicStoreList')}}>
              <Text style={[customStyle.storeTab_pillText,(!isAdhocScreen?customStyle.storeTab_pillActiveText:{color:PageTheme.$text_color})]}>Planned</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[customStyle.storeTab_pill,(isAdhocScreen?customStyle.storeTab_pillActive:{})]} key={2} onPress={()=>{props.navigation.pop();props.navigation.push('DynamicStoreList',{'isAdhoc': true})}}>
              <Text style={[customStyle.storeTab_pillText,(isAdhocScreen?customStyle.storeTab_pillActiveText:{color:PageTheme.$text_color})]}>Adhoc</Text>
            </TouchableOpacity>
          </ScrollView>

          { nodataFound && 
          <View style={customStyle.noDataCon}>
            <Text style={customStyle.noDataText}>No Data Available</Text>
          </View>
          }
          { (props.isDataDownloaded==true && !nodataFound) && rerenderdata==rerenderdata &&
            _renderList()
          }
          </View>
         
          
         </View>      
       </LinearGradient>       
        
      </Container>   
    ); 
  }
  


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