import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme } from "../styles/Global";
import {Image,View,Text,ScrollView,TouchableOpacity,FlatList} from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {checkRange, marktext1,marktext2, resizeImage, restore_ImageWithMetaData, UpdateStoreStatus, UploadData, UploadData2, UploadFormData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {AppVersion, CoverageImagePath, db, URL_IMAGE, version} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, MaterialCommunityIcons,} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import CustomModal from '../components/CustomModal';
import GradientButton from '../components/gradientButton';
import * as RNFS from 'react-native-fs';
import Geolocation from 'react-native-geolocation-service';
import {_checkLocationPermission} from '../components/geolocation';
import CustomCamera from '../components/Camera';

import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { AppTables } from '../constants/tableConstants';
import { uploadStoreStatus } from '../constants/uploadData';
import { ConfirmSaveAlert } from '../components/alert';


function StoreNonWorkingReasons(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const [processing, setProcessing] = useState((props.isDataDownloaded?true:false));
    
    const [storeData, setStoreData] = useState({});
    const [nonWorkingRsns, setNonWorkingRsns] = useState([]);
    const [selectedReason, setSelectedReason] = useState({});
    const [reason, setReason] = useState('');
    const [reasonId, setReasonId] = useState('');
    const [Image1, setImage1] = useState('');
    const [Image1Path, setImage1Path] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [isAnyStoreUploaded, setIsAnyStoreUploaded] = useState(false);
    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);
    const [isStoreSearch, setIsStoreSearch] = useState(false);
    const [showAlert, setShowAlert] = useState(false);

    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

    const [GeoFenceEnable_Checkout, setGeoFenceEnable_Checkout] = useState(false);
    const [GeoFenceRadius_Checkout, setGeoFenceRadius_Checkout] = useState('');


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

      let CO_GeoFenceEnable=props.GFEnable_checkout!=null?props.GFEnable_checkout:false;
      let CO_GeoFenceRadius=props.GFRadius_checkout!=null?props.GFRadius_checkout:'';
       console.log("GeoFenceEnable_Checkout",CO_GeoFenceEnable)
      setGeoFenceEnable_Checkout(CO_GeoFenceEnable);
      setGeoFenceRadius_Checkout(CO_GeoFenceRadius);

      
      getNonWorkingRsns();
      getData();

      const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
      
      return function cleanup() {
        return unsubscribe;
      };
    }, []);

    useEffect(() => {
      const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
      return unsubscribe;
    }, [showCamera]); 

    function  onBeforeRemove(e){
      if(showCamera==true){
          e.preventDefault();
          setShowCamera(false);
      }
      else{
        return;
      } 
    }



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

      // set store type: adhoc or planned
      let params=props.route.params? props.route.params:{};
      let storeData1=params.storeData || {};
      let isAdhoc=params.isAdhoc || false;
      let isBeat=params.isBeat!=null? params.isBeat : false;
      let isNonMerchan1=params.isNonMerchans!=null? params.isNonMerchans : false;
      let isNonProgam=params.isNonProgs!=null? params.isNonProgs : false;
      let isStoreSearch1=params.isStoreSearch!=null? params.isStoreSearch : false;
      
      setIsAdhocScreen(isAdhoc);
      setIsBeatPlan(isBeat);
      setIsNonMerchan(isNonMerchan1);
      setIsNonProg(isNonProgam)
      setIsStoreSearch(isStoreSearch1)
      setStoreData(storeData1);


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

      // let q=`SELECT * FROM Non_Working_Reason WHERE EntryAllow=1`;

      let q=`SELECT * FROM Non_Working_Reason where ChannelId='${storeData1.ChannelId}'`;
      console.log("Non_Working_Reason---q:",q)
      await db.transaction(async function (txn) {  

        await txn.executeSql(q,[],async function (txn2, txnres2) {           
          if(txnres2.rows.length>0){ 
            // show from local
            var storeArr=[];
            for(var i=0;i<txnres2.rows.length;i++){
              let sdata=txnres2.rows.item(i);               
              storeArr.push(sdata); 
              if(i==(txnres2.rows.length-1)){
                console.log(storeArr);
                setNonWorkingRsns(storeArr);
                setProcessing(false);
              }
            }            
          }
          else{            
            setProcessing(false); 
            notify(ST.Nodatafound);
          }
        },function(Etxn,txnerr){console.log(txnerr);});
      });   
    }

    async function getData(){
      let isAny=await checkIfAlreadyUploaded();
      setIsAnyStoreUploaded(isAny);
    }

    async function checkIfAlreadyUploaded(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
  
            // let join=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
            let q=`Select t1.* from Mapping_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus!='N' and t1.UploadStatus!='' `
            
            // let join2=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Adhoc_JourneyPlan' `;
            let q2=`Select t1.* from Adhoc_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus!='N' and t1.UploadStatus!='' `
            
            await txn.executeSql(q,[],async function (txn2, txnres2) {           
                if(txnres2.rows.length>0){ 
                  // show from local
                  resolve(true);      
                }
                else{            
                  await txn.executeSql(q2,[],async function (txn2, txnres3) {           
                    if(txnres3.rows.length>0){ 
                      // show from local
                      resolve(true);      
                    }
                    else{   
                      resolve(false);
                    }
                  },function(Etxn,txnerr){console.log(txnerr);resolve(false);  });
                }
            },function(Etxn,txnerr){console.log(txnerr);resolve(false); });
  
          }); 
  
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        return false;
      });
    }

    //user loction upload function
    async function sendUserLocation(data = {}) {
        console.log("sendUserLocation");
        const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
        let postData = {
          'MID': storeData.MID,
          'Keys': "GeoFenceDataNonWorkingReason",
          'JsonData': JSON.stringify(data),
          'UserId': props.UserId,
        }
        console.log("urlllllllllll",url, postData);
        return await UploadData2(url, postData)
          .then(async (res) => {
            if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
                  notify('GeoFenceData Uploaded Succesfully', 'SHORT');
              // console.log(KPIdata+' uploaded');
              return true;
            }
            return false;
          })
          .catch(async (err) => {
            return false;
          });
      }

    async function _getCurrentLocation() {  
      setProcessing(true);
      setLoaderTitle('Getting location...');
      const hasPermission=await _checkLocationPermission();
      if(hasPermission==true)
      {    
        
        Geolocation.getCurrentPosition(
          async (position) => {
            let loc={lat:position.coords.latitude,lng:position.coords.longitude}; 
            var distance = checkRange(loc.lat,loc.lng,storeData.Latitude,storeData.Longitude);
            console.log('COut distance NW:',distance + "--Store lat,longt"+storeData.Latitude,storeData.Longitude + "----current_lat_lot"+loc.lat,loc.lng);

            let EntryAllow=(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1);
            let GPSMandatory=(selectedReason.GPSMandatory=='true' || selectedReason.GPSMandatory==true || selectedReason.GPSMandatory==1);
      
           
            console.log("GeoFenceEnable_Checkout",GeoFenceEnable_Checkout, "GPSMandatory",GPSMandatory,"EntryAllow",EntryAllow);
            if(GPSMandatory &&  GeoFenceEnable_Checkout==true){
              if(GeoFenceRadius_Checkout!='' && distance>GeoFenceRadius_Checkout){
                 let locData = { "UserId": props.UserId, "StoreId": storeData.StoreId, "StoreLatitude": storeData.Latitude, 'StoreLongitude': storeData.Longitude, 'currentLatitude': loc.lat, 'currentLongitude': loc.lng ,'VisitDate':storeData.VisitDate};
                await sendUserLocation(locData);
                notify(ST.Youcannotcheckout+' '+ST.Youarenotwithinthealloweddistancefromthestore+' '+GeoFenceRadius_Checkout+' m','LONG')
                setProcessing(false);
                props.navigation.goBack();
              }
              else{
                checkOutAfterLoc(loc);
              }
            }
            else{
              checkOutAfterLoc(loc);
            }
          
          },
          (error) => {
            notify(ST.Cannotgetuserposition);
            setProcessing(false);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else{        
        notify(ST.Pleaseallowlocationpermission);
      }
    }

    async function checkOutAfterLoc(loc){
      setLoaderTitle(ST.UploadingData+'...');
      let EntryAllow=(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1);
      let createJourneyPlan=(isAdhocScreen==true || isBeatPlan==true || isNonMerchan==true || isNonProg==true || isStoreSearch==true );
      createJourneyPlan? await createJCP(loc,EntryAllow): (EntryAllow?await uploadNonWRsnWithImage(loc,'L'):await uploadNonWRsn(loc,'U',storeData));
    }

    async function uploadNonWRsn(loc,UploadStatus='U',storeData1){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');      
      let data={
        "Mid":storeData1.MID,
        "StoreId":storeData1.StoreId,
        "VisitDate":d2,
        "Latitude":(loc.lat || ''),
        "Longitude":(loc.lng || ''),
        "ReasonId":reasonId,
        "Remark":"",
        "Appversion":AppVersion,
        "UploadStatus":UploadStatus,
        "UserName":(props.UserId || ''),
      }

      const url=props.baseurl+getMethodName(METHODS.COVERAGENOTALLOW_METHOD);
      console.log(url,data);
      await UploadData(url,data)
      .then(async(res)=>{  
        console.log('COVERAGENOTALLOW_METHOD',res);
        if(res=='1'){
          let isupdated=await InsertCoverageData(loc,false,UploadStatus);
          console.log("isupdated:",isupdated);
          // let isupdated=await update_Store_UploadStatus(false);
          if(isupdated==true){
            notify(ST.AllDataUploaded+'!','SHORT');
            setProcessing(false);
            goBack();
          }
          else{
            notify(ST.DataUploadedButcouldnotupdatestorestatus,'SHORT');
            setProcessing(false);
          }
        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploaddata,'SHORT');
        }
      })
      .catch((err)=>{
        console.log(err);
      });
    }

    async function uploadNonWRsnWithImage(loc,UploadStatus='L'){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');    

      var data1 = new FormData();         
      if(Image1Path!='' && Image1Path!=null){
         
        data1.append('file', {
          uri: Image1Path,
          type: 'image/jpg',
          name: Image1,
        });

        let foldername=getFolderName(Image1);
        data1.append('Foldername',foldername);
        data1.append('Path', d2);
      }
      
      // data1.append('UserName', (props.UserId || ''));
      
      let data={
        "Mid":storeData.MID,
        "StoreId":storeData.StoreId,
        "VisitDate":d2,
        "Latitude":(loc.lat || ''),
        "Longitude":(loc.lng || ''),
        "ReasonId":reasonId,
        "Remark":"",
        "Appversion":AppVersion,
        "UploadStatus":UploadStatus,
        "UserName":(props.UserId || ''),
        "ImageName":Image1,
        "CheckoutImage":"",
      }

      const url=props.baseurl+getMethodName(METHODS.GETCOVERAGE_METHOD);
      const url1=(props.imageUploadUrl || URL_IMAGE)+getMethodName(METHODS.UPLOADIMAGES_METHOD);
      console.log(url,data);

      await UploadData2(url,data)
      .then(async(res)=>{         
        console.log('res:',res);
        if(parseInt(res)>0){
          let isUpdated=await InsertCoverageData(loc,true,UploadStatus);
          console.log("isUpdated:",isUpdated);
          if(isUpdated==true){
            // Upload Image 
            console.log("isUpdated:",isUpdated);
            if((selectedReason.ImageAllow=='true' || selectedReason.ImageAllow==true || selectedReason.ImageAllow=='1') && Image1Path!='' && Image1Path!=null){
              await UploadFormData(url1,data1)
              .then(async(res1)=>{         
                console.log('res1:',res1);   
                // let tbname=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan')));

                let tbname = isStoreSearch == true ?'StoreSearch_JourneyPlan':(isBeatPlan == true ? 'JourneyPlan_RouteWise'  : (isAdhocScreen == true  ? 'Adhoc_JourneyPlan' : (isNonMerchan == true    ? 'NonMerchandising_JourneyPlan':(isNonProg == true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan'))));

                let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
                console.log("isUpdated:",isUpdated);
                if(isuploaded==true){
                  notify(ST.DataUploaded+'!');
                  setProcessing(false);
                  goBack();
                }
                else{
                  notify(ST.Cannotuploaddata);
                  setProcessing(false);
                }
                
              })
              .catch((err)=>{
                console.log(err);
              });
            }
            else{
              // let tbname=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan')));
              let tbname = isStoreSearch == true ? 'StoreSearch_JourneyPlan':(isBeatPlan == true ? 'JourneyPlan_RouteWise'  : (isAdhocScreen == true?'Adhoc_JourneyPlan': (isNonMerchan == true? 'NonMerchandising_JourneyPlan':(isNonProg == true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan'))));
              let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
              console.log("isuploaded status :",isuploaded);
              if(isuploaded==true){
                notify(ST.DataUploaded+'!');
                setProcessing(false);
                goBack();
              }
              else{
                notify(ST.Cannotuploaddata);
                setProcessing(false);
              }
              
            }
          }
          else{
            setProcessing(false);
            notify(ST.Cannotuploaddata);
          }
        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploaddata);
        }
      })
      .catch((err)=>{
        console.log(err);setProcessing(false);notify(ST.Cannotuploaddata);
      });
    }

    async function InsertCoverageData(loc,entryAllowed=true,UploadStatus){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let now=moment(d1).format('MM/DD/YYYY HH:mm:ss');

      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          
          let {StoreId,MID}=storeData;
          let {lat,lng}=loc;
          let q=`delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `; 
          // let JcpType=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan')));
          let JcpType = isStoreSearch == true ? 'StoreSearch_JourneyPlan':(isBeatPlan == true ? 'JourneyPlan_RouteWise'  : (isAdhocScreen == true  ? 'Adhoc_JourneyPlan': (isNonMerchan == true? 'NonMerchandising_JourneyPlan':(isNonProg == true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan'))));

          let values=` ('${StoreId}','${d2}','${lat}','${lng}','${Image1}','${now}','${Image1Path}','${reasonId}','${reason}','','','${MID}','${JcpType}','${d2}')`; 
          let insert_q=` insert into ${AppTables.COVERAGE_DATA}(STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) values ${values}`;


          let values2=` ('${StoreId}','${d2}','${lat}','${lng}','${now}','${Image1Path}','${now}','${Image1Path}','','${JcpType}','${d2}')`; 
          let insert_q2=` INSERT INTO ${AppTables.CHECKIN_DATA}(STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
          
          // if entry not allowed for the uploaded reason 
          // i.e. if user selects week off type non working reason then add coverage for all store with U status 
          if(!entryAllowed){
            // insert coverage for all stores 
            function getQ(tbname){
              return `select jp.StoreId,'${d2}','${lat}','${lng}','${Image1}','${now}','${Image1Path}','${reasonId}','${reason}','','',jp.MID,'${tbname}','${d2}' from ${tbname} jp`;
            }

            // insert coverage data in table 2 for all stores 
            function getQ2(tbname){
              return `select jp.StoreId,'${d2}','${lat}','${lng}','${now}','${Image1Path}','${now}','${Image1Path}','','${tbname}','${d2}' from ${tbname} jp`;
            }

            let MappingJP=getQ('Mapping_JourneyPlan');
            let AdhocJP=getQ('Adhoc_JourneyPlan');

            let storesq=MappingJP+' UNION '+AdhocJP;
            let storesq2=getQ2('Mapping_JourneyPlan')+' UNION '+getQ2('Adhoc_JourneyPlan');

            if(props.ShowNonMerList==true){
              let NonMerchJP=getQ('NonMerchandising_JourneyPlan');
              storesq+=` UNION ${NonMerchJP} `;
              storesq2+=` UNION ${getQ2('NonMerchandising_JourneyPlan')} `;
            }
            if(props.ShowNonProgram==true){
              let NonProgJP=getQ('NonProgram_JourneyPlan');
              storesq+=` UNION ${NonProgJP} `;
              storesq2+=` UNION ${getQ2('NonProgram_JourneyPlan')} `;
            }

            if(props.ShowStoreSearch==true){
              let StoreSearchJP=getQ('StoreSearch_JourneyPlan');
              storesq+=` UNION ${StoreSearchJP} `;
              storesq2+=` UNION ${getQ2('StoreSearch_JourneyPlan')} `;
            }

            if(props.ShowBeatPlanList==true){
              let RouteJP=getQ('JourneyPlan_RouteWise');
              storesq+=` UNION ${RouteJP} `;
              storesq2+=` UNION ${getQ2('JourneyPlan_RouteWise')} `;
            }

            insert_q=` insert into ${AppTables.COVERAGE_DATA}(STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) ${storesq} `;

            insert_q2=` INSERT INTO ${AppTables.CHECKIN_DATA}(STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) ${storesq2} `;
          }

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

          await txn.executeSql(q,[],async function (txn2, txnres2) {
            console.log('store coverage deleted');
            await txn.executeSql(insert_q,[],async function (txn2, txnres3) {
              console.log('InsertCoverageData done'); 
            },function(Etxn,txnerr){console.log(txnerr);});
          },function(Etxn,txnerr){console.log(txnerr);});


          await txn.executeSql(`delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`,[],async function (txn2, txnres2) {
            console.log('store checkin deleted');
            await txn.executeSql(insert_q2,[],async function (txn2, txnres3) {

              console.log('store checkin added as leave'); 
              let issup=await update_Store_UploadStatus(entryAllowed);  
              console.log("issup:",issup);
              resolve(issup);

            },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
          },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
          
        }); 
      }).then((val)=>{
        console.log('on InsertCoverageData complete:',val);
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });
      
    }

    async function createJCP(loc,EntryAllow=true){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');      
      // let data={"UserId":(props.UserId || ''),"JcpType":1,"StoreId":storeData.StoreId,"VisitDate":d2}
      let data = {"UserId": props.UserId || '',"JcpType": isStoreSearch == true ? 6 :  (isBeatPlan == true ? 2 : (isNonMerchan == true ? 3 : (isNonProg == true ? 5 : 1))), "StoreId": storeData.StoreId,  "VisitDate": d2 };
      const url=props.baseurl+getMethodName(METHODS.CREATEJP_METHOD);
      console.log(url,data);
      await UploadData(url,data)
      .then(async(res)=>{  
        console.log(res);
        if(res!=null && res!='' && res!='0' && parseInt(res)>0){          
          updateMID(res,loc,EntryAllow);// update mid in db
        }
        else{
          setProcessing(false);notify(ST.OopsSomethingwentwrongcannotcreateJCP,'SHORT');
        }
        
      })
      .catch((err)=>{
        setProcessing(false);console.log(err);
      });

    }

    const goBack=()=>{
      props.navigation.goBack();
    }

    async function updateMID(MID=0,loc,EntryAllow=true){
      try{
        await db.transaction(async function (txn) {   
          let JcpType=isBeatPlan==true?'JourneyPlan_RouteWise':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true?'NonProgram_JourneyPlan':(isStoreSearch==true?'StoreSearch_JourneyPlan':'Adhoc_JourneyPlan')));
          //let q=`UPDATE  Adhoc_JourneyPlan SET MID='${MID}' WHERE StoreId='${storeData.StoreId}' `;    
          let q=`UPDATE  ${JcpType} SET MID='${MID}' WHERE StoreId='${storeData.StoreId}' `;       
          await txn.executeSql(q,[],async function (txn2, txnres2) {
            console.log('mid updated',storeData.StoreId,MID);  
            let new_st=storeData;   
            new_st['MID']=MID;
            setStoreData(new_st);
            EntryAllow?uploadNonWRsnWithImage(loc,'L'):await uploadNonWRsn(loc,'U',new_st);
          },function(Etxn,txnerr){console.log(txnerr);});
        }); 
      }
      catch(e){
        setProcessing(false);
        notify(ST.CouldnotcreateJCP,'SHORT');
      }
    }

    // async function updateMID(MID=0,loc){
    //   try{
    //     let JcpType=isBeatPlan==true?'JourneyPlan_RouteWise':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true?'NonProgram_JourneyPlan':(isStoreSearch==true?'StoreSearch_JourneyPlan':'Adhoc_JourneyPlan')));

    //     await db.transaction(async function (txn) {   
    //       let q=`UPDATE  ${JcpType} SET MID='${MID}' WHERE StoreId='${storeData.StoreId}' `;               
    //       await txn.executeSql(q,[],async function (txn2, txnres2) {
    //         console.log('mid updated',storeData.StoreId,MID);  
    //         let new_st=storeData;   
    //         new_st['MID']=MID;
    //         setStoreData(new_st);
    //         uploadCheckIn(loc);

    //       },function(Etxn,txnerr){ setProcessing(false);console.log(txnerr);});
    //     }); 
    //   }
    //   catch(e){
    //     setProcessing(false);
    //     notify(ST.CouldnotcreateJCP,'SHORT');
    //   }
    // }

    async function update_Store_UploadStatus(entryAllowed=true){ 
       
      return new Promise(async(resolve,reject)=>{

          //Upload U status for all stores and add coverage with checking and chcekout time in local 
          if(entryAllowed==false){
            
            if(props.ShowNonMerList==true){
              console.log("exec isupdated uss1");
              let q3=`UPDATE NonMerchandising_JourneyPlan SET UploadStatus='U' `;
              let isupdated1=await executeQuery(q3);
              console.log("isupdated uss1:",isupdated1);
            }
            if(props.ShowNonProgram==true){
              console.log("exec isupdated uss2");
              let q3=`UPDATE NonProgram_JourneyPlan SET UploadStatus='U' `;
              let isupdated1=await executeQuery(q3);
              console.log("isupdated uss2:",isupdated1);
            }
            if(props.ShowStoreSearch==true){
              console.log("exec isupdated uss4");
              let q3=`UPDATE StoreSearch_JourneyPlan SET UploadStatus='U' `;
              let isupdated1=await executeQuery(q3);
              console.log("isupdated uss4:",isupdated1);
            }
            if(props.ShowBeatPlanList==true){
              console.log("exec isupdated uss3");
              let q3=`UPDATE JourneyPlan_RouteWise SET UploadStatus='U' `;
              let isupdated1=await executeQuery(q3);
              console.log("isupdated uss3:",isupdated1);
            }
            let q=`UPDATE Mapping_JourneyPlan SET UploadStatus='U' `;

            db.transaction(async function (txn) { 
              await txn.executeSql(q,[],async function (txn2, txnres1) {           
                console.log('store status updated')
                
                let q2=`UPDATE Adhoc_JourneyPlan SET UploadStatus='U' `;
                // let isupdated=await executeQuery(q2);

                await txn.executeSql(q2,[],async function (txn2, txnres1) {           
                  console.log('store status updated2')
                  console.log("resolve true ");
                  resolve(true);
                },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
                
              },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
            }); 
          }
          else{
           // let tbname=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan')));
           let tbname = isStoreSearch == true ? 'StoreSearch_JourneyPlan':(isBeatPlan == true ? 'JourneyPlan_RouteWise'  : (isAdhocScreen == true  ? 'Adhoc_JourneyPlan': (isNonMerchan == true? 'NonMerchandising_JourneyPlan':(isNonProg == true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan'))));
            let datan={StoreId:storeData.StoreId,UploadStatus:'L',tbname:tbname} ;            
            const isUpdated=await UpdateStoreStatus(props,datan);
            resolve(isUpdated);
            
          }
       
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      })
    }

    async function executeQuery(q,txn){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
        txn.executeSql(q,[],async function (txn2, txnres2) {           
          resolve(true);
        },function(Etxn,txnerr){console.log(txnerr);resolve(false) });
        });
      }).then((val)=>{
        return val;
      }).catch((err)=>{
          console.log(err);
        return false;
      })
    }

    async function submitNonWorkingRsns(){
      if(validate()){
        setShowAlert(true);   
      }      
    }

    async function saveData(){
      setShowAlert(false);
      _getCurrentLocation();     
    }

    function validate(){
      if(reasonId=='' || reasonId==null || reason=='' || reason==null){
        notify(ST.Pleaseselectreasonfornotworking,'SHORT');
        return false;
      }
      if( (selectedReason.ImageAllow=='true' || selectedReason.ImageAllow=='1' || selectedReason.ImageAllow==true) && (Image1Path=='' || Image1Path==null)){
        notify(ST.Pleaseclickselfieinfrontofstore,'SHORT');
        return false;
      }
      return true;
    }

    async function selectReason(item){
      if(isAnyStoreUploaded==true && (item.EntryAllow=='false' || item.EntryAllow==false)){
        notify(ST.Youcannotselectthisreasonasthereisalreadyastore);
        return;
      }

      setSelectedReason(item);
      setReason(item.Reason);
      setReasonId(item.ReasonId);
      setrerenderdata(!rerenderdata);
      
      if(item.ImageAllow=='true' || item.ImageAllow=='1' || item.ImageAllow==true){
        if((Image1Path!='' && Image1Path!=null)){
          setShowImageSaveOp(false);
        }
        else{
          setShowImageSaveOp(true);
        }
        openImageModal();
      }
    }

    function openImageModal(){
      setShowModal(true);    
    }

    function closeImageModal(){
      setShowModal(false);
    }

    function cancelImage(){
      setImage1('');
      setImage1Path('');
      closeImageModal();
    }

    async function getImage(imgdata){
      setLoaderTitle('Processing Image...')
      setProcessing(true);
      if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
        notify(ST.Cameraunavailable);
      }
      else if(typeof imgdata =='object' && imgdata.uri!=null){
          const img=imgdata;
          const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
          let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
          let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
          let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
          let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

         console.log("time", picture_clicked_time);
         console.log("time1", picture_clicked_time_for_pic_name);
         let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
         let calculate_tym_date_over_img = picture_clicked_time;

          let filename=storeData.StoreId+'_NonworkImg-'+calculate_tym_date_for_filename+'.jpg'; 
          const mark_text1=calculate_tym_date_over_img;
          const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Not Working'+' | Date:'+calculate_tym_date_over_img;
                
          setImage1(filename);
            
          let imagePath=`${CoverageImagePath}${filename}`;
          // if(resize_res.success){
            // file resized now rename file
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                console.log('image marker',uri);
                setImage1Path(uri);  

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
            })
            .catch(err => {
                console.log(ST.Errorimagefilewritefailed+'!!!');
                console.log(err.message, err.code);
            }); 
                           
      } 
      setProcessing(false);       
    }

    async function openCamera(){   
      setShowCamera(true);
      // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
    }

    function onSaveCancel(){
      setShowAlert(false);
    }
  
    function _OpenCaptureImage_Modal(){
      const isImageCap=(Image1Path=='' || Image1Path==null)?false:true;
      return (
        <CustomModal 
          style={customStyle.nonWCapImgModal}
          title={ST.NonWorkingReason}
          message={ST.Pleaseclickselfieinfrontofstore}
          titleStyle={customStyle.nonWCapImgModal_title}
          messageStyle={customStyle.nonWCapImgModal_subtitle}
          showModal={showModal}
        >
          {
            !isImageCap && 
            <View style={customStyle.nonWCapImgModalCon}>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Camera} onPress={()=>{openCamera()}}>
                <CameraImg2 width={100} height={100} />
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
            </View>
          }
          { 
          isImageCap && 
          <View style={customStyle.nonWCapImgModalCon}>
            <View style={customStyle.nonWCapImgModal_ImgWrap}>
              <Image  style={[customStyle.nonWCapImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:Image1Path}} />
            </View>
            <TouchableOpacity style={customStyle.nonWCapImgModal_CameraSmall} onPress={()=>{openCamera()}}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
            </TouchableOpacity>
            { showImageSaveOp &&
            <View style={customStyle.nonWCapImgModal_btng}>              
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
              </TouchableOpacity>
            </View>}
            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }
            
          </View>

          }
        </CustomModal>
      )
    }

  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <View style={{zIndex: 10}}>
          <CustomHeader {...props}showaddstore={true}  title={ST.NotWorking}/>        
        </View>
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {_OpenCaptureImage_Modal()}
        <CustomCamera cameraType={'front'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Not Working'} enableGallerForScreen={props.CheckInCameraGallery} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,customStyle.pageContentWrapper_bgLight]}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          {props.isDataDownloaded && Object.keys(storeData).length>0 &&
            <View style={customStyle.storeD_Main}>
              <View style={[customStyle.storeD_storelMain]}>
              <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

              <View style={customStyle.storel_card_outer}> 
                <View style={customStyle.storel_card}>
                  <View style={customStyle.storel_card_content}>
                    <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                  </View>                  
                </View>
                <View style={customStyle.storel_details}>
                  <View style={customStyle.storel_code}>
                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                  </View>
                  <View style={customStyle.storel_code}>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.Address+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.Address}</Text>
                    </View>
                  </View>                                 
                </View>                
              </View> 

              </View>
              </View>

              <View style={customStyle.nonWorking_con}>
                <View style={customStyle.nonWorking_form}> 
                  <Text style={customStyle.nonWform_hd}>{ST.Reasonfornotworkinginstore}</Text>                          
                  <FlatList 
                  contentContainerStyle={customStyle.storeD_scroll}
                  extraData={rerenderdata}
                  style={customStyle.storeD_scrollCon}
                  data={nonWorkingRsns}
                  renderItem={({item,index})=>{

                    const nWselStyle=reasonId==item.ReasonId?customStyle.nWselStyle:{};
                    const nWselStyleText=reasonId==item.ReasonId?customStyle.nWselStyleText:{};
                    const CapImageShow=(Image1Path!='' && Image1Path!=null) && reasonId==item.ReasonId?true:false;
                    let isDisabled=(isAnyStoreUploaded==true && (item.EntryAllow=='false' || item.EntryAllow==false));
                    return (
                      <TouchableOpacity key={index} style={[customStyle.nonWlist,nWselStyle,isDisabled==true?{backgroundColor:'#cdcdcd'}:{}]} disabled={isDisabled} onPress={()=>{selectReason(item)}}>
                        <Text style={[customStyle.nonWlist_Text,nWselStyleText]}>{item.Reason}</Text>
                        { (item.ImageAllow=='true' || item.ImageAllow=='1' || item.ImageAllow==true) && 
                          <TouchableOpacity  style={customStyle.nonWlist_camera} onPress={()=>{selectReason(item)}}>
                            {!CapImageShow && <CameraImg2 width={30} height={30}  />}
                            {CapImageShow && <CameraImg3 width={30} height={30} />}
                          </TouchableOpacity>
                        }
                      </TouchableOpacity>
                    );
                  }}
                  />
                </View>                
              </View>
              
              <View style={customStyle.nonW_btnWrap}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitNonWorkingRsns();}}/> 
              </View>    

            </View>   
            
          }          
         </View>      
       </LinearGradient>       
       
      </Container>   
    ); 
  }
  


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