import moment from 'moment';
import React from 'react';
import { db } from './constants';
import { AppTables } from './tableConstants';


export function  Q_GetAvailabityDefaultData(storeData){
    let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
    let join=` INNER JOIN Product_Master p on c.CategoryId=p.CategoryId  `;
    let join2=` INNER JOIN Mapping_ProductAssortment mp on p.ProductId=mp.ProductId `;
    let q=` SELECT DISTINCT c.CategoryId,c.CategoryName,mp.MSL from Master_Category c ${join} ${join2} Where mp.StateId ='${StateId}' and mp.ChainId ='${ChainId}'  and mp.StoreTypeId ='${StoreTypeId}' order by p.CategorySequence`;
    return q;
}

export function  Q_getdefaltShareofSelf(storeData){
    let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
    let join=` INNER JOIN Master_Category mc on mc.CategoryId = p.CategoryId  `;
    let join2=` INNER JOIN Mapping_ShareOfShelf m on p.SubCategoryId=m.SubCategoryId `;
    let q=`SELECT DISTINCT p.CategoryId,p.CategoryName from Product_Master p ${join} ${join2} Where m.StateId ='${StateId}' and m.ChainId ='${ChainId}'  and m.StoreTypeId ='${StoreTypeId}' order by p.CategorySequence`;
    return q;
}

export function  Q_getCompetitorQuery(storeData){
  let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
  let q=`SELECT DISTINCT CategoryId,CategoryName from Sup_Product_Master  Where IsCompetitor='1' or IsCompetitor='true'  order by CategorySequence`;
  return q;
}

export function Q_getpaidvisibility(storeData){
    let {StoreId,ChainId,StoreTypeId}=storeData;
    let join=` INNER JOIN Mapping_Visibility v on p.SubCategoryId=v.SubCategoryId `;
    let join2=` INNER join Master_Display md on md.DisplayId=v.DisplayId  `;
    let q=`SELECT DISTINCT p.SubCategoryName,p.SubCategoryId from Product_Master p  ${join} ${join2} Where v.StoreId='${StoreId}' `;
    return q;
}

export function Q_getAvlblDBVisiCooler(props,menu,PJP_Table){
  console.log("Q_getAvlblDBVisiCooler-----1",menu,PJP_Table)
  let {MenuId}= menu
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');
  
  let q=`SELECT JP.DistributorId, ${MenuId} as MenuID,1 as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_MenuDistributorPointSup MW on MW.MenuId='${MenuId}'
  group by JP.DistributorId`;
  // Where JP.VisitDate='${d2}'
  
  // let join2=` inner join Sup_VisibilityAudit s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  `;
  // let q=` Select * from Sup_Master_VisibilityDefinition w  ${join2} where s.StoreId='${StoreId}'`;

  console.log("Q_getAvlblDBVisiCooler-----",q)
  return q;
}


export function Q_getvisibilityAudit(storeData){
  let {StoreId,ChainId,StoreTypeId}=storeData;

  // let q=`SELECT DISTINCT VisibilityDefinitionId from Sup_VisibilityAudit  Where StoreId='${StoreId}'`;

  let join2=` inner join Sup_VisibilityAudit s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  `;
  let q=` Select * from Sup_Master_VisibilityDefinition w  ${join2} where s.StoreId='${StoreId}'`;

  console.log("Q_getvisibilityAudit-----",q)
  return q;
}

export function Q_getpromotionmappingList(storeData){
    let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
    let join=`  INNER JOIN Mapping_Promotion m  on p.SubCategoryId=m.SubCategoryId`;
    let q=`SELECT DISTINCT p.SubCategoryId,p.SubCategoryName from Product_Master p ${join} where m.StateId='${StateId}' and m.ChainId='${ChainId}' and m.StoreTypeId='${StoreTypeId}' `;
    return q;
}

export function Q_getSamplingData(storeData){
    let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
    let join=` INNER JOIN Mapping_Sample m  on s.SampleId=m.SampleId`;
    let q=`SELECT DISTINCT s.Sample,s.SampleId from Master_Sample s ${join} where m.ChainId='${ChainId}' and  m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' `;
    return q;
}

export function Q_getSurveys(storeData,menu1){
    let {StoreId,ChainId,StoreTypeId,StateId} =storeData;
    // let join=` INNER JOIN Mapping_SurveySup M on T.SurveyId=M.SurveyId`;
    let q=`Select Distinct T.SurveyName ,T.SurveyId ,T.ShowCat from Sup_Master_SurveyQuestion T INNER JOIN Mapping_SurveySup M on T.SurveyId=M.SurveyId WHERE T.MenuId='${menu1?.MenuId}' and  M.StoreId='${StoreId}'`;
   
    console.log('query==============>',q);
    
    return q;
}

 // add posSale

export function Q_getAvailbl_POSSaleOneApp(menuItem,storeData,checkPosale=false){

  console.log(checkPosale , "checkPosale---")
  let {StoreId,ChainId,StoreTypeId}=storeData;
  let {MenuId}= menuItem
  console.log('PossaleMenuId',MenuId)
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');
 let q=""
  if(checkPosale){
     q=`SELECT *  from Sup_Master_PosSaleDefinition p`
  }else{
      q=`SELECT * ,mps.StoreId from Sup_Master_PosSaleDefinition p INNER join Sup_Mapping_StorePosSaleDefinition mps on p.PosDefinitionId=mps.PosDefinitionId where mps.StoreId='${StoreId}'`
    }
  return q;
}


//end posSale


export function Q_MenuList(storeData1,isAdhoc,isNPND){
  let {StoreId,ChannelId,RegionId,StoreTypeId}=storeData1;
  let q=`SELECT DISTINCT t1.* from Sup_Menu_Master t1 INNER join Mapping_MenuSup t2 on t1.MenuId=t2.MenuId and t2.VisitType='${isAdhoc?"Adhoc":isNPND?"NPND":"JCP"}' Order by t1.MenuSequence `;
  q = q.replace(/\\/g, "");
  console.log("Queryyyy------1",q)

  return q;
}
    

export async function checkFilledSurveys(ScreenName,txnres2,storeData,menu1){
  
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    let {StoreId}=storeData;
    let isSurveyDone=true;

    return new Promise((resolve,reject)=>{
      db.transaction(async function (txn) { 
        
        if(txnres2.rows.length>0){
          for(var i=0;i<txnres2.rows.length;i++){
            let data =txnres2.rows.item(i);
            let c_index=i;
            let {SurveyId,ShowCat}=data;
            let isshowcat=(ShowCat==1 || ShowCat=='true' || ShowCat==true);
            let isDone=await checkIf_surveyDone(storeData,SurveyId,isshowcat,menu1);
            
            if(!isDone){
              isSurveyDone=false;
              resolve(isSurveyDone);
              break;
            }
            else if(i==txnres2.rows.length-1){
              resolve(isSurveyDone)
            }
          }
        }
        else{
          resolve(true);
        }
      }); 
    }).then(val=>{
      return val;
    }).catch(err=>{
      console.log(err);
      return false;
    });
    
    
}

export function getAvailblQuery(ScreenName,storeData,menu1,checkPosale=false){

  // console.log("getavailablequery--->>",ScreenName)
    
    let d1=new Date();
    let d2=moment(d1).format('MM/DD/YYYY');
    let q=``;
    let join=``,join2=``;
    let {StoreId,ChainId,StoreTypeId} =storeData;
    // let join=` inner join Mapping_SurveySup M on T.SurveyId=M.SurveyId `;
    // let q=`Select Distinct T.SurveyName as SurveyName,T.SurveyId as SurveyId from Sup_Master_SurveyQuestion T ${join} Where M.StoreId='${StoreId}' `;
        
    switch(ScreenName){
        // case 'COMPETITIONSKU':
        //   q=Q_getCompetitorQuery(storeData);
        // return q;
        // case 'COMPETITIONACT':
        //   q=Q_getCompetitorQuery(storeData);
        // return q;
        case 'COMPVISI':
          q=Q_getCompetitorQuery(storeData);
        return q;
        case 'STOREAUDIT': 
          q=Q_getSurveys(storeData,menu1);
        return q;
        case 'STOREPHOTO':
          q="SELECT * FROM Sup_ImageType  ";
          return q;
        case 'COMPPROMO':
          q=` select '1' as CompanyId `;
          return q;
        case 'VISIBILITYAUDIT':
          q=Q_getvisibilityAudit(storeData);
          console.log('Generated query for VISIBILITYAUDIT:', q);
          return q;
          // add posSale 
        case 'POSSALE':
          q= Q_getAvailbl_POSSaleOneApp(menu1,storeData,checkPosale);
          console.log('Generated query for POSSALE:', q);
          // console.log('menu+PJPTable',q)
          return q;

  
          
        default: return '';
        
    }
}

export function getIfAvlbl(ScreenName,txnres2,storeData={}){
    let isAvlbl=false;
    switch(ScreenName){
      // case 'COMPETITIONSKU':
      //   if(txnres2.rows.length>0){ isAvlbl=true;}
      // return isAvlbl;
      // case 'COMPETITIONACT':
      //   if(txnres2.rows.length>0){ isAvlbl=true;}
      // return isAvlbl;
      case 'COMPVISI':
        if(txnres2.rows.length>0){ isAvlbl=true;}
      return isAvlbl;
      case 'STOREAUDIT':
        if(txnres2.rows.length>0){ isAvlbl=true;}
      return isAvlbl;
      case 'STOREPHOTO':
        if(txnres2.rows.length>0){ isAvlbl=true;}
      return isAvlbl;
      case 'COMPPROMO':
        if(txnres2.rows.length>0){ isAvlbl=true;}
      return isAvlbl;
      case 'VISIBILITYAUDIT':
        if(txnres2.rows.length>0){ isAvlbl={"isAvlbl":true, avlblCount:txnres2.rows.length}}
      return isAvlbl;
      // add posSale
      case 'POSSALE':
        console.log('POSSALE txnres2:', txnres2.rows.length);
        if(txnres2.rows.length>0){ isAvlbl=true;}
      return isAvlbl;


      default: return isAvlbl;
    }
}




export function getQuery(ScreenName,storeData,menu1){

// console.log(menu1 , "getQuerydata---->>>>>")

  let {MenuId}=menu1;
    let d1=new Date();
    let d2=moment(d1).format('MM/DD/YYYY');
    let q=``;
    switch(ScreenName){
        // case 'COMPETITIONSKU':
        //   q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}'  and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `
        //   return q;
        // case 'COMPETITIONACT':
        //   q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}'  and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `
        //   return q;
        case 'COMPVISI':
          q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `
          return q;
        case 'STOREAUDIT':
          q=Q_getSurveys(storeData,menu1);
          //  q=`SELECT * FROM ${AppTables.SURVEY} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' and MENUID='${menu1.MenuId}' `
          //  q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' and MENUID='${menu1.MenuId}' `
          return q;
        case 'STOREPHOTO':
          q=`SELECT * FROM ${AppTables.STORE_IMAGES} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `
          return q;
        case 'COMPPROMO':
          q=`SELECT * FROM ${AppTables.COMPETITION_PROMOTION} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `
          return q;
        case 'VISIBILITYAUDIT':
          let join3=` inner join Sup_VisibilityAudit s on w.PVIS_DEFINITION_ID=s.VisibilityDefinitionId  `;
          q=`SELECT  DISTINCT w.PVIS_DEFINITION_ID FROM ${AppTables.VISAUDIT_HDR_DATA} w ${join3} WHERE w.STORE_ID='${storeData.StoreId}' and w.VISIT_DATE='${d2}' `
          return q;

        // add posSale

        case 'POSSALE': 
        // q=` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        // (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.POSSALE_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
        // ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;

        // q = `SELECT JP.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM (SELECT DISTINCT StoreId FROM ${AppTables.POSSALE_DATA} WHERE VISIT_DATE = '${d2}') JP LEFT OUTER JOIN (
        //  SELECT STORE_ID AS StoreId, IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.POSSALE_DATA}  WHERE VISIT_DATE = '${d2}' GROUP BY STORE_ID) DR 
        //  ON JP.StoreId = DR.StoreId;`;

        q=`SELECT * FROM ${AppTables.POSSALE_DATA} WHERE STORE_ID='${storeData.StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `

        return q;
          
        default: return '';
        
    }
}

export async function getIfKPIDone(ScreenName,txnres2,storeData,isAvlbl,menu1){

  // console.log(ScreenName, "ScreenNamegetQueryyy---")

    let isDone=false;
    switch(ScreenName){
      // case 'COMPETITIONSKU':
      //   if(txnres2.rows.length>0) isDone=true;
      // return isDone; 
      // case 'COMPETITIONACT':
      //   if(txnres2.rows.length>0) isDone=true;
      // return isDone; 
      case 'COMPVISI':
        if(txnres2.rows.length>0) isDone=true;
      return isDone; 
      case 'STOREAUDIT': 
        isDone=await checkFilledSurveys(ScreenName,txnres2,storeData,menu1);
      return isDone;
      case 'STOREPHOTO':
        if(txnres2.rows.length>0){ isDone=true;}
      return isDone;
      case 'COMPPROMO':
        if(txnres2.rows.length>0) isDone=true;
      return isDone;
      case 'VISIBILITYAUDIT':
        if((txnres2.rows.length>0) && ( isAvlbl && isAvlbl.avlblCount && (txnres2.rows.length==isAvlbl.avlblCount))){
          isDone=true;
        } 
      return isDone;

      // add posSale
      case 'POSSALE':
        if(txnres2.rows.length>0) { isDone=true;}
      return isDone;

      default: return isDone;
      
    }
}



export function get_DBAvailblQuery(props,menu,PJP_Table){
  let {ScreenName,MenuId}=menu
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');
  let q=``;
      
  console.log("ScreenName---------",ScreenName)
  switch(ScreenName){
      case 'DBPOSMONEAPP':
        q=Q_getAvlblDBPOSM(props,menu,PJP_Table);
        return q;
      case 'DBWINDOWONEAPP':
        q=Q_getAvlblDBWindow(props,menu,PJP_Table);
        return q;
      case 'VISICOOLER':
        q=Q_getAvlblDBVisiCooler(props,menu,PJP_Table);
        return q;
      default: return '';
  }
}

export function get_DBQuery(menu,PJP_Table){
  let {ScreenName,MenuId}=menu
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');
  let q=``;
      
  switch(ScreenName){
      case 'DBPOSMONEAPP':
        q=` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DBPOSM_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
        return q;
      case 'DBWINDOWONEAPP':
        q=` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DB_WINDOW_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
        return q;
      case 'VISICOOLER':
        q=` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DB_VISICOOLER} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
        
        return q;
      default: return '';
      
  }
}
export function Q_DBMenuList(storeData1,screen=''){
  let {StoreId,ChannelId,RegionId,StoreTypeId}=storeData1;

  let join=` INNER join Mapping_MenuDistributorPointSup t2 on t1.MenuId=t2.MenuId`;
  let q=`SELECT DISTINCT t1.MenuId,t1.MenuName,t1.NormalIcon,t1.TickIcon,t1.GreyIcon,t1.MenuPath,t1.ScreenName from Sup_Menu_Master t1 ${join}`;
  q+=screen!=''?` where t1.ScreenName='${screen}' `:'';
  q+=' Order by t1.MenuSequence ';
  return q;
}

export async function Q_getMyDBMenuList(storeData,props){
  console.log('Q_getMyDBMenuList:',storeData)
  let q='',tb2=AppTables.CHECKIN_DATA;
  let join_tbl='Sup_MasterDistributor';
  let superQ_tblName='StoreCats';
  // let superQ2_tblName='StoreData';
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');

  let menusQ=`(select Distinct JP.DistributorId,MM_Inner.MenuId,MM_Inner.MenuName,MM_Inner.NormalIcon,MM_Inner.TickIcon,MM_Inner.GreyIcon,MM_Inner.MenuPath,MM_Inner.ScreenName,MM_Inner.MenuSequence from ${join_tbl} JP 
    cross join 
    (select MMAS.* from Sup_Menu_Master MMAS Inner Join Mapping_MenuDistributorPointSup MMap on MMap.MenuId=MMAS.MenuId) as MM_Inner
    Order by JP.DistributorId, MM_Inner.MenuId) as Menu `;

  
  let DataAvailable_QList=``,KPIAvailable_QList=``;
  return await  new Promise((resolve,reject)=>{
    db.transaction(async function (txn) {        
      let mq=`SELECT DISTINCT t1.ScreenName,t1.MenuId from Sup_Menu_Master t1 INNER join Mapping_MenuDistributorPointSup t2 on t1.MenuId=t2.MenuId`;
      
      await txn.executeSql(mq,[],async function (txn2, txnres) { 
      
       if(txnres.rows.length>0){ 
         for(let i=0;i<txnres.rows.length;i++){
          let data=txnres.rows.item(i);
          
          let avlblQ=get_DBAvailblQuery(props,data,join_tbl);
          let isDoneQ=get_DBQuery(data,join_tbl);

          KPIAvailable_QList+=KPIAvailable_QList!='' && avlblQ!=''?' UNION ':' ';
          DataAvailable_QList+=DataAvailable_QList!='' && isDoneQ!=''?' UNION ':' ';
          KPIAvailable_QList+=' '+avlblQ+' ';
          DataAvailable_QList+=' '+isDoneQ+' ';

          
          if(i==txnres.rows.length-1){
            let KPIAvlblJoin=`LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.DistributorId=AVLSTK.DistributorId and Menu.MenuId=AVLSTK.MenuId`;
            let DataAvailableJoin=` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.DistributorId=dataavl.DistributorId and Menu.MenuId=dataavl.MenuId `;
            q=`Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount from ${menusQ} ${KPIAvlblJoin} ${DataAvailableJoin} Where Menu.DistributorId='${storeData.StoreId}' order by Menu.MenuSequence `;
            resolve(q);
          }
           
         }
       }
       else{
        resolve('');
       }
     },function (txnE,txnerr) { console.log(txnerr); resolve('');},);
  
   }); 
  }).then((val)=>{
    // console.log('myval',val);
    return val;
  }).catch((err)=>{
    console.log('error in query:',err);
    return '';
  })
  

}
    


export async function Q_getMyDistributorList(props){
  let q='',tb2=AppTables.DISTRIBUTOR_CHECKIN;
  let join_tbl='Sup_MasterDistributor';
  let superQ_tblName='StoreCats';
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');

  // Mapping_MenuDistributorPointSup
  let menusQ=` (select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    cross join (select MMAS.* from Sup_Menu_Master MMAS Inner Join Mapping_MenuDistributorPointSup MMap on MenuId on MMap.MenuId=MMAS.MenuId) as MM
    Order by JP.DistributorId, MM.MenuId) as Menu `;


  let menuQ2=`(select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    Left outer join 
	  (select Distinct  JP.DistributorId,MM_Inner.* from ${join_tbl} JP cross join (select MMAS.* from Sup_Menu_Master MMAS Inner Join Mapping_MenuDistributorPointSup MMap on MMap.MenuId=MMAS.MenuId) as MM_Inner) 
    MM on JP.DistributorId=MM.DistributorId
    Order by JP.DistributorId, MM.MenuId) as Menu `;

  let stored_Select=`${superQ_tblName}.DMID as MID,${superQ_tblName}.EmpId,${superQ_tblName}.DistributorId as StoreId,${superQ_tblName}.DistributorName as StoreName,${superQ_tblName}.DistributorCode as StoreCode,${superQ_tblName}.Latitude,${superQ_tblName}.Longitude,${superQ_tblName}.InTime,${superQ_tblName}.OutTime,${superQ_tblName}.UploadStatus,${superQ_tblName}.GeoTag`;
  let checkinSelect=`CheckInData.CHECKIN_TIME as CheckInTime,CheckInData.CHECKOUT_TIME as CheckOutTime`;


            
  let DataAvailable_QList=``,KPIAvailable_QList=``;
  return new Promise((resolve,reject)=>{
    db.transaction(async function (txn) {        
     let mq=`SELECT DISTINCT t1.ScreenName,t1.MenuId from Sup_Menu_Master t1 INNER join Mapping_MenuDistributorPointSup t2 on t1.MenuId=t2.MenuId`;
     
     await txn.executeSql(mq,[],async function (txn2, txnres) { 
       if(txnres.rows.length>0){ 
         for(let i=0;i<txnres.rows.length;i++){
          let data=txnres.rows.item(i);
          let avlblQ=get_DBAvailblQuery(props,data,join_tbl);
          let isDoneQ=get_DBQuery(data,join_tbl);
          console.log('isDoneQ',avlblQ)

          KPIAvailable_QList+=KPIAvailable_QList!='' && avlblQ!=''?' UNION ':' ';
          DataAvailable_QList+=DataAvailable_QList!='' && isDoneQ!=''?' UNION ':' ';
          KPIAvailable_QList+=' '+avlblQ+' ';
          DataAvailable_QList+=' '+isDoneQ+' ';

          if(i==txnres.rows.length-1){
            
            let KPIAvlblJoin=`LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.DistributorId=AVLSTK.DistributorId and Menu.MenuId=AVLSTK.MenuId `;
            let DataAvailableJoin=` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.DistributorId=dataavl.DistributorId and Menu.MenuId=dataavl.MenuId  `;
            
            let StoreData_join =` Left Outer Join ( Select ${tb2}.* From ${tb2} Where ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID    `;//and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L')
            // var SD_orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;

            
            q=`Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount from ${menuQ2} ${KPIAvlblJoin} ${DataAvailableJoin}  `;
            let superQ=`select ${checkinSelect},${stored_Select},count((CASE WHEN (${superQ_tblName}.KPIAVBL==1) THEN 1 ELSE null END)) as MenuCount,count((CASE WHEN (${superQ_tblName}.KPIAVBL==1 and ${superQ_tblName}.DataRowCount==1) THEN 1 ELSE null END )) as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
            console.log('superQ',superQ)
            // let superQ2=`select  ${checkinSelect},${stored_Select2},IFNULL(count(StoreData.CategoryId) ,0) as CategoryCount,IFNULL(count((CASE WHEN (${superQ2_tblName}.MenuCount==${superQ2_tblName}.MenuDoneCount) THEN 1 ELSE null END )),0) as CategoryDoneCount  from (${superQ}) as ${superQ2_tblName} ${StoreData_join} GROUP BY ${superQ2_tblName}.StoreId`;

            resolve(superQ);
          }
           
         }
       }
       else{
        
        let StoreData_join =` Left Outer Join ( Select ${tb2}.* From ${tb2} Where  ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID   `; //and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L') 
        // var SD_orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;

        
        q=`Select Menu.*, 0 as KPIAVBL, 0 as DataRowCount from ${menuQ2}   `;
        let superQ=`select ${checkinSelect},${stored_Select},0 as MenuCount,0 as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
        // let superQ2=`select  ${checkinSelect},${stored_Select2},IFNULL(count(StoreData.CategoryId) ,0) as CategoryCount,IFNULL(count((CASE WHEN (${superQ2_tblName}.MenuCount==${superQ2_tblName}.MenuDoneCount) THEN 1 ELSE null END )),0) as CategoryDoneCount  from (${superQ}) as ${superQ2_tblName} ${StoreData_join} GROUP BY ${superQ2_tblName}.StoreId`;
        
        resolve(superQ);
       }
     },function (txnE,txnerr) { console.log('txnerr in store q:',txnerr); resolve('');},);
  
   }); 
  }).catch((err)=>{
    console.log('error in query:',err);
    return '';
  })

}

export async function Q_getMyNPNDStoreList(props){
  let q='',tb2=AppTables.DISTRIBUTOR_CHECKIN;
  let join_tbl='Sup_NPNDStore';
  let superQ_tblName='StoreCats';
  let d1=new Date();
  let d2=moment(d1).format('MM/DD/YYYY');

  // Mapping_MenuDistributorPointSup
  let menusQ=` (select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    cross join (select MMAS.* from Sup_Menu_Master MMAS Inner Join Mapping_MenuSup MMap on MenuId on MMap.MenuId=MMAS.MenuId) as MM
    Order by JP.DistributorId, MM.MenuId) as Menu `;


  let menuQ2=`(select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    Left outer join 
	  (select Distinct  JP.StoreId,MM_Inner.* from ${join_tbl} JP cross join (select MMAS.* from Sup_Menu_Master MMAS Inner Join Mapping_MenuSup MMap on MMap.MenuId=MMAS.MenuId) as MM_Inner) 
    MM on JP.StoreId=MM.StoreId
    Order by JP.StoreId, MM.MenuId) as Menu `;

  let stored_Select=`${superQ_tblName}.MID,${superQ_tblName}.EmpId,${superQ_tblName}.StoreId,${superQ_tblName}.StoreName,${superQ_tblName}.StoreCode,${superQ_tblName}.Latitude,${superQ_tblName}.Longitude,${superQ_tblName}.InTime,${superQ_tblName}.OutTime,${superQ_tblName}.UploadStatus,${superQ_tblName}.GeoTag`;
  let checkinSelect=`CheckInData.CHECKIN_TIME as CheckInTime,CheckInData.CHECKOUT_TIME as CheckOutTime`;


            
  let DataAvailable_QList=``,KPIAvailable_QList=``;
  return new Promise((resolve,reject)=>{
    db.transaction(async function (txn) {        
     let mq=`SELECT DISTINCT t1.ScreenName,t1.MenuId from Sup_Menu_Master t1 INNER join Mapping_MenuSup t2 on t1.MenuId=t2.MenuId`;
     
     await txn.executeSql(mq,[],async function (txn2, txnres) { 
       if(txnres.rows.length>0){ 
         for(let i=0;i<txnres.rows.length;i++){
          let data=txnres.rows.item(i);
          let avlblQ=get_DBAvailblQuery(props,data,join_tbl);
          let isDoneQ=get_DBQuery(data,join_tbl);
          console.log('isDoneQ',avlblQ)

          KPIAvailable_QList+=KPIAvailable_QList!='' && avlblQ!=''?' UNION ':' ';
          DataAvailable_QList+=DataAvailable_QList!='' && isDoneQ!=''?' UNION ':' ';
          KPIAvailable_QList+=' '+avlblQ+' ';
          DataAvailable_QList+=' '+isDoneQ+' ';

          if(i==txnres.rows.length-1){
            
            let KPIAvlblJoin=`LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.DistributorId=AVLSTK.DistributorId and Menu.MenuId=AVLSTK.MenuId `;
            let DataAvailableJoin=` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.DistributorId=dataavl.DistributorId and Menu.MenuId=dataavl.MenuId  `;
            
            let StoreData_join =` Left Outer Join ( Select ${tb2}.* From ${tb2} Where ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID    `;//and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L')
            // var SD_orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;

            
            q=`Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount from ${menuQ2} ${KPIAvlblJoin} ${DataAvailableJoin}  `;
            let superQ=`select ${checkinSelect},${stored_Select},count((CASE WHEN (${superQ_tblName}.KPIAVBL==1) THEN 1 ELSE null END)) as MenuCount,count((CASE WHEN (${superQ_tblName}.KPIAVBL==1 and ${superQ_tblName}.DataRowCount==1) THEN 1 ELSE null END )) as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
            console.log('superQ',superQ)
            // let superQ2=`select  ${checkinSelect},${stored_Select2},IFNULL(count(StoreData.CategoryId) ,0) as CategoryCount,IFNULL(count((CASE WHEN (${superQ2_tblName}.MenuCount==${superQ2_tblName}.MenuDoneCount) THEN 1 ELSE null END )),0) as CategoryDoneCount  from (${superQ}) as ${superQ2_tblName} ${StoreData_join} GROUP BY ${superQ2_tblName}.StoreId`;

            resolve(superQ);
          }
           
         }
       }
       else{
        
        let StoreData_join =` Left Outer Join ( Select ${tb2}.* From ${tb2} Where  ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID   `; //and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L') 
        // var SD_orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;

        
        q=`Select Menu.*, 0 as KPIAVBL, 0 as DataRowCount from ${menuQ2}   `;
        let superQ=`select ${checkinSelect},${stored_Select},0 as MenuCount,0 as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
        // let superQ2=`select  ${checkinSelect},${stored_Select2},IFNULL(count(StoreData.CategoryId) ,0) as CategoryCount,IFNULL(count((CASE WHEN (${superQ2_tblName}.MenuCount==${superQ2_tblName}.MenuDoneCount) THEN 1 ELSE null END )),0) as CategoryDoneCount  from (${superQ}) as ${superQ2_tblName} ${StoreData_join} GROUP BY ${superQ2_tblName}.StoreId`;
        
        resolve(superQ);
       }
     },function (txnE,txnerr) { console.log('txnerr in store q:',txnerr); resolve('');},);
  
   }); 
  }).catch((err)=>{
    console.log('error in query:',err);
    return '';
  })

}




async function checkIf_StockWithCat_KPIDone(txnres2,storeData){
  let {StoreId}=storeData;
  return await new Promise((resolve,reject)=>{
    if(txnres2.rows.length>0){
      db.transaction(async function (txn) { 
        let allDone=true;
        for(var i=0;i<txnres2.rows.length;i++){
          let cat=txnres2.rows.item(i);
          let isDone=await isCatDone(storeData,cat)
          if(isDone==false){
            allDone=false;
          }

          if(i==txnres2.rows.length-1){
            resolve(allDone);
          }
        }
      });   
      
    }
    else{
      resolve(false);
    }
  }).catch((err)=>{
    console.log(err);
    return false;
  });
  
}

async function isCatDone(storeData1,cat){
  let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
  return await new Promise((resolve,reject)=>{
      db.transaction(async function (txn) {  
          let seletlist=`STOCK_UID,PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK`;
          let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}'    `;
          await txn.executeSql(sku_q,[],async function (txn2, txnres2) { 
              if(txnres2.rows.length>0){
                  resolve(true);
              }else{
                  resolve(false);
              }
          },function (txn2, txnerr) { console.log(txnerr);resolve(false); },);
          
        });   
  }).catch((err)=>{
      console.log(err);
      return false;
  })
}

export async function checkIf_surveyCatDone(storeData1,SurveyId,CategoryId,ShowCat1,menu1){
  
  var d1=new Date();
  var d2=moment(d1).format('MM/DD/YYYY');
  return new Promise((resolve,reject)=>{
    try{
      db.transaction(async function (txn) { 

        let {StoreId}=storeData1;
        
        // get inserted audit
        let selectlist=` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids `;
        let join=` INNER JOIN Mapping_SurveySup M on T.SurveyId=M.SurveyId`;
        let join2=` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID and T.SubCategoryId=T1.SUB_CATEGORY_ID And T.QuestionId=T1.QUESTION_ID and T1.MENUID='${menu1?.MenuId}'`;
        let q2=`Select ${selectlist} FROM Sup_Master_SurveyQuestion T ${join}  ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.EMP_ID='${storeData1.MerchandiserId}' AND T1.VISIT_DATE= '${d2}' AND T1.SURVEY_ID=${SurveyId} and  T1.ANSWER_ID Is Not NULL `;
        if(ShowCat1==true){
          q2+=` AND  T1.CATEGORY_ID=${CategoryId} `;
        }
        q2+=` ORDER BY T.SubCategorySequence `;

       
        await txn.executeSql(q2,[],async function (txn2, txnres) { 
          
            if(txnres.rows.length>0){
              resolve(true);
            }
            else{
              resolve(false);
            }
            
        },function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
       
      });  

    }
    catch(err){
      console.log('checkIfDone Error CatSurvey',err)
      resolve(false);
    }
  }).catch((err)=>{
    console.log('checkIfDone Error CatSurvey',err)
    return false;
  });
}


export async function checkIf_VisiAuditDone(storeData1,SurveyId,CategoryId,ShowCat1){
  
  var d1=new Date();
  var d2=moment(d1).format('MM/DD/YYYY');
  return new Promise((resolve,reject)=>{
    try{
      db.transaction(async function (txn) { 

        let {StoreId}=storeData1;
        
        // get inserted audit

        let join3=` inner join Sup_VisibilityAudit s on w.PVIS_DEFINITION_ID=s.VisibilityDefinitionId  `;
        let q2=` Select * from ${AppTables.VISAUDIT_HDR_DATA} w  ${join3} where w.STORE_ID='${StoreId}' and w.PVIS_DEFINITION_ID='${SurveyId.VisibilityDefinitionId}' and s.StoreId='${StoreId}' and s.VisibilityDefinitionId='${SurveyId.VisibilityDefinitionId}'  `;


       
        await txn.executeSql(q2,[],async function (txn2, txnres) { 
          
            if(txnres.rows.length>0){
              resolve(true);
            }
            else{
              resolve(false);
            }
            
        },function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
       
      });  

    }
    catch(err){
      console.log('checkIfDone Error CatSurvey',err)
      resolve(false);
    }
  }).catch((err)=>{
    console.log('checkIfDone Error CatSurvey',err)
    return false;
  });
}


export async function checkIf_surveyDone(storeData1,SurveyId,ShowCat1,menu1){
 
  var d1=new Date();
  var d2=moment(d1).format('MM/DD/YYYY');
  return new Promise((resolve,reject)=>{
    try{
      db.transaction(async function (txn) { 
        let {StoreId}=storeData1;
       
        if(ShowCat1==true){
          let q2=`SELECT DISTINCT T.Category,T.CategoryId,T.CategorySequence FROM Sup_Master_SurveyQuestion T INNER JOIN Mapping_SurveySup M on T.SurveyId=M.SurveyId WHERE T.SurveyId='${SurveyId}' order by T.CategorySequence`;
          await txn.executeSql(q2,[],async function (txn2, txnres) { 
             
              if(txnres.rows.length>0){
                let arr=[],isSurveyDone=true;
                for(var i=0;i<txnres.rows.length;i++){
                  let data =txnres.rows.item(i);
                  let isDone=await checkIf_surveyCatDone(storeData1,SurveyId,data.CategoryId,true,menu1)
                  if(isDone!=true){
                    isSurveyDone=false;
                    resolve(isSurveyDone)
                    break;
                  }
                  else if(i==txnres.rows.length-1){
                    resolve(isSurveyDone)
                  }
                }
              }
              else{
                resolve(true);
              }
          },function (txn2, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else{
          let isDone=await checkIf_surveyCatDone(storeData1,SurveyId,'',false,menu1)
          resolve(isDone)
        }
      });  

    }
    catch(err){
      console.log('checkIfDone Error CatSurvey',err)
      resolve(false);
    }
  }).catch((err)=>{
    console.log('checkIfDone Error CatSurvey',err)
    return false;
  });
}