import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme, STATUSBAR_HEIGHT } from "../styles/Global";
import {Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,FlatList, Alert, Dimensions,Animated, Easing, AppState, Keyboard} from 'react-native';
import { connect  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {getAllFolderImages, getKPIFields, marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {db, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, FontAwesome, FontAwesome5, Fontisto, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector';
import MultiSelect from 'react-native-multiple-select';
import { PageTheme } from '../styles/Themes';
import DateTimePicker from '@react-native-community/datetimepicker';
import DraggableFlatList,{ScaleDecorator} from 'react-native-draggable-flatlist'
import AudioRecorderPlayer, { AudioEncoderAndroidType, AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption } from 'react-native-audio-recorder-player';
import CustomCamera from '../components/Camera';
import { clear_item, get_item, set_item } from '../components/localStorage';

const {height, width} = Dimensions.get('window');
const topbarht=STATUSBAR_HEIGHT+50;
const actualWindowHt=parseInt((height-topbarht)+10);



function SamplingInventory(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    const audioRecorderPlayer = new AudioRecorderPlayer();
    const AudioSet = {
        AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
        AudioSourceAndroid: AudioSourceAndroidType.MIC,
        AVModeIOS: AVModeIOSOption.measurement,
        AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
        AVNumberOfChannelsKeyIOS: 2,
        AVFormatIDKeyIOS: AVEncodingOption.aac,
      };
    // 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(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);
    const [showRecorder, setShowRecorder] = useState(false);
    const [VRS, setVRS] = useState({});
    const [RecorderTimer, setRecorderTimer] = useState({});
    const [playerTimer, setPlayerTimer] = useState({});
    const [rerenderView, setRerenderView] = useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [VoiceRecorderStatus, setVoiceRecorderStatus] = useState(ST.Pressmictostartrecordingvoice);
    const [RecFilePath, setRecFilePath] = useState({});
    const [dateValue, setDateValue] = useState('');
    const [openDatePicker, setOpenDatePicker]= useState(0);
    const [storeData, setStoreData] = useState({});
    const [ShowCat, setShowCat] = useState(false);
    const [ActiveSampling, setActiveSampling]= useState({});
    const [ActiveCategory, setActiveCategory]= useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [SurveySubCats, setSurveySubCats]= useState([]);
    const [SurveyQuestions, setSurveyQuestions]= useState([]);
    const [QuestionsData,setQuestionsData]=useState({});
    const [showAlert, setShowAlert] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);

    const inputRefs = useRef({});

    const animatedRipple=useRef(new Animated.Value(0)).current;
    const animatedRipple2=useRef(new Animated.Value(0.5)).current;

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(QuestionsData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef({});
    const NavigationRef=React.useRef({});

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let SamplingData=params.SamplingData || {};
        let menu1=params.menu || {};

        let isAdhoc=params.isAdhocScreen || false;
        let isBeat=params.isBeat || false;

        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setActiveSampling(SamplingData)
        setCurrentMenu(menu1);
       
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current={BgscreenName:menu1.ScreenName,BgMenuId:menu1.MenuId }
        let navData={
            'surveyData':SamplingData,
            'storeData':storeData1,
            'menu':menu1,
            'isAdhocScreen':isAdhoc,
            'isBeat':isBeat,
            }
        NavigationRef.current=navData
       
        getData(SamplingData,storeData1,menu1)

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return (()=>{
            audioRecorderPlayer.removePlayBackListener();
            audioRecorderPlayer.removeRecordBackListener();
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(QuestionsData,pro)});
            return unsubscribe;
        });
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current && ScreenNameRef.current.BgscreenName,
               StoreId1:StoreIdRef.current,
               NavData:NavigationRef.current,
               BgMenuID: ScreenNameRef.current && ScreenNameRef.current.BgMenuId,
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 
       }
     }

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

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
               return;
            }   
        }
    }

    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val){
        WindowDataRef.current=val
        setQuestionsData(val);
    }


    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }



    async function getData(SamplingData1,storeData1,menu1){

        let AllKPIFields=await getKPIFields(menu1);
        setKPIFields(AllKPIFields);

        // set switch camera flag as defined in mapping menu flag (if exists)
        let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
        let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
        let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
        setShowSwitchCamera(SwitchingCamera);
        
        let storeBGData1=[],bgStoreJson={};
        let windData = await get_item('storeData')
        if(windData!=null && windData!=''){
            let StoreJson = JSON.parse(windData)
            let { storeBGData,menuName,StoreId1,BgMenuID,visiteDate }= StoreJson
            if(Object.keys(storeBGData).length>0 && menuName == menu1.ScreenName && menu1.MenuId==BgMenuID && StoreId1== storeData1.StoreId && visiteDate==d2){
                storeBGData1=storeBGData;
                bgStoreJson=StoreJson
                // setQuestionsData(storeBGData);
                BgUnsavedChanges(true)
                BgWindowData(storeBGData)
            }
        }

        return new Promise((resolve,reject)=>{
            try {   
                let {StoreId}=storeData1;
                let { InventoryQuestionCategoryId,SamplingDefinitionId }=SamplingData1;
                
                db.transaction(async function (txn) {  
                  
                    // get inserted audit
                    let selectlist=` DISTINCT T.SQMaximumChar as MaxLength,T.SQMinimumChar as MinLength,T.QuestionCategoryId as CategoryId,T.SQLengthValidationRequired as LengthValidation,T.SAShowCamera as QuestionImageAllow,"" as DateRange,T.SQDefaultQuestionEnable as QEnable,T.SamplingQuestionName as Question,T.SamplingQuestionId as QuestionId,T.QuestionType as QuestionType,"" 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,T1.IS_DISABLED as isDisabled `;
                    let join2=` INNER JOIN ${AppTables.SAMPLING_INVENTORY} T1 on T.QuestionCategoryId=T1.CATEGORY_ID And T.SamplingQuestionId=T1.QUESTION_ID  `;
                    let join3=` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId And T2.SamplingDefinitionId='${SamplingDefinitionId}' `
                    let q2=`Select ${selectlist} FROM Master_SamplingQuestion T ${join2} ${join3} WHERE T1.STORE_ID='${StoreId}'  AND T1.VISIT_DATE= '${d2}'  AND T1.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND  T.QuestionCategoryId='${InventoryQuestionCategoryId}' `;
                    q2+=` ORDER BY T.SamplingQuestionSequence `;

                    //load data from master if not inserted
                    let sl=` DISTINCT T.SQMaximumChar as MaxLength,T.SQMinimumChar as MinLength,T.QuestionCategoryId as CategoryId,T.SQLengthValidationRequired as LengthValidation,T.SAShowCamera as QuestionImageAllow,"" as DateRange,T.SQDefaultQuestionEnable as QEnable,T.SamplingQuestionName as Question,T.SamplingQuestionId as QuestionId,T.QuestionType as QuestionType,"" as OTP`;
                    let q=`Select ${sl} FROM Master_SamplingQuestion T ${join3} WHERE T.QuestionCategoryId='${InventoryQuestionCategoryId}' `;
                    q+=` ORDER BY T.SamplingQuestionSequence `;
                  
                    await txn.executeSql(q2,[],async function (txn2, txnres) { 
                      console.log('getSurveyData len',txnres.rows.length);
                      if(txnres.rows.length>0){
                          let arr=[];
                          var QD=QuestionsData;
                          for(var i=0;i<txnres.rows.length;i++){
                              let data =txnres.rows.item(i);
                              data.QEnable=data.QEnable==1 || data.QEnable=='true'?true:false;
                              
                              let answers=[];
                              let qtn=data;
                              qtn.isDisabled=qtn.isDisabled==1 || qtn.isDisabled=='1'?true:false
                             
                              if(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text'){
                                inputRefs.current['input1_'+qtn.QuestionId]='';
                              }
                             
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  let allanswers=await getAnswers(data,SamplingData1,storeData1,true);
                                
                                  answers=allanswers.Answers || [];
                                  if(data.QuestionType=='Rating'){
                                      data.showRating=false;
                                  }
                              }
                              else if(data.QuestionType=='Date'){
                                  data.showDatePicker=false;
                              }
                              data.Answers=answers;
      
                              let id_key=qtn.QuestionId+'_AnswerId'; 
                              let ans_key=qtn.QuestionId+'_Answer'; 
                              let multi_key=qtn.QuestionId+'_MultiOption';
                              let date_key=qtn.QuestionId+'_Date';
                              let img_key=qtn.QuestionId+'_ImagePath1';
                              let imgname_key=qtn.QuestionId+'_ImageName1';
                              let img_key2=qtn.QuestionId+'_ImagePath2';
                              let imgname_key2=qtn.QuestionId+'_ImageName2';
                              let rating_key=qtn.QuestionId+'_Rating'; 
                              let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
      
                              let showImageTag=(data.QuestionImageAllow==true || data.QuestionImageAllow=='true' || data.QuestionImageAllow==1) ;
                              let showImageTag2=false;
      
                              QD[id_key]=data.AnswerId;
                              QD[ans_key]=data.Answer;

                              
                              let selansid=data.AnswerId;
                              if(qtn.QuestionType=='Multi choice list'){
                                  selansid=data.multi_op_ids?data.multi_op_ids.split(','):[];
                                  QD[multi_key]=data.multi_op_ids;
                              }
      
                              if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                  if (qtn.Answers && qtn.Answers.length>0){
                                      for(var k=0;k<qtn.Answers.length;k++){
                                          let ansss=qtn.Answers[k];
                                          let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                                          let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                                          if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                              showImageTag=true;
                                          }

                                            if(qtn.QuestionType=='Single choice list' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                                showImageTag2=true;
                                            }
                                            else if(qtn.QuestionType=='List_Multi_Choice' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                                showImageTag2=true;
                                            }

                                      }
                                  }
                              }
      
                              if(showImageTag){
                                  let imgPath=data.Image1!=''?((Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+menu1.ScreenName}/`+data.Image1):'';
                                  QD[imgname_key]=data.Image1;
                                  QD[img_key]=imgPath;
                              }

                              if(showImageTag2){
                                let imgPath=data.Image2!=''?((Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+menu1.ScreenName}/`+data.Image2):'';
                                QD[imgname_key2]=data.Image2;
                                QD[img_key2]=imgPath;
                              }
      
                              if(qtn.QuestionType=='Audio'){
                                  let voicefile_path=(Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+menu1.ScreenName}/`+'Recordings/'+data.Answer;
                                  QD[voiceClip_key]={'path':voicefile_path,'filename':data.Answer};
                              }
      
                              if(qtn.QuestionType=='Date'){
                                  let dayonly=moment().format('DD');
                                  let actual_date=data.Answer?data.Answer.split('/'):[];
                                  let month=actual_date[0],year=actual_date[1];
                                  let fulldate=month+'/'+dayonly+'/'+year;
                                  QD[date_key]=fulldate;
                                  
                              }
                              arr.push(data);  
                              if(i==txnres.rows.length-1){

                                let { storeBGData,menuName,StoreId1,BgMenuID,visiteDate }=bgStoreJson
                                if(storeBGData!=null && storeBGData!='' && menuName == menu1.ScreenName && StoreId1== StoreId && menu1.MenuId==BgMenuID && visiteDate==d2){
                                    if(Object.keys(storeBGData).length<=0){
                                        // setQuestionsData(QD);
                                        BgWindowData(QD)
                                    }
                                }else{
                                    // setQuestionsData(QD); 
                                    BgWindowData(QD)
                                }
                                //   setQuestionsData(QD);
                                console.log("QD--------1",QD)
                                setSurveyQuestions(arr)
                                setProcessing(false);
                                resolve(arr);
                              }
                          }
                      }
                      else{
                           await txn.executeSql(q,[],async function (txn2, txnres2) { 
                              console.log('Surveys:',txnres2.rows.length)
                              let arr=[];
                              if(txnres2.rows.length>0){
                                  for(var i=0;i<txnres2.rows.length;i++){
                                      let data =txnres2.rows.item(i);
                                      data.QEnable=data.QEnable==1 || data.QEnable=='true'?true:false;
                                      data['isDisabled']=!data.QEnable;
                                      let answers=[];
                                      if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                          let allanswers=await getAnswers(data,SamplingData1,storeData1,false);
                                          answers=allanswers.Answers || [];
                                          if(data.QuestionType=='Rating'){
                                              data.showRating=false;
                                          }
                                      }
                                      else if(data.QuestionType=='Date'){
                                          data.showDatePicker=false;
                                      }
                                      
                                      data.Answers=answers;
                                      arr.push(data);
                                      
                                      if(i==txnres2.rows.length-1){
                                        console.log("inventory--data--",arr)
                                        setSurveyQuestions(arr)
                                        setProcessing(false);
                                          resolve(arr);
                                      }
                                  }
                              }
                              else{
                                resolve([]);
                              }
      
                          },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
                      }
                      
                    },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
                 
                });          
              } catch (err) {
                console.log(err);          
              }  
        })
    }

    async function getAnswers(qtn,SamplingData1,storeData1,isInserted){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        let {SamplingDefinitionId,InventoryQuestionCategoryId}=SamplingData1;
        console.log("SAQuestionDisable---------",qtn)
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                // get inserted audit
                let sl=` DISTINCT T.SamplingAnswerName as Answer,T.SamplingAnswerId as AnswerId,"" as ImageAllow1,"" as ImageAllow2,T.SAQuestionEnable,T.SAQuestionDisable`;
                let join3=` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId `
                let q2=`Select ${sl} FROM Master_SamplingQuestion T ${join3} WHERE T.SamplingQuestionId='${qtn.QuestionId}'  AND  T.QuestionCategoryId='${qtn.CategoryId}' ORDER BY T.SamplingQuestionSequence `;

                
                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                    // console.log('answers len',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                setSurveyQuestions(arr);
                                resolve(arr);
                            }
                        }
                    }
                    else{
                        resolve([]);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
               
              });    
        }).then((val)=>{
            return {'Answers':val,'Success':true};
        }).catch((err)=>{
            console.log(err);
            return {'Success':false,'Error':err}
        });
    }

    async function getImage(imgdata){
        let qtn=getImageProps.qtn || '';
        let type=getImageProps.type || '1';
        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+'_'+ActiveSampling.SurveyId+'_'+qtn.QuestionId+'_SamplingInventory_'+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+' | Question Id :'+qtn.QuestionId+' | Image Type: Sampling Inventory'+' | Date:'+calculate_tym_date_over_img;
                 
            let qd=QuestionsData;
            let img_key=type=='1'?qtn.QuestionId+'_ImagePath1':qtn.QuestionId+'_ImagePath2';
            let imgname_key=type=='1'?qtn.QuestionId+'_ImageName1':qtn.QuestionId+'_ImageName2';
            qd[imgname_key]=filename;

            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                console.log('image marker',uri);
                qd[img_key]=uri; 

                // setQuestionsData(qd);
                BgWindowData(qd)
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);

                // 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('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });                     
        }        
    }
  
    async function openCamera(qtn,type){  
        setGetImageProps({'qtn':qtn,'type':type}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    async function disableQtns(sqtns,DQtns,data,isreturn=false){
       console.log('disableQtns');
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                    console.log('sqtns qid',qid,s_qtnindex)
                    let s_qtn=s_qtnindex>=0?sqtns[s_qtnindex]:{};
                    if(s_qtnindex>=0){
                        console.log('sqtns not found',s_qtnindex)
                        s_qtn['isDisabled']=true
                        sqtns[s_qtnindex]=s_qtn;
                        let id_key=s_qtn.QuestionId+'_AnswerId'; 
                        let ans_key=s_qtn.QuestionId+'_Answer'; 
                        data[id_key]=0;
                        data[ans_key]='';
                    }
                    return false
                })
            ).then(async (val)=>{
                setSurveyQuestions(sqtns);
                // setQuestionsData(data);
                BgWindowData(data)
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data){
        console.log('enableQtns');
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                let s_qtn=s_qtnindex>=0?sqtns[s_qtnindex]:{};
                if(s_qtnindex>=0){
                    s_qtn['isDisabled']=false
                    sqtns[s_qtnindex]=s_qtn;
                }
                return false
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                disableQtns(sqtns,DQtns,data)
            }
            else{
                setSurveyQuestions(sqtns);
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
            }
        })
    }
   
    function onselectionChange(option,qtn){
        let data=QuestionsData;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        data[id_key]=option.value;
        data[ans_key]=option.label;

        // setQuestionsData(data);
        BgWindowData(data)

        let aq_ans=qtn.Answers!=null?qtn.Answers:[];
        let ans_obj=aq_ans.find(i=>i.AnswerId==option.value) || {};
        let EQtns=ans_obj.SAQuestionEnable!=null && ans_obj.SAQuestionEnable!=''?ans_obj.SAQuestionEnable.replace(' ','').split(','):[];
        let DQtns=ans_obj.SAQuestionDisable!=null && ans_obj.SAQuestionDisable!=''?ans_obj.SAQuestionDisable.replace(' ','').split(','):[];
      
        console.log('EQtns:',EQtns,DQtns);
        let sqtns=SurveyQuestions
        if(EQtns.length>0){
            enableQtns(sqtns,EQtns,DQtns,data)
        }
        else if(DQtns.length>0){
            disableQtns(sqtns,DQtns,data)
        }
        else{
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }
       
        
        
    }

    function setTextValue(value,qtn,type='') {   
        if(value!=''){
            let isValid=validateNumber(value,type);
            if(!isValid){
                return;
            }
        }     

        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        
        let obj=QuestionsData;
        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.QuestionId+'_Date'; 
            let d=value!=null?new Date(value):new Date();
            let mfdate=moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn,false);
            obj[id_key]=0;
            obj[ans_key]=mfdate;
            obj[date_key]=moment(d).format('MM/DD/YYYY');
        }
        else{
            obj[id_key]=0;
            obj[ans_key]=value;
        }
        console.log(value,obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setRatingValue(data){
        // let ids=[];
        // data.map((item,index)=>{
        //     ids.push(item.AnswerId);
        // })
        setRatingOrder(data);
    }


    async function setMultiSelectValue(selectedItems=[],qtn) {  
        console.log('setMultiSelectValue',selectedItems);      
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let multi_key=qtn.QuestionId+'_MultiOption';
        let obj=QuestionsData;
        obj[id_key]=0;
        obj[multi_key]=selectedItems.join(',');
        let anss=[];
        selectedItems.map((itemValue)=>{
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue); 
            if(ans.Answer){anss.push(ans.Answer)}
        });
        obj[ans_key]=anss.join(',');
        console.log('obj:',obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }


    function showQtnDatePicker(qtn,show=false){
        let newqtnIndex=SurveyQuestions.findIndex(q=>q.QuestionId==qtn.QuestionId);
        console.log('showQtnDatePicker:',newqtnIndex);
        if(newqtnIndex>=0){
            let sq=SurveyQuestions;
            let newqtn=sq[newqtnIndex];
            newqtn.showDatePicker=show;
            sq[newqtnIndex]=newqtn;
            setSurveyQuestions(sq);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    
    function setShowQtnKey(qtn,key,show=false){
        if(key!=null && key!=''){
            let newqtnIndex=SurveyQuestions.findIndex(q=>q.QuestionId==qtn.QuestionId);
            console.log('setShowQtnKey:',newqtnIndex);
            if(newqtnIndex>=0){
                let sq=SurveyQuestions;
                let newqtn=sq[newqtnIndex];
                newqtn[key]=show;
                sq[newqtnIndex]=newqtn;
                setSurveyQuestions(sq);
                if(show==true) setrerenderdata(!rerenderdata);
            }
        }
    }

    function onRatingCancel(){ 
        setShowRating(false);
        
    }

    function onRatingSave(){
        setShowRating(false);

        let qtn=RatingQtn;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let rating_key=qtn.QuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })
        let obj=QuestionsData;
        obj[rating_key]=ids.join(',');
        obj[id_key]=0;
        obj[ans_key]=anss.join(',');
        
        console.log(obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

  

    async function focusToNext(qtn,type='1'){

        let activeKey='';
        let arr=Object.keys(inputRefs.current);
        
        activeKey='input'+type+'_'+qtn.QuestionId;

        let activeIndex=arr.indexOf(activeKey);
        if(activeIndex<arr.length-1){
            let nextKey = arr[++activeIndex] 
            let nextRef= inputRefs.current[nextKey];
            console.log("nextKey", nextKey,nextRef, inputRefs.current[nextKey])
            nextRef.focus();    
        }
        else{
            return
        }
    }
    

    const RippleAnimation = (value,minValue,maxValue,delay) =>
    Animated.loop(
        Animated.sequence([
            Animated.timing(value, {
                toValue: maxValue,
                duration: 1000,
                delay:delay,
                useNativeDriver:(Platform.OS=='ios'?false:true),
            }),
            Animated.timing(value, {
                toValue: minValue,
                duration: 1000,
                delay:delay,
                useNativeDriver:(Platform.OS=='ios'?false:true),
            }),
        ]),
        
    ).start();

   

    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){ 
            Keyboard.dismiss();   
            setShowAlert(true);
        }
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {  

            
                let { InventoryQuestionCategoryId,SamplingDefinitionId }=ActiveSampling;
                let {MenuId}=currentMenu;
                //  remove old data
                let q=`DELETE FROM ${AppTables.SAMPLING_INVENTORY} WHERE STORE_ID='${StoreId}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' and CATEGORY_ID='${InventoryQuestionCategoryId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('survey data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);

              
                var values='';
              
                for(var i=0;i<SurveyQuestions.length;i++){
                    values+=values!=''?' , ':'';

                    let qtn=SurveyQuestions[i];
                    
                    let id_key=qtn.QuestionId+'_AnswerId'; 
                    let ans_key=qtn.QuestionId+'_Answer'; 
                    let multi_key=qtn.QuestionId+'_MultiOption';
                    let date_key=qtn.QuestionId+'_Date';
                    let img_key1=qtn.QuestionId+'_ImagePath1';
                    let imgname_key1=qtn.QuestionId+'_ImageName1';
                    let img_key2=qtn.QuestionId+'_ImagePath2';
                    let imgname_key2=qtn.QuestionId+'_ImageName2';
                    let rating_key=qtn.QuestionId+'_Rating'; 
                    let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 

                    let {CategoryId,DateRange,LengthValidation,MaxLength,MinLength,OTP,Question,QuestionId,QuestionImageAllow,QuestionType}=qtn;
                    
                    let selansid=QuestionsData[id_key] || 0;
                    let selans=QuestionsData[ans_key] || '';
                    let imgName1=QuestionsData[imgname_key1] || '';
                    let imgName2=QuestionsData[imgname_key2] || '';
                    let multiops=QuestionsData[multi_key] || '';
                    let isQtnDisabled=qtn.isDisabled!=null && qtn.isDisabled!=''?qtn.isDisabled?1:0:0;
                    let allanss=qtn.Answers || {};
                    let ans_obj=allanss.find(i=>i.AnswerId==selansid)
                    let imgallow1=ans_obj!=null && ans_obj['ImageAllow1']!=null?ans_obj.ImageAllow1:false;
                    let imgallow2=ans_obj!=null && ans_obj['ImageAllow2']!=null?ans_obj.ImageAllow2:false;
                    let f_imgalloq1=(QuestionImageAllow=='true' || QuestionImageAllow==1) || (imgallow1=='true' || imgallow1==1)
                    
                    values+=` ('${StoreId}','${d2}','${SamplingDefinitionId}','${CategoryId}','${Question}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${(imgName1 || '')}','${imgallow2}','${(imgName2 || '')}','${multiops}','${isQtnDisabled}','${d2}') `;
                }
              
                console.log("SAMPLING_INVENTORY value:",values,SamplingDefinitionId)
                let add_data=`INSERT INTO ${AppTables.SAMPLING_INVENTORY} (STORE_ID,VISIT_DATE,SAMPLING_DEFINITION_ID,CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,IMAGE_ALLOW2,IMAGE2,MULTI_OPTIONS_IDS,IS_DISABLED,ADDED_DATE) VALUES ${values} `;
                
                await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                    console.log('surveys added');
                    // props.set_autoback({'AutoGoToPrev':true});
                    notify("Sampling Inventory updated successfully",'SHORT');
                    setProcessing(false);
                    props.navigation.goBack();
                    
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify("Cannot update Sampling Inventory") },);
                
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function validate(){  
        let Image1MandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Image1Mandatory');
        let Image1MandObj=Image1MandIndex>=0?KPIFields[Image1MandIndex]:{};
        let isImage1Mand=Image1MandIndex>=0?Image1MandObj['KPIFieldEnable']:true;

        let Image2MandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Image2Mandatory');
        let Image2MandObj=Image2MandIndex>=0?KPIFields[Image2MandIndex]:{};
        let isImage2Mand=Image2MandIndex>=0?Image2MandObj['KPIFieldEnable']:false;

        var isvalid=true;
        const QD=QuestionsData;
        console.log(SurveyQuestions.length);
        for(var i=0;i<SurveyQuestions.length;i++){
            let qtn=SurveyQuestions[i];
            let selansid='',selanswer='',selimg='',showImageTag=false,showImageTag2=false;
            let id_key=qtn.QuestionId+'_AnswerId'; 
            let ans_key=qtn.QuestionId+'_Answer'; 
            let multi_key=qtn.QuestionId+'_MultiOption';
            let date_key=qtn.QuestionId+'_Date';
            let img_key=qtn.QuestionId+'_ImagePath1';
            let imgname_key=qtn.QuestionId+'_ImageName1';
            let img_key2=qtn.QuestionId+'_ImagePath2';
            let imgname_key2=qtn.QuestionId+'_ImageName2';
            let rating_key=qtn.QuestionId+'_Rating'; 
            let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
            let list_mcdata=[];

            let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
           
            if(isDisabled==true){

            }
            else{
                let isImgAllowed=(qtn.QuestionImageAllow==true || qtn.QuestionImageAllow=='true' || qtn.QuestionImageAllow==1);
                let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating') ;
                if(qtn.QuestionType=='Single choice list')
                {
                    selansid=QD[id_key];
                }
                else if(qtn.QuestionType=='Multi choice list')
                {
                    selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
                }
                
            
                if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                    isvalid=false;
                    notify(ST.Pleaseselectoptionsfortherequiredfield,'SHORT');
                    break;
                }
                else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                    isvalid=false;
                    let msg=( qtn.QuestionType=='Date'?ST.Pleasepickadate:(qtn.QuestionType=='Rating'?ST.Pleaseselectrating:ST.Pleasefillalldetails));
                    notify(msg,'SHORT');
                    break;
                }
                else if( qtn.QuestionType=='Audio' && (Object.keys(QD).indexOf(voiceClip_key)<0 || (Object.keys(QD).indexOf(voiceClip_key)>=0 && (QD[voiceClip_key]==null || QD[voiceClip_key].filename==null || QD[voiceClip_key].filename=='')))){
                    isvalid=false;
                    notify(ST.Pleaserecordaudioclipfortherequiredfield,'SHORT');
                    break;
                }
                else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))){
                    isvalid=false;
                    notify(ST.Pleasefillalldetails,'SHORT');
                    console.log(QD[id_key],QD,id_key)
                    break;
                }
                else if(isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                    isvalid=false;
                    notify(ST.Pleaseaddimages,'SHORT');
                    break;
                }else{
                    console.log('no condition found');
                }

                if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                    if (qtn.Answers && qtn.Answers.length>0){
                        for(var j=0;j<qtn.Answers.length;j++){
                            let ansss=qtn.Answers[j];
                            let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                            if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                showImageTag=true;
                            }
                            else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                showImageTag=true;
                            }
                            
                            let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                            if(qtn.QuestionType=='Single choice list' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                showImageTag2=true;
                            }
                            else if(qtn.QuestionType=='Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                showImageTag2=true;
                            }
                        }
                    }
                }

                if((isImage1Mand=='1' || isImage1Mand==true) && showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                    isvalid=false;
                    notify(ST.Pleaseaddimages,'SHORT');
                    break;
                }
                
                if((isImage2Mand=='1' || isImage2Mand==true) &&  showImageTag2 && (Object.keys(QD).indexOf(img_key2)<0 || (Object.keys(QD).indexOf(img_key2)>=0 && QD[img_key2]===''))){
                    isvalid=false;
                    notify(ST.Pleaseaddimages,'SHORT');
                    break;
                }

            }
        } 
        
        return isvalid;
    }
   
    function render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        let isQtnDisabled=qtn.isDisabled!=null && qtn.isDisabled!=''?qtn.isDisabled:false;
        let allAnswers=qtn.Answers || [];
        
        allAnswers.map((item,index)=>{
            let obj={ key: index, label: item[label_key],value:item[value_key] };
            if(selected_data.value==item[label_key])
                obj['component']= <View style={customStyle.addvis_selectedOpStyle}><Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text></View>;
            data.push(obj);
        });
        
        return (
            <ModalSelector
            data={data}
            
            touchableActiveOpacity={0.8}
            
            style={customStyle.addVisPickerStyle}
            onChange={(option)=>{onChange(option,qtn) }}
            overlayStyle={customStyle.addVisPickerOverlay}
            cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            optionStyle={customStyle.addvis_opStyle}
            optionTextStyle={customStyle.addvis_opTextStyle}
            optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            selectedKey={'1'}
            disabled={isQtnDisabled}
            cancelText={ST.Cancel}
            >
            <Text style={[customStyle.addVisPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-select-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn){
        let qtnn=qtn;
        let DateRange=qtn.DateRange;
        let maxDate=moment().add(10,'years').format('MM/DD/YYYY');
        let minDate=moment().subtract(10,'years').format('MM/DD/YYYY');
        if(DateRange=='RFD'){
            maxDate=moment().format('MM/DD/YYYY');
        }
        else if(DateRange=='RPD'){
            minDate=moment().format('MM/DD/YYYY');
        }
        
        return (
            <DateTimePicker
            testID="dateTimePicker"
            value={(dateValue!=null && dateValue!=''?new Date(dateValue):new Date())}
            mode={'date'}
            display="default"  
            onChange={(event, selectedDate)=>{setTextValue(selectedDate,qtnn)}}
            maximumDate={new Date(maxDate)}
            minimumDate={new Date(minDate)}
            />    
        );
    }

    function renderItem({ item, drag, isActive }){
        return (
          <ScaleDecorator>
            <TouchableOpacity
              
              onLongPress={drag}
              disabled={isActive}
              style={[customStyle.RModal_listItem,{ backgroundColor: isActive ? PageTheme.$primary_color : PageTheme.$secondary_color_light },]}
            >
              <Text style={[customStyle.RModal_listItemText,(isActive?{color:PageTheme.$accent_color}:{})]}>{item.Answer}</Text>
            </TouchableOpacity>
          </ScaleDecorator>
        );
    };

    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.QuestionId+'_AnswerId'; 
        let ans_key=qtn.QuestionId+'_Answer'; 
        let rating_key=qtn.QuestionId+'_Rating'; 
        // let ratings=QuestionsData[rating_key]!=null?QuestionsData[rating_key].split(','):[];
        
        let newarr=RatingOrder;
        if(RatingOrder.length<=0){
            newarr=Answers;
        }

        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>{ST.DragItemsInOrder}</Text>
                <Text style={customStyle.VRSubHeding}>{ST.Pressandholdtodrag}</Text>
                <DraggableFlatList
                    data={newarr}
                    style={customStyle.RModal_list}
                    contentContainerStyle={customStyle.RModal_listInner}
                    onDragEnd={({ data }) =>{setRatingValue(data)}}
                    keyExtractor={(item) => item.AnswerId}
                    renderItem={renderItem}
                />
                <View style={customStyle.RModal_Btns}>
                    <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={()=>{onRatingCancel()}}>
                        <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRatingSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        )
    }


    
    function _renderSurveyQtns(){
        return (
        <View style={customStyle.SVn_GroupViewList}>
            {
                SurveyQuestions.length>0 && 
                SurveyQuestions.map((item,index)=>{
                    
                    let qtn=item;  
                    let selansid='',selanswer='',selimg='',selimg2='',showImageTag=false,showImageTag2=false;
                    let id_key=qtn.QuestionId+'_AnswerId'; 
                    let ans_key=qtn.QuestionId+'_Answer'; 
                    let multi_key=qtn.QuestionId+'_MultiOption';
                    let date_key=qtn.QuestionId+'_Date';
                    let img_key=qtn.QuestionId+'_ImagePath1';
                    let imgname_key=qtn.QuestionId+'_ImageName1';
                    let img_key2=qtn.QuestionId+'_ImagePath2';
                    let imgname_key2=qtn.QuestionId+'_ImageName2';
                    let rating_key=qtn.QuestionId+'_Rating'; 
                    let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 
                    let list_mcdata=[];

                    if(qtn.QuestionType=='Single choice list')
                    {
                        selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                        selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                    }
                    else if(qtn.QuestionType=='Multi choice list')
                    {
                        
                        if(qtn.Answers!=null){
                            console.log('qtn.Answers:',qtn.Answers.length);
                            for(var i=0;i<qtn.Answers.length;i++){
                                let obj={'AnswerId':parseInt(qtn.Answers[i].AnswerId),'Answer':qtn.Answers[i].Answer};
                                list_mcdata.push(obj);
                            }
                        }
                        selansid=QuestionsData[multi_key]!=null && QuestionsData[multi_key]!=''?QuestionsData[multi_key].split(','):[];
                        if(selansid!=null && selansid.length>0){
                            let arr=[];
                            for(var i=0;i<selansid.length;i++){
                                arr.push(parseInt(selansid[i]));
                            }
                            selansid=arr;
                        }
                    }
                    else if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                    {
                        selansid=QuestionsData[ans_key];
                        selanswer=(qtn.QuestionType=='Date'  )?(QuestionsData[date_key] || moment().format('MM/DD/YYYY')):'';
                        showImageTag=(qtn.QuestionImageAllow==true || qtn.QuestionImageAllow=='true' || qtn.QuestionImageAllow==1);
                        showImageTag2=false;
                    }
                    else if(qtn.QuestionType=='Rating'){
                        selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                    }
                    else if(qtn.QuestionType=='Audio'){
                        selansid=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                        selanswer=QuestionsData[voiceClip_key]?(QuestionsData[voiceClip_key].filename || ''):'';
                    }

                    if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                        if (qtn.Answers && qtn.Answers.length>0){
                            for(var i=0;i<qtn.Answers.length;i++){
                                let ansss=qtn.Answers[i];
                                
                                let isandImgAl=(ansss.ImageAllow1==true || ansss.ImageAllow1=='true' || ansss.ImageAllow1==1);
                                let isandImgAl2=(ansss.ImageAllow2==true || ansss.ImageAllow2=='true' || ansss.ImageAllow2==1);
                                
                                if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                    showImageTag=true;
                                }
                                else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                    showImageTag=true;
                                }

                                if(qtn.QuestionType=='Single choice list' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                    showImageTag2=true;
                                }
                                else if(qtn.QuestionType=='Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                    showImageTag2=true;
                                }
                            }
                        }
                    }
                    
                    if(showImageTag){
                        selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                    }

                    if(showImageTag2){
                        selimg2=QuestionsData[img_key2]!=null && QuestionsData[img_key2]!=''?'file://'+QuestionsData[img_key2]:'';                    
                    }
                    
                    let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
                    console.log('isDisabled',qtn.QuestionId,qtn.isDisabled,isDisabled)
                    if(isDisabled==true){
                        return (
                            <View></View> 
                        )
                    }
                    else{
                        return(
                        <View style={[customStyle.sform_group2,]} key={index}>
                            <Text style={[customStyle.sform_label3]}>{qtn.Question}</Text>                     
                            {qtn.QuestionType=='Single choice list' && qtn.Answers && 
                                render_Picker('Answer','AnswerId',onselectionChange,{value:selanswer,qtn:qtn})
                            }
                            {qtn.QuestionType=='Multi choice list' && qtn.Answers &&
                                <MultiSelect
                                    items={list_mcdata}
                                    uniqueKey="AnswerId"
                                    onSelectedItemsChange={(selectedItems)=>{console.log('onSelectedItemsChange');setMultiSelectValue(selectedItems,qtn) }} 
                                    selectedItems={selansid}
                                    selectText="Pick Items"
                                    searchInputPlaceholderText="Search Items..."
                                    // onChangeInput={ (text)=> console.log(text)}
                                    tagRemoveIconColor={PageTheme.$primary_color}
                                    tagBorderColor={PageTheme.$primary_color}
                                    tagTextColor={PageTheme.$primary_color}
                                    selectedItemTextColor={PageTheme.$primary_color}
                                    selectedItemIconColor={PageTheme.$primary_color}
                                    tagContainerStyle={{height:30,width:'100%',paddingVertical:5}}
                                    styleTextTag={{fontSize:14}}
                                    itemTextColor={PageTheme.$text_color}
                                    displayKey="Answer"
                                    searchInputStyle={{ color: '#CCC' }}
                                    submitButtonColor={PageTheme.$primary_color}
                                    submitButtonText="Submit"
                                />
                            }
                            { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text') &&  
                                <TextInput 
                                    ref={(reff)=>{inputRefs.current['input1_'+qtn.QuestionId]=reff;}}    
                                    style={[customStyle.surveyQtn_InputStyle]}
                                    placeholder=""
                                    autoComplete='off'
                                    placeholderTextColor={PageTheme.$placeholder_color} 
                                    // keyboardType={'ascii-capable'}
                                    maxLength={qtn.QuestionType=='Number'?3:null}
                                    returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                    blurOnSubmit={false}
                                    keyboardType={(qtn.QuestionType=='Decimal'?'decimal-pad':(qtn.QuestionType=='Text'?'default':'number-pad'))}
                                    value={selansid}
                                    onSubmitEditing={()=>{focusToNext(qtn,'1')}}
                                    onChangeText={(val)=>{setTextValue(val,qtn,(qtn.QuestionType=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':'numeric')))}}
                                />
                            }
                            {
                                (qtn.QuestionType=='Date') && 
                                <View style={customStyle.surveyQtn_datePicker_con}>
                                    <Text style={customStyle.surveyQtn_datePicker_text}>{selansid!=''?selansid:'MM/YYYY'}</Text>
                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setDateValue(selanswer);showQtnDatePicker(qtn,true)}}>
                                        <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                    </TouchableOpacity> 
                                </View>     
                            }
                            {   ((qtn.showDatePicker==true || qtn.showDatePicker=='true') && (qtn.QuestionType=='Date') ) && 
                                renderDatePicker(qtn)
                            }  
                            {
                                (qtn.QuestionType=='Rating') && 
                                <View style={customStyle.surveyQtn_datePicker_con}>
                                    <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                    <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{setRatingQtn(qtn);setShowRating(true);}}>
                                        <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag"/>
                                    </TouchableOpacity> 
                                </View>    
                            }

                            
                            
                            {
                                showImageTag &&
                                <View style={[customStyle.store_audit_img_con,]}>                    
                                    <Image source={(selimg!='' && selimg!=null )?{uri:selimg}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg!='' && selimg!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                    <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(qtn,'1')}}>
                                        <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                    </TouchableOpacity>
                                </View>
                            }

                            {
                                showImageTag2 &&
                                <View style={[customStyle.store_audit_img_con,]}>                    
                                    <Image source={(selimg2!='' && selimg2!=null )?{uri:selimg2}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg2!='' && selimg2!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                    <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(qtn,'2')}}>
                                        <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                    </TouchableOpacity>
                                </View>
                            }
                        </View> 
                        )
                    }
                    
                })
            }
        </View>
                  
        );
    }

    function _renderSurveyView(){
        return (
            <View style={customStyle.SVn_ContentCon}>
            <FlatList 
            style={customStyle.SVn_ContentOuter} 
            extraData={rerenderdata}
            nestedScrollEnabled={true}
            removeClippedSubviews={false}
            showsVerticalScrollIndicator={false}     
            contentContainerStyle={customStyle.SVn_ContentInner}
            data={SurveySubCats}
            renderItem={({ item, index, separators }) =>{  
                let subcat=item,s_index=index;
                
                return (
                    <View style={customStyle.SVn_GroupView} key={s_index}>
                        <LinearGradient colors={[PageTheme.$bg_color,PageTheme.$primary_color,PageTheme.$bg_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}  style={customStyle.SVn_GroupView_hdr}>
                            <Text style={customStyle.SVn_GroupView_hdrText}>{subcat.SubCategory}</Text>
                        </LinearGradient>
                        { _renderSurveyQtns(subcat)}
                    </View>
                )
            }}
            >
                
            </FlatList>
            </View>
        );
    }

    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={"S-Inventory"} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName+' Inventory'} enableCameraFlip={showSwitchCamera}  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,customStyle.roundScrollZIndex]}>
            <View style={[customStyle.pageContentWrapper,customStyle.SVn_PageWrapper]}>
                <View style={customStyle.SVn_activeSurvey}>
                    <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$gradient1]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.SVn_activeSurvey_tile}>
                        <Text style={customStyle.SV_activeSurvey_name}>{"Inventory Question"}</Text>
                    </LinearGradient>
                </View>
                
                { Object.keys(ActiveSampling).length>0 &&    
                    <>        
                        <View style={customStyle.SVn_GroupView} >
                            <View style={customStyle.SVn_ContentOuter} >
                            <ScrollView contentContainerStyle={[customStyle.SVn_ContentInner,{ paddingBottom:30}]}  style={[customStyle.SVn_ContentOuter]} >
                            { _renderSurveyQtns()}
                            </ScrollView>
                            </View>
                        </View>
                        
                    </>
                }
                <View style={[customStyle.SVn_SubmitBtn]}>
                    <GradientButton {...props} title={ST.Save} onPress={()=>{
                        // getAllFolderImages()
                        onSubmitData()
                        }}/> 
                </View> 
            </View>  
        </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
        
      </Container>   
    ); 
  }
  

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