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 { getIf_UserIsManager } from '../controller/functions';
import { getDownloadJson1,fetchProjectConfig } from '../controller/functions';

export async function getDownloadDataTask(props, Redownload = false) {
  console.log('getDownloadDataTask Redownload:', "hello");
  let userIsManager = await getIf_UserIsManager(props);
  const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

  var DownloadTasks = [];

  // include these keys in download only when either user is not in prop.SUP_ManagerDesigList i.e. not a manager or if it is a manager then redownload should not be true
  // these keys are not required in redownload functionality
  if (userIsManager == false || (userIsManager == true && Redownload == false)) {
    DownloadTasks.push("Table_Structure_Sup");

    DownloadTasks.push("Sup_AttendanceStatus");
    DownloadTasks.push("Sup_Menu_Master");
    DownloadTasks.push("Mapping_MenuConfiguration_Sup")
    DownloadTasks.push("Sup_ImageType");
    DownloadTasks.push("Sup_NonWorkingReason");
    DownloadTasks.push("Sup_Master_MenuReports");
    DownloadTasks.push("Sup_Master_DetailerContent");
    DownloadTasks.push("Sup_TeamList");
    DownloadTasks.push("Sup_SupervisorList")
    console.log("storewisePjpDOWnload--->:", storewisePjp);
    if (storewisePjp == true) {
      DownloadTasks.push("Sup_JourneyPlanStorewiseSup");
      DownloadTasks.push("Sup_JourneyPlanStorewiseSup_Adhoc");
    }

    // add these keys only if user is manager and this is not called for redonwload 
    if ((userIsManager == true && Redownload == false)) {
      DownloadTasks.push("Sup_JourneyPlan");
    }

  }
  DownloadTasks.push("Sup_NPNDStore");
  // include these keys in download only when either user is not in prop.SUP_ManagerDesigList i.e. not a manager or if it is a manager then redownload must be true
  // these keys are required in redownload functionality only if it is search wise store checkin
  // always include these either in download or in redownload
  // if(userIsManager==false || (userIsManager==true && Redownload)){
  // supervisor Downloads
  DownloadTasks.push("Sup_Product_Master");
  DownloadTasks.push("Mapping_MenuSup");
  DownloadTasks.push("Sup_Master_Display")
  // DownloadTasks.push("Sup_Master_ActivationType");
  // DownloadTasks.push("Sup_Master_ProductFlavour"); 
  // DownloadTasks.push("Sup_Master_ProductPack"); 

  DownloadTasks.push("Sup_Master_PromoType")
  DownloadTasks.push("Sup_Master_Competitor");

  // DownloadTasks.push("Sup_Album"); 
  DownloadTasks.push("Sup_Master_SurveyQuestion");
  DownloadTasks.push("Mapping_SurveySup");

  DownloadTasks.push("Sup_Master_VisibilityDefinition");
  DownloadTasks.push("Sup_Master_VisibilityQuestion");
  DownloadTasks.push("Sup_VisibilityAudit");
  DownloadTasks.push("Sup_Master_VisibilityReason");
  DownloadTasks.push("Sup_MasterDistributor");
  DownloadTasks.push("Mapping_MenuDistributorPointSup");
  DownloadTasks.push("Sup_Distributor_PreviousVisicooler");

  DownloadTasks.push("Sup_Non_Working_ReasonDistributor");

  // new 
  DownloadTasks.push("Sup_ImageAuditKPIImages");
  DownloadTasks.push("Sup_ImageAuditKPIQuestion");
  DownloadTasks.push("Sup_ImageAuditStoreList");
  DownloadTasks.push("Sup_Mapping_VisibilityQuestion");
  DownloadTasks.push("Sup_Master_VisibilityStockDefinition");

  // posSale downloads

  DownloadTasks.push("Sup_Master_PosSaleDefinition");
  DownloadTasks.push("Sup_Mapping_PosSaleDefinition");
  DownloadTasks.push("Sup_Master_PosSaleReason");
  DownloadTasks.push("Sup_Master_PosSaleCycle");

  // dashboard
  DownloadTasks.push("Sup_MenuAppDashboard");


  // return DownloadTasks;
  let DownloadTasks1 = [];
  for (let i = 0; i < DownloadTasks.length; i++) {
    let key = DownloadTasks[i];
    let index = i + 1;
    let IsMandatory = (key == 'Table_Structure') ? 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);
      return DownloadTasks1;
    }
  }

}

// manual download post data function
// export async function getDownloadDataTask(props, Redownload = false) {
//   console.log('getDownloadDataTask Redownload:', "hello");
//   let userIsManager = await getIf_UserIsManager(props);
//   //const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
//   const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

//   var DownloadTasks = [];

//   // include these keys in download only when either user is not in prop.SUP_ManagerDesigList i.e. not a manager or if it is a manager then redownload should not be true
//   // these keys are not required in redownload functionality
//   if (userIsManager == false || (userIsManager == true && Redownload == false)) {
//     DownloadTasks.push("Table_Structure_Sup");
    
//     DownloadTasks.push("Sup_NonWorkingReason");
//     DownloadTasks.push("Sup_TeamList");
//     DownloadTasks.push("Sup_Product_Master")
//     DownloadTasks.push("Mapping_MenuSup");
//     DownloadTasks.push("Sup_Master_Display");
//     DownloadTasks.push("Sup_Master_ActivationType");
//     DownloadTasks.push("Sup_Master_ProductFlavour");
//     DownloadTasks.push("Sup_Master_ProductPack");
//     DownloadTasks.push("Sup_Master_PromoType")
//     console.log("storewisePjpDOWnload--->:", storewisePjp);
//     if (storewisePjp == true) {
//       DownloadTasks.push("Sup_JourneyPlanStorewiseSup");
//       DownloadTasks.push("Sup_JourneyPlanStorewiseSup_Adhoc");
//     }

//     // add these keys only if user is manager and this is not called for redonwload 
//     if ((userIsManager == true && Redownload == false)) {
//       DownloadTasks.push("Sup_JourneyPlan");
//     }

//   }
//   DownloadTasks.push("Sup_Master_Competitor");
//   // include these keys in download only when either user is not in prop.SUP_ManagerDesigList i.e. not a manager or if it is a manager then redownload must be true
//   // these keys are required in redownload functionality only if it is search wise store checkin
//   // always include these either in download or in redownload
//   // if(userIsManager==false || (userIsManager==true && Redownload)){
//   // supervisor Downloads
//   DownloadTasks.push("Sup_Master_SurveyQuestion");
//   DownloadTasks.push("Sup_Master_VisibilityDefinition");
//   DownloadTasks.push("Sup_Master_VisibilityQuestion")
//   // DownloadTasks.push("Sup_Master_ActivationType");
//   // DownloadTasks.push("Sup_Master_ProductFlavour"); 
//   // DownloadTasks.push("Sup_Master_ProductPack"); 

//   DownloadTasks.push("Sup_VisibilityAudit")
//   DownloadTasks.push("Sup_Master_VisibilityReason");

//   // DownloadTasks.push("Sup_Album"); 
//   DownloadTasks.push("Sup_Menu_Master");
//   DownloadTasks.push("Mapping_MenuConfiguration_Sup");

//   DownloadTasks.push("Sup_ImageType");
//   DownloadTasks.push("Sup_AttendanceStatus");
//   DownloadTasks.push("Sup_Master_MenuReports");
//   DownloadTasks.push("Sup_Master_DetailerContent");
//   DownloadTasks.push("Sup_SupervisorList");
//   DownloadTasks.push("Sup_MenuAppDashboard");
//   DownloadTasks.push("Mapping_SurveySup");
//   DownloadTasks.push("Sup_Mapping_VisibilityQuestion");
//   DownloadTasks.push("Sup_Master_VisibilityStockDefinition");

 
//   // return DownloadTasks;
//   let DownloadTasks1 = [];
//   for (let i = 0; i < DownloadTasks.length; i++) {
//     let key = DownloadTasks[i];
//     let index = i + 1;
//     let IsMandatory = (key == 'Table_Structure') ? 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);
//       return DownloadTasks1;
//     }
//   }

// }





// MODIFIED BY AJEET

export async function getPostData(DownloadTasks, index = 0, props) {
  // var DownloadTasks=await getDownloadDataTask(props);
  // let token=await get_item('loginToken');
  const params = props.route.params || {};
  let StoreSearchFlag=params.StoreSearchFlag || false;
  let empData=params.empData 

// console.log('ye wala call hua ',empData);
// console.log('props. props. props. props. props----->',props);


  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");

  const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
  console.log("currentConfigDw:", storewisePjp);
  console.log("storewisePjpDw:", storeSearch);

  var postdata = {};
  if (index >= 0) {
    postdata = {
      Downloadtype: key,
      Username: loginDetails.UserId,
      Param1: storewisePjp==false||(StoreSearchFlag && key=="Mapping_SurveySup")? (empData?.EmpId||0) :0,
      Param2: storewisePjp ? 1 : 0,
    };
  }
  console.log("postdata----",key,postdata)
  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: '',
    };
  }
  return postdata;
}

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;
  });
}

//************************** Redownload functionallity*******************
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);
            // let sortedDTs={"KeyId":0,"DownloadKey":"Mapping_StoreShareOfShelf","IsMandatory":false,"DevActive":true,"ProdActive":true,"DownloadSequence":0};
            resolve(sortedDTs);
          }
        }
      }
      else {
        resolve([]);
      }


    }
    else {
      DownloadTasks1 = await getDownloadDataTask(props, true);
      resolve(DownloadTasks1);
    }

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

}

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! ";
    }
    // notify(msg); 

    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 = () => { }) {
  console.log('insert_TaskDownloadedData:', D_key);
  let r_obj = { r: false, data_arr: [] };
  return await new Promise(async (resolve, reject) => {
    // if (res[D_key]!=null && res[D_key]!='') {
    if (res != null && typeof res == 'object' && res[D_key] != null && res[D_key] != '') {
      let data_arr = res[D_key] || [];
      var values = [], cols = '(';
      data_arr.map((data_obj, d_index) => {
        // let {StateId, ChainId, StoreTypeId, ProductId, MSL,MBQ}=data_obj;
        let str = '(';
        for (var i = 0; i < D_ColList.length; i++) {
          let colname = D_ColList[i];
          let col_value = data_obj[colname];
          if (typeof col_value == 'string') {
            col_value = col_value.replace(/'/g, "");
          }
          if (col_value == false) {
            col_value = 0
          }
          if (col_value == true) {
            // console.log("coltype:",typeof col_value);
            col_value = 1
          }

          str += `'${col_value}'`;

          if (i != D_ColList.length - 1) {
            str += `,`;
          }

          if (d_index == 0) {
            cols += `${colname}`;
            if (i != D_ColList.length - 1) {
              cols += `,`;
            }
          }
        }
        str += ')';
        values.push(str);
        // values.push(` ('${StateId}', '${ChainId}', '${StoreTypeId}', '${ProductId}','${MSL}','${MBQ}')`);
      })
      cols += ')'
      var all_vals = values.join(',');
      var sql_stmnt = `INSERT INTO ${D_key}${cols} values ${all_vals}`;
      console.log('execute sql_stmnt');
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(`delete from ${D_key} where 1=1`, [], function (txn1, txnres) {
          // insert or refresh all today data
          txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
            console.log(D_key + ' added');
            r_obj['r'] = true;
            r_obj['data_arr'] = data_arr;
            resolve(r_obj);
          }, function (txnE, txnerr) {
            console.log(txnerr);
            r_obj['r'] = true;
            resolve(r_obj);
          });
        }, function (txnE, txnerr) {
          console.log(txnerr);
          r_obj['r'] = true;
          resolve(r_obj);
        });
      });




    }
    // else if(res!=null && typeof(res)=='object' && (res.success==false || (res[0]!=null && res[0].Result!=null))){
    //   console.log('No data found');
    //   await onNoData([`No data for ${D_key}`],false,D_key,props);
    //   r_obj['r']=true;
    //   resolve(r_obj); 
    // }
    // else{  
    //   console.log('else no data');
    //   await onNoData([`No data for ${D_key}`],false,D_key,props); 
    //   r_obj['r']=true; 
    //   resolve(r_obj); 
    // }
    // 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 ${D_key}`], false, D_key, props, showErrorModal);
      r_obj['r'] = true;
      resolve(r_obj);
    }
    // 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 ${D_key}`], true, D_key, props, showErrorModal, res);
      r_obj['r'] = false;
      resolve(r_obj);
    }
    // Stop Downloading and report error
    else {
      console.log('Error in downloading else', res);
      await onNoData([`No data for ${D_key}`], true, D_key, props, showErrorModal, res);
      r_obj['r'] = false;
      resolve(r_obj);
    }

  }).catch((err) => {
    console.log('err:', err);
    return r_obj;
  })

}

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;
  }
}

export async function startRedownload(props, DownloadTasks, dowloadedCount, totalCount, setDowloadedCount = () => { }, setTotalCount = () => { }) {
  console.log('startRedownload', DownloadTasks.length);
  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, props);
      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);
          console.log("isAdded=====", isAdded)
          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');
      }
    }
  }

}

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 'Sup_VisibilityAudit': {
        let IsDataAvlbl = await checkIfDataAvlbl(storeData, key, 'MID,StoreId');
        console.log('IsDataAvlbl:', IsDataAvlbl);
        resolve(IsDataAvlbl);
        break;
      }
      default: resolve(false); break;

    }

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

}

export async function updateTaskRes(props, storeData, res, index, DownloadTasks, setTaskResponse = () => { }, isDownloadExists = true, showErrorModal = () => { }) {
  // var DownloadTasks=getDownloadDataTask();   

  const todate = new Date();
  const today = moment(todate).format("MM/DD/YYYY");
  let d2 = today;
  let dk_data = DownloadTasks[index];
  let key = dk_data.DownloadKey || '';
  let IsMandatory = dk_data.IsMandatory == 'true' || dk_data.IsMandatory == 1 ? true : false;

  return new Promise(async (resolve, reject) => {

    console.log("key========", key)

    switch (key) {

      case 'Sup_Product_Master': {
        let colList = ['ProductId', 'ProductCode', 'ProductName', 'Mrp', 'BrandId', 'BrandName', 'SubCategoryId', 'SubCategoryName', 'CategoryId', 'CategoryName', 'CompanyId', 'ProductSequence', 'BrandSequence', 'SubCategorySequence', 'CategorySequence', 'IsCompetitor'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }
      case 'Mapping_MenuSup': {
        let colList = ['MenuId', 'VisitType'];
        if (isDownloadExists) {
          let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
          let data_arr = i_res['data_arr'];
          let r = i_res['r'];
          if (r == true) {
            setTaskResponse(data_arr);
          }
          //console.log('r:', r);
          resolve(r);
        }
        else {
          setTaskResponse([key]);
          resolve(true);
        }
        break;
      }

      case 'Sup_Master_Display': {
        let colList = ['DisplayId', 'DisplayName', 'RefImage'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }
      case 'Sup_Master_PromoType': {
        let colList = ['PromoTypeId', 'PromoType'];
        if (isDownloadExists) {
          let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
          let data_arr = i_res['data_arr'];
          let r = i_res['r'];
          if (r == true) {
            setTaskResponse(data_arr);
          }
          //console.log('r:', r);
          resolve(r);
        }
        else {
          setTaskResponse([key]);
          resolve(true);
        }
        break;
      }
      case 'Sup_Master_Competitor': {
        let colList = ['CompanyId', 'Company', 'CategoryId', 'CategoryName', 'SubCategoryId', 'SubCategoryName', 'BrandId', 'BrandName', 'SubBrandId', 'SubBrandName', 'ProductId', 'ProductName'];
        if (isDownloadExists) {
          let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
          let data_arr = i_res['data_arr'];
          let r = i_res['r'];
          if (r == true) {
            setTaskResponse(data_arr);
          }
          //console.log('r:', r);
          resolve(r);
        }
        else {
          setTaskResponse([key]);
          resolve(true);
        }
        break;
      }
      case 'Sup_Master_SurveyQuestion': {
        let colList = ['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'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }

      case 'Mapping_SurveySup': {
        let colList = ['SurveyId', 'StoreId'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }


      case 'Sup_Master_VisibilityDefinition': {
        let colList = ['VisibilityDefinitionId', 'MenuId', 'MenuName', 'VisibilityId', 'VisibilityName', 'VisibilityTable', 'VisibilityField', 'VisibilityValue', 'ChildName', 'VisibilityRefImage', 'VisibilityElementStockRequired', 'VisibilityElementCheckAssortment', 'NoOfSplit', 'VisibilityImage1', 'VisibilityImage2', 'VisibilityImage1Lable', 'VisibilityImage2Lable', 'VisibilityNotExistCamera', 'VisibilityExistReasonEnable', 'VisibilityNotExistReasonEnable', 'VisibilityImage1CameraGrid', 'VisibilityImage2CameraGrid', 'StockQtyRequired', 'VisiDefSequence'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }
      case 'Sup_Master_VisibilityQuestion': {
        let colList = ['VisibilityQuestionId', 'VisibilityQuestionCode', 'VisibilityQuestionName', 'QuestionType', 'VQShowCamera', 'VQCameraMandatory', 'VQLengthValidationRequired', 'VQMinimumChar', 'VQMaximumChar', 'VQDecimalPoint', 'VQDateRangeMin', 'VQDateRangeMax', 'VQVoiceLengthInMinutes', 'VQDefaultQuestionEnable', 'VisibilityQuestionSequence', 'VisibilityAnswerId', 'VisibilityAnswerName', 'VAShowCamera', 'VACameraMandatory', 'VAQuestionEnable', 'VAQuestionDisable', 'VASequence'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }
      case 'Sup_VisibilityAudit': {
        let colList = ['VId', 'MID', 'StoreId', 'LastVisitDate', 'VisibilityDefinitionId', 'Present', 'VisibilityReasonId', 'VisibilityImages', 'VisibilityQuestion'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }
      case 'Sup_Master_VisibilityReason': {
        let colList = ['VisibilityReasonId', 'VisibilityReason', 'MenuId', 'IsRemarkTaken'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
       // console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }

      // new 

      case 'Sup_ImageAuditKPIImages': {
        let colList = ['MID', 'MenuId', 'KPIImageId', 'QuestionImageId', 'DefId', 'DefName', 'ImageName', 'Image1', 'Image2'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }

      case 'Sup_ImageAuditKPIQuestion': {
        let colList = ['AIQuestionId', 'AIQuestionCode', 'AIQuestionName', 'QuestionType', 'AIShowCamera', 'AICameraMandatory', 'AILengthValidationRequired', 'AIMinimumChar', 'AIMaximumChar', 'AIDecimalPoint', 'AIDateRangeMin', 'AIDateRangeMax', 'AIVoiceLengthInMinutes', 'AIDefaultQuestionEnable', 'AIQuestionSequence', 'AIAnswerId', 'AIAnswerName', 'AIAShowCamera', 'AIACameraMandatory', 'AIAQuestionEnable', 'AIAQuestionDisable', 'AIASequence'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }

      case 'Sup_ImageAuditStoreList': {
        let colList = ['MID', 'CoveredBy', 'StoreId', 'StoreName', 'StoreType', 'Address', 'CityName', 'VisitDate'];
        let i_res = await insert_TaskDownloadedData(res, key, colList, props, showErrorModal);
        //console.log('i_res:', i_res);
        let data_arr = i_res['data_arr'];
        let r = i_res['r'];
        if (r == true) {
          setTaskResponse(data_arr);
        }
        //console.log('r:', r);
        resolve(r);
        break;
      }

    }

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







