import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme, WP, HP } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Pressable, Platform, PermissionsAndroid, Modal, Alert, Dimensions, LogBox, StyleSheet } 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, DownloadData, getDownloadJson1, fetchProjectConfig, UpdateStoreStatus, getKPIS, getAttendNonWorkingRsns, getProjectInfo, UploadData2, UploadFormData, getIf_UserIsManager, UploadData, get_rowColSettings } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, resumeurl, common_ImagePath } from '../constants/constants';
import SplashScreen from 'react-native-splash-screen';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import DownloadDataModal from '../components/downloadDataModal';
import DrawerHeader from '../components/drawerHeader';
import LinearGradient from 'react-native-linear-gradient';
import { getDownloadDataTask, getPostData } from '../components/downloadTasks';
import { getMethodName, METHODS } from '../constants/methodNames';
import { getImagePOSTData, uploadAllData, uploadAllImages, uploadAllVisitors, uploadStoreStatus } from '../constants/uploadData';
import { AppTables } from '../constants/tableConstants';
import Svg, { SvgUri, SvgXml } from 'react-native-svg';
import * as RNFS from 'react-native-fs';
import { Q_MenuList } from '../constants/ConstantQueries';
import kwaza_image from '../assets/performics/kwaza.png';
import store_planned from '../assets/performics/Planned.svg';
import store_covered from '../assets/performics/Covered.svg';
import { Directions, FlatList } from 'react-native-gesture-handler';
import { logout } from '../components/logout';
import Carousel, { Pagination } from 'react-native-snap-carousel';
import { FontAwesome, MaterialCommunityIcons, AntDesign, Entypo, EvilIcons } from '../components/icons';
import CustomModal from '../components/CustomModal';
import { Feather } from '../components/icons';
import { ProgressChart } from 'react-native-chart-kit';
import cross_icon from '../assets/icons/crossmodal.svg';

// webview survey
import { useIsFocused } from "@react-navigation/native";

function NoticeBoard(props) {

  const { width: screenWidth, height: screenHeight } = Dimensions.get('window')

  const cardPadding = 15
  const totalPadding = 15 * 3 // left-side, in-between, right-side
  const imageWidth = (screenWidth - totalPadding) / 2
  const imageHeight = 250


  const route = useRoute();

  const ST = props.StaticText || {};
  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const globalStyle = globalStyles(props.DarkMode, route.name);


  const [state, setState] = useState({ webviewurl: '' });
  const [processing, setProcessing] = useState(true);
  const [loaderTitle, setLoaderTitle] = useState();

  // download data state
  const [isDataDownloaded, setisDataDownloaded] = useState(false);
  const [isDataUploaded, setisDataUploaded] = useState(false);


  const [TaskResponse, setTaskResponse] = useState([]);

  const [downloadingText, setDownloadingText] = useState('');
  const [dowloadedCount, setDowloadedCount] = useState(-1);
  const [totalCount, setTotalCount] = useState(0);
  const [AllTableQueries, setAllTableQueries] = useState([]);
  const [IsPJPMandatory, setIsPJPMandatory] = useState(true);

  const [DErrorMsg, setDErrorMsg] = useState({});
  const [showDErrAlert, setshowDErrAlert] = useState(false);


  const projectCode = props.projectCode;
  const [activeSlide, setActiveSlide] = useState(0);

  const imageSlider = useRef(null);
  const [nodataFound, setNodataFound] = useState(false);
  const [EmployeesList, setEmployeesList] = useState([]);
  const [globalEmplist, setGlobalEmplist] = useState([]);
  const [planned, setPlanned] = useState(0);
  const [covered, setCovered] = useState(0);
  const [merchandised, setmerchandised] = useState(0);
  const [bannerdetail, setBannerDetail] = useState([]);
  const [DownloadTasks, setDownloadTasks] = useState([]);
  const GMUploadedCountref = useRef(0);
  const IAUploadedCountref = useRef(0);

  const [AppDashReportsSec, setAppDashReportsSec] = useState([]);

  const [modaldata, setModalData] = useState({ colname: '', colValue: '', 'row': {}, item: {} });

  // modal 
  const [modalVisible, setModalVisible] = useState(false);
  const toggleModal = (colname, colValue, row, item) => {
    setModalVisible(!modalVisible);
    setModalData({ colname: colname, colValue: colValue, row: row, item: item })
  };


  //add noticeboard data

  const SUP_StorewisePJP = props.SUP_StorewisePJP

  const DATA = [
    {
      text: 'Download Data',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <AntDesign name={'clouddownloado'} color={PageTheme.$primary_color} size={24} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { AskForDownload() }

    },
    {
      text: 'Attendance',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <FontAwesome name={'user-o'} color={PageTheme.$primary_color} size={24} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { props.navigation.navigate('Attendance'); }
    },


    {
      text: 'Daily Route Map',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <AntDesign name={'fork'} color={PageTheme.$primary_color} size={20} />
          </View>
        )
      },
      iconType: 'Icon',
      // props.route.params? props.route.params:{}
      // ==true && 
      itemOnPress: () => { gotoStore() }
    },
    {
      text: 'Grooming Images',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <Image source={require('../assets/icons/audit/grooming.png')} style={{ height: 32, width: 32, resizeMode: 'contain' }} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { props.navigation.navigate('GroomingPictures'); }

    },
    {
      text: 'Reports',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <MaterialCommunityIcons name={'file-document-outline'} color={PageTheme.$primary_color} size={24} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { props.navigation.navigate('ReportsMenu'); }

    },
    {
      text: 'Upload Data',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <AntDesign name={'clouduploado'} color={PageTheme.$primary_color} size={24} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { AskForUpload() }

    },

    {
      text: 'Exit',
      icon: () => {
        return (
          <View style={{ backgroundColor: '#fff', height: 45, width: 45, borderRadius: 50, padding: 10, alignItems: 'center', justifyContent: 'center' }}>
            <MaterialCommunityIcons name={'exit-to-app'} color={PageTheme.$primary_color} size={24} />
          </View>
        )
      },
      iconType: 'Icon',
      itemOnPress: () => { logout(props) }

    },
  ];



  const images = [
    {
      urlImage: kwaza_image,
      descImage: "https://www.shutterstock.com/image-photo/panorama-beautiful-countryside-romania-sunny-600w-1302294157.jpg"
    },
    {
      urlImage: kwaza_image,
      descImage: "https://www.shutterstock.com/image-photo/panorama-beautiful-countryside-romania-sunny-600w-1302294157.jpg"
    },
  ];


  const storeperformancetext = [
    {
      text: 'Store Visited',
      icon: store_planned,
      value: planned,
    },
    {
      text: 'Store Executed',
      icon: store_covered,
      value: covered,
    },

  ];



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

    const item = props;
    dashboardview();
    getdashboardData();

    const willFocusSubscription = props.navigation.addListener('focus', () => {

      getdashboardData();
    });

    return willFocusSubscription;
  }, []);



  // useEffect(() => {
  //   if(props.startDownload==true){
  //     beforeExecuteTasks();
  //     startDownload();
  //   }
  // }, [props.startDownload]);
  useEffect(() => {
    console.log('on props.startDownload change:', props.startDownload);
    if (props.startDownload == true) {
      beforeExecuteTasks();
    }
  }, [props.startDownload]);

  useEffect(() => {
    console.log('on totalCount change:', totalCount, props.startDownload);
    if (props.startDownload == true) {
      startDownload();
    }
  }, [totalCount]);

  useEffect(() => {
    if (props.startUpload == true) {
      startUpload();
    }
  }, [props.startUpload]);



  useEffect(() => {

    if (props.startDownload && TaskResponse != null) {
      console.log('increment dowloadedCount changed');
      let count = dowloadedCount + 1;
      setDowloadedCount(count);
    }
  }, [TaskResponse]);


  useEffect(() => {
    console.log | ("dowloadedCount on change:", dowloadedCount, totalCount)
    if (dowloadedCount >= 0 && dowloadedCount <= totalCount) {
      // dowloadAllData();
      executeTasks();
    }
    else {
      props.set_startDownload({ startDownload: false });
      notify(ST.DataDownloaded, 'SHORT');
    }
  }, [dowloadedCount]);

  async function gotoStore() {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    console.log("loginDetails--------", loginDetails)
    let userIsManager = await getIf_UserIsManager(props);
    // let storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
    const { StorewisePJP: storewisePjp } = await fetchProjectConfig(props.ManagerAppConfig);
    console.log("userIsManager", userIsManager)

    console.log("storewisePjpGotoStore>>:", storewisePjp);

    if (storewisePjp == true) {
      props.navigation.navigate('StoreList', { showSearchWiseStore: true })
    }
    else {
      if (loginDetails?.Designation != "Supervisor") {
        props.navigation.navigate('TeamList');
      }
      else if (loginDetails?.Designation == "Supervisor") {
        storewisePjp == true ? props.navigation.navigate('StoreList') : props.navigation.navigate('TeamList');
      } else {
        props.navigation.navigate('StoreList', { showSearchWiseStore: true });
      }

    }

  }

  async function checkData() {
    let projectInfo = await get_item('projectInfo');
    let projectCode = await get_item('projectCode');
    let projectDetails = JSON.parse(projectInfo);
    let isPJPMand = projectDetails.PJPMandatory != null ? projectDetails.PJPMandatory : true;
    setIsPJPMandatory(isPJPMand);

    if (props.baseurl == '' || props.baseurl == null || props.baseurl == undefined) {

      //set project info in global redux state
      let imgurl = projectDetails.imageUploadURL != null ? projectDetails.imageUploadURL + '/' : '';
      const pdata = getProjectInfo(res, projectid);
      // const pdata={pid:projectCode,pname:projectDetails.projectName,pcode:projectCode,alldata:projectDetails,baseurl:projectDetails.baseURL,imageUploadUrl:imgurl,GeoFenceEnable:(projectDetails.GeoFenceEnable_checkin!=null && projectDetails.GeoFenceEnable_checkin==1),GeoFenceRadius:(projectDetails.GeoFenceRadius_checkin || 0),GFEnable_checkout:(res.GeoFenceEnable_checkout!=null && res.GeoFenceEnable_checkout==1),GFRadius_checkout:(res.GeoFenceRadius_checkout || 0),CheckOut_PhotoReq:res.PhotoRequired_Checkout };
      props.set_project(pdata);

      // setisDataDownloaded(props.isDataDownloaded);
      // await checkIfData_Downloaded();
    }
  }



  async function dashboardview() {
    // console.log("dashboardview-----call----")
    await checkData();
    await getDTasks();

    downloaddatabanner();
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const todate = new Date();
    const today = moment(todate).format("HH:mm:ss");
    // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
    const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
    // console.log("storewisePjpNoticBoard::", storewisePjp);
    // console.log("storeSearch::", storeSearch);

    const data = { Downloadtype: "Notice_Board", username: loginDetails.UserId, empid: '', storeWisePjp: storewisePjp };
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    await getDownloadJson(url, data)
      .then(async (res) => {

        if (res.Notice_Board) {

          let obj = res.Notice_Board.length > 0 ? res.Notice_Board[0] : {};
          // console.log('noticeBoard: webview',obj.NOTICE_BOARD);    
          setState({ ...state, webviewurl: obj.NOTICE_BOARD });
          setProcessing(false);


          // if(props.ShowBeatPlanList==true){

          // }
          // else{
          let isAlreadyDownl = await checkIfData_Downloaded();
          let params = props.route.params ? props.route.params : {};
          // let isTodayLogin=params.TodayLogin!=null?params.TodayLogin:true;
          let isTodayLogin = props.isTodayLoginExists != null ? props.isTodayLoginExists : true;

          // check for autodownload 
          console.log('check for auto download', isTodayLogin, isAlreadyDownl, props.startDownload);
          if (isAlreadyDownl == false && props.startDownload == false) {//isTodayLogin==false
            await clear_item('storeData');
            console.log('start auto download');
            // start auto download
            props.set_startDownload({ startDownload: true });
          }
          // new
          else {
            // get dashboards reports 
            { }
            getAppDashBReports();
          }
          // }
        }
      })
      .catch((err) => {
        console.log('onPage Login error1', err);
      });

    SplashScreen.hide();
  }

  async function getDTasks() {
    return new Promise(async (resolve, reject) => {
      var DownloadTasks1 = [];
      if (props.DownloadKey != null && props.DownloadKey != '') {
        let prop_dk = JSON.parse(props.DownloadKey);
        console.log('set server d keys');
        let AllDTs = prop_dk['DownloadKey'] || [];

        await new Promise.all(AllDTs.sort((a, b) => {
          if (a.DownloadSequence < b.DownloadSequence) {
            return -1;
          }
          if (a.DownloadSequence > b.DownloadSequence) {
            return 1;
          }
          // a must be equal to b
          return 0;
        })).then((val) => {
          DownloadTasks1 = AllDTs
        });
        // for(let i=0;i<AllDTs1.length;i++){
        //   DownloadTasks1.push(AllDTs1[i]);
        //   if(i==AllDTs1.length-1){
        //     setDownloadTasks(DownloadTasks1);
        //     resolve(true);
        //   }
        // }
        setDownloadTasks(DownloadTasks1);
        resolve(true);

      }
      else {

        DownloadTasks1 = await getDownloadDataTask(props);
        console.log('else all', DownloadTasks1);
        setDownloadTasks(DownloadTasks1);
        resolve(true);
      }

    }).catch((Err) => {
      return false;
      console.log('getDTasks err', Err);
    })

  }

  async function checkIfData_Downloaded() {
    console.log('checkIfData_Downloaded');
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    const isDataStorageCleared = await get_item('DataStorageCleared');
    let dateWiseDataDownload = await get_item('dateWiseDataDownload');
    let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
    let todayDate = moment(new Date()).format('DD/MM/YYYY');
    if (isDataStorageCleared != '1') {

      if (dateWiseDataDownload1[todayDate] != null) {
        let d = dateWiseDataDownload1[todayDate];
        console.log('isdtatdownloaded:', d);
        props.setTodayDataExists(d);
        props.setGlobalData({ isDataDownloaded: d })
        return d;
      }
      else {

        let lods = {};
        lods[todayDate] = false;
        console.log('lods:', lods);
        await set_item('dateWiseDataDownload', JSON.stringify(lods));
        props.setTodayDataExists(false);
        return false;
      }

    }
    else {
      return false;
    }

  }


  // download functionality start
  async function startDownload() {
    console.log("startDownload downloadedCount:", dowloadedCount);
    props.set_startDownload({ startDownload: true });
    setDowloadedCount(0);
  }

  async function beforeExecuteTasks() {
    console.log('beforeExecuteTasks:');
    let clear_data = props.Clear_storage;
    let clearOnInstall = await get_item('clearOnInstall');
    console.log("clear_data :", clear_data, clearOnInstall)
    // if (clear_data == true && clearOnInstall=="true") {
    //   let isCleared=await clearStorage();
    //   console.log("isCleared:",isCleared);
    //   await clear_item("clearOnInstall");
    //   await clear_item('storeData');
    //   console.log('Storage cleared');
    // }

    let ddata = { isDataDownloaded: false };
    await DownloadData(props, ddata).then((res) => {
      console.log('isAllTablesCreates:', res, DownloadTasks.length, totalCount, props.startDownload)
      console.log('DownloadTasks===>', DownloadTasks);

      if (totalCount == (DownloadTasks.length - 1) && totalCount > 0 && props.startDownload == true) {
        startDownload();
      }
      else {
        setTotalCount((DownloadTasks.length - 1));
      }
    });
  }

  // function onNoData(data=[],shouldStop=false,tbname=''){
  //   if(tbname!=''){
  //     db.transaction(function(txn) {
  //       // delete all today data
  //       txn.executeSql(`delete from ${tbname} where 1=1`,[],function(txn1,txnres){
  //         console.log('deleted all data for '+tbname);
  //       },function(txn1,err){
  //         console.log('err:',err);
  //       });                                        
  //     });  
  //   }

  //   if(shouldStop==true){
  //     let msg=ST.Nodatafoundfor+tbname+'';
  //     if(tbname=='Sup_JourneyPlan'){
  //       msg=ST.Youhavenojourneyplanfortoday;
  //     }
  //     notify(msg); 
  //     props.set_startDownload({startDownload:false});
  //   }
  //   else{
  //     setTaskResponse(data); 
  //   } 
  // }

  async function onNoData(data = [], shouldStop = false, tbname = '', res = '') {
    console.log("res on no data:", res);
    if (tbname != '') {
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(`delete from ${tbname} where 1=1`, [], function (txn1, txnres) {
          console.log('deleted all data for ' + tbname);
        }, function (Etxn, err) {
          console.log('err:', err);
        });
      });
    }

    if (shouldStop == true) {
      let msg = '';
      // res should be set only when there is network or other related issue
      if (res == '') {
        msg = ST.Nodatafoundfor + tbname + '';
      }
      else {
        msg = res + " Please ensure you are connected to the internet and retry downloading! ";
      }

      console.log("msg :", msg);

      // set is Data downloaded to false so that no other parts of app can be accessed if data is not downloaded

      // update download status on local async storage
      let dateWiseDataDownload = await get_item('dateWiseDataDownload');
      let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
      let todayDate = moment(new Date()).format('DD/MM/YYYY');
      dateWiseDataDownload1[todayDate] = false;
      set_item('dateWiseDataDownload', JSON.stringify(dateWiseDataDownload1));

      // update downloaed status on redux props
      props.setTodayDataExists(false);
      props.setGlobalData({ isDataDownloaded: false })


      // notify(msg); 
      // show error msg
      let obj = { "ErrorMsg": "!! Error in downloading data !!", "ErrorSubMsg": tbname, "ErrorDetail": msg }
      setDErrorMsg(obj);
      props.set_startDownload({ startDownload: false });
      setDowloadedCount(-1);
      setshowDErrAlert(true);
    }
    else {
      setTaskResponse(data);
    }
  }

  function onTaskError() {
    notify(ST.Cannotdownloaddata);
    props.set_startDownload({ startDownload: false });
  }

  async function executeTasks() {
    console.log("executeTasks");
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    var currentIndex = dowloadedCount;

    console.log('currentIndex:', currentIndex);
    if (currentIndex >= 0) {
      let dk_data = DownloadTasks[currentIndex];
      console.log('dk_data', dk_data);
      let key = dk_data.DownloadKey || '';
      setDownloadingText(key);
      var data = await getPostData(DownloadTasks, currentIndex, props);
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);


      console.log(url, data);
      await getDownloadJson1(url, data)
        .then(async (res) => {
          let isAdded = await updateTaskRes(res, currentIndex, 1);
          console.log("isAdded:", isAdded);
          if (isAdded == true) {
            if (currentIndex == DownloadTasks.length - 1) {
              console.log('last found all downloaded');
              await InsertAttendance()
              onDownloadComplete();
            }
            else {
              console.log('all downloaded but last not found ');
            }

          }
          else {
            console.log('Cannot download all Data');
          }
        })
        .catch(err => {
          console.log('onPage Team error', err);
        });
    }

  }


  async function onDownloadComplete() {
    console.log("onDownloadComplete");
    let dateWiseDataDownload = await get_item('dateWiseDataDownload');
    let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
    let todayDate = moment(new Date()).format('DD/MM/YYYY');
    dateWiseDataDownload1[todayDate] = true;
    set_item('dateWiseDataDownload', JSON.stringify(dateWiseDataDownload1));
    // last download  
    // let ddata={isDataDownloaded:false};
    // await DownloadData(props,ddata).then(()=>{
    // await CreateDirKPIimg();
    // await UploadAllPrevImages();
    setisDataDownloaded(true);
    let count = dowloadedCount + 1;
    props.set_startDownload({ startDownload: false });
    setDowloadedCount(-1);
    props.setTodayDataExists(true);
    props.setGlobalData({ isDataDownloaded: true })
    clear_item('DataStorageCleared');
    setDowloadedCount(count);
    notify(ST.DataDownloaded, 'SHORT');

    // });
  }

  function AskForDownload() {
    Alert.alert(
      "Performics",
      ST.Doyouwanttodownloaddata,
      [
        {
          text: ST.Cancel,
          onPress: () => { },
          style: "cancel"
        },
        { text: ST.OK, onPress: () => { startDownload(); } }
      ],
    );
  }

  function AskForUpload() {
    Alert.alert(
      "Performics",
      ST.Doyouwanttouploaddata,
      [
        {
          text: ST.Cancel,
          onPress: () => { },
          style: "cancel"
        },
        { text: ST.OK, onPress: () => { startUpload(); } }
      ],
    );
  }


  async function downloaddatabanner() {
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);

    // const data={Downloadtype: 'Sup_NoticeBoard',username: loginDetails.UserId,empid: '',token: token,};
    const data = { Downloadtype: "Sup_NoticeBoard", username: loginDetails.UserId, empid: '', };
    console.log('da', data);
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    console.log('res', data)

    //download position data

    await getDownloadJson(url, data)
      .then((res) => {
        if (res.Sup_NoticeBoard) {

          let dataarr = res.Sup_NoticeBoard ? res.Sup_NoticeBoard : [];
          console.log('dataarr banner', dataarr);
          setBannerDetail(dataarr);
          // call education
          setProcessing(false);
        }
      })
      .catch((err) => {
        setProcessing(false);
        notify('Not data downloaded..!', 'SHORT');
        console.log('Position_Master not download data...!', err);
      });





  }

  async function InsertAttendance() {
    const todate = new Date();
    const today = moment(todate).format("MM/DD/YYYY");
    let nonWrkRsns = await getAttendNonWorkingRsns() || [];
    return new Promise((resolve, reject) => {
      db.transaction(function (txn) {
        let q = `DELETE FROM ${AppTables.ATTENDANCE} WHERE EMP_ID='${props.UserId}' and ATTENDANCE_DATE='${today}' `;
        //  remove old data
        txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('old attend deleted');

          let query = "SELECT * FROM Sup_AttendanceStatus"
          txn.executeSql(query, [], async function (txn2, txnres3) {
            if (txnres3.rows.length > 0) {
              for (var i = 0; i < txnres3.rows.length; i++) {
                // let sdata=txnres3.rows.item(i);               
                let sdata3 = txnres3.rows.item(i);
                let ReasonId = sdata3?.ReasonId
                console.log("ReasonId--------", ReasonId, sdata3)
                let selRsn_I = nonWrkRsns.findIndex(i => i.ReasonId == ReasonId);
                if (selRsn_I >= 0) {

                  let selRsn = selRsn_I >= 0 ? nonWrkRsns[selRsn_I] : {};
                  let { EntryAllow, Reason } = selRsn;
                  let values = ` ('${props.UserId}','${today}','${EntryAllow}','','${ReasonId}','${Reason}','','${today}') `;

                  console.log('values:', values);
                  let add_data = `INSERT INTO ${AppTables.ATTENDANCE} (EMP_ID,ATTENDANCE_DATE,ENTRY_ALLOW,REMARK,REASON_ID, REASON,IMAGE1 ,ADDED_DATE) VALUES ${values} `;

                  txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('attend added');
                    props.setAttendanceStatus({ isAttendanceMarked: true, isEntryAllow: (EntryAllow == '1' || EntryAllow == 'true' ? true : false) });
                    resolve(true);
                  }, function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
                }
                else {
                  resolve(false);
                }

              }

            } else {
              resolve(false);
            }

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


        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
      });
    }).catch((err) => {
      console.log(err);
      return false;
    })
  }

  // DOWNLOAD FUNCTIONALITY START
  async function updateTaskRes(res, index, count) {
    const todate = new Date();
    const today = moment(todate).format("MM/DD/YYYY");
    let d2 = today;
    let dk_data = DownloadTasks[index];
    console.log('updateTaskRes', dk_data)
    let key = dk_data != null ? dk_data.DownloadKey : '';
    console.log('key', dk_data)
    let IsMandatory = dk_data.IsMandatory == 'true' || dk_data.IsMandatory == 1 ? true : false;
    console.log("call promise");
    console.log("keys===============>", key)
    return new Promise(async (resolve, reject) => {

      switch (key) {

        case 'Table_Structure_Sup': {
          if (res != null && res.Table_Structure_Sup) {

            const Table_Structure_Sup = res.Table_Structure_Sup;
            setAllTableQueries(Table_Structure_Sup);
            var allstmnts = [];
            if (Table_Structure_Sup.length > 0) {
              for (const i in Table_Structure_Sup) {
                const table = Table_Structure_Sup[i];
                let stmnt = table.SqlText;
                db.transaction(function (txn) {
                  txn.executeSql(stmnt, [], function (txn2, txnres) {
                    if (i == (Table_Structure_Sup.length - 1)) {
                      setTaskResponse(Table_Structure_Sup);
                      resolve(true);
                    }
                  }, function (txn2, txnerr) {
                    console.log('txnerr', txnerr, stmnt);
                    if (i == (Table_Structure_Sup.length - 1)) {
                      resolve(true);
                    }
                  });
                });
              }
            }
            else {
              resolve(false);
            }
          }
          else {
            resolve(false);
          }
          break;
        }

        case 'Sup_SupervisorList': {
          if (res != null && typeof res == 'object' && res.Sup_SupervisorList != null && res.Sup_SupervisorList != '') {
            let data_arr = res.Sup_SupervisorList || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { EmpId, UserId, EmployeeName, VisitDate } = data_obj;
              values.push(` ('${EmpId}', '${UserId}', '${EmployeeName}','${VisitDate}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_SupervisorList(EmpId,UserId,EmployeeName,VisitDate) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_SupervisorList where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_SupervisorList added');
                  // console.log('data_arr',data_arr)
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_SupervisorList'], false, 'Sup_SupervisorList');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_SupervisorList'], true, 'Sup_SupervisorList', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_SupervisorList'], true, 'Sup_SupervisorList', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_TeamList': {
          if (res != null && typeof res == 'object' && res.Sup_TeamList != null && res.Sup_TeamList != '') {
            let data_arr = res.Sup_TeamList || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { EmpId, UserId, EmployeeName, VerticalId, Vertical, VisitDate, TodayPJP } = data_obj;
              values.push(` ('${EmpId}', '${UserId}', '${EmployeeName}', '${VerticalId}', '${Vertical}', '${VisitDate}', '${TodayPJP}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_TeamList(EmpId,UserId,EmployeeName,VerticalId,Vertical,VisitDate,TodayPJP) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_TeamList where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_TeamList added');
                  console.log('data_arr', data_arr)
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_TeamList'], false, 'Sup_TeamList');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_TeamList'], true, 'Sup_TeamList', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_TeamList'], true, 'Sup_TeamList', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_JourneyPlanStorewiseSup': {
          console.log("res:", res);
          if (res != null && typeof res == 'object' && res.Sup_JourneyPlanStorewiseSup != null && res.Sup_JourneyPlanStorewiseSup != '') {
            let data_arr = res.Sup_JourneyPlanStorewiseSup || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, Deviation, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = data_obj;
              StoreName = StoreName.replace(/'/g, '');
              Address = Address.replace(/'/g, '');
              StateName = StateName.replace(/'/g, '');
              CityName = CityName.replace(/'/g, '');
              values.push(` ('${MID}', '${ChannelId}','${StoreId}','${StoreCode}','${EmpId}','${MerchandiserId || 0}', '${VisitDate}','${ChainId}','${ChainName}','${StoreName}', '${Address}','${Location}','${Landmark}','${CityId}', '${CityName}','${StateId}','${StateName}','${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}' , '${Deviation}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}','${OutTime}','${CameraAllow}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_JourneyPlanStorewiseSup(MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId,VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email,Deviation, UploadStatus, GeoTag, GeoFenceRadius,InTime,OutTime,CameraAllow) 
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_JourneyPlanStorewiseSup where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_JourneyPlanStorewiseSup added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1)
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1)
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup'], false, 'Sup_JourneyPlanStorewiseSup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup'], true, 'Sup_JourneyPlanStorewiseSup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup'], true, 'Sup_JourneyPlanStorewiseSup', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_NPNDStore': {
          console.log("res:", res);
          if (res != null && typeof res == 'object' && res.Sup_NPNDStore != null && res.Sup_NPNDStore != '') {
            let data_arr = res.Sup_NPNDStore || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = data_obj;
              StoreName = StoreName.replace(/'/g, '');
              Address = Address.replace(/'/g, '');
              StateName = StateName.replace(/'/g, '');
              CityName = CityName.replace(/'/g, '');
              values.push(` ('${MID}', '${ChannelId}','${StoreId}','${StoreCode}','${EmpId}','${MerchandiserId}', '${VisitDate}','${ChainId}','${ChainName}','${StoreName}', '${Address}','${Location}','${Landmark}','${CityId}', '${CityName}','${StateId}','${StateName}','${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}' , '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}','${OutTime}','${CameraAllow}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_NPNDStore(MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId,VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius,InTime,OutTime,CameraAllow) 
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_NPNDStore where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_NPNDStore added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1)
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1)
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_NPNDStore'], false, 'Sup_NPNDStore');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_NPNDStore'], true, 'Sup_NPNDStore', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_NPNDStore'], true, 'Sup_NPNDStore', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_JourneyPlanStorewiseSup_Adhoc': {
          if (res != null && typeof res == 'object' && res.Sup_JourneyPlanStorewiseSup_Adhoc != null && res.Sup_JourneyPlanStorewiseSup_Adhoc != '') {
            let data_arr = res.Sup_JourneyPlanStorewiseSup_Adhoc || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = data_obj;
              StoreName = StoreName.replace(/'/g, '');
              Address = Address.replace(/'/g, '');
              StateName = StateName.replace(/'/g, '');
              CityName = CityName.replace(/'/g, '');
              values.push(` ('${MID}', '${ChannelId}','${StoreId}','${StoreCode}','${EmpId}', '${MerchandiserId}','${VisitDate}','${ChainId}','${ChainName}','${StoreName}', '${Address}','${Location}','${Landmark}','${CityId}', '${CityName}','${StateId}','${StateName}','${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}','${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}','${OutTime}','${CameraAllow}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_JourneyPlanStorewiseSup_Adhoc(MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId,VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius,InTime,OutTime,CameraAllow) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_JourneyPlanStorewiseSup_Adhoc where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_JourneyPlanStorewiseSup_Adhoc added');
                  setTaskResponse(data_arr);
                  resolve(true);
                },
                  function (Etxn, err) {
                    console.log('err:', err);
                    resolve(true);
                  });
              }, function (Etxn, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup_Adhoc'], false, 'Sup_JourneyPlanStorewiseSup_Adhoc');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup_Adhoc'], true, 'Sup_JourneyPlanStorewiseSup_Adhoc', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_JourneyPlanStorewiseSup_Adhoc'], true, 'Sup_JourneyPlanStorewiseSup_Adhoc', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Menu_Master': {
          if (res != null && typeof res == 'object' && res.Sup_Menu_Master != null && res.Sup_Menu_Master != '') {
            let data_arr = res.Sup_Menu_Master || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { MenuId, MenuName, NormalIcon, TickIcon, GreyIcon, MenuPath, MenuSequence, ScreenName } = data_obj;
              values.push(` ('${MenuId}', '${MenuName}', '${NormalIcon}', '${TickIcon}', '${GreyIcon}', '${MenuPath}', '${MenuSequence}', '${ScreenName}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Menu_Master(MenuId,MenuName,NormalIcon,TickIcon,GreyIcon,MenuPath,MenuSequence,ScreenName) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Menu_Master where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Menu_Master added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Menu_Master'], false, 'Sup_Menu_Master');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Menu_Master'], true, 'Sup_Menu_Master', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Menu_Master'], true, 'Sup_Menu_Master', res);
            resolve(false);
          }
          break;
        }

        case 'Mapping_MenuSup': {
          if (res != null && typeof res == 'object' && res.Mapping_MenuSup != null && res.Mapping_MenuSup != '') {
            let data_arr = res.Mapping_MenuSup || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { MenuId, VisitType } = data_obj;
              values.push(` ('${MenuId}','${VisitType}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Mapping_MenuSup(MenuId,VisitType) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Mapping_MenuSup where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Mapping_MenuSup added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_MenuSup'], false, 'Mapping_MenuSup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_MenuSup'], true, 'Mapping_MenuSup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_MenuSup'], true, 'Mapping_MenuSup', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_ImageType': {
          if (res != null && typeof res == 'object' && res.Sup_ImageType != null && res.Sup_ImageType != '') {
            let data_arr = res.Sup_ImageType || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { ImageTypeId, ImageType } = data_obj;
              values.push(` ('${ImageTypeId}','${ImageType}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_ImageType(ImageTypeId, ImageType)
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_ImageType where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_ImageType added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1);
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1);
                resolve(true);
              });
            });
          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_ImageType'], false, 'Sup_ImageType');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_ImageType'], true, 'Sup_ImageType', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_ImageType'], true, 'Sup_ImageType', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_ActivationType': {
          if (res != null && typeof res == 'object' && res.Sup_Master_ActivationType != null && res.Sup_Master_ActivationType != '') {
            let data_arr = res.Sup_Master_ActivationType || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { ActivationTypeId, ActivationType, ShowContactFlag } = data_obj;
              values.push(` ('${ActivationTypeId}','${ActivationType}','${ShowContactFlag}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_ActivationType(ActivationTypeId, ActivationType,ShowContactFlag)
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_Master_ActivationType where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_ActivationType added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1);
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_ActivationType'], false, 'Sup_Master_ActivationType');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_ActivationType'], true, 'Sup_Master_ActivationType', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_ActivationType'], true, 'Sup_Master_ActivationType', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_SkuSize': {
          if (res != null && typeof res == 'object' && res.Sup_Master_SkuSize != null && res.Sup_Master_SkuSize != '') {
            let data_arr = res.Sup_Master_SkuSize || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { SkuSize } = data_obj;
              values.push(` ('${SkuSize}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_SkuSize(SkuSize)
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_Master_SkuSize where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_SkuSize added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1);
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_SkuSize'], false, 'Sup_Master_SkuSize');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_SkuSize'], true, 'Sup_Master_SkuSize', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_SkuSize'], true, 'Sup_Master_SkuSize', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_ProductFlavour': {
          if (res.Sup_Master_ProductFlavour) {
            let data_arr = res.Sup_Master_ProductFlavour || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { ProductFlavour } = data_obj;
              values.push(` ('${ProductFlavour}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_ProductFlavour(ProductFlavour)
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_Master_ProductFlavour where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_ProductFlavour added');
                  setTaskResponse(data_arr);
                }, function (txn1, txnerr1) { console.log(txnerr1) });
              }, function (txn1, txnerr1) { console.log(txnerr1) });
            });

          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            // console.log('No data found');
            onNoData(['No data for Sup_Master_ProductFlavour'], false, 'Sup_Master_ProductFlavour');
          }
          else { onNoData(['No data for Sup_Master_ProductFlavour']); }
          break;
        }

        case 'Sup_Master_ProductPack': {
          if (res != null && typeof res == 'object' && res.Sup_Master_ProductPack != null && res.Sup_Master_ProductPack != '') {
            let data_arr = res.Sup_Master_ProductPack || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { PackName } = data_obj;
              values.push(` ('${PackName}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_ProductPack(PackName)
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_Master_ProductPack where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_ProductPack added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1);
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_ProductPack'], false, 'Sup_Master_ProductPack');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_ProductPack'], true, 'Sup_Master_ProductPack', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_ProductPack'], true, 'Sup_Master_ProductPack', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_JourneyPlan': {

          if (res != null && typeof res == 'object' && res.Sup_JourneyPlan != null && res.Sup_JourneyPlan != '') {
            let data_arr = res.Sup_JourneyPlan || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = data_obj;
              values.push(` ('${MID}', '${ChannelId}', '${StoreId}', '${StoreCode}', '${EmpId}', '${MerchandiserId}', '${VisitDate}', '${ChainId}', '${ChainName}', '${StoreName}', '${Address}', '${Location}', '${Landmark}', '${CityId}', '${CityName}', '${StateId}', '${StateName}', '${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}', '${OutTime}', '${CameraAllow}')`);
            });

            var all_vals = values.join(',');

            var sql_stmnt = `INSERT INTO Sup_JourneyPlan(MID,ChannelId,StoreId,StoreCode,EmpId,MerchandiserId,VisitDate,ChainId,ChainName,StoreName,Address,Location,Landmark,CityId,CityName,StateId,StateName,RegionId,StoreTypeId,StoreType,Pincode,Latitude,Longitude,Phone,Mobile,ContactPerson,Email,UploadStatus,GeoTag,GeoFenceRadius,InTime,OutTime,CameraAllow) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_JourneyPlan where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_JourneyPlan added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_JourneyPlan'], false, 'Sup_JourneyPlan');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_JourneyPlan'], true, 'Sup_JourneyPlan', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_JourneyPlan'], true, 'Sup_JourneyPlan', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_AdhocJourneyPlan': {
          if (res != null && typeof res == 'object' && res.Sup_AdhocJourneyPlan != null && res.Sup_AdhocJourneyPlan != '') {
            let data_arr = res.Sup_AdhocJourneyPlan || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, ChannelId, StoreId, StoreCode, EmpId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, ExpiryStock, InTime, OutTime } = data_obj;
              values.push(` ('${MID}', '${ChannelId}','${StoreId}','${StoreCode}','${EmpId}', '${VisitDate}','${ChainId}','${ChainName}','${StoreName}', '${Address}','${Location}','${Landmark}','${CityId}', '${CityName}','${StateId}','${StateName}','${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${ExpiryStock}','${InTime}','${OutTime}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_AdhocJourneyPlan(MID, ChannelId, StoreId, StoreCode, EmpId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, ExpiryStock,InTime,OutTime) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_AdhocJourneyPlan where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_AdhocJourneyPlan added');
                  setTaskResponse(data_arr);
                  resolve(true);
                },
                  function (txn1, err) {
                    console.log('err:', err);
                    resolve(true);
                  });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_AdhocJourneyPlan'], false, 'Sup_AdhocJourneyPlan');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_AdhocJourneyPlan'], true, 'Sup_AdhocJourneyPlan', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_AdhocJourneyPlan'], true, 'Sup_AdhocJourneyPlan', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_MasterDistributor': {

          if (res != null && typeof res == 'object' && res.Sup_MasterDistributor != null && res.Sup_MasterDistributor != '') {
            let data_arr = res.Sup_MasterDistributor || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { DMID, EmpId, DistributorId, DistributorName, DistributorCode, Latitude, Longitude, InTime, OutTime, UploadStatus, GeoTag } = data_obj;
              values.push(` ('${DMID}', '${EmpId}', '${DistributorId}', '${DistributorName}', '${DistributorCode}', '${Latitude}','${InTime}', '${OutTime}', '${Longitude}','${UploadStatus}', '${GeoTag}')`);
            });

            var all_vals = values.join(',');

            var sql_stmnt = `INSERT INTO Sup_MasterDistributor(DMID,EmpId,DistributorId,DistributorName,DistributorCode,Latitude,InTime,OutTime,Longitude,UploadStatus,GeoTag) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_MasterDistributor where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_MasterDistributor added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_MasterDistributor'], false, 'Sup_MasterDistributor');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_MasterDistributor'], true, 'Sup_MasterDistributor', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_MasterDistributor'], true, 'Sup_MasterDistributor', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Non_Working_ReasonDistributor': {

          if (res != null && typeof res == 'object' && res.Sup_Non_Working_ReasonDistributor != null && res.Sup_Non_Working_ReasonDistributor != '') {
            let data_arr = res.Sup_Non_Working_ReasonDistributor || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { ReasonId, Reason, EntryAllow, ImageAllow } = data_obj;
              values.push(` ('${ReasonId}', '${Reason}', '${EntryAllow}', '${ImageAllow}')`);
            });

            var all_vals = values.join(',');

            var sql_stmnt = `INSERT INTO Sup_Non_Working_ReasonDistributor(ReasonId,Reason,EntryAllow,ImageAllow) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Non_Working_ReasonDistributor where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Non_Working_ReasonDistributor added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Non_Working_ReasonDistributor'], false, 'Sup_Non_Working_ReasonDistributor');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Non_Working_ReasonDistributor'], true, 'Sup_Non_Working_ReasonDistributor', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Non_Working_ReasonDistributor'], true, 'Sup_Non_Working_ReasonDistributor', res);
            resolve(false);
          }
          break;
        }

        case 'Mapping_MenuDistributorPointSup': {

          if (res != null && typeof res == 'object' && res.Mapping_MenuDistributorPointSup != null && res.Mapping_MenuDistributorPointSup != '') {
            let data_arr = res.Mapping_MenuDistributorPointSup || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { MenuId } = data_obj;
              values.push(` ('${MenuId}')`);
            });

            var all_vals = values.join(',');

            var sql_stmnt = `INSERT INTO Mapping_MenuDistributorPointSup(MenuId) 
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Mapping_MenuDistributorPointSup where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Mapping_MenuDistributorPointSup added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, err) {
                  console.log('err:', err);
                  resolve(true);
                });
              }, function (txn1, err) {
                console.log('err:', err);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], false, 'Mapping_MenuDistributorPointSup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], true, 'Mapping_MenuDistributorPointSup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], true, 'Mapping_MenuDistributorPointSup', res);
            resolve(false);
          }
          break;
        }

        case 'Mapping_MenuDistributorPointSup': {
          if (res != null && typeof res == 'object' && res.Mapping_MenuDistributorPointSup != null && res.Mapping_MenuDistributorPointSup != '') {
            let data_arr = res.Mapping_MenuDistributorPointSup || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MenuId } = data_obj;
              values.push(` ('${MenuId}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Mapping_MenuDistributorPointSup(MenuId)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Mapping_MenuDistributorPointSup where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Mapping_MenuDistributorPointSup added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], false, 'Mapping_MenuDistributorPointSup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], true, 'Mapping_MenuDistributorPointSup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_MenuDistributorPointSup'], true, 'Mapping_MenuDistributorPointSup', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Distributor_PreviousVisicooler': {
          if (res != null && typeof res == 'object' && res.Sup_Distributor_PreviousVisicooler != null && res.Sup_Distributor_PreviousVisicooler != '') {
            let data_arr = res.Sup_Distributor_PreviousVisicooler || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { DistributorId, VisitDate, VC_QRCode, VC_AssetCode } = data_obj;
              values.push(` ('${DistributorId}','${VisitDate}','${VC_QRCode}','${VC_AssetCode}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Distributor_PreviousVisicooler(DistributorId,VisitDate,VC_QRCode,VC_AssetCode)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Distributor_PreviousVisicooler where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Distributor_PreviousVisicooler added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Distributor_PreviousVisicooler'], false, 'Sup_Distributor_PreviousVisicooler');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Distributor_PreviousVisicooler'], true, 'Sup_Distributor_PreviousVisicooler', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Distributor_PreviousVisicooler'], true, 'Sup_Distributor_PreviousVisicooler', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Product_Master': {
          if (res != null && typeof res == 'object' && res.Sup_Product_Master != null && res.Sup_Product_Master != '') {
            let data_arr = res.Sup_Product_Master || [];
            var values = [];
            data_arr.map((data_obj, index) => {
              let { ProductId, ProductCode, ProductName, Mrp, BrandId, BrandName, SubCategoryId, SubCategoryName, CategoryId, CategoryName, CompanyId, ProductSequence, BrandSequence, SubCategorySequence, CategorySequence, IsCompetitor } = data_obj;
              values.push(` ('${ProductId}', '${ProductCode}','${ProductName}','${Mrp}','${BrandId}', '${BrandName}','${SubCategoryId}','${SubCategoryName}','${CategoryId}', '${CategoryName}','${CompanyId}','${ProductSequence}','${BrandSequence}', '${SubCategorySequence}','${CategorySequence}','${(IsCompetitor == true ? 1 : 0)}')`);

            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Product_Master(ProductId, ProductCode, ProductName, Mrp, BrandId, BrandName, SubCategoryId, SubCategoryName, CategoryId, CategoryName, CompanyId, ProductSequence, BrandSequence, SubCategorySequence, CategorySequence,IsCompetitor)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Product_Master where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Product_Master added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Product_Master'], false, 'Sup_Product_Master');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Product_Master'], true, 'Sup_Product_Master', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Product_Master'], true, 'Sup_Product_Master', res);
            resolve(false);
          }
          break;
        }


        case 'Sup_NonWorkingReason': {
          if (res != null && typeof res == 'object' && res.Sup_NonWorkingReason != null && res.Sup_NonWorkingReason != '') {
            let data_arr = res.Sup_NonWorkingReason || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { ReasonId, Reason, EntryAllow, ImageAllow, GPSMandatory, ShowAttendance, ShowStore } = data_obj;
              values.push(` ('${ReasonId}', '${Reason}', '${(EntryAllow == true ? 1 : 0)}', '${(ImageAllow == true ? 1 : 0)}', '${(GPSMandatory == true ? 1 : 0)}', '${(ShowAttendance == true ? 1 : 0)}', '${(ShowStore == true ? 1 : 0)}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_NonWorkingReason(ReasonId,Reason,EntryAllow,ImageAllow,GPSMandatory,ShowAttendance,ShowStore)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_NonWorkingReason where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_NonWorkingReason added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_NonWorkingReason'], false, 'Sup_NonWorkingReason');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_NonWorkingReason'], true, 'Sup_NonWorkingReason', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_NonWorkingReason'], true, 'Sup_NonWorkingReason', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_Competitor': {
          if (res != null && typeof res == 'object' && res.Sup_Master_Competitor != null && res.Sup_Master_Competitor != '') {
            let data_arr = res.Sup_Master_Competitor || [];
            console.log('data_arr', data_arr)
            var values = [];
            data_arr.map((data_obj) => {
              let { CompanyId, Company, CategoryId, CategoryName, SubCategoryId, SubCategoryName, BrandId, BrandName, SubBrandId, SubBrandName, ProductId, ProductName } = data_obj;
              values.push(` ('${CompanyId}', '${Company}', '${CategoryId}' , '${CategoryName}', '${SubCategoryId}', '${SubCategoryName}', '${BrandId}', '${BrandName}', '${SubBrandId}', '${SubBrandName}', '${ProductId}', '${ProductName}')`);
            });

            var all_vals = values.join(',');
            console.log('')
            var sql_stmnt = `INSERT INTO Sup_Master_Competitor(CompanyId, Company, CategoryId, CategoryName, SubCategoryId, SubCategoryName, BrandId, BrandName,SubBrandId, SubBrandName, ProductId, ProductName)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_Competitor where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_Competitor added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_Competitor'], false, 'Sup_Master_Competitor');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_Competitor'], true, 'Sup_Master_Competitor', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_Competitor'], true, 'Sup_Master_Competitor', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_Display': {
          if (res != null && typeof res == 'object' && res.Sup_Master_Display != null && res.Sup_Master_Display != '') {
            let data_arr = res.Sup_Master_Display || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { DisplayId, DisplayName, RefImage } = data_obj;
              values.push(` ('${DisplayId}', '${DisplayName}', '${RefImage}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_Display(DisplayId, DisplayName, RefImage)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_Display where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_Display added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_Display'], false, 'Sup_Master_Display');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_Display'], true, 'Sup_Master_Display', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_Display'], true, 'Sup_Master_Display', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_AttendanceStatus': {
          if (res != null && typeof res == 'object' && res.Sup_AttendanceStatus != null && res.Sup_AttendanceStatus != '') {
            let data_arr = res.Sup_AttendanceStatus || [];
            console.log('data_arr', data_arr)
            var values = [], RsnId = '';
            data_arr.map((data_obj) => {

              let { ReasonId } = data_obj;
              RsnId = ReasonId;
              values.push(` ('${ReasonId}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_AttendanceStatus(ReasonId)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_AttendanceStatus where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], async function (txn1, txnres) {
                  console.log('Sup_AttendanceStatus added');
                  // let isInserted=await InsertAttendance(RsnId);
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_AttendanceStatus'], false, 'Sup_AttendanceStatus');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_AttendanceStatus'], true, 'Sup_AttendanceStatus', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_AttendanceStatus'], true, 'Sup_AttendanceStatus', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_MenuReports': {
          if (res != null && typeof res == 'object' && res.Sup_Master_MenuReports != null && res.Sup_Master_MenuReports != '') {
            let data_arr = res.Sup_Master_MenuReports || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { ReportId, ReportName, ReportType, DownloadKey, ColumnConfig } = data_obj;
              values.push(` ('${ReportId}', '${ReportName}', '${ReportType}','${DownloadKey}','${ColumnConfig}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_MenuReports(ReportId,ReportName,ReportType,DownloadKey,ColumnConfig)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_MenuReports where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_MenuReports added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_MenuReports'], false, 'Sup_Master_MenuReports');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_MenuReports'], true, 'Sup_Master_MenuReports', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_MenuReports'], true, 'Sup_Master_MenuReports', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_PromoType': {
          if (res != null && typeof res == 'object' && res.Sup_Master_PromoType != null && res.Sup_Master_PromoType != '') {
            let data_arr = res.Sup_Master_PromoType || [];

            var values = [];
            data_arr.map((data_obj) => {
              let { PromoTypeId, PromoType } = data_obj;
              values.push(` ('${PromoTypeId}','${PromoType}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_PromoType(PromoTypeId,PromoType)
            values ${all_vals}`;
            console.log('sql_stmnt', sql_stmnt)
            console.log('values', values)

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_PromoType where 1=1`, [], function (txn1, txnres) {
                console.log('txnres', txnres)                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_PromoType added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_PromoType'], false, 'Sup_Master_PromoType');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_PromoType'], true, 'Sup_Master_PromoType', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_PromoType'], true, 'Sup_Master_PromoType', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_SurveyQuestion': {

          if (res != null && typeof res == 'object' && res.Sup_Master_SurveyQuestion != null && res.Sup_Master_SurveyQuestion != '') {
            let data_arr = res.Sup_Master_SurveyQuestion || [];
            console.log('surveys:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { SurveyId, SurveyName, CategoryId, Category, CategorySequence, QuestionId, Question, QuestionType, QuestionImageAllow, QEnable, LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence, AnswerId, Answer, ImageAllow1, ImageAllow2, EnableQuestion, DisableQuestion, AnswerSequence, ShowCat, SubCategoryId, SubCategory, SubCategorySequence, MenuId, QuestionTypeNew, QuestionImageMandatory, Image1Mandatory, Image2Mandatory, CalFormula, RefImage, QuestionRefImage } = data_obj;
              values.push(` ('${SurveyId}','${SurveyName}','${CategoryId}','${Category}','${CategorySequence}','${QuestionId}','${Question}','${QuestionType}','${QuestionImageAllow}','${QEnable}','${LengthValidation}','${MinLength}','${MaxLength}','${OTP}','${DateRange}','${QuestionSequence}','${AnswerId}','${Answer}','${ImageAllow1}','${ImageAllow2}','${EnableQuestion}','${DisableQuestion}','${AnswerSequence}','${(ShowCat == true ? 1 : 0)}','${SubCategoryId}','${SubCategory}','${SubCategorySequence}','${MenuId}','${QuestionTypeNew}','${QuestionImageMandatory}','${Image1Mandatory}','${Image2Mandatory}','${CalFormula}','${RefImage}','${QuestionRefImage}')`);
            });

            console.log('sdjh')

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_SurveyQuestion(SurveyId, SurveyName, CategoryId, Category, CategorySequence, QuestionId, Question, QuestionType, QuestionImageAllow, QEnable, LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence, AnswerId, Answer, ImageAllow1, ImageAllow2, EnableQuestion, DisableQuestion, AnswerSequence,ShowCat, SubCategoryId,SubCategory, SubCategorySequence,MenuId,QuestionTypeNew,QuestionImageMandatory,Image1Mandatory,Image2Mandatory,CalFormula,RefImage,QuestionRefImage)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_SurveyQuestion where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_SurveyQuestion added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_SurveyQuestion'], false, 'Sup_Master_SurveyQuestion');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_SurveyQuestion'], true, 'Sup_Master_SurveyQuestion', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_SurveyQuestion'], true, 'Sup_Master_SurveyQuestion', res);
            resolve(false);
          }
          break;
        }

        case 'Mapping_SurveySup': {

          if (res != null && typeof res == 'object' && res.Mapping_SurveySup != null && res.Mapping_SurveySup != '') {
            let data_arr = res.Mapping_SurveySup || [];
            console.log('surveys:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { SurveyId, StoreId } = data_obj;
              values.push(` ('${SurveyId}','${StoreId}')`);
            });

            console.log('sdjh')

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Mapping_SurveySup(SurveyId, StoreId)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Mapping_SurveySup where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Mapping_SurveySup added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_SurveySup'], false, 'Mapping_SurveySup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_SurveySup'], true, 'Mapping_SurveySup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_SurveySup'], true, 'Mapping_SurveySup', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Mapping_VisibilityQuestion': {

          if (res != null && typeof res == 'object' && res.Sup_Mapping_VisibilityQuestion != null && res.Sup_Mapping_VisibilityQuestion!= '') {
            let data_arr = res.Sup_Mapping_VisibilityQuestion || [];
            console.log('Sup_Mapping_VisibilityQuestion:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { VisibilityDefinitionId, VisibilityQuestionId } = data_obj;
              values.push(` ('${VisibilityDefinitionId}','${VisibilityQuestionId}')`);
            });


            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Mapping_VisibilityQuestion(VisibilityDefinitionId, VisibilityQuestionId)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Mapping_VisibilityQuestion where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Mapping_VisibilityQuestion added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], false, 'Sup_Mapping_VisibilityQuestion');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], true, 'Sup_Mapping_VisibilityQuestion', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], true, 'Sup_Mapping_VisibilityQuestion', res);
            resolve(false);
          }
          break;
        }


        case 'Sup_Master_VisibilityStockDefinition': {

          if (res != null && typeof res == 'object' && res.Sup_Master_VisibilityStockDefinition != null && res.Sup_Master_VisibilityStockDefinition!= '') {
            let data_arr = res.Sup_Master_VisibilityStockDefinition || [];
            console.log('Sup_Master_VisibilityStockDefinition:', data_arr.length)
            let values = [];
            data_arr.map((data_obj) => {
              let { VisibilityStockDefinitionId, VisibilityDefinitionId,VisibilityStockTable,VisibilityStockField,VisibilityStockValue,VisibilityStockMBQ,ProductName } = data_obj;
              values.push(` ('${VisibilityStockDefinitionId}',  '${VisibilityDefinitionId}','${VisibilityStockTable}','${VisibilityStockField}','${VisibilityStockValue}','${VisibilityStockMBQ}','${ProductName}')`);
            });


            let all_vals = values.join(',');
            let sql_stmnt = `INSERT INTO Sup_Master_VisibilityStockDefinition(VisibilityStockDefinitionId, VisibilityDefinitionId,VisibilityStockTable,VisibilityStockField,VisibilityStockValue,VisibilityStockMBQ,ProductName)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_VisibilityStockDefinition where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_VisibilityStockDefinition added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], false, 'Sup_Mapping_VisibilityQuestion');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], true, 'Sup_Mapping_VisibilityQuestion', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Mapping_VisibilityQuestion'], true, 'Sup_Mapping_VisibilityQuestion', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_DetailerContent': {
          if (res != null && typeof res == 'object' && res.Sup_Master_DetailerContent != null && res.Sup_Master_DetailerContent != '') {
            let data_arr = res.Sup_Master_DetailerContent || [];
            console.log('data_arr', data_arr)
            var values = [];
            data_arr.map((data_obj) => {
              let { Id, ContentTypeId, ContentType, Topic, Description, MediaType, FilePath, FName, PublishDate, IconPath, Icon, InnerScreenView, InnerScreenConfig, ContentSequence, DownloadKey, ReportView } = data_obj;
              values.push(` ('${Id}','${ContentTypeId}','${ContentType}', '${Topic}', '${Description}', '${MediaType}', '${FilePath}', '${FName}', '${PublishDate}','${IconPath}','${Icon}','${InnerScreenView}','${InnerScreenConfig}','${ContentSequence}','${DownloadKey}','${ReportView}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_DetailerContent(Id,ContentTypeId,ContentType,Topic,Description,MediaType,FilePath,FName,PublishDate, IconPath,Icon,InnerScreenView,InnerScreenConfig,ContentSequence,DownloadKey,ReportView) 
            values ${all_vals}`;
            console.log('sql_stmnt', sql_stmnt)

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_DetailerContent `, [], function (txn1, txnres) {
                // insert or refresh all today dataz

                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_DetailerContent added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_DetailerContent'], false, 'Sup_Master_DetailerContent');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_DetailerContent'], true, 'Sup_Master_DetailerContent', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_DetailerContent'], true, 'Sup_Master_DetailerContent', res);
            resolve(false);
          }
          break;
        }

        case 'Mapping_MenuConfiguration_Sup': {
          if (res != null && typeof res == 'object' && res.Mapping_MenuConfiguration_Sup != null && res.Mapping_MenuConfiguration_Sup != '') {
            let data_arr = res.Mapping_MenuConfiguration_Sup || [];
            console.log('data_arr', data_arr)
            var values = [];
            data_arr.map((data_obj) => {
              let { Id, ScreenName, KPIFieldName, KPIFieldDisplayName, KPIFieldEnable, KPISequence, KPIType, KPIMandatory } = data_obj;
              values.push(` ('${Id}', '${ScreenName}', '${KPIFieldName}', '${KPIFieldDisplayName}', '${KPIFieldEnable}', '${KPISequence}', '${KPIType}', '${KPIMandatory}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Mapping_MenuConfiguration_Sup(Id,ScreenName,KPIFieldName,KPIFieldDisplayName,KPIFieldEnable,KPISequence,KPIType,KPIMandatory) 
            values ${all_vals}`;
            console.log('sql_stmnt', sql_stmnt)

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Mapping_MenuConfiguration_Sup `, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_TeamList added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_MenuConfiguration_Sup'], false, 'Mapping_MenuConfiguration_Sup');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_MenuConfiguration_Sup'], true, 'Mapping_MenuConfiguration_Sup', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_MenuConfiguration_Sup'], true, 'Mapping_MenuConfiguration_Sup', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_VisibilityDefinition': {

          if (res != null && typeof res == 'object' && res.Sup_Master_VisibilityDefinition != null && res.Sup_Master_VisibilityDefinition != '') {
            let data_arr = res.Sup_Master_VisibilityDefinition || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { VisibilityDefinitionId, MenuId, MenuName, VisibilityId, VisibilityName, VisibilityTable, VisibilityField, VisibilityValue, ChildName, VisibilityRefImage, VisibilityElementStockRequired, VisibilityElementCheckAssortment, NoOfSplit, VisibilityImage1, VisibilityImage2, VisibilityImage1Lable, VisibilityImage2Lable, VisibilityNotExistCamera, VisibilityExistReasonEnable, VisibilityNotExistReasonEnable, VisibilityImage1CameraGrid, VisibilityImage2CameraGrid, StockQtyRequired, VisiDefSequence } = data_obj;
              values.push(` ('${VisibilityDefinitionId}','${MenuId}','${MenuName}','${VisibilityId}','${VisibilityName}','${VisibilityTable}','${VisibilityField}','${VisibilityValue}','${ChildName}','${VisibilityRefImage}','${VisibilityElementStockRequired}','${VisibilityElementCheckAssortment}','${NoOfSplit}','${VisibilityImage1}','${VisibilityImage2}','${VisibilityImage1Lable}','${VisibilityImage2Lable}','${VisibilityNotExistCamera}','${VisibilityExistReasonEnable}','${VisibilityNotExistReasonEnable}','${VisibilityImage1CameraGrid}','${VisibilityImage2CameraGrid}','${StockQtyRequired}','${VisiDefSequence}')`);
            });


            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_VisibilityDefinition(VisibilityDefinitionId,MenuId,MenuName,VisibilityId,VisibilityName,VisibilityTable,VisibilityField,VisibilityValue,ChildName,VisibilityRefImage,VisibilityElementStockRequired,VisibilityElementCheckAssortment,NoOfSplit,VisibilityImage1,VisibilityImage2,VisibilityImage1Lable,VisibilityImage2Lable,VisibilityNotExistCamera,VisibilityExistReasonEnable,VisibilityNotExistReasonEnable,VisibilityImage1CameraGrid,VisibilityImage2CameraGrid,StockQtyRequired,VisiDefSequence)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_VisibilityDefinition where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_VisibilityDefinition added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_VisibilityDefinition'], false, 'Sup_Master_VisibilityDefinition');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_VisibilityDefinition'], true, 'Sup_Master_VisibilityDefinition', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_VisibilityDefinition'], true, 'Sup_Master_VisibilityDefinition', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_VisibilityQuestion': {
          if (res != null && typeof res == 'object' && res.Sup_Master_VisibilityQuestion != null && res.Sup_Master_VisibilityQuestion != '') {
            let data_arr = res.Sup_Master_VisibilityQuestion || [];
            console.log('surveys:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { VisibilityQuestionId, VisibilityQuestionCode, VisibilityQuestionName, QuestionType, VQShowCamera, VQCameraMandatory, VQLengthValidationRequired, VQMinimumChar, VQMaximumChar, VQDecimalPoint, VQDateRangeMin, VQDateRangeMax, VQVoiceLengthInMinutes, VQDefaultQuestionEnable, VisibilityQuestionSequence, VisibilityAnswerId, VisibilityAnswerName, VAShowCamera, VACameraMandatory, VAQuestionEnable, VAQuestionDisable, VASequence } = data_obj;
              values.push(` ('${VisibilityQuestionId}','${VisibilityQuestionCode}','${VisibilityQuestionName}','${QuestionType}','${VQShowCamera}','${VQCameraMandatory}','${VQLengthValidationRequired}','${VQMinimumChar}','${VQMaximumChar}','${VQDecimalPoint}','${VQDateRangeMin}','${VQDateRangeMax}','${VQVoiceLengthInMinutes}','${VQDefaultQuestionEnable}','${VisibilityQuestionSequence}','${VisibilityAnswerId}','${VisibilityAnswerName}','${VAShowCamera}','${VACameraMandatory}','${VAQuestionEnable}','${VAQuestionDisable}','${VASequence}')`);
            });

            console.log('sdjh')

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_VisibilityQuestion(VisibilityQuestionId,VisibilityQuestionCode,VisibilityQuestionName,QuestionType,VQShowCamera,VQCameraMandatory,VQLengthValidationRequired,VQMinimumChar,VQMaximumChar,VQDecimalPoint,VQDateRangeMin,VQDateRangeMax,VQVoiceLengthInMinutes,VQDefaultQuestionEnable,VisibilityQuestionSequence,VisibilityAnswerId,VisibilityAnswerName,VAShowCamera,VACameraMandatory,VAQuestionEnable,VAQuestionDisable,VASequence)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_VisibilityQuestion where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_VisibilityQuestion added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_VisibilityQuestion'], false, 'Sup_Master_VisibilityQuestion');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_VisibilityQuestion'], true, 'Sup_Master_VisibilityQuestion', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_VisibilityQuestion'], true, 'Sup_Master_VisibilityQuestion', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_VisibilityAudit': {
          if (res != null && typeof res == 'object' && res.Sup_VisibilityAudit != null && res.Sup_VisibilityAudit != '') {
            let data_arr = res.Sup_VisibilityAudit || [];
            console.log('surveys:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { VId, MID, StoreId, LastVisitDate, VisibilityDefinitionId, Present, VisibilityReasonId, VisibilityImages, VisibilityQuestion } = data_obj;
              values.push(` ('${VId}','${MID}','${StoreId}','${LastVisitDate}','${VisibilityDefinitionId}','${Present}','${VisibilityReasonId}','${VisibilityImages}','${VisibilityQuestion}')`);
            });

            console.log('sdjh')

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_VisibilityAudit(VId,MID,StoreId,LastVisitDate,VisibilityDefinitionId,Present,VisibilityReasonId,VisibilityImages,VisibilityQuestion)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_VisibilityAudit where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_VisibilityAudit added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_VisibilityAudit'], false, 'Sup_VisibilityAudit');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_VisibilityAudit'], true, 'Sup_VisibilityAudit', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_VisibilityAudit'], true, 'Sup_VisibilityAudit', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_VisibilityReason': {
          if (res != null && typeof res == 'object' && res.Sup_Master_VisibilityReason != null && res.Sup_Master_VisibilityReason != '') {
            let data_arr = res.Sup_Master_VisibilityReason || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { VisibilityReasonId, VisibilityReason, MenuId, IsRemarkTaken } = data_obj;
              values.push(` ('${VisibilityReasonId}','${VisibilityReason}','${MenuId}','${IsRemarkTaken}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_VisibilityReason(VisibilityReasonId,VisibilityReason,MenuId,IsRemarkTaken)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_VisibilityReason where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_VisibilityReason added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_VisibilityReason'], false, 'Sup_Master_VisibilityReason');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_VisibilityReason'], true, 'Sup_Master_VisibilityReason', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_VisibilityReason'], true, 'Sup_Master_VisibilityReason', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_PosSaleReason': {
          if (res != null && typeof res == 'object' && res.Sup_Master_PosSaleReason != null && res.Sup_Master_PosSaleReason != '') {
            let data_arr = res.Sup_Master_PosSaleReason || [];
            // data_arr.push({"ChannelId":1,"RegionId":1,"MenuId":18})         
            var values = [];
            data_arr.map((data_obj) => {
              let { PosReasonId, PosReason } = data_obj;
              values.push(` ('${PosReasonId}', '${PosReason}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_PosSaleReason(PosReasonId,PosReason)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_PosSaleReason where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_PosSaleReason added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_PosSaleReason'], false, 'Sup_Master_PosSaleReason');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_PosSaleReason'], true, 'Sup_Master_PosSaleReason', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_PosSaleReason'], true, 'Sup_Master_PosSaleReason', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Mapping_PosSaleDefinition': {
          if (res != null && typeof res == 'object' && res.Sup_Mapping_PosSaleDefinition != null && res.Sup_Mapping_PosSaleDefinition != '') {
            let data_arr = res.Sup_Mapping_PosSaleDefinition || [];
            // data_arr.push({"ChannelId":1,"RegionId":1,"MenuId":18})         
            var values = [];
            data_arr.map((data_obj) => {
              let { PosDefinitionId, PosSaleValue, ChildName } = data_obj;
              values.push(`('${PosDefinitionId}', '${PosSaleValue}', '${ChildName}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Mapping_PosSaleDefinition(PosDefinitionId,PosSaleValue,ChildName)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Mapping_PosSaleDefinition where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Mapping_PosSaleDefinition added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Mapping_PosSaleDefinition'], false, 'Sup_Mapping_PosSaleDefinition');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Mapping_PosSaleDefinition'], true, 'Sup_Mapping_PosSaleDefinition', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Mapping_PosSaleDefinition'], true, 'Sup_Mapping_PosSaleDefinition', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_PosSaleDefinition': {
          if (res != null && typeof res == 'object' && res.Sup_Master_PosSaleDefinition != null && res.Sup_Master_PosSaleDefinition != '') {
            let data_arr = res.Sup_Master_PosSaleDefinition || [];
            // data_arr.push({"ChannelId":1,"RegionId":1,"MenuId":18})         
            var values = [];
            data_arr.map((data_obj) => {
              let { PosDefinitionId, PosTable, PosField, PosOverall, PosCheckAssortment, ShowPosValue, ShowPosVolume, PosValueLabel, PosVolumeLabel, PosNotExistReasonEnable, HeaderImageRequired, HeaderImageCount, HeaderImageMandatory } = data_obj;
              values.push(` ('${PosDefinitionId}', '${PosTable}' , '${PosField}','${PosOverall}', '${PosCheckAssortment}', '${ShowPosValue}', '${ShowPosVolume}','${PosValueLabel}','${PosVolumeLabel}','${PosNotExistReasonEnable == true ? 1 : 0}','${HeaderImageRequired == true ? 1 : 0}','${HeaderImageCount}','${HeaderImageMandatory}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_PosSaleDefinition(PosDefinitionId,PosTable,PosField,PosOverall,PosCheckAssortment,ShowPosValue,ShowPosVolume,PosValueLabel,PosVolumeLabel,PosNotExistReasonEnable,HeaderImageRequired,HeaderImageCount,HeaderImageMandatory)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_PosSaleDefinition where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_PosSaleDefinition added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_PosSaleDefinition'], false, 'Sup_Master_PosSaleDefinition');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_PosSaleDefinition'], true, 'Sup_Master_PosSaleDefinition', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_PosSaleDefinition'], true, 'Sup_Master_PosSaleDefinition', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Master_PosSaleCycle': {
          if (res != null && typeof res == 'object' && res.Sup_Master_PosSaleCycle != null && res.Sup_Master_PosSaleCycle != '') {
            let data_arr = res.Sup_Master_PosSaleCycle || [];
            // data_arr.push({"ChannelId":1,"RegionId":1,"MenuId":18})         
            var values = [];
            data_arr.map((data_obj) => {
              let { CycleId, CycleYear, CycleMonth, CyclePeriod } = data_obj;
              values.push(` ('${CycleId}', '${CycleYear}' , '${CycleMonth}','${CyclePeriod}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Master_PosSaleCycle(CycleId,CycleYear,CycleMonth,CyclePeriod)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Master_PosSaleCycle where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Master_PosSaleCycle added', data_arr);
                  setTaskResponse(data_arr);

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

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Master_PosSaleCycle'], false, 'Sup_Master_PosSaleCycle');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Master_PosSaleCycle'], true, 'Sup_Master_PosSaleCycle', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Master_PosSaleCycle'], true, 'Sup_Master_PosSaleCycle', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_Mapping_StorePosSaleDefinition': {
          if (res != null && typeof res == 'object' && res.Sup_Mapping_StorePosSaleDefinition != null && res.Sup_Mapping_StorePosSaleDefinition != '') {
            let data_arr = res.Sup_Mapping_StorePosSaleDefinition || [];
            // data_arr.push({"ChannelId":1,"RegionId":1,"MenuId":18})         
            var values = [];
            data_arr.map((data_obj) => {
              let { PosDefinitionId, StoreId, VisitDate } = data_obj;
              values.push(`('${PosDefinitionId}', '${StoreId}','${VisitDate})`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_Mapping_StorePosSaleDefinition(PosDefinitionId,StoreId,VisitDate)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Mapping_StorePosSaleDefinition where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_Mapping_StorePosSaleDefinition added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txnE, txnerr) {
                  console.log(txnerr);
                  resolve(true);
                });
              }, function (txnE, txnerr) {
                console.log(txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_Mapping_StorePosSaleDefinition'], false, 'Sup_Mapping_StorePosSaleDefinition');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_Mapping_StorePosSaleDefinition'], true, 'Sup_Mapping_StorePosSaleDefinition', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_Mapping_StorePosSaleDefinition'], true, 'Sup_Mapping_StorePosSaleDefinition', res);
            resolve(false);
          }
          break;
        }

        // new cases 
        case 'Sup_ImageAuditKPIImages': {
          if (res != null && typeof res == 'object' && res.Sup_ImageAuditKPIImages != null && res.Sup_ImageAuditKPIImages != '') {
            let data_arr = res.Sup_ImageAuditKPIImages || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, MenuId, Menu, KPIImageId, QuestionImageId, DefId, DefName, BaseUrl, ImageName, Image1, Image2 } = data_obj;
              values.push(`('${MID}','${MenuId}','${Menu}','${KPIImageId}','${QuestionImageId}','${DefId}','${DefName}','${BaseUrl}','${ImageName}','${Image1}','${Image2}')`);
            });

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_ImageAuditKPIImages(MID ,MenuId,Menu,KPIImageId,QuestionImageId,DefId,DefName,BaseUrl,ImageName,Image1,Image2)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_ImageAuditKPIImages where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_ImageAuditKPIImages added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_ImageAuditKPIImages'], false, 'Sup_ImageAuditKPIImages');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_ImageAuditKPIImages'], true, 'Sup_ImageAuditKPIImages', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_ImageAuditKPIImages'], true, 'Sup_ImageAuditKPIImages', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_ImageAuditKPIQuestion': {
          if (res != null && typeof res == 'object' && res.Sup_ImageAuditKPIQuestion != null && res.Sup_ImageAuditKPIQuestion != '') {
            let data_arr = res.Sup_ImageAuditKPIQuestion || [];
            console.log('surveys:', data_arr.length)
            var values = [];
            data_arr.map((data_obj) => {
              let { AIQuestionId, AIQuestionCode, AIQuestionName, QuestionType, AIShowCamera, AICameraMandatory, AILengthValidationRequired, AIMinimumChar, AIMaximumChar, AIDecimalPoint, AIDateRangeMin, AIDateRangeMax, AIVoiceLengthInMinutes, AIDefaultQuestionEnable, AIQuestionSequence, AIAnswerId, AIAnswerName, AIAShowCamera, AIACameraMandatory, AIAQuestionEnable, AIAQuestionDisable, AIASequence } = data_obj;
              values.push(` ('${AIQuestionId}','${AIQuestionCode}','${AIQuestionName}','${QuestionType}','${AIShowCamera}','${AICameraMandatory}','${AILengthValidationRequired}','${AIMinimumChar}','${AIMaximumChar}','${AIDecimalPoint}','${AIDateRangeMin}','${AIDateRangeMax}','${AIVoiceLengthInMinutes}','${AIDefaultQuestionEnable}','${AIQuestionSequence}','${AIAnswerId}','${AIAnswerName}','${AIAShowCamera}','${AIACameraMandatory}','${AIAQuestionEnable}','${AIAQuestionDisable}','${AIASequence}')`);
            });

            console.log('Sup_ImageAuditKPIQuestion');

            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_ImageAuditKPIQuestion(AIQuestionId,AIQuestionCode,AIQuestionName,QuestionType,AIShowCamera,AICameraMandatory,AILengthValidationRequired,AIMinimumChar,AIMaximumChar,AIDecimalPoint,AIDateRangeMin,AIDateRangeMax,AIVoiceLengthInMinutes,AIDefaultQuestionEnable,AIQuestionSequence,AIAnswerId,AIAnswerName,AIAShowCamera,AIACameraMandatory,AIAQuestionEnable,AIAQuestionDisable,AIASequence)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_ImageAuditKPIQuestion where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_ImageAuditKPIQuestion added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr) {
                  console.log('err:', txnerr);
                  resolve(true);
                });
              }, function (txn1, txnerr) {
                console.log('err:', txnerr);
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_ImageAuditKPIQuestion'], false, 'Sup_ImageAuditKPIQuestion');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_ImageAuditKPIQuestion'], true, 'Sup_ImageAuditKPIQuestion', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_ImageAuditKPIQuestion'], true, 'Sup_ImageAuditKPIQuestion', res);
            resolve(false);
          }
          break;
        }

        case 'Sup_ImageAuditStoreList': {
          console.log("res:", res);
          if (res != null && typeof res == 'object' && res.Sup_ImageAuditStoreList != null && res.Sup_ImageAuditStoreList != '') {
            let data_arr = res.Sup_ImageAuditStoreList || [];
            var values = [];
            data_arr.map((data_obj) => {
              let { MID, CoveredBy, StoreId, StoreName, StoreType, Address, CityName, VisitDate } = data_obj;
              StoreName = StoreName?.replace(/'/g, '');
              Address = Address?.replace(/'/g, '');
              CityName = CityName?.replace(/'/g, '');
              values.push(` ('${MID}', '${CoveredBy}','${StoreId}','${StoreName}','${StoreType}','${Address}', '${CityName}','${VisitDate}')`);
            });
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_ImageAuditStoreList(MID,CoveredBy,StoreId,StoreName,StoreType,Address,CityName,VisitDate) 
            values ${all_vals}`;
            db.transaction(function (txn) {
              txn.executeSql(`delete from Sup_ImageAuditStoreList where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Sup_ImageAuditStoreList added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (txn1, txnerr1) {
                  console.log(txnerr1)
                  resolve(true);
                });
              }, function (txn1, txnerr1) {
                console.log(txnerr1)
                resolve(true);
              });
            });

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Sup_ImageAuditStoreList'], false, 'Sup_ImageAuditStoreList');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Sup_ImageAuditStoreList'], true, 'Sup_ImageAuditStoreList', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Sup_ImageAuditStoreList'], true, 'Sup_ImageAuditStoreList', res);
            resolve(false);
          }
          break;
        }

        // dashboard 
        case 'Sup_MenuAppDashboard': {
          if (res != null && typeof res == 'object' && res.Sup_MenuAppDashboard != null && res.Sup_MenuAppDashboard != '') {
            let data_arr = res.Sup_MenuAppDashboard || [];
            var values = [], reportKeysToDownload = [], MainReportsToShow = [];
            data_arr.map((data_obj) => {
              let { DashboardId, DashboardName, DashboardType, DashboardSection, TabName, DownloadKey, GraphDetail, DrillDown, ParentId, ShowGraph, DisplayOrder } = data_obj;

              values.push(` ('${DashboardId}','${DashboardName}','${DashboardType}','${DashboardSection}','${TabName}','${DownloadKey}','${GraphDetail}','${DrillDown}','${ParentId}','${ShowGraph}','${DisplayOrder}')`);

              if (DashboardSection != "DrilldownScreen" && DashboardSection != "PeopleDrilldownScreen") {
                reportKeysToDownload.push(DownloadKey);
              }
              // reportKeysToDownload.push(DownloadKey);

              // only those report will be shown which parent id is either null or 0

              if (ParentId == null || ParentId == 0 || ParentId == '0') {
                MainReportsToShow.push(data_obj);
              }

            });

            MainReportsToShow.sort((a, b) => a.DisplayOrder - b.DisplayOrder);

            setAppDashReportsSec(MainReportsToShow);
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Sup_MenuAppDashboard(DashboardId,DashboardName,DashboardType,DashboardSection,TabName,DownloadKey,GraphDetail,DrillDown,ParentId,ShowGraph,DisplayOrder)
            values ${all_vals}`;

            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_MenuAppDashboard where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], async function (txn1, txnres) {
                  console.log('Sup_MenuAppDashboard added');


                  // download reports data for dashboard
                  let isReportsDownloaded = await downloadReportKeys(reportKeysToDownload)
                  if (!isReportsDownloaded.success && isReportsDownloaded.error != null && isReportsDownloaded.error != '') {
                    console.log("Cannot download dashboard reports");
                    await onNoData(['No data for Sup_MenuAppDashboard'], true, 'Sup_MenuAppDashboard - ' + isReportsDownloaded.reportKey, isReportsDownloaded.error);
                    resolve(false);
                  }
                  else {
                    setTaskResponse(data_arr);
                    console.log("All Report Keys Dowbloaded", isReportsDownloaded);
                    resolve(true);
                  }

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

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            setAppDashReportsSec([]);
            await onNoData(['No data for Sup_MenuAppDashboard'], false, 'Sup_MenuAppDashboard');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            setAppDashReportsSec([]);
            await onNoData(['No data for Sup_MenuAppDashboard'], true, 'Sup_MenuAppDashboard', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            setAppDashReportsSec([]);
            await onNoData(['No data for Sup_MenuAppDashboard'], true, 'Sup_MenuAppDashboard', res);
            resolve(false);
          }
          break;
        }

        case "default": return false;
      }
    }).catch((err) => {
      console.log('error in downloading', err);
      return false;
    });
  }
  // DOWNLOAD FUNCTIONALITY END


  // upload functionality start
  async function startUpload() {
    console.log("start upload called");
    setLoaderTitle(ST.UploadingData + '...');
    setProcessing(true);
    UploadOnCheckOut();
  }

  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) {
          console.log("Menu List Query:", txnres.rows.length);
          if (txnres.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              console.log("Menu List Query:", data);
              arr.push(data);
              if (i == (txnres.rows.length - 1)) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('')
      return []
    })
  }



  async function UploadOnCheckOut() {
    try {
      let userIsManager = await getIf_UserIsManager(props);
      //  const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
      const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

      setLoaderTitle("Loading...");
      setProcessing(true);
      GMUploadedCountref.current = 0;
      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);
      console.log("storewisePjpAskForUpload>>:", storewisePjp);
      let AllEmployees = await getEmployees();

      let AllVisitors = [];//await getVisitorLogin(d2);

      let ALlGMs = await getGateMeetingsToUpload();
      console.log("ALlGMs", ALlGMs)
      if (ALlGMs.length > 0) {
        setLoaderTitle(`Uploading Gate Meetings Data (${GMUploadedCountref.current}/${ALlGMs.length})...`);
        let isGMUploaded = await uploadGateMeetings(ALlGMs);
        setLoaderTitle("Loading...");
      }

      // image audit 

      let ALlIAs = await getImageAuditToUpload();
      console.log("ALlIAs", ALlIAs)
      if (ALlIAs.length > 0) {
        setLoaderTitle(`Uploading Image Audit Data (${IAUploadedCountref.current}/${ALlIAs.length})...`);
        let isIAUploaded = await uploadImageAudits(ALlIAs);
        setLoaderTitle("Loading...");
      }

      await db.transaction(async function (txn) {

        for (let empINdex = 0; empINdex < AllEmployees.length; empINdex++) {

          let PJPStores = [];
          // if user is manager 
          if (userIsManager) {
            AllStores = await getPJPStoresData('Sup_JourneyPlan', [], d2);
          }
          else if (storewisePjp == true) {
            PJPStores = await getPJPStoresData('Sup_JourneyPlanStorewiseSup', [], d2);
            AllStores = await getPJPStoresData('Sup_JourneyPlanStorewiseSup_Adhoc', PJPStores, d2);
          }
          else {
            PJPStores = await getPJPStoresData('Sup_JourneyPlan', [], d2);
            AllStores = await getPJPStoresData('Sup_AdhocJourneyPlan', PJPStores, d2);
          }

          console.log('stores to upload:', AllStores.length);
          if (AllStores.length > 0) {
            if (AllVisitors.length > 0) {
              setLoaderTitle(ST.Uploadingvisitorsdata + '...');
              let isallVisUploaded = await uploadAllVisitors(props, AllVisitors);

              if (isallVisUploaded == true) {
                notify(ST.AllDataUploaded + '...');
              }
              else {
                notify(ST.CannotUploadVisitors);
              }
            }
            for (var i = 0; i < AllStores.length; i++) {
              let data = AllStores[i];
              const index = i;
              let { StoreId, StoreName, EmpId, MerchandiserId, MID, UploadStatus, Status, VisitDate, REASON_ID, JCP_TYPE } = data;
              // get all checkout ids data
              setLoaderTitle(ST.UploadingDatafor + ' ' + StoreName + '...');
              let MenuList = await getMenuList(data);
              let allKPIs = await getKPIS(MenuList);
              if (UploadStatus == 'C') {
                let isUploaded_P = await uploadStoreStatus(props, data, 'P', JCP_TYPE);
                if (isUploaded_P == true) {
                  console.log('proceed to upload after C to P status', MenuList, allKPIs);
                  await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE)
                }
                else {
                  notify(ST.Erroroccurwhileuploadingdatafor + ' ' + StoreName, 'LONG');
                  if (index == AllStores.length - 1) {
                    setProcessing(false);
                  }
                }
              }
              else if (UploadStatus == 'D') {
                //  this never be called if there is no KPI
                console.log('uploadAfter_P_status - MenuList.length:', allKPIs);
                let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, false, MenuList,true);
                console.log('allFilesToUpload.length:', allFilesToUpload.length);
                if (allFilesToUpload.length > 0) {
                  await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload);
                }
                else {
                  notify(ST.Alldatauploadedfor + ' ' + 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) {
                  notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                  if (index == AllStores.length - 1) {
                    setProcessing(false);
                  }
                }
                else {
                  if (index == AllStores.length - 1) {
                    setProcessing(false); notify(ST.Erroroccurwhileuploadingdatafor, 'LONG');
                  }
                }
              }

              if (index == 0) {
                props.set_startUpload({ startUpload: false });
              }
            }

          }
          else if (AllVisitors.length > 0) {
            setLoaderTitle(ST.Uploadingvisitorsdata + '...');
            let isallVisUploaded = await uploadAllVisitors(props, AllVisitors);
            setProcessing(false);
            props.set_startUpload({ startUpload: false });
            if (isallVisUploaded == true) {
              notify(ST.AllDataUploaded);
            }
            else {
              notify(ST.CannotUploadVisitors);
            }
          }
          else if (ALlGMs.length > 0) {
            props.set_startUpload({ startUpload: false });
            setProcessing(false);
          }
          else if (ALlIAs.length > 0) {
            props.set_startUpload({ startUpload: false });
            setProcessing(false);
          }
          else {
            setProcessing(false);
            notify(ST.NodatatoUpload);
            props.set_startUpload({ startUpload: false });
          }
        }

      });



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


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

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let query1 = `SELECT DISTINCT MenuId, MID, Menu FROM ${AppTables.IMAGE_AUDIT_HDR_DATA} WHERE (STATUS != 'U' OR STATUS IS NULL) AND VISIT_DATE = '${d2}'`;
        console.log("query1", query1);

        await txn.executeSql(query1, [], async function (txn2, txnres1) {
          if (txnres1.rows.length > 0) {
            let fetchedData = [];

            // Wrap the loop in a Promise.all to wait for all async operations to complete
            await Promise.all(Array.from({ length: txnres1.rows.length }, async (_, i) => {
              let item = txnres1.rows.item(i);
              let defArray = [];

              // Step 2: Fetch DefName and DefId for each MenuId and MID
              let query2 = `SELECT DISTINCT DefName, DefId, MID, MenuId FROM ${AppTables.IMAGE_AUDIT_HDR_DATA} WHERE MID = '${item.MID}' AND MenuId = '${item.MenuId}'`;
              console.log("query2", query2);

              return new Promise(async (resolveDef, rejectDef) => {
                await txn.executeSql(query2, [], async function (txn3, txnres2) {
                  // Wrap another Promise.all to wait for the completion of this loop
                  await Promise.all(Array.from({ length: txnres2.rows.length }, async (_, j) => {
                    let defItem = txnres2.rows.item(j);
                    let images1Array = [];

                    // Step 3: Fetch images for each DefId
                    let query3 = `SELECT DISTINCT S.KPIImageId, S.QuestionImageId, S.DefId, S.DefName, S.BaseUrl, S.ImageName, S.Image1, S.Image2,
                  IFNULL(S.pictureokay, 0) AS pictureokay, IFNULL(S.pictureokay2, 0) AS pictureokay2
                  FROM ${AppTables.IMAGE_AUDIT_HDR_DATA} S WHERE DefId = '${defItem.DefId}' AND MenuId = '${item.MenuId}' AND MID = '${item.MID}'`;
                    console.log("query3", query3);

                    return new Promise((resolveImg, rejectImg) => {
                      txn.executeSql(query3, [], function (txn4, txnres3) {
                        for (let k = 0; k < txnres3.rows.length; k++) {
                          let imageItem = txnres3.rows.item(k);
                          images1Array.push({
                            KPIImageId: imageItem.KPIImageId,
                            QuestionImageId: imageItem.QuestionImageId,
                            ImageName: imageItem.ImageName,
                            Image1: imageItem.Image1,
                            Image2: imageItem.Image2,
                            pictureokay: imageItem.pictureokay,
                            pictureokay2: imageItem.pictureokay2
                          });
                        }

                        // Step 4: Push DefData and resolve the promise for the image query
                        defArray.push({
                          DefName: defItem.DefName,
                          DefId: defItem.DefId,
                          Images: images1Array
                        });
                        resolveImg();
                      }, (error) => {
                        console.log("Error in query3", error);
                        rejectImg();
                      });
                    });
                  }));

                  // Resolve when defArray is fully populated
                  resolveDef();
                }, (error) => {
                  console.log("Error in query2", error);
                  rejectDef();
                });
              }).then(() => {
                // Add the final data to fetchedData once the defArray is ready
                fetchedData.push({
                  MenuId: item.MenuId,
                  MID: item.MID,
                  Menu: item.Menu,
                  DefData: defArray
                });
              });
            }));

            // Resolve the promise when everything is done
            resolve(fetchedData);
          } else {
            resolve([]); // No data found
          }
        }, function (txnErr) {
          console.log(txnErr);
          resolve([]); // Error in first query
        });
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return [];
    });
  }



  async function uploadImageAudits(ALlIAs = []) {
    console.log("uploadImageAudits", ALlIAs.length)
    // let isUploaded=true;
    // return Promise.all(
    // ALlIAs.map(async(item,index)=>{
    let isGMuploaded = await uploadImageAuditData(ALlIAs);
    if (isGMuploaded) {
      notify("All Image Audit Data uploaded!")
      return true;
    }
    notify("Cannot upload all Image Audit data!")
    return false;
    // else{
    //   isUploaded=false;
    // }
    // })
    // ).then((val)=>{
    //   if(isUploaded){
    //     notify("All Image Audit Data uploaded!")
    //   }
    //   else{
    //     notify("Cannot upload all Image Audit data!")
    //   }
    //   return isUploaded;
    // }).catch((err)=>{
    //   console.log("Error in uploading data:",err);
    //   return false;
    // });

  }




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

    setLoaderTitle('Uploading Data...');

    let storeInfo = data;

    let arr = [];

    console.log(JSON.stringify(data), "DATATTATATATTATTA___AUDIT")
    // Create a shallow copy or filtered version of dataInfo
    let filteredStoreInfo = data.map(item => {
      let filteredDefData = item.DefData.map(defItem => {
        // Include all images, setting pictureokay/pictureokay2 to 0 if not already set
        let allImages = defItem.Images.map(image => ({
          ...image,
          pictureokay: image.pictureokay ? image.pictureokay : 0,
          pictureokay2: image.pictureokay2 ? image.pictureokay2 : 0,
        }));

        return {
          ...defItem,
          Images: allImages
        };
      });

      return {
        ...item,
        DefData: filteredDefData
      };
    });

    // Filter out any entries where Images is empty
    filteredStoreInfo = filteredStoreInfo.filter(item => item.DefData.some(defItem => defItem.Images.length > 0));


    await filteredStoreInfo.map((item, i) => {
      let itemObj2 = item;

      if (item.Status !== "U") {
        let rsData = item.DefData.map(item3 => {
          let Images = [];

          item3?.Images.map(item2 => {
            let obj = {
              KPIImageId: item2.KPIImageId,
              QuestionImageId: item2.QuestionImageId
            };

            if (item2?.Image1) {
              Images.push({
                ...obj,
                imageType: "Image1",
                Questions: item2.Questions1,
                Image: item2?.Image1,
                pictureokay: item2.pictureokay
              });
            }

            if (item2?.Image2) {
              Images.push({
                ...obj,
                imageType: "Image2",
                Questions: item2.Questions2,
                Image: item2?.Image2,
                pictureokay: item2.pictureokay2
              });
            }
          });

          item3["Images"] = Images;
          return item3;
        });

        itemObj2["UserId"] = props.UserId;
        itemObj2["DefData"] = rsData;
        arr.push(itemObj2);
      }
    });

    console.log(JSON.stringify(arr), "postDATAAAA----------")

    let postData = {
      "MID": 0,
      "Keys": "Sup_Image_Audit_Info",
      "JsonData": JSON.stringify(arr),
      "UserId": props.UserId,
    };


    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

    console.log(url, postData, 'url and postDaata...');

    return await UploadData(url, postData)
      .then(async (res) => {
        console.log('res: 12', res);
        if (res?.UploadJsonResult == "Success") {
          setProcessing(false);
          updateImageAuditUploadStatus();
          return true;
        } else {
          setProcessing(false);
        }
      })
      .catch((err) => {
        console.log(err);
        setProcessing(false);
      });

  }

  async function updateImageAuditUploadStatus() {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `Update ${AppTables.IMAGE_AUDIT_HDR_DATA} SET STATUS='U'`;
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('Image Audit upload status Updated');
          resolve(true);
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });
  }

  // image audit upload end

  async function getGateMeetingsToUpload() {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `select * from ${AppTables.GATE_MEETING} where (UPLOADSTATUS!='U' or UPLOADSTATUS is null)`;
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('meets', txnres.rows.length);
          if (txnres.rows.length > 0) {
            let allMeet = [];
            for (let i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              let discP = await getDiscussionPoint(data);
              data["DISCUSSION_POINTS"] = discP != null && discP != "" ? discP : [];
              allMeet.push(data)
              if (i == txnres.rows.length - 1) {
                resolve(allMeet)
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return [];
    });
  }

  async function getDiscussionPoint(gateMeeting) {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        // get inserted audit
        let q = `SELECT DISCUSSION_POINTS FROM ${AppTables.GATE_MEETING_DISCUSSION} WHERE GATEMEETING_ID='${gateMeeting.UNIQUE_ID}'  `
        await db.transaction(async function (txn) {
          await txn.executeSql(q, [], async function (txn2, txnres2) {
            // console.log('txnres4',txnres2.rows.length)
            if (txnres2.rows.length > 0) {
              let dp = [];
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                dp.push(data.DISCUSSION_POINTS)

                if (i == (txnres2.rows.length - 1)) {
                  resolve(dp)
                }
              }
            }
            else {
              resolve([])
            }

          }, function (txn2, txnerr) { console.log(txnerr); resolve([]) });
        });

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

  async function uploadGateMeetings(ALlGMs = []) {
    console.log("uploadGateMeetings", ALlGMs.length)
    let isUploaded = true;
    return Promise.all(
      ALlGMs.map(async (item, index) => {
        let isGMuploaded = await uploadGateMeetingData(item);
        if (isGMuploaded) {
          GMUploadedCountref.current++;
          setLoaderTitle(`Uploading Gate Meetings Data (${GMUploadedCountref.current}/${ALlGMs.length})...`);
        }
        else {
          isUploaded = false;
        }
      })
    ).then((val) => {
      if (isUploaded) {
        notify("All Gate Meetings Data uploaded!")
      }
      else {
        notify("Cannot upload all Gate Meetings data!")
      }
      return isUploaded;
    }).catch((err) => {
      console.log("Error in uploading data:", err);
      return false;
    });
  }


  async function uploadGateMeetingData(data) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    setLoaderTitle("Uploading Data...")
    setProcessing(true);
    let employeesArr = data.EMP_ID != null && data.EMP_ID != '' ? data.EMP_ID.split(',') : [];

    let obj = {
      "MID": 0,
      "UniqueId": data.UNIQUE_ID,
      "UserId": props.UserId,
      "VisitDate": d2,
      "Time": data.TIME,
      "Image": data.IMAGE,
      "MerchandiserId": employeesArr,
      "DiscussionPoints": data.DISCUSSION_POINTS
    }

    let JsonChange = JSON.stringify(obj)?.replace(/'/g, '"')

    let postData = {
      "MID": 0,
      "Keys": "GateMeeting_Sup",
      "JsonData": JsonChange,
      "UserId": props.UserId,
    };

    console.log('postData', postData)

    let ImageName = data.IMAGE;
    let imgPath = 'file://' + `${common_ImagePath}${ImageName}`;

    return await UploadData2(url, postData)
      .then(async (res) => {
        console.log('res:', res);
        if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {

          // uplod images
          const url2 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
          if (ImageName != '' && ImageName != null) {
            let file = {
              uri: imgPath,
              type: 'image/jpeg',
              name: ImageName,
              filetype: 'image',
              folderName: 'SupGateMeetingImages',
            }

            let isExists = await RNFS.exists(file.uri).then((res) => { return res; });
            console.log('isExists file', isExists);
            if (isExists == true) {
              let fileData = getImagePOSTData(file, d2);

              let isImageUploaded = await UploadFormData(url2, fileData);
              console.log('isImageUploaded', isImageUploaded)
              if (isImageUploaded == false) {
                notify('Cannot upload GateMeeting image!');
              }
            }
            else {
              notify("Error uploading image! GateMeeting Image does not exists ");
            }
          }

          let isupdated = updateGateMeetUploadStatus(data.UNIQUE_ID);
          return isupdated;

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

  async function updateGateMeetUploadStatus(uniqueId) {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `Update ${AppTables.GATE_MEETING} SET UPLOADSTATUS='U' WHERE UNIQUE_ID='${uniqueId}'`;
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('Gate Meeting upload status Updated');
          resolve(true);
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });
  }





  async function uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE) {
    let { StoreName } = data;
    if (MenuList.length > 0) {
      // Upload data with Images
      console.log('uploadAfter_P_status - MenuList.length:', allKPIs);
      let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, true, MenuList,true);
      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) {
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          setProcessing(false);
        }
      }
      else {
        if (index == AllStores.length - 1) {
          setProcessing(false); notify(ST.Erroroccurwhileuploadingdatafor, 'LONG');
        }
      }
    }
  }

  async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload) {

    let { StoreName } = data;
    if (allFilesToUpload.length > 0) {
      setLoaderTitle(ST.UploadingImages + '...');

      let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE);

      if (isAllUploaded == true) {
        notify(ST.Alldataandimagesuploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          setProcessing(false);
        }
      } else {
        notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          setProcessing(false);
        }
      }
    }
    else {
      notify(ST.Alldatauploadedfor + ' ' + 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.EMP_ID=t1.MerchandiserId and t2.JCP_TYPE='${tbname}' `;
        await txn.executeSql(`Select t1.*,t2.REASON_ID,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 (txn2, txnerr) { console.log(txnerr); resolve(Stores) },);

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

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

        await txn.executeSql(`Select * from Sup_TeamList `, [], async function (txn2, txnres2) {

          if (txnres2.rows.length > 0) {
            let arr = [];
            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 (txn2, txnerr) { console.log(txnerr); resolve([]) },);

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

  async function getVisitorLogin(d2) {
    let allVisitors = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {

        let q = `Select * from ${AppTables.VISITOR_LOGIN} where VISIT_DATE='${d2}' and OUT_TIME!='' and UPLOADSTATUS!='U' `;
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              allVisitors.push(data);
            }
            resolve(allVisitors);
          }
          else {
            resolve(allVisitors);
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve(allVisitors) },);

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

  async function getdashboardData() {

    async function getPlannedData() {
      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 = '';

      q = `Select Distinct STORE_ID from DR_COVERAGE  where VISIT_DATE='${d2}'`;
      // console.log('teamlistq',q);


      await db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {

          // console.log('txnres5',txnres2.rows.length)


          setPlanned(txnres2.rows.length)

          if (txnres2.rows.length > 0) {
            // show from local
            var storeArr = [];
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              console.log('teamlistdata', data)
              // let ChekedInStatus=await getCheckInStatus(data);
              // data['ChekedInStatus']=ChekedInStatus;

              storeArr.push(data);



              if (i == (txnres2.rows.length - 1)) {
                setEmployeesList(storeArr);
                setGlobalEmplist(storeArr);
                setProcessing(false);

              }
            }
          }
          else {
            setProcessing(false);
          }
        }, function (txn2, txnerr) { console.log(txnerr); });
      });
    }

    async function getExecutedData() {
      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 = '';

      q = `Select Distinct STORE_ID from DR_COVERAGE where VISIT_DATE='${d2}' and REASON_ID=0`;
      console.log('teamlistq', q);


      await db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {




          setCovered(txnres2.rows.length)

          if (txnres2.rows.length > 0) {
            // show from local
            var storeArr = [];
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              console.log('teamlistdata', data)
              // let ChekedInStatus=await getCheckInStatus(data);
              // data['ChekedInStatus']=ChekedInStatus;

              storeArr.push(data);



              if (i == (txnres2.rows.length - 1)) {
                setEmployeesList(storeArr);
                setGlobalEmplist(storeArr);
                setProcessing(false);

              }
            }
          }
          else {
            setProcessing(false);
          }
        }, function (txn2, txnerr) { console.log(txnerr); });
      });
    }



    getPlannedData();
    getExecutedData();
  }


  // new dashboard data sup

  async function downloadReportKeys(reportKeysToDownload = []) {
    console.log('downloadReportKeys');
    let defData = { success: true, error: '', }
    return new Promise(async (resolve, reject) => {
      let reports = {};
      for (let i = 0; i < reportKeysToDownload.length; i++) {
        let reportKey = reportKeysToDownload[i];
        let reportData = await DownloadDashboardReportData(reportKey);
        console.log('DownloadDashboardReportData downloded:', reportKey, reportData);
        if (!reportData.success && reportData.error != null && reportData.error != '') {
          defData["success"] = false;
          defData["error"] = reportData.error;
          defData["reportKey"] = reportKey;
          resolve(defData);
        }

        reports[reportKey] = reportData.data;

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

          console.log('all reports downloded:', JSON.stringify(reports));
          set_item('Sup_MenuAppDashboard', JSON.stringify(reports));
          props.set_DashboardReports(reports);
          resolve(defData);
        }
      }
    }).catch((err) => {
      console.log("err:", err);
      defData["success"] = false;
      defData["error"] = "Error while downloading dashboard reports!";
      resolve(defData);
    });
  }

  // doownload reports 
  async function DownloadDashboardReportData(reportKey = '') {
    console.log('DownloadDashboardReportData:', reportKey);
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    console.log("report Key dashboard sup:", reportKey);
    let defData = { success: false, data: {} };

    if (reportKey != null && reportKey != '') {
      setDownloadingText("Sup_MenuAppDashboard - " + reportKey);
      let postdata = {
        Downloadtype: reportKey,
        Username: loginDetails.UserId,
        Param1: '',
        Param2: '',
      };

      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, postdata);

      return await getDownloadJson1(url, postdata)
        .then(async (res) => {
          if (res != null && typeof res == 'object' && res[reportKey] != null && res[reportKey] != '') {
            let data_arr = res[reportKey] || [];

            // Get columns and columnWidth based on the first row
            let allCols = [], columnWidth = '50%';
            let keylen = Object.keys(data_arr[0] || {}).length;

            // Loop through all rows to process columns
            for (let row of data_arr) {
              let i = 0;
              for (let key in row) {
                if (i < keylen) {
                  let obj = { 'actual_colname': key };
                  let colname = key.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
                  obj['colname'] = colname;
                  let dontShowCol = (colname == 'Srno' || colname == 'AdKPIId' || colname == 'ReportValue' || colname == 'Color' || colname == 'DisplayOrder' || colname == 'KPIDrilldown');

                  // Add columns to display
                  if (!dontShowCol && !allCols.some(col => col.actual_colname === key)) {
                    allCols.push(obj);
                  }
                }
                i++;
              }
            }

            // Adjust column width based on the number of columns
            if (allCols.length > 0) {
              let colLen = allCols.length;
              columnWidth = (94 / colLen) + '%';
            }

            // No need to map through the rows again if you're not altering them.
            defData["success"] = true;
            defData["data"] = {
              "report_data": data_arr,
              "report_colWidth": columnWidth,
              "report_cols": allCols
            };

            return defData;
          }
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            defData["success"] = true;
            return defData;
          } else {
            defData["error"] = res;
            return defData;
          }

        }).catch((err) => {
          notify("Please retry downloading! There is some error while downloading data");
          props.set_startDownload({ startDownload: false });
          console.log('onDownload report error', err);
          return defData;
        });
    } else {
      return defData;
    }
  }


  async function getAppDashBReports() {

    console.log("sup getAppDashBReports called manager --->");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let arr = [];

    await db.transaction(async function (txn) {
      //get MenuAppDashboard Reports sections to show
      // only those report will be shown which parent id is either null or 0
      let q = `Select * from Sup_MenuAppDashboard where ParentId is null or ParentId='0' order by DisplayOrder`;
      await txn.executeSql(q, [], async function (txn2, txnres2) {
        console.log('Sup_MenuAppDashboard count:', txnres2.rows.length);
        if (txnres2.rows.length > 0) {
          for (let i = 0; i < txnres2.rows.length; i++) {
            let data = txnres2.rows.item(i);
            arr.push(data);
            if (i == txnres2.rows.length - 1) {
              // console.log("array-------",arr)
              setAppDashReportsSec(arr)
            }
          }
        }
        else {
          setAppDashReportsSec([])
        }
      }, function (txn2, txnerr) { console.log(txnerr); setAppDashReportsSec([]) });
    });
  }


  function DownloadErrorAlert() {

    let { ErrorMsg, ErrorSubMsg, ErrorDetail } = DErrorMsg;

    return (
      <CustomModal
        style={customStyle.dErrM_Style}
        titleStyle={customStyle.dErrMsg}
        title={(ErrorMsg || '')}
        message={(ErrorSubMsg || '')}
        messageStyle={customStyle.dErrSubMsg}
        showModal={showDErrAlert}
      >
        {ErrorDetail != null && ErrorDetail != '' && <Text style={customStyle.dErrDetail}>{ErrorDetail}</Text>}
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setshowDErrAlert(false) }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{'Ok'}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  async function refreshDashBReport() {
    console.log('refreshDashBReportSup');
    setLoaderTitle("Refreshing dashboard reports..")
    setProcessing(true);
    try {

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);

      let dk_index = DownloadTasks.findIndex(i => i.DownloadKey == 'Sup_MenuAppDashboard');
      var data = {
        Downloadtype: "Sup_MenuAppDashboard",
        Username: loginDetails.UserId,
        Param1: '',
        Param2: '',
      };
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, data);

      await getDownloadJson1(url, data)
        .then(async (res) => {
          let isAdded = await updateTaskRes(res, dk_index, 1);
          if (isAdded == true) {
            notify("Sup Dashboard reports  refreshed!");
            setProcessing(false);
          }
          else {
            notify("Cannot refresh sup dashboard reports!");
            setProcessing(false);
          }
        })
        .catch(err => {
          notify("Cannot refresh sup dashboard reports!");
          setProcessing(false);
        });

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

  const _renderAttendanceReport = (item) => {

    let report_key = item.DownloadKey;
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};

    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];
    // console.log("report_cols:",report_cols,report_data);


    return (
      <View style={styles.screen} >
        <View style={styles.divider} />

        <View style={styles.statsContainer}>

          {report_data?.map((item, index) => (
            <View key={index} style={styles.statItem}>
              <Text style={styles.presentStatValue}>{item.Attendance}</Text>
              <Text style={styles.statLabel}>{item.TotCount}</Text>
            </View>
          ))}

        </View>

        <View style={styles.divider} />
      </View>
    );
  };


  function renderPeopleList(activeTab) {

    const [peoplelist, setPeopleList] = useState([]);
    const [tabledata, setTableData] = useState([]);
    const [searchedmiddyItem, setSearchedMiddyItem] = useState('');

    const [filterData, setFilterData] = useState([]);

    useEffect(() => {
      getPeopleDataTable();
    }, [activeTab]);


    async function getPeopleDataTable() {
      try {

        db.transaction(async function (txn) {
          // get data for report 
          let q = `Select * from Sup_MenuAppDashboard where DashboardSection ='People' order by DisplayOrder`;
          console.log("Detailed reports q:", q);
          txn.executeSql(q, [], async function (txn2, txnres2) {
            console.log("Detailed reports count:", txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              let arr = [];
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                arr.push(data);
                if (i == txnres2.rows.length - 1) {
                  if (activeTab == 1) {
                    DownloadDataPeopledashboard(arr);
                    setTableData(arr);
                  }
                }
              }
            } else {

              setProcessing(false);
            }
          }, function (txnE, txnerr) { console.log(txnerr); setTableData([]); setProcessing(false); },);

        });


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


    function transformData(peoplelist) {
      const transformedData = [];

      peoplelist?.forEach(item => {
        // Check if EmpId already exists in transformedDatas
        let employee = transformedData.find(emp => emp.EmpId == item.EmpId);

        if (employee) {
          // If the employee already exists, just push the new KPI data to their KPIs array
          employee?.KPIs?.push({
            "KPI": item?.KPI,
            "PER": item?.PER,
            "Color": item?.Color,
          });
        } else {
          // If the employee doesn't exist, create a new entry
          transformedData.push({
            "EmpId": item?.EmpId,
            "NAME": item?.NAME,
            "LastMechandisedVisit": item?.LastMechandisedVisit,
            "KPIs": [
              {
                "KPI": item?.KPI,
                "PER": item?.PER,
                "Color": item?.Color,
              }
            ]
          });
        }
      });

      return transformedData;
    }

    const sortedPeopleList = React.useMemo(() => {
      return [...peoplelist].sort((a, b) => {
        if (a.NAME && b.NAME) {

          return a.NAME.localeCompare(b.NAME);
        } else {
          return 0;
        }
      });
    }, [peoplelist]);

    const transformedJSON = transformData(sortedPeopleList);

    const handleSearch = text => {
      // console.log(text)
      setSearchedMiddyItem(text);
      const filteredList = transformedJSON?.filter(item => {
        // console.log(item?.NAME, 'item....JJJj....');
        return item?.NAME?.toLowerCase()?.trim().includes(text?.toLowerCase()?.trim());
      });
      setFilterData(filteredList);
    };

    const ClearSearch = text => {
      setSearchedMiddyItem('');
      setFilterData(transformedJSON);
    };

    //  async function DownloadDataPeopledashboard(tabledata){

    //     // console.log(tabledata[0].DownloadKey)
    //     let downloadkey = tabledata[0].DownloadKey ;

    //     let loginInfo = await get_item('loginInfo');
    //     const loginDetails = JSON.parse(loginInfo);
    //     const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);

    //     let data='';

    //     data={ 
    //       Downloadtype:downloadkey,
    //       Username: loginDetails.UserId,
    //       Param1: '',
    //       Param2: '',
    //     }

    //     console.log(url,data);
    //     return await getDownloadJson1(url,data)
    //     .then(async(res)=>{  
    //       // console.log("DownloadDataPosSaleDefination res:",res);
    //       if(res.Sup_Dashboard_People!=null || res.Sup_Dashboard_People!= ''){

    //       let peopleListArr = [];
    //       peopleListArr= res.Sup_Dashboard_People; 

    //       if(peopleListArr?.length > 0 ) {

    //         setLoaderTitle("Downloading People list Data...");
    //         setProcessing(true);

    //         if(peopleListArr?.length > peoplelist) {
    //           setPeopleList(peopleListArr);
    //           notify("People list downloaded successfully.");
    //           setProcessing(false);
    //         }
    //         else{
    //          setPeopleList(peopleListArr);
    //          setProcessing(false);
    //         }

    //       } else {
    //         setPeopleList([]);
    //         notify('No data found!');
    //         setProcessing(false);
    //       }

    //     }

    //       else{
    //         notify('No data found!');
    //         setProcessing(false);
    //         return [];
    //       }        

    //     })
    //     .catch((err)=>{
    //       console.log('onPage Team error people',err);
    //       setProcessing(false);
    //       notify("Cannot download people list data!")
    //       return [];
    //     }); 
    //   }

    async function DownloadDataPeopledashboard(tabledata) {
      let downloadkey = tabledata[0].DownloadKey;

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);

      let data = {
        Downloadtype: downloadkey,
        Username: loginDetails.UserId,
        Param1: '',
        Param2: '',
      };

      console.log(url, data);

      return await getDownloadJson1(url, data)
        .then(async (res) => {
          // Check if res.Sup_Dashboard_People is valid
          if (res?.Sup_Dashboard_People) {
            let peopleListArr = res.Sup_Dashboard_People;

            // Proceed if we received data
            if (peopleListArr?.length > 0) {
              // Compare the new data length with existing peoplelist length
              const isDataChanged = peopleListArr.length !== peoplelist.length;

              // Only show loader if data has changed
              if (isDataChanged) {
                setLoaderTitle("Downloading People list Data...");
                setProcessing(true);
              }

              // Update state with the new data
              setPeopleList(peopleListArr);

              // Notify if the list is updated
              if (isDataChanged) {
                notify("People list downloaded successfully.");
              }

              // Hide the loader after processing
              setProcessing(false);

            } else {
              // No data found scenario
              setPeopleList([]);
              notify('No data found!');
              setProcessing(false);
            }
          } else {
            // Handle null or empty response
            notify('No data found!');
            setProcessing(false);
            return [];
          }
        })
        .catch((err) => {
          console.log('Error in downloading people list:', err);
          setProcessing(false);
          notify("Cannot download people list data!");
          return [];
        });
    }


    const ProgressBar = ({ progress, kpi }) => (

      <View style={styles.progressBarContainer}>
        <View style={[styles.progressBarFill, { width: `${progress}%`, backgroundColor: kpi?.Color }]} />
      </View>
    );


    const ListItem = ({ name, kpis, tabledata, items }) => {
      // console.log("tabledata------>",tabledata)
      return (
        <TouchableOpacity onPress={() => props.navigation.navigate('PeopleDetail', { "Reportdata": tabledata, "peopledata": items })}>
          <View style={styles.itemContainer}>
            {/* Name and Sale */}
            <View style={styles.textContainer}>
              <Text style={styles.nameText}>{name}</Text>
            </View>

            <View style={styles.verticalLine} />
            {kpis?.length > 0 &&
              kpis?.map((kpi, index) => {
                return (
                  <View>
                    <Text style={styles.saleText}>{kpi?.KPI}</Text>
                    <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: '#F6F6F6', borderRadius: 5, paddingVertical: 10, paddingHorizontal: 5 }}>
                      <ProgressBar progress={kpi?.PER} kpi={kpi} />
                      <Text style={styles.progressText}>{Math.round(kpi?.PER)}%</Text>
                    </View>
                  </View>
                )
              })
            }

            <View style={styles.verticalLine} />

            <Text style={[styles.nameText, { marginTop: 5 }]}>Store Visited: {items?.LastMechandisedVisit ? (moment(items?.LastMechandisedVisit).format('DD/MM/YYYY')) : 'NA'}</Text>

            {/* Progress Bar */}

          </View>
        </TouchableOpacity>
      );
    };

    let report_key = 'Sup_Dashboard_People';
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};

    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];

    // console.log("report_dataPeoples", report_data);

    return (
      <View style={{ paddingHorizontal: 10, marginTop: 10, flex: 1 }}>
        <Text style={{ color: '#000', fontSize: 15, fontWeight: '600', marginBottom: 5 }}>Sort By: Alphabet A To Z</Text>

        <View style={[
          customStyle.storel_searchbar,
          { marginHorizontal: 1, marginTop: 10 }
        ]}>
          <TextInput
            style={[customStyle.storel_searchInput]}
            placeholder={ST.SearchByPeopleName}
            autoComplete='off'
            placeholderTextColor={PageTheme.$placeholder_color}
            value={searchedmiddyItem}
            onChangeText={text => handleSearch(text)}
          />
          <TouchableOpacity style={[customStyle.storel_crossBtn]} onPress={(text) => { ClearSearch(text) }}>
            <Entypo style={[customStyle.storel_searchBtnIcon]} name='cross' size={28} color={PageTheme.$text_color} />
          </TouchableOpacity>

          <TouchableOpacity style={customStyle.storel_searchBtn}>
            <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
          </TouchableOpacity>
        </View>

        {filterData.length === 0 && searchedmiddyItem !== '' ? (
          <Text style={{ color: 'red', marginTop: 10, marginLeft: 10 }}>No results found</Text>
        ) :
          <FlatList
            data={searchedmiddyItem != '' ? filterData : transformedJSON || []}
            keyExtractor={(item, index) => index.toString()}
            contentContainerStyle={{
              paddingBottom: 250
            }}
            renderItem={({ item }) => <ListItem name={item.NAME} kpis={item.KPIs} tabledata={tabledata} items={item} />}
            scrollEnabled={true}
          />
        }
      </View>
    )
  }

  function _renderTabularReport(item) {
    let report_key = item.DownloadKey;
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};

    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];
    // console.log("report_cols:",report_data , "report_colss",report_cols);


    return (
      <View style={customStyle.DashBTbl_ReportWrap} >
        {/* render No data */}
        {report_data.length <= 0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
        {report_data.length > 0 && <ScrollView horizontal={true} style={{ width: '100%' }} contentContainerStyle={{}}>
          {/* render columns */}
          <View>
            {/* render header */}
            <View style={customStyle.DashBTbl_ReportHdr}>
              {report_cols.map((column, index) => {
                return (
                  <View style={[customStyle.DashBTbl_ReportHdrCol, customStyle.DashBTbl_ReportColW]}>
                    <Text style={customStyle.DashBTbl_ReportHdrColTxt}>{column.colname}</Text>
                  </View>
                )
              })}
            </View>

            {/* render content */}
            <View style={[customStyle.DashBTblBodyNB1, { marginTop: -5 }]}>
              <View style={[customStyle.DashBTblBodyNB2]}>
                {report_data.map((row, row_index) => {

                  let gset_obj = row["Color"] != null && row["Color"] != null != '' ? (row["Color"]) : {};

                  // console.log("gset_obj",gset_obj);

                  return (
                    <View disabled={item.DrillDown ? false : true} style={[customStyle.DashBTbl_Item, (row_index == report_data.length - 1 ? {} : customStyle.DashBTbl_ItemB), { borderRadius: 5 }]}>
                      {report_cols.map((column, index) => {
                        let colValue = row[column.actual_colname] != null ? row[column.actual_colname] : '';

                        // console.log("colValue",colValue)

                        let color_obj = get_rowColSettings(colValue, column.actual_colname, row);

                        let cust_style = {}, bg_style = {};
                        if (color_obj.color != null && color_obj.color != '') {
                          bg_style["backgroundColor"] = color_obj.color;
                          cust_style["color"] = '#fff'
                        }
                        if (color_obj.fontsize != null && color_obj.fontsize != '') {
                          cust_style["fontSize"] = color_obj.fontsize
                        }
                        if (color_obj.bold == 1) {
                          cust_style["fontWeight"] = "600"
                        }

                        return (
                          <Pressable
                            style={[customStyle.DashBTbl_ItemCol, customStyle.DashBTbl_ReportColW, bg_style]}
                            onLongPress={() => toggleModal(column.colname, colValue, row, item)}
                          >
                            <Text style={[customStyle.DashBTbl_ItemColText, cust_style]}>{colValue}</Text>
                          </Pressable>
                        )
                      })}
                    </View>
                  )
                })}
              </View>
            </View>
          </View>

        </ScrollView>}
      </View>
    )
  }

  function _renderCardReport(item) {
    let report_key = item.DownloadKey;
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};

    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];
    //  console.log("report_cols:",report_data ,"itemss",item);
    let ShowGraph = item?.ShowGraph

    return (
      <View style={customStyle.DashBTbl_ReportWrap} >
        {/* render No data */}
        {report_data.length <= 0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
        {report_data.length > 0 && <ScrollView horizontal={true} style={{ width: '100%' }} contentContainerStyle={{}}>
          {/* render columns */}

          <View>
            {/* render content */}
            <View style={customStyle.DashBCard_Wrap}>
              <FlatList
                numColumns={2}
                data={report_data}
                keyExtractor={(item, index) => index.toString()}
                renderItem={({ item, index }) => {
                  let gset_obj = item["Color"] != null && item["Color"] != '' ? item["Color"] : {};
                  let card_bgColor = gset_obj["bgColor"] != null ? gset_obj["bgColor"] : '';
                  let card_font = gset_obj["font"] != null ? gset_obj["font"] : {};
                  let card_name = gset_obj["card_name"] != null ? gset_obj["card_name"] : '';
                  let card_icon = gset_obj["icon"] != null ? gset_obj["icon"] : '';
                  let show_random_icon = gset_obj["random_icon"] != null ? gset_obj["random_icon"] : true;
                  let hide_report_name = gset_obj["hide_report_name"] != null ? gset_obj["hide_report_name"] : false;
                  let isfirsItem = index == 0;
                  let islastItem = index == report_data.length - 1;
                  let isLastItem = report_data.length % 2 !== 0 && index === report_data.length - 1;

                  // console.log("itemm----",item)

                  const chartConfig = {
                    backgroundGradientFrom: "#fff",
                    backgroundGradientTo: "#fff",
                    color: (opacity = 1, dataIndex) => {
                      const color = gset_obj;
                      return color ? `${color}${Math.floor(opacity * 255).toString(16).padStart(2, '0')}` : `rgba(255, 255, 255, 0)`;
                    },
                    strokeWidth: 2,
                    barPercentage: 0.5,
                    useShadowColorFromDataset: false,
                  };

                  let label = [];
                  let labelVal = [];
                  let barColor = [];

                  label.push(item?.KPI);
                  let percentage = item?.PER?.replace('%', '');

                  if (percentage > 100) {
                    labelVal.push(parseFloat(100) / 100);
                  } else {
                    labelVal.push(parseFloat(item?.PER) / 100);
                  }
                  barColor.push(() => item?.Color);

                  let showgraph = ShowGraph ? ShowGraph : false;

                  let itemStyle = isLastItem ? { flex: 1, marginLeft: 'auto', marginRight: 'auto', width: '95%' } : { flex: 1 };

                  return (
                    <TouchableOpacity
                      disabled={item.DrillDown ? false : true}
                      style={[
                        report_data.length > 1
                          ? [customStyle.DashBCard_ItemNB1, { width: WP(isLastItem ? '92%' : '45%'), margin: 5, paddingVertical: 0, paddingHorizontal: 0 }]
                          : [customStyle.DashBCard_ItemNB1, { width: WP('95%') }],
                        (!isfirsItem && !islastItem ? customStyle.DashBCard_ItemMid : (isfirsItem ? customStyle.DashBCard_ItemFirst : customStyle.DashBCard_ItemLast))
                      ]}
                    >
                      <View style={[
                        report_data.length > 1
                          ? [customStyle.DashBCard_ItemNB2, { width: WP(isLastItem ? '92%' : '45%'), margin: 0, paddingVertical: 0, paddingHorizontal: 0 }]
                          : [customStyle.DashBCard_ItemNB2, { width: WP('95%') }]
                      ]}>
                        <View style={[customStyle.DashBCard_ItemContent, { paddingVertical: 8, paddingHorizontal: 5 }]}>
                          {item?.Attendance != null && item?.Attendance != undefined &&
                            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 0, justifyContent: 'space-between' }}>
                              <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>{item?.Attendance}</Text>
                              <Text style={{ color: `${gset_obj}`, fontSize: 18, fontWeight: '500', borderColor: `${gset_obj}`, borderWidth: 1, borderRadius: 5, padding: 8, textAlign: 'center' }}>{item?.TotalCount}</Text>
                            </View>
                          }

                          {item?.KPI != null && item?.KPI != undefined && <Text style={{ color: '#000', fontSize: 13, fontWeight: '700' }}>{item?.KPI}</Text>}
                          {item?.AvgCFT != null && item?.AvgCFT != undefined && <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>{item?.AvgCFT}</Text>}

                          {item?.TGT != null && item?.TGT != undefined &&
                            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 }}>
                              <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>Target: </Text>
                              <Text style={{ color: '#000', fontSize: 16, fontWeight: '500' }}>{item?.TGT}</Text>
                            </View>
                          }

                          {item?.ACT != null && item?.ACT != undefined && (!showgraph ? (
                            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 15, marginBottom: 5 }}>
                              <View>
                                <Text style={{ color: '#000', fontSize: 24, fontWeight: '700' }}>{item?.ACT}</Text>
                                <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>Achievement</Text>
                              </View>
                              <View style={{ alignSelf: 'center', marginTop: 10, borderColor: `${gset_obj}`, borderWidth: 1, borderRadius: 5, padding: 8 }}>
                                <Text style={{ color: `${gset_obj}`, fontSize: 18, fontWeight: '500' }}>{item?.PER}</Text>
                              </View>
                            </View>
                          ) : (
                            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
                              <View>
                                <Text style={{ color: '#000', fontSize: 24, fontWeight: '700' }}>{item?.ACT}</Text>
                                <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>Achievement</Text>
                              </View>
                              <View style={styles.chartContainer}>
                                <ProgressChart
                                  absolute
                                  data={labelVal}
                                  width={WP('21.5%')}
                                  height={HP('10%')}
                                  strokeWidth={5}
                                  radius={30}
                                  chartConfig={chartConfig}
                                  hideLegend={true}
                                  style={{
                                    marginVertical: 1,
                                    borderRadius: 16,
                                    backgroundColor: "transparent"
                                  }}
                                />
                                <View style={styles.percentageContainer}>
                                  <Text style={{ color: `${gset_obj}`, fontSize: 18, fontWeight: '500' }}>{item?.PER}</Text>
                                </View>
                              </View>
                            </View>
                          ))}

                          {item?.Vacancy != null && item?.Vacancy != undefined &&
                            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 0, justifyContent: 'space-between' }}>
                              <Text style={{ color: '#000', fontSize: 13, fontWeight: '400' }}>{item?.Name}</Text>
                              <Text style={{ color: '#000', fontSize: 18, fontWeight: '500', borderColor: (gset_obj ? `${gset_obj}` : ''), borderWidth: (gset_obj ? 1 : 0), borderRadius: 5, padding: 8, textAlign: 'center' }}>{item?.Vacancy}</Text>
                            </View>
                          }

                        </View>
                      </View>
                    </TouchableOpacity>
                  );
                }}
              />

            </View>
          </View>

        </ScrollView>}
      </View>
    )
  }

  function _renderDashboardReports() {

    const [activeTabday, setActiveTabDay] = useState(0);

    const mainScreenTabs = AppDashReportsSec?.filter(item => item?.DashboardSection == "MainScreen")?.map(item => item?.TabName)?.filter(tabName => tabName);


    const uniqueTabs = [...new Set(mainScreenTabs)];

    const tabs = uniqueTabs.map((tabName) => ({
      title: tabName,  // Tab title
      content: `${tabName} content` // Placeholder for the content
    }));


    const filteredData = AppDashReportsSec?.filter((item) => item?.TabName?.includes(tabs[activeTabday].title));


    const renderItem = ({ item, index }) => {
      const isAttendance = item?.DownloadKey && item?.DownloadKey?.includes("Attendance");

      return (
        <View style={customStyle.DashB_ReportConNB} key={index}>
          <View style={customStyle.DashB_ReportConHdr}>
            <Text style={[customStyle.DashB_ReportConHdrTxt, { marginBottom: 5, marginLeft: 5 }]}>{item.DashboardName}</Text>

            {/* Render attendance data separately */}
            {/* isAttendance == true && _renderAttendanceReport(item) */}

            {/* Render custom view for Attendance reports */}
            {item.DashboardType === 'Card' && _renderCardReport(item)}

            {item.DashboardType === 'Tabular' && _renderTabularReport(item)}

            {/* Uncomment if needed */}
            {/* {item.DrillDown && 
            <TouchableOpacity style={customStyle.DashB_ReportConHdrIcon} onPress={() => { props.navigation.navigate("DashboardReportDetail", { "ReportData": item }) }}>
              <MaterialCommunityIcons name="arrow-right-thick" size={20} color={PageTheme.$accent_color} />
            </TouchableOpacity>} */}
          </View>
        </View>
      );
    };

    return (
      <View style={customStyle.DashB_ReportWrap}>

        {/* Custom Tab Bar */}
        <View style={[styles.subtabBar,]}>
          {tabs.map((tab, index) => (
            <TouchableOpacity
              key={index}
              style={[styles.subtabButton, activeTabday === index ? styles.subactiveTab : styles.subinactiveTab, { marginRight: 10 }]}
              onPress={() => setActiveTabDay(index)}
            >
              <Text style={[styles.tabText, activeTabday === index ? styles.subactiveTabText : styles.subinactiveTabText, {}]}>
                {tab.title}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        <View style={[styles.verticalLine, { marginVertical: 10, height: 2 }]} />

        {filteredData.length > 0 &&
          <>
            <View style={[customStyle.mtb5, { flexDirection: 'row', justifyContent: 'space-between', width: '95%', left: 10 }]}>
              <TouchableOpacity onPress={() => { refreshDashBReport() }} style={[customStyle.Dashboard_refrehButton]}>
                <Text style={[customStyle.hr_viewButtonText, { color: '#000000' }]}>REFRESH</Text>
                <View style={[globalStyle.drawerItemIcon, { width: 30 }]} ><Feather name="refresh-cw" size={18} color={'#000'} /></View>
              </TouchableOpacity>

              <TouchableOpacity style={[customStyle.Dashboard_viewButton]} onPress={() => { props.navigation.navigate('DashboardReportDetail', { "ReportData": {} }) }}>
                <View>
                  <Text style={[customStyle.hr_viewButtonText, { color: '#000000' }]}>SEE DETAIL</Text>
                </View>
                <View style={[globalStyle.drawerItemIcon, { width: 15 }]}><Feather name="chevron-right" size={20} color={'#000'} /></View>
              </TouchableOpacity>
            </View>
          </>
        }

        <View style={[]}>
          <FlatList
            data={filteredData || []}
            renderItem={renderItem}
            keyExtractor={(item, index) => index.toString()}
            contentContainerStyle={{ paddingBottom: 100 }}
          />
        </View>


      </View>
    )
  }

  function _renderDashboardView() {

    const [activeTab, setActiveTab] = useState(0);

    const tabs = [
      // { title: 'Dashboard', content: _renderDashboard() },
      { title: 'Dashboard', content: _renderDashboardReports() },

      { title: 'People', content: renderPeopleList(activeTab) },
    ];

    return (
      <View style={styles.container}>
        {/* Custom Tab Bar */}
        <View style={styles.tabBar}>
          {tabs.map((tab, index) => (
            <TouchableOpacity
              key={index}
              style={[styles.tabButton, activeTab === index && styles.activeTab]}
              onPress={() => setActiveTab(index)}
            >
              <Text style={[styles.tabText, activeTab === index && styles.activeTabText]}>
                {tab.title}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        {/* Screen Content */}
        <View style={styles.screenContainer}>
          {tabs[activeTab].content}
        </View>
      </View>
    )
  }

  // console.log("AppDashReportsSec", AppDashReportsSec)
  const excludeKeys = ['AdKPIId', 'Color', 'KPIDrilldown', 'DisplayOrder'];



  // WebView Survey

  const [surveydata, setSurveyData] = useState({});
  const [modalVisiblesurvey, setModalVisibleSurvey] = useState(false);
  const [surveyloader, setSurveyLoader] = useState(false);
  const webViewRef = useRef(null);
  const isFocused = useIsFocused();

  const ShowSurveyPopup = async () => {
    console.log("Survey popup called---")
    let projectInfo = await get_item('projectInfo');
    let projectCode = await get_item('projectCode');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const projectDetails = JSON.parse(projectInfo);

    try {
      setSurveyLoader(true);
      const raw = JSON.stringify({
        ProjectId: projectDetails?.projectID,
        UserId: loginDetails?.UserId || '',

      });
      let res = await fetch(
        "https://api1.parinaam.in/api/cpminternal/GetPopupWeburl",
        {
          method: "POST",
          body: raw,
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        }
      );
      let responseJson = await res.json();
      if (responseJson) {
        setSurveyData(responseJson?.GetPopupWeburl || {});
        // console.log("responseJson?.GetPopupWeburl[0]?.Status",responseJson?.GetPopupWeburl[0])
        if (responseJson?.GetPopupWeburl[0]?.Status) {
          setModalVisibleSurvey(false);
        } else {
          setModalVisibleSurvey(true);
        }

      } else {
        setSurveyData({});
      }
    } catch (error) {
      Alert.alert("Survey Popup:" + error);
    } finally {
      setSurveyLoader(false);
    }
  };

  useEffect(() => {
    ShowSurveyPopup();
  }, [isFocused]);

  let webUrl = surveydata[0]?.WebUrl;


  const injectedJS = `
  (function() {
    const element = document.getElementById('cpminternalclose');
    console.log(element, "element")
    if (element) {
      window.ReactNativeWebView.postMessage(JSON.stringify({ id: element.id }));
    } else {
      // window.ReactNativeWebView.postMessage(JSON.stringify({ message: "Element not found" }));
    }
  })();
  true;
  `;

  const handleMessage = (event) => {
    try {
      const data = JSON.parse(event.nativeEvent.data);
      if (data.error) {
        Alert.alert(data.error);
      } else {
        console.log('Element data:', data);
        if (data?.id == 'cpminternalclose') {
          setTimeout(() => {
            setModalVisibleSurvey(false);
            ShowSurveyPopup();
          }, 1500);
        } else {
          Alert.alert("Id not found");
        }

      }
    } catch (error) {
      Alert.alert('Error parsing message:', error);
    }
  };

  return (

    <>
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)} >
        {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
        {(props.startDownload && dowloadedCount <= totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText} />}
        <DownloadErrorAlert />
        <DrawerHeader {...props} drawer_title={ST.NoticeBoard} projectCode={projectCode} />
        {/* <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
      <View style={[customStyle.pageContentWrapper,customStyle.roundScrollInner,{paddingTop:0}]}>
      {(state.webviewurl!='' && state.webviewurl!=null) && <WebView style={customStyle.fullwebview} containerStyle={customStyle.webViewCon} source={{ uri: state.webviewurl }} />}
      </View>
    </LinearGradient>  */}

        <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={customStyle.noticeboard_customstylewrapper}>

            <View style={customStyle.noticeboard_background} >
              <Text style={customStyle.noticeboard_text}> Quick Links</Text>
              <FlatList
                horizontal={true}
                data={DATA}
                renderItem={({ item, index }) => {
                  // console.log('onrender item ', item);
                  let IconCompFunc = item.icon;
                  let showVectoreIcon = item.iconType == 'Icon' ? true : false;
                  return (
                    <View style={customStyle.noticeboard_tblHdrparent} key={index}>
                      <TouchableOpacity onPress={item.itemOnPress} >
                        <View style={[customStyle.noticeboard_tblHdr, (!showVectoreIcon ? customStyle.noticeboard_tblHdr2 : {}), (index % 2 != 0 ? { backgroundColor: '#f4e8fb' } : {})]} >
                          {!showVectoreIcon && <SvgXml width={45} height={45} marginTop={10} xml={item.icon} />}
                          {showVectoreIcon && IconCompFunc()}
                        </View>
                        <Text style={customStyle.noticeboard_tblTextItem} >{item.text}</Text>
                      </TouchableOpacity>
                    </View>
                  )
                }}
              />
            </View>

            <ScrollView style={{}}>
              {bannerdetail.length > 0 &&
                <View style={customStyle.bannerimagebackground} >
                  <Carousel
                    ref={imageSlider}
                    sliderWidth={WP('100%') - 20}
                    itemWidth={WP('100%') - 40}
                    autoplay={true}
                    loop={true}
                    autoplayDelay={1000}
                    data={bannerdetail}
                    style={{ backgroundColor: '#000', width: '100%' }}
                    contentContainerStyle={{ backgroundColor: 'red' }}
                    onSnapToItem={(index) => { setActiveSlide(index) }}
                    renderItem={({ item, index }) => {
                      let url = item.NoticeLink_Thumbnail;
                      // console.log('onrender item ',url);
                      return (
                        <View style={[customStyle.bannerCard]}>
                          <TouchableOpacity onPress={() => { props.navigation.navigate('Bannerdetail', { imagedesc: item }) }} >
                            <Image source={{ uri: url }} key={index} style={customStyle.bannerCardImg} />
                          </TouchableOpacity>
                        </View>
                      )
                    }}
                  />

                  <Pagination
                    dotsLength={bannerdetail.length}
                    activeDotIndex={activeSlide}
                    dotColor={PageTheme.$primary_color}
                    containerStyle={{ marginBottom: -30, marginTop: -20 }}
                    dotStyle={{
                      width: 10,
                      height: 10,
                      borderRadius: 5, elevation: 2,
                    }}
                    activeOpacity={0.6}
                    inactiveDotColor={PageTheme.$tertiary_color}
                    inactiveDotOpacity={0.4}
                    inactiveDotScale={0.8}
                    carouselRef={imageSlider}
                    tappableDots={true}
                  />

                </View>
              }

              {props.Show_OldMTDReports &&
                <View style={customStyle.sfimagebackground} >
                  <Text style={customStyle.noticeboard_text}>Performance</Text>
                  <FlatList
                    horizontal={true}
                    data={storeperformancetext}
                    renderItem={({ item, index }) => {
                      return (
                        <View style={customStyle.sftblHdrparent} key={index}>
                          <TouchableOpacity disabled={true}>
                            <View style={[customStyle.sftblHdr, (index % 2 != 0 ? { backgroundColor: '#f4f1e0' } : { backgroundColor: '#fbe7e8' })]} >
                              <SvgXml width={'100%'} height={'50%'} marginTop={5} marginLeft={15} xml={item.icon} />
                              <View style={customStyle.sf_storecol}>
                                <Text style={customStyle.sftblTextItem} >{item.text}</Text>
                                <Text style={customStyle.sftblTextValue} >{item.value}</Text>
                              </View>
                            </View>

                          </TouchableOpacity>
                        </View>

                      )
                    }}
                  />
                </View>
              }

              {props.ShowDashboard && _renderDashboardView()}

            </ScrollView>


            <Modal
              animationType="fade"
              transparent={true}
              visible={modalVisible}
              onRequestClose={() => {
                Alert.alert('Modal has been closed.');
                setModalVisible(!modalVisible);
              }}>
              <View style={customStyle.modalContainer}>
                <View style={customStyle.centeredView}>
                  <View style={customStyle.modalView}>

                    <TouchableOpacity style={[customStyle.modalrow, { justifyContent: 'space-between' }]} onPress={() => setModalVisible(false)}>
                      <View><Text style={[customStyle.DashBTbl_ReportHdrColTxt, { color: '#000', fontWeight: '700', fontSize: 16 }]}>{modaldata?.item.DashboardName + ' Detail'}</Text></View>
                      <View style={{ marginLeft: 10 }}><SvgXml width={35} height={35} xml={cross_icon} /></View>
                    </TouchableOpacity>

                    <View style={customStyle.modalInView}>
                      {Object.entries(modaldata?.row)
                        .filter(([key]) => !excludeKeys.includes(key)) // Filter out excluded keys
                        .map(([key, value]) => (
                          <View key={key} style={customStyle.modalrow}>
                            <Text style={[customStyle.DashBTbl_ReportHdrColTxt, { color: '#000', fontWeight: '700' }]}>{key}: </Text>
                            <Text style={[customStyle.DashBTbl_ReportHdrColTxt, { color: '#000' }]}>{value.toString()}</Text>
                          </View>
                        ))}
                    </View>

                  </View>
                </View>
              </View>
            </Modal>

          </View>
        </LinearGradient>

      </Container>

      {
        <Modal
          animationType="slide"
          transparent={true}
          visible={modalVisiblesurvey}
          // visible={true}
          onRequestClose={() => setModalVisibleSurvey(false)}
        >
          <View style={styles.modalContainer}>
            <View style={styles.modalContent}>
              {surveyloader && <CustomLoader fullHeight={true} title={"Loading"} />}
              <WebView
                style={styles.webView}
                source={{ uri: webUrl }}
                onLoadStart={() => setSurveyLoader(true)}
                onLoadEnd={() => {
                  setSurveyLoader(false);
                  // setWebViewReady(true);
                  console.log("ENd Loadingggg...---");
                }}
                ref={webViewRef}
                injectedJavaScript={injectedJS}
                onMessage={handleMessage}
              />
            </View>
          </View>
        </Modal>
      }
    </>

  );
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  tabBar: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: '#e6ecec',
  },
  tabButton: {
    paddingHorizontal: 30,
    paddingVertical: 10

  },
  subtabButton: {
    paddingHorizontal: 20,
    paddingVertical: 6

  },
  tabText: {
    fontSize: 16,
    color: '#666',
  },
  activeTab: {
    borderBottomWidth: 3,
    borderBottomColor: '#000',
  },
  activeTabText: {
    color: '#000',
    fontWeight: '500'
  },
  subtabBar: {
    flexDirection: 'row',
    // justifyContent: 'space-around',
    paddingHorizontal: 10,
    marginTop: 10
  },
  subactiveTab: {
    borderRadius: 20,
    backgroundColor: '#01978C',
    //overflow: 'hidden',
  },
  subinactiveTab: {
    borderRadius: 20,
    borderColor: '#01978C',
    borderWidth: 1,
    overflow: 'hidden'
  },
  subactiveTabText: {
    color: '#fff',
    fontWeight: '500'
  },
  subinactiveTabText: {
    color: '#000',
    fontWeight: '500'
  },
  screenContainer: {
    //  flex:1
  },
  screen: {
    //  flex:1
  },
  screenText: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  divider: {
    height: 2,

  },
  verticalLine: {
    height: 1.5,
    width: '100%',
    backgroundColor: '#ACB7C233',
    marginVertical: 5
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    // alignItems: 'center',
    // width: WP('92%'), 
    backgroundColor: '#71c4c0',
    padding: 0
  },
  statItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  presentStatValue: {
    backgroundColor: '#71c4c0',
    padding: 15,
    fontSize: 14,
    fontWeight: '500',
    color: '#000'
  },
  absentStatValue: {
    backgroundColor: '#F8C6AB',
    padding: 15,
    fontSize: 14,
    fontWeight: '500',
  },
  statLabel: {
    paddingLeft: 20,
    paddingRight: 20,
    fontSize: 14,
    fontWeight: '500',
    color: '#000'
  },
  // list of peoples 
  itemContainer: {
    backgroundColor: '#fff',
    padding: 10,
    borderRadius: 10,
    marginVertical: 10,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 5,
    borderColor: '#B2BCCE',
    borderWidth: 1
  },
  textContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 5,
  },
  nameText: {
    fontSize: 15,
    fontWeight: '500',
    color: '#000000',

  },
  saleText: {
    fontSize: 14,
    fontWeight: '400',
    color: '#000',
    marginBottom: 5,

  },
  progressBarContainer: {
    height: 8,
    flex: 1,
    backgroundColor: '#D3D3D3',
    borderRadius: 5,
    overflow: 'hidden',
  },
  progressBarFill: {
    height: '100%',
    // backgroundColor: '#00968e',
    borderRadius: 5,
  },
  coverageButton: {
    backgroundColor: '#E9F1FE',
    paddingVertical: 10,
    borderRadius: 5,
    flexDirection: 'row',
    alignItems: 'center',
    width: '40%',
    justifyContent: 'center',
    // alignSelf: 'flex-end'
    alignSelf: 'flex-start'


  },
  progressText: {
    marginLeft: 10,
    fontSize: 14,
    color: '#000',
    fontWeight: '500'
  },
  buttonText: {
    color: 'gray',
    fontSize: 14,
    fontWeight: '500',
  },
  chartContainer: {
    position: 'relative',
    alignItems: 'center',
    marginTop: 0
  },
  percentageContainer: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{ translateX: -15 }, { translateY: -12 }],
  },

  // modal survey
  // modal
  screen: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f2f2f2',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
  modalContainer: {
    flex: 1,
    // backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
    marginTop: -20
  },
  modalContent: {
    width: '90%',
    height: '90%',
    backgroundColor: '#fff',
    borderRadius: 10,
    overflow: 'hidden',
  },
  webView: {
    flex: 1,
  },
});


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