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 { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, AddStore, checkRange, UploadData2, UploadData, UpdateDistributorStatus, getKPIS, marktext1, marktext2, UploadFormData, resizeImage, restore_ImageWithMetaData } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, AppVersion, CoverageImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, EvilIcons, 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 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_getMyDistributorList, Q_getMyStoresList, Q_DBMenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { uploadAll_DBData, uploadAllImages, uploadDBStatus } from '../constants/uploadData';
import * as RNFS from 'react-native-fs';

import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import HeaderTabs from '../components/HeaderTabs';
import DownloadDataModal from '../components/downloadDataModal';



const DistributorItem = memo((props) => {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const item = props.item;

  const ST = props.StaticText || {};

  async function get_to_store_details(data) {
    // data.UploadStatus = "N"

    if (data.UploadStatus == 'U') {
      notify('All data already uploaded for the distributor');
    }
    else if (data.UploadStatus == 'L') {
      notify('Already marked not working reasons for the distributor');
    }
    else if (data.UploadStatus == 'I') {
      let MenuListLen = data.MenuListLen;
      console.log('menuList length:', MenuListLen);
      if (MenuListLen > 0) {
        props.set_autoback({ 'AutoGoToPrev': false });
        props.navigation.navigate('DB_StoreDailyMenu', { storeData: data });
      } else {
        notify("No menu map for this distributor!");
      }

    }
    else if (data.UploadStatus == 'C') {
      notify(ST.Alreadycheckedout);
    }
    else if (data.UploadStatus == 'D') {
      notify(ST.Dataalreadyuploaded);
    }
    else if (data.UploadStatus == 'P') {
      notify(ST.Datapartiallyuploaded);
    }
    else if (data.UploadStatus == 'N' || data.UploadStatus == '') {
      let isChcekedIn = await checkIfAlreadyCheckdIn();
      console.log('isChcekedIn', isChcekedIn);
      if (isChcekedIn == true) {
        console.log("logs---------------------2")
        notify('You have already checked in into other distributor', 'LONG');
      }
      else {
        props.setShowStoreVisitModal(true);
        console.log("test js-------", true)
        props.setCurrentStore(data);
      }
    }

  }

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



  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.DISTRIBUTOR_CHECKIN} t2 on t2.DISTRIBUTOR_ID=t1.DistributorId  `;
        let q = `Select t1.* from Master_Distributor t1 ${join} where t2.VISIT_DATE='${d2}' and t1.UploadStatus='I'`

        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            // show from local
            resolve(true);
          }
          else {
            resolve(false);
          }
        }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

      });

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

  return (
    <TouchableOpacity
      style={customStyle.storel}
      key={props.index}
      onPress={() => { get_to_store_details(item) }}>
      <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_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Distributor Id:'}</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Distributor Code:'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.StoreCode}</Text>
            </View>
          </View>

          {
            (item.CheckInTime != null && item.CheckInTime != '' && item?.CheckInTime != '00:00:00') &&
            <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}>{ST.CheckIn + ':'}</Text>

                <Text style={customStyle.storel_codeText}>{item.CheckInTime}</Text>
              </View>
              {(item.CheckOutTime != null && item.CheckOutTime != '' && item?.CheckOutTime != '00:00:00') &&
                <View style={[customStyle.storel_codeCon]}>
                  <Text style={customStyle.storel_codeText}>{ST.CheckOut + ':'}</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 == 'L' &&
                  <View style={[customStyle.storel_usCon]}>
                    <MaterialCommunityIcons name='exclamation' color='red' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'red' }, customStyle.storel_usBtnText]}>{ST.NotWorking}</Text>
                  </View>}
                {item.UploadStatus != null && item.UploadStatus == 'I' &&
                  <View style={[customStyle.storel_usCon]}>
                    <MaterialCommunityIcons name='login' color='#1f7dbc' size={20} />
                    <Text style={[customStyle.storel_usText, { color: PageTheme.$primary_color }, customStyle.storel_usBtnText]}>{ST.CheckedIn}</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' }]}>{ST.CheckedOut}</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' }]}>{ST.PartiallyUploaded}</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' }]}>{ST.DataUploaded}</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' }]}>{ST.Uploaded}</Text>
                  </View>}


                {item.allDone == true && (item.UploadStatus == 'I') &&
                  <TouchableOpacity style={customStyle.storel_CheckOutBtn} onPress={() => { props.onCheckOut ? props.onCheckOut(item) : ''; }}>
                    <Text style={customStyle.storel_CheckOutBtnText}>{ST.CheckOut}</Text>
                  </TouchableOpacity>
                }
              </View>
            </View>}
        </View>
        {item.GeoTag == 'Y' &&
          <TouchableOpacity activeOpacity={0.5} style={customStyle.storel_geotag_btn} onPress={() => { props.navigation.navigate('ShowMap', { storeData: item }) }} >
            <MapIcon width={30} height={30} />
          </TouchableOpacity>
        }
        {item.GeoTag == 'N' &&
          <TouchableOpacity activeOpacity={1} style={customStyle.storel_geotag_btn} onPress={() => { }} >
            <Entypo name='location-pin' size={30} color={'#b4b4b4'} />
          </TouchableOpacity>
        }
      </View>
    </TouchableOpacity>
  );
});

function DistributorList(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 [loaderTitle, setLoaderTitle] = useState();
  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 [storeDistanceinM, setStoreDistanceinM] = useState(0);
  const [showAlert, setShowAlert] = useState(false);
  const [checkOutStore, setCheckOutStore] = useState({});
  const [rerenderdata, setrerenderdata] = useState(false);
  let [state, setState] = useState({ storeList: [] });
  const [globalStorelist, setGlobalStorelist] = useState([]);
  const [cancelCheckOutStore, setCancelCheckOutStore] = useState({});
  const [showCancelCIModal, setShowCancelCIModal] = useState(false);
  const [searchedItem, setSearchedItem] = useState('');


  const [CheckOutImage, setCheckOutImage] = useState('');
  const [CheckOutImagePath, setCheckOutImagePath] = useState('');
  const [CheckOutImageModal, setCheckOutImageModal] = useState(false);
  const [CheckOutLoc, setCheckOutLoc] = useState({});
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [showCamera, setShowCamera] = useState(false);
  const [DBCO_GeoFenceEnable, setDBCO_GeoFenceEnable] = useState(false);
  const [DBCO_GeoFenceRadius, setDBCO_GeoFenceRadius] = useState('');


  const [uploadedCount, setUploadedCount] = useState(0);
  const [TotalUpCount, setTotalUpCount] = useState(0);
  const [startUploading, setStartUploading] = useState(false);
  const [UploadingSubText, setUploadingSubText] = useState("");
  const [UploadingText, setUploadingText] = useState("Uploading Data...");
  const [showProgresssBar, setshowProgresssBar] = useState(false);



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

    console.log('props.isDataDownloaded in storelist:', props.isDataDownloaded);

    let CO_GeoFenceEnable = props.DBCO_GeoFenceEnable != null ? props.DBCO_GeoFenceEnable : false;
    let CO_GeoFenceRadius = props.DBCO_GeoFenceRadius != null ? props.DBCO_GeoFenceRadius : '';
    setDBCO_GeoFenceEnable(CO_GeoFenceEnable);
    setDBCO_GeoFenceRadius(CO_GeoFenceRadius);

    getData();

    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

    const unsubscribeFocus = props.navigation.addListener('focus', () => {
      checkLocalData();
    });

    return function cleanup() {
      unsubscribeFocus();
      return unsubscribe;
    };
  }, []);

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

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



  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);
            setStoreDistanceinM(distance);

            if (props.DBCI_GeoFenceEnable == true && distance > props.DBCI_GeoFenceRadius) {
              setShowDistanceModal(true);
            }
            else {
              props.navigation.navigate('DistributorCheckIn', { storeData: currentStore });
            }
          },
          (error) => {
            notify(ST.Cannotgetuserposition);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else {
        notify(ST.Pleaseallowlocationpermission);
      }
    }
    else {
      notify(ST.Storelocationnotavailable);
    }

  }


  async function getData() {
    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 myDistributorsListQ = await Q_getMyDistributorList(props);
    console.log('myDistributorsListQ:', myDistributorsListQ);

    let checkInData = await checkIfCheckInAvlbl();
    console.log('checkInData', checkInData);
    if (checkInData != null && checkInData.DistributorId != null && checkInData.IsCheckInAvlbl == 0) {
      await restoreCheckIn(checkInData);
    }

    checkLocalData();
  }



  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 myDistributorsListQ = await Q_getMyDistributorList(props);
    console.log('myDistributorsListQ:', myDistributorsListQ);


    await db.transaction(async function (txn) {
      await txn.executeSql(myDistributorsListQ, [], async function (txn2, txnres2) {
        console.log('distr:', txnres2.rows.length);
        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, MenuCount, MenuDoneCount, StoreName } = sdata;

            if (InTime != null && InTime != "" && InTime != "00:00:00") {
              sdata.CheckInTime = InTime;
            } else {
              let time = sdata.CheckInTime != null && sdata.CheckInTime != '' ? moment(sdata.CheckInTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : '';
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(sdata.CheckOutTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : ''; //new Date(sdata.CheckOutTime)
              let In_Time = (time == '' && UploadStatus != '' && UploadStatus != 'N') ? InTime : time;
              sdata.CheckInTime = In_Time;
            }

            if (OutTime != null && OutTime != "" && OutTime != "00:00:00") {
              sdata.CheckOutTime = OutTime;
            } else {
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(sdata.CheckOutTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : ''; //new Date(sdata.CheckOutTime)
              let Out_Time = (time2 == '' && UploadStatus != '' && UploadStatus != 'N' && UploadStatus != 'I') ? OutTime : time2;
              sdata.CheckOutTime = Out_Time;
            }

            // 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 allDone = MenuCount != null && MenuDoneCount != null && MenuCount == MenuDoneCount;
            sdata.allDone = allDone;
            sdata.MenuListLen = MenuCount;
            console.log('MenuCount:', MenuCount);
            storeArr.push(sdata);

            if (i == (txnres2.rows.length - 1)) {
              setState({ storeList: storeArr });
              setGlobalStorelist(storeArr);
              setProcessing(false);
            }
          }
        }
        else {
          setProcessing(false); notify(ST.Nodatafound); setNodataFound(true);
        }
      }, function (Etxn, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Nodatafound); setNodataFound(true); });
    });

  }

  async function checkIfCheckInAvlbl() {
    console.log('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 = `LEFT OUTER JOIN ${AppTables.DISTRIBUTOR_CHECKIN} t2 on t2.DISTRIBUTOR_ID=t1.DistributorId and t2.VISIT_DATE='${d2}' `;
        let q = `Select t1.*,(CASE WHEN t2.DISTRIBUTOR_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl  from Master_Distributor t1 ${join} where t1.UploadStatus='I'`

        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            // show from local
            let data = txnres2.rows.item(0);
            let { DistributorId } = data;
            console.log('data:', data);
            resolve(data);
          }
          else {
            resolve({});
          }
        }, function (Etxn, txnerr) { console.log(txnerr); resolve({}); });

      });

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

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

        let { DistributorId, DMID, Latitude, Longitude, UploadStatus, InTime, OutTime } = item;
        let JcpType = 'Master_Distributor';

        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 storeCheckin data
        let q2 = `delete from ${AppTables.DISTRIBUTOR_CHECKIN} where DISTRIBUTOR_ID='${DistributorId}' and VISIT_DATE='${d2}' `;
        let values2 = ` ('${DistributorId}','${d2}','${Latitude}','${Longitude}','${In_Time}','','${Out_Time}','','','${d2}')`;
        let insert_q2 = ` INSERT INTO ${AppTables.DISTRIBUTOR_CHECKIN}(DISTRIBUTOR_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,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); });

      });

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


  async function getMenuList(storeData1) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = Q_DBMenuList(storeData1);
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];//txnres.rows.raw();   
            // resolve(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 checkAvailability(storeData1, data) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getAvailblQuery(data.ScreenName, storeData1);
        if (q2 != '' && q2 != null) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
            resolve(isAvlbl);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          let isAvlbl = getIfAvlbl(data.ScreenName, {}, 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.ScreenName, storeData1);
        if (q2 != '' && q2 != null && isAvlbl == true) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isDone = await getIfKPIDone(data.ScreenName, 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 (storeData1.allDone == true) {
      setCheckOutStore(storeData1);
      setShowAlert(true);
    }
    else {
      notify(ST.PleasefillallKPI, false);
    }
  }

  function onSaveCancel() {
    setShowAlert(false);
  }




  async function getLocOnCheckout() {
    setShowAlert(false);
    setLoaderTitle(ST.Gettinglocation + '...');
    setProcessing(true);

    Geolocation.getCurrentPosition(
      async (position) => {
        let { latitude, longitude } = position.coords;
        let loc = { lat: latitude, lng: longitude };
        var distance = checkRange(loc.lat, loc.lng, checkOutStore.Latitude, checkOutStore.Longitude);
        console.log('COut distance:', distance);
        setProcessing(false);
        if (DBCO_GeoFenceEnable == true) {
          if (DBCO_GeoFenceRadius != '' && distance > DBCO_GeoFenceRadius) {
            notify('You cannot checkout! You are not within the allowed distance from the distributor ' + DBCO_GeoFenceRadius + ' m')
          } else {
            checkOutAfterLoc(loc);
          }
        }else {
          checkOutAfterLoc(loc);
        }
      },
      (error) => {
        notify(ST.Cannotgetuserposition);
        setProcessing(false);
      },
      { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
    );
  }

  async function checkOutAfterLoc(loc) {
    let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
    if (CheckOut_PhotoReq) {
      setCheckOutLoc(loc);
      setShowAlert(false);
      setCheckOutImageModal(true);
    }
    else {
      UpdateCheckOutStatus(loc);
    }
  }

  async function UpdateCheckOutStatus(loc) {
    setTotalUpCount(0);
    setshowProgresssBar(false);
    setUploadingText(ST.UpdatingCheckoutStatus + '...');
    setStartUploading(true);
    let { StoreId, MID } = checkOutStore;
    let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
    let d = new Date();
    let d2 = moment(d).format('MM/DD/YYYY');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);

    let data1 = {
      "UserId": loginDetails.UserId,
      "DistributorId": StoreId,
      "VisitDate": d2,
      "CheckOutImage": CheckOut_PhotoReq == true ? CheckOutImage : '',
    }

    var data2 = new FormData();
    data2.append('file', {
      uri: CheckOutImagePath,
      type: 'image/jpg',
      name: CheckOutImage,
    });

    data2.append('Foldername', 'DBCoverageImages');
    data2.append('Path', d2);
    const url = props.baseurl + getMethodName(METHODS.DISTRIBUTOR_CHECKOUT);
    const url1 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
    console.log(url, data1);
    await UploadData2(url, data1)
      .then(async (res) => {
        console.log('DB CheckOutSup1:', res, ' --- Data1 :',data1 + "---Error--",res.error);
        if (!res.error) {
          if (res == 1) {
            //Check out completed
            if (CheckOut_PhotoReq) {
              //Upload Image 
              await UploadFormData(url1, data2)
                .then(async (res1) => {
                  console.log('checkout image upload:', res1);
                })
                .catch((err) => {
                  console.log(err);
                });
            }
            let data = { checkout_image: '' };
            const isCheckOutUpdated = await UpdateStoreCheckOut(data);
            if (isCheckOutUpdated == true) {
              let datan = { StoreId: StoreId, UploadStatus: 'C', tbname: 'Master_Distributor' };
              const isUpdated = await UpdateDistributorStatus(props, datan);
              if (isUpdated == true) {
                let outtime = moment(d).format('HH:mm:ss');;
                await UpdateDistributorStatuslocal('C', checkOutStore, false, true, outtime);
                UploadOnCheckOut(loc);
              }else {
                setStartUploading(false);
                notify(ST.Erroroccurwhilecheckout, 'LONG');
              }
            } else {
              setStartUploading(false);
              notify(ST.Erroroccurwhilecheckout, 'LONG');
            }
          }
          else {
            setStartUploading(false);
            notify(ST.Somethingwentwrong, 'SHORT');
          }
        }
        else {
          setStartUploading(false);
          notify(ST.Somethingwentwrong, 'SHORT');
        }
      })
      .catch((err) => {
        console.log('onPage Team error', err);
        notify(ST.Somethingwentwrong, 'SHORT');
        setStartUploading(false);
      });
  }
  async function UpdateDistributorStatuslocal(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 });
      setGlobalStorelist(storeArr);
      setrerenderdata(!rerenderdata);
    }
  }

  async function UpdateUploadCountLocal(upCount) {
    // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
    setUploadedCount(upCount - 1);
  }

  async function UpdateStoreCheckOut(data) {
    let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
    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 q = `UPDATE ${AppTables.DISTRIBUTOR_CHECKIN} SET CHECKOUT_TIME='${now}', CHECKOUT_IMAGE='${CheckOut_PhotoReq ? CheckOutImage : ''}' WHERE DISTRIBUTOR_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 AllStores = await getPJPStoresData('Master_Distributor', [], 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 = MenuList;
            let totalUpC = MenuList.length - 1; // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
            setTotalUpCount(totalUpC);
            setshowProgresssBar(false);
            setUploadingSubText("Uploading Data for Distributor:" + StoreId);
            if (UploadStatus == 'C') {
              let isUploaded_P_Status = await uploadDBStatus(props, data, 'P', JCP_TYPE, loc);
              console.log('isUploaded_P_Status:', isUploaded_P_Status);
              if (isUploaded_P_Status) {
                await UpdateDistributorStatuslocal('P', data);
                setTotalUpCount(totalUpC);
                setshowProgresssBar(true);
                setUploadingText(ST.UploadingData + '...');
                await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc);
              }
              else {
                // Stop processing if all distributors uploaded
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                  notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                }
              }
            }
            else if (UploadStatus == 'D') {
              setTotalUpCount(totalUpC);
              setshowProgresssBar(true);
              setUploadingText(ST.UploadingData + '...');
              //  this never be called if there is no KPI
              let allFilesToUpload = await uploadAll_DBData(props, data, allKPIs, props.UserId, JCP_TYPE, false, loc, UpdateUploadCountLocal);
              if (allFilesToUpload.length > 0) {
                await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc);
              }
              else {
                notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                }
              }
            }
            else if (UploadStatus == 'P') {
              setTotalUpCount(totalUpC);
              setshowProgresssBar(true);
              setUploadingText(ST.UploadingData + '...');
              await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc);
            }
            else if (UploadStatus == 'L') {
              setshowProgresssBar(false);
              setUploadingText(ST.UploadingData + '...');
              let isAllUploaded_S = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
              if (isAllUploaded_S == true) {
                await UpdateDistributorStatuslocal('U', data);
                notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                }
              }
              else {
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                  notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                }
              }
            }
            else {
              console.log("No UploadStatus case found while uploading Distributor");
            }
          }
        }
      });

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

  async function uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc) {
    let { StoreName } = data;
    if (MenuList.length > 0) {
      // Upload data with Images
      let allFilesToUpload = await uploadAll_DBData(props, data, allKPIs, props.UserId, JCP_TYPE, true, loc, UpdateUploadCountLocal);
      console.log('allFilesToUpload:', allFilesToUpload.length);
      await UpdateDistributorStatuslocal('D', data);
      UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc);
    }
    else {
      //  Upload status u if no data exists
      let isAllUploaded_S = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
      if (isAllUploaded_S == true) {
        await UpdateDistributorStatuslocal('U', data);
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
        }
      }
      else {
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
          notify(ST.Erroroccurwhileuploadingdata, 'LONG');
        }
      }
    }
  }

  async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc) {
    let { StoreName } = data;
    if (allFilesToUpload.length > 0) {
      setUploadedCount(0);
      setTotalUpCount(allFilesToUpload.length - 1);
      setshowProgresssBar(true);
      setUploadingText(ST.UploadingImages + '...');
      let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE, loc, UpdateUploadCountLocal);
      if (isAllUploaded == true) {
        await UpdateDistributorStatuslocal('U', data);
        notify(ST.Alldataandimagesuploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
        }
      } else {
        notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
        }
      }
    }
    else {
      let isupdatedU = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
      console.log('on no files found to upload , isupdated::', isupdatedU);
      if (isupdatedU) {
        await UpdateDistributorStatuslocal('U', data);
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
      }
      if (index == AllStores.length - 1) {
        // setProcessing(false);
        setStartUploading(false);
      }
    }
  }



  async function getPJPStoresData(tbname, Stores = [], d2) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join = `INNER JOIN ${AppTables.DISTRIBUTOR_CHECKIN} t2 on t2.DISTRIBUTOR_ID=t1.DistributorId `;
        await txn.executeSql(`Select t1.DMID as MID,t1.EmpId,t1.DistributorId as StoreId,t1.DistributorName as StoreName,t1.DistributorCode as StoreCode,t1.Latitude,t1.Longitude,t1.InTime,t1.OutTime,t1.UploadStatus,t1.GeoTag,'Master_Distributor' as JCP_TYPE,t2.CHECKIN_IMAGE  from ${tbname} t1 ${join} where t2.VISIT_DATE='${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();
    }
  }

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

  async function onVisitCancel() {
    setLoaderTitle(ST.DeletingCheckInData + '...')
    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: 'Master_Distributor' };
            let isUpdated = await UpdateDistributorStatus(props, data);
            if (isUpdated == true) {
              await UpdateDistributorStatuslocal('N', cancelCheckOutStore, true);
              setProcessing(false);
              notify(ST.CheckInRemoved);
            }
            else {
              setProcessing(false);
              notify(ST.CheckInremovedsuccessfullybutcannotupdatestatus);
            }
          }
          else {
            setProcessing(false);
            notify(ST.CheckInremovedsuccessfullybutcannotupdatestatus);
          }
        }
        else {
          setProcessing(false);
          notify(ST.CannotRemoveCheckIn);
        }

      }).catch(err => {
        console.log('onPage Team error', err);
        setProcessing(false);
        notify(ST.CannotRemoveCheckIn);
      });

  }

  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}' `,
      `Delete from ${AppTables.DB_VISICOOLER} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.RETURN_STOCK} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ORDER_SIMPLIFY} where STORE_ID='${StoreId}' `,
      `DELETE FROM ${AppTables.DB_WINDOW_HDR_DATA} WHERE DISTRIBUTOR_ID='${StoreId}'`,
      `DELETE FROM ${AppTables.DBPOSM_HDR_DATA} WHERE DISTRIBUTOR_ID='${StoreId}'`
    ]
    return await Promise.all(
      allQueries.map(async (q, index) => {
        let isDeleted = await executeQuery(q);
        return isDeleted == true;
      })
    ).then((val) => {
        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 {
            if (txnres2.rows.length > 0) {
              let arr = [];//txnres2.rows.raw();
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                arr.push(data);
                if (i == (txnres2.rows.length - 1)) {
                  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 FilterStores(searchedQry) {
    searchedQry = searchedQry.toLowerCase();
    console.log('searchedQry', searchedQry);
    let { storeList } = state;
    let arr = []
    if (searchedQry != null && searchedQry != '') {
      globalStorelist.map((item, index) => {
        let { StoreName, StoreId, StoreCode } = item;
        StoreId = StoreId + '';
        if (StoreName.toLowerCase().includes(searchedQry) || StoreCode.toLowerCase().includes(searchedQry) || StoreId.includes(searchedQry)) {
          arr.push(item);
        }
      });
    }
    else {
      arr = globalStorelist;
    }
    setState({ storeList: arr });
    setrerenderdata(!rerenderdata)
  }

  function _render_StoreVisitModal() {
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={'Distributor 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}>{ST.Yes}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { storeNotVisited() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.No}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  function _render_GeoTagModal() {
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={'You need to geotag distributor'}
        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}>{ST.Cancel}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowGeoTagModal(false); props.navigation.navigate('GeoTag', { storeData: currentStore, 'isDistributor': true }); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )

  }

  function _render_CancelCheckinModal() {
    let storename = cancelCheckOutStore.StoreName || '';
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={ST.DoyoureallywanttoCancelCheckIn}
        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}>{ST.Yourallcheckindatawillbelost}</Text>
        </View>

        <View style={customStyle.storelVisitM_options}>

          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowCancelCIModal(false); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { onVisitCancel() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  async function onDistanceM_OK() {

    if (props.DBCI_GeoFenceEnable) {
      if (storeDistanceinM > props.DBCI_GeoFenceRadius) {
        setShowDistanceModal(false);
        notify(ST.Youcannotcheckin + ' ' + ST.Youarenotwithinthealloweddistancefromthestore + ' ' + props.DBCI_GeoFenceRadius + ' m', 'LONG')
      }
      else {
        setShowDistanceModal(false); props.navigation.navigate('DistributorCheckIn', { storeData: currentStore });
      }
    }
    else {
      setShowDistanceModal(false); props.navigation.navigate('DistributorCheckIn', { storeData: currentStore });
    }
  }


  function closeImageModal() {
    setCheckOutImageModal(false);
  }

  function cancelImage() {
    setCheckOutImage('');
    setCheckOutImagePath('');
    closeImageModal();
  }

  async function openCamera() {
    setShowCamera(true);
  }

  async function getImage(imgdata) {
    let storeData = checkOutStore
    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;
      let filename = storeData.StoreId + '_DBCheckoutImg-' + calculate_tym_date_for_filename + '.jpg';

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'Distributor Name:' + storeData.StoreName + ' | Distributor Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: DB Check Out' + ' | Date:' + calculate_tym_date_over_img;
      setCheckOutImage(filename);

      let imagePath = `${CoverageImagePath}${filename}`;
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          setCheckOutImagePath(uri);
          // 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);
        });
    }
  }


  function _OpenCaptureImage_Modal() {
    const isImageCap = (CheckOutImagePath == '' || CheckOutImagePath == null) ? false : true;
    return (
      <CustomModal
        style={customStyle.nonWCapImgModal}
        title={ST.CheckOutImage}
        message={ST.Pleaseclickselfieinfrontofstore}
        titleStyle={customStyle.nonWCapImgModal_title}
        messageStyle={customStyle.nonWCapImgModal_subtitle}
        showModal={CheckOutImageModal}
      >
        {
          !isImageCap &&
          <View style={customStyle.nonWCapImgModalCon}>
            <TouchableOpacity style={customStyle.nonWCapImgModal_Camera} onPress={() => { openCamera() }}>
              <CameraImg2 width={100} height={100} />
            </TouchableOpacity>
            <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { closeImageModal() }}>
              <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
            </TouchableOpacity>
          </View>
        }
        {
          isImageCap &&
          <View style={customStyle.nonWCapImgModalCon}>
            <View style={customStyle.nonWCapImgModal_ImgWrap}>
              <Image style={[customStyle.nonWCapImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: CheckOutImagePath }} />
            </View>
            <TouchableOpacity style={customStyle.nonWCapImgModal_CameraSmall} onPress={() => { openCamera() }}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
            </TouchableOpacity>
            {showImageSaveOp &&
              <View style={customStyle.nonWCapImgModal_btng}>
                <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                  <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
                </TouchableOpacity>
                <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={() => { closeImageModal(); UpdateCheckOutStatus(CheckOutLoc); }}>
                  <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
                </TouchableOpacity>
              </View>}
            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { closeImageModal() }}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Close}</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}>{ST.Youneedtobeinthestore}</Text>
          <Text style={[customStyle.storeDistanceM_message, customStyle.mb20]}>{ST.toCheckInCheckOut}</Text>
          <Text style={customStyle.storeDistanceM_submessage}>{`${ST.Alloweddistancefromstore}: ${(props.DBCI_GeoFenceEnable == true ? props.DBCI_GeoFenceRadius : '500')} m`}</Text>
          <Text style={customStyle.storeDistanceM_submessage}>{`${ST.Yourdistancefromstore}: ${storeDistance}`}</Text>
          <TouchableOpacity style={customStyle.storeDistanceM_btn} onPress={() => { onDistanceM_OK() }}>
            <Text style={customStyle.storeDistanceM_btnText}>Ok</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )

  }


  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar} />}
      <CustomHeader {...props} showaddstore={true} title={'Distributor List'} />
      {_render_StoreVisitModal()}
      {_render_GeoTagModal()}
      {_render_DistanceModal()}
      {_render_CancelCheckinModal()}
      {_OpenCaptureImage_Modal()}
      {ConfirmSaveAlert(props, showAlert, onSaveCancel, getLocOnCheckout, ST.Doyoureallywanttocheckout)}
      <CustomCamera cameraType={'front'} BottomText={'Distributor Name:' + checkOutStore.StoreName + ' | Distributor Id:' + checkOutStore.StoreId + ' | User Id:' + checkOutStore.EmpId + ' | Image Type: DB Check Out'} 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}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          <View style={[customStyle.storelist_parentwrap]}>
            <HeaderTabs {...props} isDBPOSMScreen={true} />
            <View style={customStyle.storel_searchbar}>
              <TextInput
                style={[customStyle.storel_searchInput]}
                placeholder={ST.Searchby + ` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
                autoComplete='off'
                placeholderTextColor={PageTheme.$placeholder_color}
                value={searchedItem}
                onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
              </TouchableOpacity>
            </View>

            {nodataFound &&
              <View style={customStyle.noDataCon}>
                <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
              </View>
            }
            {(props.isDataDownloaded == true && !nodataFound) &&
              <View style={customStyle.storel_Con}>
                <FlatList
                  data={state.storeList}
                  extraData={rerenderdata}
                  style={customStyle.listcon}
                  initialNumToRender={4}
                  contentContainerStyle={customStyle.iteml_con}
                  renderItem={({ item, index, separators }) => {
                    return (
                      <DistributorItem  {...props} item={item} index={index} isAdhocScreen={isAdhocScreen} setShowStoreVisitModal={setShowStoreVisitModal} setCurrentStore={setCurrentStore} onCheckOut={onCheckOut} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing} setShowCancelCIModal={setShowCancelCIModal} setCancelCheckOutStore={setCancelCheckOutStore} />
                    );
                  }}
                />
              </View>
            }
          </View>
        </View>
      </LinearGradient>
    </Container>
  );
}



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