import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {UploadData,UploadData2,UploadFormData,UpdateStoreStatus,UpdateImageStatus} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,testurl_upload,db,testurl_image} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import * as RNFS from 'react-native-fs';


function UploadDataScreen(props) { 
    const route = useRoute();
  
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const [processing, setProcessing] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState('loading...'); 

    let [StoreQuestions, setStoreQuestions] = useState({});
    let [StorePhotosData, setStorePhotosData] = useState({});
    let [StoreSKUPhotosData, setStoreSKUPhotosData] = useState({});
    let [StoreActPhotosData, setStoreActPhotosData] = useState({});
    let [UploadImages, setUploadImages] = useState([]);
    let [UploadImages2, setUploadImages2] = useState([]);
    let [UploadImages3, setUploadImages3] = useState([]);
    let [MDetails, setMDetails] = useState([]);

    const [state, setState] = useState({teamList: [], isDataDownloaded: false});

  useEffect(() => {
    // getLocalData();
  }, []);


  async function getLocalData(){
    try {   
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let token = await get_item('loginToken');
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      MDetails=[];StorePhotosData={};StoreSKUPhotosData={};StoreActPhotosData={},UploadImages=[],UploadImages2=[],UploadImages3=[];
      setMDetails(MDetails);setStorePhotosData(StorePhotosData);setStoreSKUPhotosData(StoreSKUPhotosData);setStoreActPhotosData(StoreActPhotosData);
      setUploadImages(UploadImages);setUploadImages2(UploadImages2);setUploadImages3(UploadImages3);

      await db.transaction(async function (txn) { 

        await txn.executeSql(`Select * from Stores where VisitDate='${d2}' and (UploadStatus='C' or UploadStatus='D') `,[],async function (txn2, txnres2) { 
            if(txnres2.rows.length>0){  
              console.log('checkout ids',txnres2.rows.length);  
              // let mstatus_data=[],storePhotos=[],storeSKUPhotos=[],storeActPhotos=[];              
              for (var i=0;i<txnres2.rows.length;i++){
                let data=txnres2.rows.item(i);
                // mstatus_data.push(data);   
                console.log('stored data to upload mid',data.MID,data.StoreId);
               
                let {StoreId,EmpId,MID,UploadStatus,Status,VisitDate}=data;
                MDetails.push(data);
                setMDetails(MDetails);
                // get all checkout ids data
                if(UploadStatus=='C'){
                  await txn.executeSql(`Select * from StoreQuestions where MID='${MID}' and AddedDate='${d2}'`,[],async function (txn2, txnres3) { 
                    if(txnres3.rows.length>0){
                      for (var i=0;i<txnres3.rows.length;i++){
                        let spdata=txnres3.rows.item(i);
                        let {QuestionId,Question,AnswerId,Answer,ImagePath,ImageName}=spdata;
                        let objdata={
                          "mid": MID,
                          "UserId":loginDetails.UserId,
                          "QuestionId": QuestionId!=''?parseInt(QuestionId):0,
                          "AnswerId": AnswerId,
                          "Answer": Answer,
                          "Image1": ImageName
                        };
                        let spd_Arr=StoreQuestions[MID]!=null?StoreQuestions[MID]:[];
                        spd_Arr.push(objdata);
                        StoreQuestions[MID]=spd_Arr;                          
                        setStoreQuestions(StoreQuestions);
                      }                     
                    }                                  
                  },function (txnE,txnerr) { console.log(txnerr);});

                  let q1=`Select * from StorePhotos where StoreId='${StoreId}' and EmpId='${EmpId}' and AddedDate='${d2}' `;  
                  await txn.executeSql(q1,[],async function (txn2, txnres3) { 
                    if(txnres3.rows.length>0){
                      for (var i=0;i<txnres3.rows.length;i++){
                        let spdata=txnres3.rows.item(i);
                        let {StoreId, StoreName, Address,EmpId,CategoryId,Category,ImageTypeId,ImageType, imgPath1, imgName1, imgPath2, imgName2, imgPath3, imgName3,AddedDate}=spdata;
                        let objdata={
                          "mid": MID,
                          "UserId":loginDetails.UserId,
                          "CategoryId": CategoryId,
                          "ImageTypeId": ImageTypeId!=''?parseInt(ImageTypeId):0,
                          "image1": imgName1,
                          "image2": imgName2,
                          "image3": imgName3
                        };
                        let spd_Arr=StorePhotosData[MID]!=null?StorePhotosData[MID]:[];
                        spd_Arr.push(objdata);
                        StorePhotosData[MID]=spd_Arr;                          
                        setStorePhotosData(StorePhotosData);

                      }                     
                    }                                  
                  },function (txnE,txnerr) { console.log(txnerr);});
  
  
                  let q2=`Select * from StoreSKUPhotos where StoreId='${StoreId}' and EmpId='${EmpId}' and AddedDate='${d2}' `;  
                  await txn.executeSql(q2,[],async function (txn2, txnres3) { 
                    if(txnres3.rows.length>0){
                      for (var i=0;i<txnres3.rows.length;i++){
                        let spdata=txnres3.rows.item(i);
                        let {StoreId, StoreName, Address,EmpId,TypeId,Type,CategoryId,Category,BrandId,Brand,Size,Pack,Flavour,PriceOff,MRP,Mfg,Expiry, imgPath1, imgName1, imgPath2, imgName2,AddedDate}=spdata;
                        let sp=Type==''?0:parseInt(MRP)-parseInt(PriceOff);
                        let mrp=MRP==''?0:parseInt(MRP);
                        let objdata={
                          "MID": MID,
                          "UserId": loginDetails.UserId,
                          "Present": Type==''?'0':'1',
                          "ProductType": Type,
                          "CompBrandId": BrandId,
                          "SkuSize": Size,
                          "Flavour": Flavour,
                          "MRP": mrp,
                          "SellingPrice":sp,
                          "MfdMonthYear": Mfg,
                          "ExpMonthYear": Expiry,
                          "Remark": "",
                          "LaunchImg1": imgName1,
                          "LaunchImg2": imgName2
                        };                
                        let spd_Arr=StoreSKUPhotosData[MID]!=null?StoreSKUPhotosData[MID]:[];
                        spd_Arr.push(objdata);
                        StoreSKUPhotosData[MID]=spd_Arr;
                        setStoreSKUPhotosData(StoreSKUPhotosData);
  
                       
                      }                     
                    }                                  
                  },function (txnE,txnerr) { console.log(txnerr);});
  
                  
                  let q3=`Select * from StoreActPhotos where StoreId='${StoreId}' and EmpId='${EmpId}' and AddedDate='${d2}'`;  
                  await txn.executeSql(q3,[],async function (txn2, txnres3) {
                    if(txnres3.rows.length>0){
                      for (var i=0;i<txnres3.rows.length;i++){
                        let spdata=txnres3.rows.item(i);
                        let {StoreId, StoreName, Address,EmpId,TypeId,Type,CategoryId,Category,BrandId,Brand,NoOfContacts, imgPath1, imgName1, imgPath2, imgName2, imgPath3, imgName3,AddedDate}=spdata;
                        let ShowContactsFlag=Type==''?0:(parseInt(NoOfContacts)>0?1:0);
                        let objdata={
                          "MID": MID,
                          "UserId": loginDetails.UserId,
                          "Present": Type==''?'0':'1',
                          "ActivationTypeId": TypeId,
                          "CompBrandId": BrandId,
                          "Remark": "",
                          "ShowContactsFlag": ShowContactsFlag,
                          "NoofContacts": NoOfContacts,
                          "Image": imgName1,
                          "ImageTwo": imgName2,
                          "ImageThree": imgName3
                        }; 
                        console.log('datae tu:',objdata); 
                        let spd_Arr=StoreActPhotosData[MID]!=null?StoreActPhotosData[MID]:[];
                        spd_Arr.push(objdata);
                        StoreActPhotosData[MID]=spd_Arr;  
                        setStoreActPhotosData(StoreActPhotosData);
  
                        
                      }                     
                    }              
                  });
                }

                let q3=`Select * from imageUploadStatus where MID='${MID}' and status='0'`;
                console.log(q3);  
                await txn.executeSql(q3,[],async function (txn2, txnres3) {
                  console.log('images to upload:',txnres3.rows.length)
                  if(txnres3.rows.length>0){
                    for(var i=0;i<txnres3.rows.length;i++){
                      let spdata=txnres3.rows.item(i);
                      console.log('image row:',spdata.MID); 
                      let imgs=UploadImages[MID]!=null?UploadImages[MID]:[];
                      imgs.push(spdata);
                      UploadImages[MID]=imgs;  
                      setUploadImages(UploadImages);
                    }                     
                  }              
                });
                
              }

              
              
            } 
            
            setProcessing(false);                    
        },function (txnE,txnerr) { },);
        
      });  

      

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

  async function uploadAllData() {
    
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    
    MDetails.map(async(item,index)=>{
      const MID=item.MID;
      let sQtns=StoreQuestions[MID];
      let spdArr=StorePhotosData[MID];
      let sSKUpdArr=StoreSKUPhotosData[MID];
      let sACTpdArr=StoreActPhotosData[MID];
      console.log(MID,sACTpdArr);
      // upload store photos data data
      if(item.UploadStatus=='D')
      { 
        uploadImages(loginDetails,token,MID);
      }
      else{
      var data = {"MID": MID,"Keys":"Sup_StoreCatPics","SecurityToken":token,"JsonData":JSON.stringify(spdArr),"UserName":loginDetails.UserId}
      await UploadData2(testurl_upload, data)
        .then(async(res) => {        
          console.log('storephotos data uploaded:',res);
          
          // upload store sku photos data
          data = {"MID": MID,"Keys":"Sup_Competition_SKU","SecurityToken":token,"JsonData":JSON.stringify(sSKUpdArr),"UserName":loginDetails.UserId}
          await UploadData2(testurl_upload, data)
            .then(async(res) => {        
              console.log('compSKU data uploaded:',res);

              // upload store Act photos data
              data = {"MID": MID,"Keys":"Sup_Competition_Activation","SecurityToken":token,"JsonData":JSON.stringify(sACTpdArr),"UserName":loginDetails.UserId}
              await UploadData2(testurl_upload, data)
                .then(async(res) => {        
                  console.log('compACT data uploaded:',res);

                  // upload store qtns data
                  data = {"MID": MID,"Keys":"Sup_StoreAudit","SecurityToken":token,"JsonData":JSON.stringify(sQtns),"UserName":loginDetails.UserId}
                  console.log(data);
                  await UploadData2(testurl_upload, data)
                    .then(async(res) => {        
                      console.log('Store Qtns data uploaded:',res);

                      data_uploadStatus(loginDetails,token,MID);

                    }).catch(err => {
                      console.log('onPage Team error', err);
                      setProcessing(false);
                      notify('Cannot Upload Data!');
                  }); 

                }).catch(err => {
                  console.log('onPage Team error', err);
                  setProcessing(false);
                  notify('Cannot Upload Data!');
              });  

            }).catch(err => {
              console.log('onPage Team error', err);
              setProcessing(false);
              notify('Cannot Upload Data!');
          });

        }).catch(err => {
          console.log('onPage Team error', err);
          setProcessing(false);
          notify('Cannot Upload Data!');
      });
      }
    });

    if(MDetails.length<=0){
      setProcessing(false);
      notify('All Data and images already uploaded!','SHORT');
      props.navigation.goBack();
    }      
  }

  async function data_uploadStatus(loginDetails,token,MID){
    // update upload status
    const url='https://anitemp.parinaam.in/Webservice/Abbott_MnancService.svc/';
    let data2={'Mid':MID,'Status':'D'}
    await UploadData(url+'StoreCoverageStatusSup',data2)
      .then(async(res)=>{ 
        console.log('StoreCoverageStatusSup res:',res);         
          if(res==1){               
            let datan={Mid:MID,Status:'D'} ;               
            UpdateStoreStatus(props,datan);
            setLoaderTitle('Uploading Images...');
            uploadImages(loginDetails,token,MID);
          }
      }).catch(err => {
        console.log('onPage Team error', err);
        setProcessing(false);
        notify('Cannot Upload Data!');
      }); 
  }

  async function uploadImages(loginDetails,token,MID){
    let allimages=UploadImages[MID]!=null?UploadImages[MID]:[];
    if(allimages.length>0){
      allimages.map(async(file,index)=>{
        const data1 = new FormData();
        let {uniqueID,MID,StorePhotosId,imgType,imgPath,imgName,Status,AddedDate}=file; 
        let Foldername=imgType=='sku'?'Sup_Competition_SKUImages':(imgType=='act'?'Sup_Competition_ActivationImages':(imgType='audit'?'Sup_AuditImages':'Sup_StoreCategoryImages'));
            
        data1.append('file', {
          uri: 'file://'+file.imgPath,
          type: 'image/jpg',
          name: file.imgName
        });
        data1.append('Foldername', Foldername);
        data1.append('Path', '');
        data1.append('UserName', loginDetails.UserId);
        data1.append('SecurityToken', token);
        
        await UploadFormData(testurl_image, data1)
          .then(async(res) => { 
            console.log('image uploaded:',imgType);
            UpdateImageStatus(props,{uniqueID:uniqueID})
              if(index==(allimages.length-1)){
                // update upload status
                console.log('lastimage update status u');
                const url='https://anitemp.parinaam.in/Webservice/Abbott_MnancService.svc/';
                let data2={'Mid':MID,'Status':'U'}
                await UploadData(url+'StoreCoverageStatusSup',data2)
                .then(async(res)=>{ 
                    console.log('StoreCoverageStatusSup res:',res);         
                    if(res==1){                     
                        UpdateStoreStatus(props,data2);  
                        setProcessing(false);
                        notify('Uploaded successfully','SHORT');                       
                    }
                }).catch(err => {
                    console.log('onPage Team error', err);
                    setProcessing(false);
                    notify('Cannot Upload Data!');
                }); 
              }
          }).catch(err => {
            console.log('onPage Team error', err);
            setProcessing(false);
            notify('Cannot Upload Image!');
        });
      });
    }
    else{
      setProcessing(false);
    }

  }


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} topM={18} title={'Upload Data'}/>
        <ScrollView
            style={[customStyle.download_scroll]}
            contentContainerStyle={customStyle.download_scroll_con}
        >
            {/* <TouchableOpacity style={customStyle.downloadbtn} onPress={()=>{uploadAllData()}}>
              <Text style={customStyle.downloadbtn_label}>Upload Data</Text>
            </TouchableOpacity>   */}
            
        </ScrollView>   
      </Container>   
    ); 
  }
  
  

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