import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db } from '../constants/constants';
import { getMethodName, METHODS } from '../constants/methodNames';
import { getDownloadJson1 } from '../controller/functions';
import { AppName, PerformicsIRAppName } from '../../../AppSpecificContant';
import { Platform } from 'react-native';

export const PJP_colList = ['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', 'CameraAllow', 'AddVisiAllow', 'LastVisitDate', 'Score', 'MinTimeTaken', 'StoreCategoryId', 'StoreCategory', 'StoreClassId', 'StoreClass', 'TaxType', 'GSTno', 'GSTImage', 'MTDMerchandised', 'DistributorId'];

export function getDownloadDataTask() {
  var DownloadTasks = ["Table_Structure"]; // not required in redownload  
  DownloadTasks.push("Mapping_JourneyPlan"); // not required in redownload 
  DownloadTasks.push("Adhoc_JourneyPlan"); // not required in redownload
  DownloadTasks.push("NonProgram_JourneyPlan"); // not required in redownload
  DownloadTasks.push("Master_Distributor"); // not required in redownload
  // DownloadTasks.push("Master_Route"); // not required in redownload
  DownloadTasks.push("Master_MenuAppDashboard");

  DownloadTasks.push("Product_Master");
  DownloadTasks.push("Report_AferCheckIn"),

    DownloadTasks.push("Non_Working_Reason"); // not required in redownload
  DownloadTasks.push("Menu_Master"); // not required in redownload
  DownloadTasks.push("Mapping_Menu");
  DownloadTasks.push("Mapping_MenuConfiguration"); // not required in redownload
  DownloadTasks.push("Mapping_MenuDistributorPoint");
  DownloadTasks.push("Master_Category"); // not required in redownload
  DownloadTasks.push("Master_Competitor"); // not required in redownload && only used in competition vis, comp promo, sampling
  DownloadTasks.push("Master_NonVisibility"); // not required in redownload
  DownloadTasks.push("Master_Display"); // not required in redownload
  DownloadTasks.push("Mapping_ProductAssortmentStorewise");
  DownloadTasks.push("Mapping_ProductAssortment");
  DownloadTasks.push("Mapping_Visibility");
  DownloadTasks.push("LastVisit_ClosingStock");

  DownloadTasks.push("Master_Feedback"); // not required in redownload
  DownloadTasks.push("Master_IssueCategory");
  DownloadTasks.push("Master_IssueType"); // not required in redownload
  DownloadTasks.push("Master_PromoType"); // not required in redownload
  DownloadTasks.push("Master_WindowDefinition");
  DownloadTasks.push("Mapping_StoreWindow");
  DownloadTasks.push("Master_WindowQuestion");
  DownloadTasks.push("Mapping_WindowQuestion");
  DownloadTasks.push("Master_WindowReason");
  DownloadTasks.push("Master_WindowStockDefinition");
  DownloadTasks.push("Master_POSMDefinition");
  DownloadTasks.push("Mapping_StorePOSM");
  DownloadTasks.push("Master_POSMReason");
  DownloadTasks.push("Master_POSMQuestion");
  DownloadTasks.push("Mapping_POSMQuestion");
  // DownloadTasks.push("User_CurrentPosmStock");
  DownloadTasks.push("Master_VisibilityDefinition");
  DownloadTasks.push("Mapping_StoreVisibility");
  DownloadTasks.push("Master_VisibilityQuestion");
  DownloadTasks.push("Mapping_VisibilityQuestion");
  DownloadTasks.push("Master_VisibilityStockDefinition");
  DownloadTasks.push("Master_VisibilityReason");
  DownloadTasks.push("Master_PromotionDefinition");
  DownloadTasks.push("Mapping_StorePromotion");
  DownloadTasks.push("Master_PromotionQuestion");
  DownloadTasks.push("Mapping_PromotionQuestion");
  DownloadTasks.push("Master_PromotionStockDefinition");
  DownloadTasks.push("Master_PromotionReason");
  DownloadTasks.push("Master_ShareOfShelfDefinition");
  DownloadTasks.push("Mapping_StoreShareOfShelf");
  DownloadTasks.push("Mapping_ShareOfShelfTarget");
  DownloadTasks.push("Mapping_StoreShareOfShelfTarget");
  DownloadTasks.push("Master_ImageType"); // not required in redownload
  DownloadTasks.push("Report_PromoterMerchandiserPerformance"); // not required in redownload
  DownloadTasks.push("Master_Checklist");
  DownloadTasks.push("Mapping_DisplayChecklist");
  DownloadTasks.push("Master_SurveyQuestion");
  DownloadTasks.push("Master_FeedbackQuestion");
  DownloadTasks.push("Mapping_Survey");
  DownloadTasks.push("Master_CategoryDefinition");
  DownloadTasks.push("Mapping_StoreCategory");
  DownloadTasks.push("Master_CategoryQuestion");
  DownloadTasks.push("Mapping_CategoryQuestion");
  DownloadTasks.push("Master_CategoryStockDefinition");
  DownloadTasks.push("Master_CategoryReason");
  DownloadTasks.push("Master_PosSaleDefinition");
  DownloadTasks.push("Mapping_PosSaleDefinition");
  DownloadTasks.push("Mapping_StorePosSaleDefinition");
  DownloadTasks.push("Master_PosSaleReason");
  DownloadTasks.push("Report_ComplianceScore"); // not required in redownload
  DownloadTasks.push("Master_Document"); // not required in redownload
  DownloadTasks.push("Master_StoreChecklist");
  DownloadTasks.push("Master_MenuReports"); // not required in redownload
  DownloadTasks.push("Master_City"); // not required in redownload
  DownloadTasks.push("Master_StoreType"); // not required in redownload
  DownloadTasks.push("Master_Chain"); // not required in redownload 
  DownloadTasks.push("Master_StoreCategory"); // not required in redownload 
  DownloadTasks.push("Master_StoreClass"); // not required in redownload 
  DownloadTasks.push("Non_Working_ReasonDistributor"); // not required in redownload
  DownloadTasks.push("Master_Channel"); // not required in redownload
  DownloadTasks.push("PriviousVisit_Orders");
  DownloadTasks.push("NonMerchandising_JourneyPlan"); // not required in redownload
  DownloadTasks.push("Master_VisitorFeedbackQuestion");
  DownloadTasks.push("Master_VisitorLoginQuestion");
  DownloadTasks.push("Mapping_StoreVisibilitySpecific");
  DownloadTasks.push("Master_SamplingDefinition");
  DownloadTasks.push("Master_SamplingStockDefinition");
  DownloadTasks.push("Mapping_StoreSampling");
  DownloadTasks.push("Master_SamplingQuestion");
  DownloadTasks.push("Mapping_SamplingQuestion");
  DownloadTasks.push("Master_SamplingReason");
  DownloadTasks.push("Master_Program");
  DownloadTasks.push("Master_ProgramDefinition");
  DownloadTasks.push("Mapping_StoreProgram");
  DownloadTasks.push("Master_ProgramQuestion");
  DownloadTasks.push("Mapping_ProgramQuestion");
  DownloadTasks.push("Master_ProgramStockDefinition");
  DownloadTasks.push("Master_ProgramReason");
  DownloadTasks.push("Mapping_StoreAuditGrading");
  DownloadTasks.push("Mapping_StoreTargetBased");
  DownloadTasks.push("Master_TargetBasedQuestion");
  DownloadTasks.push("Mapping_TargetBasedQuestion");
  DownloadTasks.push("Master_ContractFormQuestion");
  DownloadTasks.push("Mapping_ContractForm");
  DownloadTasks.push("Master_NonContractFromReason");
  DownloadTasks.push("Master_ShareOfShelfEyeLevelDefinition");
  DownloadTasks.push("Mapping_StoreShareOfShelfEyeLevel");
  DownloadTasks.push("Master_DistributorFilter");
  DownloadTasks.push("Master_CityFilter");
  DownloadTasks.push("Master_StoreTypeFilter");
  DownloadTasks.push("Master_DetailerContent"); // not required in redownload
  DownloadTasks.push("Master_UserHomeLocation");
  // DownloadTasks.push("Mapping_WarehouseItem");
  DownloadTasks.push("Master_WarehouseItem");
  DownloadTasks.push("Master_WarehouseItemQuestion");
  DownloadTasks.push("Mapping_WarehouseItemQuestion");
  DownloadTasks.push("Master_WarehouseNonDeployReason");
  DownloadTasks.push("Mapping_WarehouseCampaignItem");
  DownloadTasks.push("Mapping_WarehouseCampaignItemQuestion");
  DownloadTasks.push("Mapping_WarehouseCampaignDeployment");
  DownloadTasks.push("Mapping_WarehousePrimaryItem");
  DownloadTasks.push("Report_WarehouseStockInHand");
  DownloadTasks.push("Warehouse_InwardData");
  DownloadTasks.push("Master_WarehouseReason");
  DownloadTasks.push("Master_StockPromoType");
  DownloadTasks.push("Training_Document");
  DownloadTasks.push("Mapping_AddStoreConfiguration");

  DownloadTasks.push("KYC_StoreList");
  DownloadTasks.push("Mapping_KYCConfiguration");
  DownloadTasks.push("KYC_StoreListRejected");
  DownloadTasks.push("Mapping_KYCUploaded");
  let DownloadTasks1 = [];
  for (let i = 0; i < DownloadTasks.length; i++) {
    let key = DownloadTasks[i];
    let index = i + 1;
    let IsMandatory = (key == 'Table_Structure' || key == 'Mapping_JourneyPlan') ? true : false;
    let obj = { "KeyId": index, "DownloadKey": key, "IsMandatory": IsMandatory, "DevActive": true, "ProdActive": true, "DownloadSequence": index };
    DownloadTasks1.push(obj);
    if (i == DownloadTasks.length - 1) {
      return DownloadTasks1;
    }
  }
  // return DownloadTasks;
}

export const devDownloadKeys = (availableTables = []) => {
  const allDevKeys = [
    // "Master_MenuReportStoreWise",
    // "Mapping_SideMenuMiscellaneous",
    // "StoreList_OfflineOrder",
    // "Master_NonOrderReason",
    // "Mapping_AdditionalVisibilityProduct",
    // "Gyancast_TrainingContent",
    // "Gyancast_TrainingContentQuestion",
    // "Gyancast_PopupMessage"
  ];

  // ✅ Filter only those keys which exist in Table_Structure
  const filteredKeys = allDevKeys.filter(key => availableTables.includes(key));

  return filteredKeys.map((key, index) => {
    const IsMandatory = (key === 'Table_Structure' || key === 'Mapping_JourneyPlan');
    return {
      KeyId: index + 1,
      DownloadKey: key,
      IsMandatory,
      DevActive: true,
      ProdActive: true,
      DownloadSequence: index + 1
    };
  });
};

// export const devDownloadKeys = (availableTables = []) => {
//   const allDevKeys = [
//     "Mapping_ProductPTR"
//   ];

//   const shouldFilter = Array.isArray(availableTables) && availableTables.length > 0;
//   console.log("AvailbleFilterTable:",shouldFilter)

//   const filteredKeys = shouldFilter
//     ? allDevKeys.filter(key => availableTables.includes(key))
//     : allDevKeys; // 🔥 fallback

//   return filteredKeys.map((key, index) => ({
//     KeyId: index + 1000,
//     DownloadKey: key,
//     IsMandatory: false,
//     DevActive: true,
//     ProdActive: true,
//     DownloadSequence: index + 100
//   }));
// };





export async function getReDDownloadTask(AddKeys = []) {
  return await new Promise((resolve, reject) => {
    let myd = [];
    myd.push("Mapping_ProductAssortmentStorewise");
    myd.push("Mapping_ProductAssortment");
    myd.push("LastVisit_ClosingStock");
    myd.push("Mapping_StoreWindow");
    myd.push("Mapping_WindowQuestion");
    myd.push("Mapping_StorePOSM");
    myd.push("Mapping_POSMQuestion");
    myd.push("Mapping_StoreVisibility");
    myd.push("Mapping_VisibilityQuestion");
    myd.push("Mapping_StorePromotion");
    myd.push("Mapping_PromotionQuestion");
    myd.push("Mapping_StoreShareOfShelf");
    myd.push("Mapping_DisplayChecklist");
    myd.push("Mapping_Survey");
    myd.push("Mapping_StoreCategory");
    myd.push("Mapping_CategoryQuestion");
    myd.push("Mapping_StoreVisibilitySpecific");
    myd.push("Mapping_ShareOfShelfTarget");
    myd.push("Product_Master");
    myd.push("Mapping_Menu");
    myd.push("Mapping_MenuDistributorPoint");
    myd.push("Master_WindowDefinition");
    myd.push("Master_WindowQuestion");
    myd.push("Master_WindowReason");
    myd.push("Master_WindowStockDefinition");
    myd.push("Master_POSMDefinition");
    myd.push("Master_POSMReason");
    myd.push("Master_POSMQuestion");
    myd.push("User_CurrentPosmStock");
    myd.push("Master_VisibilityDefinition");
    myd.push("Master_VisibilityQuestion");
    myd.push("Master_VisibilityStockDefinition");
    myd.push("Master_VisibilityReason");
    myd.push("Master_PromotionDefinition");
    myd.push("Master_PromotionQuestion");
    myd.push("Master_PromotionStockDefinition");
    myd.push("Master_PromotionReason");
    myd.push("Master_ShareOfShelfDefinition");
    myd.push("Master_Checklist");
    myd.push("Master_SurveyQuestion");
    myd.push("Master_FeedbackQuestion");
    myd.push("Master_CategoryDefinition");
    myd.push("Master_CategoryQuestion");
    myd.push("Master_CategoryStockDefinition");
    myd.push("Master_CategoryReason");
    myd.push("Master_PosSaleDefinition");
    myd.push("Mapping_PosSaleDefinition");
    myd.push("Master_PosSaleReason");
    myd.push("Master_StoreChecklist");
    myd.push("PriviousVisit_Orders");
    myd.push("Master_VisitorFeedbackQuestion");
    myd.push("Master_SamplingDefinition");
    myd.push("Master_SamplingStockDefinition");
    myd.push("Mapping_StoreSampling");
    myd.push("Master_SamplingQuestion");
    myd.push("Master_Program");
    myd.push("Master_ProgramDefinition");
    myd.push("Mapping_StoreProgram");
    myd.push("Master_ProgramQuestion");
    myd.push("Mapping_ProgramQuestion");
    myd.push("Master_ProgramStockDefinition");
    myd.push("Mapping_StoreTargetBased");
    myd.push("Master_TargetBasedQuestion");
    myd.push("Mapping_TargetBasedQuestion");
    var DownloadTasks = AddKeys.concat(myd);

    let DownloadTasks1 = [];
    for (let i = 0; i < DownloadTasks.length; i++) {
      let key = DownloadTasks[i];
      let index = i + 1;
      let IsMandatory = (key == 'Table_Structure' || key == 'Mapping_JourneyPlan') ? true : false;
      let obj = { "KeyId": index, "DownloadKey": key, "IsMandatory": IsMandatory, "DevActive": true, "ProdActive": true, "DownloadSequence": index };
      DownloadTasks1.push(obj);
      if (i == DownloadTasks.length - 1) {
        // console.log('DownloadTasks1:',DownloadTasks1);
        resolve(DownloadTasks1);
      }
    }
  }).catch((Err) => {
    console.log(Err);
    return [];
  })


}

export async function getReDownloadTasks1(props) {
  console.log('getReDownloadTasks1');
  return new Promise(async (resolve, reject) => {
    var DownloadTasks1 = [];
    console.log('chekc 1', props.DownloadKey);
    if (props.DownloadKey != null && props.DownloadKey != '') {
      console.log('props.DownloadKey');
      let prop_dk = JSON.parse(props.DownloadKey);
      let AllDTs = prop_dk['DownloadKey'] || [];
      console.log('set server d keys', AllDTs.length);
      if (AllDTs.length > 0) {
        for (let i = 0; i < AllDTs.length; i++) {
          let item = AllDTs[i];
          if (item.ReDownload == 1 || item.ReDownload == 'true' || item.ReDownload == '1') {
            DownloadTasks1.push(item);
          }
          if (i == AllDTs.length - 1) {
            console.log('set server d2 keys', DownloadTasks1.length);
            let sortedDTs = await SortDownloadkeys(DownloadTasks1);
            resolve(sortedDTs);
          }
        }
      }
      else {
        resolve([]);
      }
    }
    else {
      DownloadTasks1 = getDownloadDataTask();
      resolve(DownloadTasks1);
    }

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

}

export async function SortDownloadkeys(AllDTs) {
  return 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) => {
    return AllDTs;
  });
}

export async function getBeatDownloadTask() {
  let DownloadTasks = ["JourneyPlan_RouteWise"];
  return await getReDDownloadTask(DownloadTasks);
}

export async function getNewStoresDownloadTask(PJP_Table) {
  let DownloadTasks = ["Mapping_JourneyPlan", "Adhoc_JourneyPlan"];
  return await getReDDownloadTask(DownloadTasks);
}


export async function onNoData(data = [], shouldStop = false, tbname = '', props, showErrorModal = () => { }, res) {
  console.log("res on no data in ReDownloadTask:", res);
  const ST = props.StaticText || {};
  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 + '';
      if (tbname == 'Mapping_JourneyPlan') {
        msg = ST.Youhavenojourneyplanfortoday;
      }
    }
    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 }
    props.set_startDownload({ startDownload: false });
    //hide download modal and show Error in Download modal with details
    showErrorModal(obj);
  }
  else {

  }
}

export async function insert_TaskDownloadedData(
  res,
  D_key,
  D_ColList = [],
  props,
  showErrorModal = () => {},
  setTaskResponse = () => {}
) {
  console.log('insert_TaskDownloadedData:', D_key);
  let r_obj = { r: false, data_arr: [] };

  try {
    if (res && typeof res === 'object' && res[D_key] != null && res[D_key] !== '') {
      const jsonData = res[D_key] || [];

      if (!Array.isArray(jsonData) || jsonData.length === 0) {
        console.warn(`⚠️ No data to insert in table: ${D_key}`);
        return { r: true, data_arr: [] };
      }

      const columns = Array.from(
        new Set(jsonData.flatMap(row => Object.keys(row)))
      );

      const normalizedData = jsonData.map(row => {
        const normalizedRow = {};
        columns.forEach(col => {
          normalizedRow[col] = row.hasOwnProperty(col) ? row[col] : null;
        });
        return normalizedRow;
      });

      console.log("normalizedData", normalizedData);

      const valuesArray = normalizedData.map(row => {
        const valueList = columns.map(col => {
          const val = row[col];
          if (val === null || val === undefined) return 'NULL';
          if (typeof val === 'number') return val;
          if (typeof val === 'boolean') return val ? 1 : 0;

          return `'${val.toString().replace(/'/g, "")}'`;
        
        });
        return `(${valueList.join(',')})`;
      });

      const sql = `INSERT INTO ${D_key} (${columns.join(',')}) VALUES ${valuesArray.join(',')};`;

      await new Promise((resolve, reject) => {
        db.transaction((txn) => {
          txn.executeSql(`DELETE FROM ${D_key}`, [], () => {
            txn.executeSql(sql, [], () => {
              setTaskResponse(jsonData);
              console.log(`✅ Inserted data into table: ${D_key}`);
              resolve();
            }, (tx, error) => {
              console.error(`❌ Insert failed in table: ${D_key}`, error);
              reject(error);
            });
          }, (tx, error) => {
            console.error(`❌ Delete failed in table: ${D_key}`, error);
            reject(error);
          });
        });
      });

      return { r: true, data_arr: jsonData };
    }

    if (res && typeof res === 'object' && res[0]?.Result === "No Data") {
      console.log('No data found');
      return { r: true, data_arr: [] };
    }

    if (res && typeof res === 'object' && res.success === false) {
      console.log('Error in downloading network', res);
      return { r: false, data_arr: [] };
    }

    console.log('Error in downloading else', res);
    return { r: false, data_arr: [] };

  } catch (err) {
    console.log('err:', err);
    return { r: false, data_arr: [] };
  }
}




export async function checkIfDataAvlbl(storeData, D_key, cols = 'StoreId') {
  console.log('checkIfDataAvlbl', D_key)
  let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData;
  let colsToCompare = cols.split(',');
  if (cols != '' && cols != null && storeData != null && colsToCompare.length > 0) {
    return new Promise((resolve, reject) => {
      let q = '', whereq = '';
      q = `Select * from ${D_key}`;
      for (let i = 0; i < colsToCompare.length; i++) {
        let column = colsToCompare[i];
        if (column != null && column != '' && storeData[column] != null && storeData[column] != '') {
          whereq += whereq == '' ? ` Where ` : ' and ';
          whereq += ` ${column}=${storeData[column]} `;
        }
      }
      q += ' ' + whereq;
      console.log('query to check store data:', q)
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(q, [], function (txn1, txnres) {
          console.log(D_key + ' data length:', txnres.rows.length);
          if (txnres.rows.length > 0) {
            resolve(true);
          }
          else {
            resolve(false);
          }
        }, function (txnE, txnerr) {
          console.log(txnerr);
          resolve(false);
        });
      });
    }).catch((err) => {
      console.log('error:', err);
      return false;
    })
  }
  else {
    return false;
  }
}

//************************** download functionallity*******************
export async function startRedownload(props, DownloadTasks, dowloadedCount, totalCount, setDowloadedCount = () => { }, setTotalCount = () => { }) {
  console.log('startRedownload', DownloadTasks);
  if (totalCount == (DownloadTasks.length - 1) && totalCount > 0) {
    console.log('setDowloadedCount', dowloadedCount, 0);
    setDowloadedCount(0);
  }
  else {
    console.log('setTotalCount', totalCount, (DownloadTasks.length - 1));
    setTotalCount((DownloadTasks.length - 1));
  }
  return DownloadTasks;
}

export async function executeTasks(props, storeData, DownloadTasks, dowloadedCount, totalCount, setDowloadedCount = () => { }, setDownloadingText = () => { }, onDownloadComplete = () => { }, setTaskResponse = () => { }, showErrorModal = () => { }) {
  // var DownloadTasks=getDownloadDataTask();
  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);
    let IsDataExists = await CheckIfRequiredDownload(storeData, currentIndex, DownloadTasks);
    if (!IsDataExists) {
      var data = await getPostData(DownloadTasks, currentIndex);
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, data);
      await getDownloadJson1(url, data)
        .then(async (res) => {
          console.log('res of download get');
          let isAdded = await updateTaskRes(props, storeData, res, currentIndex, DownloadTasks, setTaskResponse, true, showErrorModal);
          if (isAdded == true) {
            if (currentIndex == DownloadTasks.length - 1) {
              console.log('last found all downloaded');
              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);
        });
    }
    else {
      let isAdded = await updateTaskRes(props, storeData, [{ "Result": "No Data" }], currentIndex, DownloadTasks, setTaskResponse, false, showErrorModal);
      if (isAdded == true) {
        if (currentIndex == DownloadTasks.length - 1) {
          console.log('last found all downloaded');
          onDownloadComplete();
        }
        else {
          console.log('all downloaded but last not found ');
        }
      }
      else {
        console.log('Cannot download all Data');
      }
    }
  }

}


////need to optimize this function
export async function CheckIfRequiredDownload(storeData, index, DownloadTasks) {
  let dk_data = DownloadTasks[index];
  let key = dk_data.DownloadKey || '';
  return new Promise(async (resolve, reject) => {
    switch (key) {
      case 'Mapping_Menu': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'ChannelId,RegionId,StoreTypeId,StoreCategoryId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_Visibility': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_Promotion': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StateId,ChainId,StoreTypeId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_ProductAssortmentStorewise': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId,ProductId,MSL,MBQ');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_ProductAssortment': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId,ProductId,MSL,MBQ');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'LastVisit_ClosingStock': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_StoreWindow': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StorePOSM': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreShelfTalker': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_StoreVisibility': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_StorePromotion': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_StoreShareOfShelf': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_Survey': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreCategory': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreVisibilitySpecific': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_ShareOfShelfTarget': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StateId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'Mapping_MenuDistributorPoint': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'MenuId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      case 'PriviousVisit_Orders': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreSampling': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreAuditGrading': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreProgram': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      case 'Mapping_StoreTargetBased': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }

      default: resolve(false); break;

    }

  }).catch((err) => {
    console.log('error in check', err);
    return false;
  });

}

////need to optimize this function
export async function updateTaskRes(
  props,
  storeData,
  res,
  index,
  DownloadTasks,
  setTaskResponse = () => {},
  isDownloadExists = true,
  showErrorModal = () => {}
) {
  try {
    const dk_data = DownloadTasks[index];
    const key = dk_data?.DownloadKey || '';
    const IsMandatory = dk_data?.IsMandatory === 'true' || dk_data?.IsMandatory === 1;
    console.log("res-------", key);
    const i_res = await insert_TaskDownloadedData(res, key, {}, props, showErrorModal);
    const { data_arr, r } = i_res;
    if (r) {
      setTaskResponse(data_arr);
    }
    console.log('r:', r);
    return r;
  } catch (err) {
    console.log('error in downloading', err);
    return false;
  }
}



export async function getPostData(DownloadTasks, index = 0) {
  // var DownloadTasks=getDownloadDataTask();
  // let token=await get_item('loginToken');
  let dk_data = DownloadTasks[index];
  let key = dk_data.DownloadKey || '';
  let loginInfo = await get_item('loginInfo');
  const loginDetails = JSON.parse(loginInfo);
  const todate = new Date();
  const today = moment(todate).format("HH:mm:ss");
  let projectInfo = await get_item('projectInfo');
  let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
  var postdata = {};
  if (index >= 0) {
    postdata = {
      Downloadtype: key,
      Username: loginDetails.UserId,
      Param1: '',
      Param2: (key == "Gyancast_TrainingContent" || key == "Gyancast_PopupMessage") ? projectDetails?.ProjectCode : (Platform.OS == "ios" ? "iOS" : "Android"),

    };
  }
  return postdata;
}

export async function getPostData2(key = '') {
  let loginInfo = await get_item('loginInfo');
  const loginDetails = JSON.parse(loginInfo);
  var postdata = {};
  if (key != '') {
    postdata = {
      Downloadtype: key,
      Username: loginDetails.UserId,
      Param1: '',
      Param2: Platform.OS == "ios" ? "iOS" : "Android",
    };
  }
  
  return postdata;
}

