import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import { AppState, StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated,KeyboardAvoidingView, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import { Picker } from '@react-native-picker/picker';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import DateTimePicker from '@react-native-community/datetimepicker';
import CheckBox from '@react-native-community/checkbox';

import cameraImg from '../assets/performics/camera_front_image.svg'
import MultiSelect from 'react-native-multiple-select';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import { PageTheme } from '../styles/Themes';

function TGBaseVisiCooler(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 animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [rerenderdata3, setrerenderdata3]= useState(0);
    const [rerenderdata4, setrerenderdata4]= useState(0);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const [WindowData, setWindowData] = useState([]);
    // const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const Show_zoomImageRef=useRef(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [zoomImageIndex, setzoomImageIndex] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showCamera, setShowCamera] = useState(false);
    const [showQRCamera, setShowQRCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const zoomView=useRef(null);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingWindow, setRatingWindow] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);

    const [Products, setProducts] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [toRemoveId,setToRemoveId]= useState('');
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);
    const [showRAllC_M,setShowRAllC_M]= useState(false);
    const [searchedItem, setSearchedItem]= useState('');
    const [globalWindows, setGlobalWindows] = useState([]);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [GridValue, setGridValue] = useState(false);
    const [QREnable, setQREnable] = useState(false);

    
    const [DataCleanModal, setDataCleanModal] = useState(false);
    const [DataCleanAnim, setDataCleanAnim] = useState("");
    const [DataCleanItem, setDataCleanItem] = useState({});
    const [isPresentClean, setIsPresentClean] = useState(0);

    const [InputChange, setInputChange] = useState([]);

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({img1:0,img2:0});
    const [AppStatus, setAppStatus] = useState(AppState.currentState);
    const [QRqtnData, setQRqtnData] = useState({});
    //for Partial save
    const [FilteredPromoValues,setFilteredPromoValues]= useState([]);
    const [ShowCatWise,setShowCatWise]= useState(false);
    const [CatData,setCatData]= useState(false);
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(WindowData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef({});
    const PSGroupData=React.useRef(''); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
    const BGPSAllow=React.useRef(false);

    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);


    // ******************************************************************
    const [header_list, setHeader_list] = useState([]);
    // const WindowDataRef=React.useRef(header_list);
    

    
    const inputRefs = 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 menu1=params.menu || {};
        let ShowCatWise1=params.ShowCatWise!=null?params.ShowCatWise:false;
        let CatData1=params.CatData!=null?params.CatData:{};
        let isAdhoc=params.isAdhoc || false;
        
        
        setIsAdhocScreen(isAdhoc);
        setShowCatWise(ShowCatWise1);
        setCatData(CatData1);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);

        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current={BgscreenName:menu1.ScreenName,BgMenuId:menu1.MenuId }
       
            
        getData(storeData1,menu1,CatData1,ShowCatWise1);
 
        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(WindowData,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,
               BgMenuID: ScreenNameRef.current && ScreenNameRef.current.BgMenuId,
               visiteDate:d2,
               BGPSAllow:BGPSAllow.current,
               PSGroupData:PSGroupData.current,
           }
           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]); 

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showQRCamera]); 
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [show_zoomImage]); 
    
    function  onBeforeRemove(e){
        
        if(showCamera==true || showQRCamera==true ){
            e.preventDefault();
            setShowCamera(false);
            setShowQRCamera(false)
        }
        else if(Show_zoomImageRef.current==true){
            e.preventDefault();
            UpdateShow_zoomImageRef(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
        setWindowData(val);
    }

    function UpdateShow_zoomImageRef(val){
        Show_zoomImageRef.current=val
        setShow_zoomImage(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);} }
            ]
          );
    }
    

    function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        let {window,splitItem,splitItemIndex,type,cameraType,qtn}=reCapImgModalObj
        let camera2Label=(window && window.PromoImage2Lable) || '';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={currentMenu.MenuName}
            message={camera2Label}
            titleStyle={customStyle.PromoImgModal_title}
            messageStyle={customStyle.PromoImgModal_subtitle}
            showModal={showModal}
          >
            { 
            isImageCap && 
            <View style={customStyle.PromoImgModalCon}>
              <View style={customStyle.PromoImgModal_ImgWrap}>
             
                <Image  style={[customStyle.PromoImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:SelectedImg}} />
              </View>
              <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={()=>{openCamera(window,splitItem,splitItemIndex,type,cameraType,qtn)}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage(false)}}>
                
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }
  

    async function getData(storeData1,menu1,CatData1={},ShowCatWise1=false){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            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 inputChangeFlag=[],storeBGData1=[],bgStoreJson={},isBgDataExists=false;

            //storeBGData check
            let windData = await get_item('storeData')
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,BgMenuID,visiteDate }= StoreJson
                if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && menu1.MenuId==BgMenuID && visiteDate==d2){
                    isBgDataExists=true;
                    storeBGData1=storeBGData;
                    bgStoreJson=StoreJson
                    WindowDataRef.current=storeBGData
                    setWindowData(storeBGData);
                    BgUnsavedChanges(true)
                }
            }

         
            
            await db.transaction(async function (txn) {        
                

            // ******************************************************************************************

            let q4=`SELECT * FROM Mapping_StoreTargetBased WHERE MenuId='${menu1.MenuId}' AND StoreId='${StoreId}'`;

            await txn.executeSql(q4,[],async function (txn2, txnres2) { 
                if(txnres2.rows.length>0){
                    let arr=[],allWindowsData=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        let WQr =  await getQuestions(data,storeData1,menu1);
                        let TgQuestions = WQr['TgQuestions'] || [];
                        let TgQA= WQr['TgQA'] || {};
                        data['TgQuestions']=TgQuestions;
                        data['TgQA']=TgQA
                        

                        let changesFlag = {TgQuestionId:data.TgQuestionId, Flag:(data.PVisHeaderId!=null?true:false)}
                        inputChangeFlag.push(changesFlag)
                        arr.push(data);

                        
                        let windowDataObj=WQr['allWindowsData'];    
                       
                        // let newArr=[...allWindowsData,windowDataObj]
                        allWindowsData=allWindowsData.concat(windowDataObj);                             
 
                        if(i==txnres2.rows.length-1){
                            
                            // BgWindowData(allWindowsData);
                            if(!isBgDataExists){
                                BgWindowData(allWindowsData);
                            }
                            setInputChange(inputChangeFlag)
                            // BgWindowData(arr)
                            setHeader_list(arr);
                            setProcessing(false);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);



                

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



    // **************************************************************************


    
    async function getQuestions(window,storeData1,menu1){
        let obj={'TgQA':{},'TgQuestions':[]}
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='',join='',join2='';
              
                
                //get data from masters with saved data if any 
               
                selectlist=` DISTINCT  wq.TgQuestionId,wq.TgQuestionCode,wq.TgQuestionName,wq.QuestionType,wq.TgqShowCamera1,wq.TgqShowCamera2,wq.TgqShowCamera1Grid,wq.TgqShowCamera2Grid,wq.TgqCamera1Mandatory,wq.TgqCamera2Mandatory,wq.TgqLengthValidationRequired,wq.TgqMinimumChar,wq.TgqMaximumChar,wq.TgqDecimalPoint,wq.TgqDateRangeMin,wq.TgqDateRangeMax,wq.TgqVoiceLengthInMinutes,wq.TgqDefaultQuestionEnable,(CASE WHEN q.TQQUESTIONID is not null THEN 1 ELSE 0 END) isInserted,q.TQA_QUESTION_DISABLE,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as TgaShowCamera1,q.IMAGE_ALLOW2 as TgaShowCamera2,q.IMAGE1 as Image1,q.IMAGE2 as Image2  `;
                join2=` Left Outer Join ${AppTables.VISICO_CHILD_DATA} q on wq.TgQuestionId=q.TQQUESTIONID and q.STORE_ID='${storeData1.StoreId}' and q.TARGETTYPEID='${window.TargetTypeId}' and q.VISIT_DATE='${d2}'`;
                join=` inner join Mapping_TargetBasedQuestion mq on mq.TgQuestionId=wq.TgQuestionId `;
                q=`select ${selectlist} from Master_TargetBasedQuestion wq  ${join} ${join2} order by wq.TgQuestionSequence  `;


                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[],allWindowsData=[];
                        // let wqa_obj={};
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let wqa_obj={};
                            
                            let showImageTag1=false,showImageTag2=false;
                            let {isInserted}=data;
                            data["TargetTypeId"]=window.TargetTypeId;
                            data["TargetId"]=window.TargetId; // add this line ( change)

                           
                            let answers=[];
                            data.TgqDefaultQuestionEnable=data.TgqDefaultQuestionEnable==1 || data.TgqDefaultQuestionEnable=='true'?true:false;
                            // data['isDisabled']=!data.TgqDefaultQuestionEnable;
                            if(isInserted){
                                data['isDisabled']=data.TQA_QUESTION_DISABLE==true || data.TQA_QUESTION_DISABLE=="true"?true:false;
                            }
                            else{
                                data['isDisabled']=!data.TgqDefaultQuestionEnable;
                            }



                            if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                answers=await getAnswers(data);
                                
                                if(data.QuestionType=='Rating'){
                                    data.showRating=false;
                                }
                            }
                            else if(data.QuestionType=='Date'){
                                data.showDatePicker=false;
                            }

                             
                              data['Answers']=answers;
      
                              let id_key=data.TgQuestionId+'_AnswerId'; 
                              let ans_key=data.TgQuestionId+'_Answer'; 
                              let multi_key=data.TgQuestionId+'_MultiOption';
                              let date_key=data.TgQuestionId+'_Date';
                              let img_key1=data.TgQuestionId+'_ImagePath1';
                              let imgname_key1=data.TgQuestionId+'_ImageName1';
                              let img_key2=data.TgQuestionId+'_ImagePath2';
                              let imgname_key2=data.TgQuestionId+'_ImageName1';
                              let rating_key=data.TgQuestionId+'_Rating'; 
                              
                              data.AnswerId!=null?wqa_obj[id_key]=data.AnswerId:'';
                              data.Answer!=null?wqa_obj[ans_key]=data.Answer:'';

                              
                              let selansid=data.AnswerId!=null?data.AnswerId:'';
                            
                              if(data.QuestionType=='Multi choice list' && (selansid!='' || selansid===0) && data.multi_op_ids!=null){
                                  selansid=data.multi_op_ids?data.multi_op_ids.split(','):[];
                                  wqa_obj[multi_key]=data.multi_op_ids;
                              }

                                if(data.QuestionType=='Number' || data.QuestionType=='Text' || data.QuestionType=='Decimal' || data.QuestionType=='Date' || data.QuestionType=='QR' || 'TextSpc'){
                                    showImageTag1=(data.TgqShowCamera1==1 || data.TgqShowCamera1=='true');
                                    showImageTag2=(data.TgqShowCamera2==1 || data.TgqShowCamera2=='true');
                                }
      
                              if((data.QuestionType=='Single choice list' || data.QuestionType=='Multi choice list' ) && selansid!='' && selansid!=null){
                                  if (data.Answers && data.Answers.length>0){
                                      for(var k=0;k<data.Answers.length;k++){
                                        let ansss=data.Answers[k];

                                        let isandImgAl1=(ansss.TgaShowCamera1=='true' || ansss.TgaShowCamera1==1);
                                        let isandImgAl2=(ansss.TgaShowCamera2=='true' || ansss.TgaShowCamera2==1);
    
                                        if(data.QuestionType=='Single choice list' && (isandImgAl1 && ansss.AnswerId==selansid)){
                                            showImageTag1=true;
                                        }
                                        else if(data.QuestionType=='Multi choice list' && (isandImgAl1 && selansid.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag1=true;
                                        }
    
                                        if(data.QuestionType=='Single choice list' && (isandImgAl2 && ansss.AnswerId==selansid)){
                                            showImageTag2=true;
                                        }
                                        else if(data.QuestionType=='Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag2=true;
                                        }
                                      }
                                  }
                              }

      
                            if(showImageTag1 && data.Image1!=null && data.Image1!="" ){                                
                                let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image1;
                                wqa_obj[imgname_key1]=data.Image1;
                                wqa_obj[img_key1]=imgPath;
                                wqa_obj["TgaShowCamera1"]=showImageTag1
                            }

                           
                            if(showImageTag2 && data.Image2!=null && data.Image2!="" ){
                                let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image2;
                                wqa_obj[imgname_key2]=data.Image2;
                                wqa_obj[img_key2]=imgPath;
                                wqa_obj["TgaShowCamera2"]=showImageTag2
                            }

      
                              if(data.QuestionType=='Date' && data.Answer!=null){
                                  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;
                                  wqa_obj[date_key]=fulldate;
                                  
                              }

                            arr.push(data);

                            let windowDataObj={'TargetTypeId':data.TargetTypeId,'TgQA':wqa_obj,'TgQuestionId':data.TgQuestionId , 'TargetId' : data.TargetId};         
                            allWindowsData.push(windowDataObj);    

                            if(i==txnres2.rows.length-1){
                                obj['TgQuestions']=arr;
                                obj['TgQA']=wqa_obj;
                                obj["allWindowsData"]=allWindowsData
                                resolve(obj)
                            }                                
                        }
                    }
                    else{
                        resolve(obj)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(obj) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return obj;
        });
    }


    async function getAnswers(qtn){
        
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='';
                selectlist=` DISTINCT  TgAnswerId as AnswerId,TgAnswerName as Answer,TgaShowCamera1,TgaShowCamera2,TgaCamera1Mandatory,TgaCamera2Mandatory,TgaQuestionEnable,TgaQuestionDisable `;
                q=`select ${selectlist} from  Master_TargetBasedQuestion  where TgQuestionId='${qtn.TgQuestionId}'  order by TgaSequence  `;

                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            data["TargetTypeId"]=qtn.TargetTypeId;
                            data["TargetId"]=qtn.TargetId;
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                resolve(arr)
                            }                                
                        }
                    }
                    else{
                        resolve([])
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve([]) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return [];
        });
    }

    // **************************************************************************


    async function focusToNext(WindowStocks,windowIndex,stockProd,index)
    {
        console.log('focusToNext is call');
        console.log('WindowStocks',index+1)
        
        if(index==WindowStocks.length-1){
            return;
        }
     
        try{
            // inputRefs.current['input1_'+data.VisibilityDefinitionId+"_"+data.VisibilityStockDefinitionId]='';
            // use (index+1) instead of WindowStocks[index+1].VisibilityStockDefinitionId as the condition does not work in case of isSpecificMappingEnable is true ( because all VisibilityStockDefinitionId are 0) 
            console.log('next 1 call','input1_'+WindowStocks[index+1].VisibilityDefinitionId+'_'+(index+1))
            let refIn2=inputRefs.current['input1_'+WindowStocks[index+1].VisibilityDefinitionId+'_'+(index+1)];
            // let refIn2=inputRefs.current['input1_'+stockProd.WindowDefinitionId+'_'+stockProd.WindowStockDefinitionId];
            
            if(refIn2!=null){
                refIn2.focus();
            }
        }
        catch(err){
            console.log(err);
        }
   }


    async function getImage(imgdata){
        let type=getImageProps.type || '';
        let window=getImageProps.window || {};
        let splitItem=getImageProps.splitItem || {};
        let splitItemIndex=getImageProps.splitItemIndex || 0;
        let qtn=getImageProps.qtn || {};
        let cameraType=getImageProps.cameraType!=null?getImageProps.cameraType:'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+'_'+qtn.TargetTypeId+'_'+qtn.TargetId+'_'+qtn.TgQuestionId+'_'+(props.UserId || '')+'_STImg-'+calculate_tym_date_for_filename+'.jpg';
            
            let allData=WindowData;
            let defData={'TgQuestionId':qtn.TgQuestionId,'TargetTypeId':qtn.TargetTypeId , 'TargetId':qtn.TargetId  };
            
            const wind_index=allData.findIndex(i=>i.TgQuestionId==qtn.TgQuestionId && i.TargetTypeId==qtn.TargetTypeId && i.TargetId==qtn.TargetId) ;
            let wind=wind_index>=0?allData[wind_index]:defData;

            let extraLabel='';
            if(cameraType=='2'){
                var QD=wind.TgQA || {};
                var image_key=qtn.TgQuestionId+(type=='1'?`_ImageName1`:`_ImageName2`);
                var image_key_path=qtn.TgQuestionId+(type=='1'?`_ImagePath1`:`_ImagePath2`);
                QD[image_key]=filename;
                extraLabel='Qtn Id: '+qtn.TgQuestionId;
            }
            else if(cameraType=='3'){
                var image_key='NAImage1';
                var image_key_path='NAImage1Path';
                wind[image_key]=filename;
                extraLabel='Not Exist';
            }
            else{
                var WindowSplits=wind.WindowSplits || [];
                var image_key=type=='1'?'Image1Name':'Image2Name';
                var image_key_path=type=='1'?'Image1':'Image2';
                splitItem[image_key]=filename;
            }
            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | TargetType Id:'+qtn.TargetTypeId+(extraLabel!=''?' ('+extraLabel+')':'')+' | Image Type: '+currentMenu.MenuName+' | Date:'+calculate_tym_date_over_img;
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                if(cameraType=='2'){
                    QD[image_key_path]=uri;
                    wind.TgQA=QD;
                    
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    WindowDataRef.current=allData
                    setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata3(!rerenderdata3);
                }
                else if(cameraType=='3'){
                    wind[image_key_path]=uri;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    WindowDataRef.current=allData
                    setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                else{
                    splitItem[image_key_path]=uri;
                    splitItemIndex>=0?WindowSplits[splitItemIndex]=splitItem:WindowSplits.push(splitItem);
                    wind.WindowSplits=WindowSplits;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    WindowDataRef.current=allData
                    setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                }
                setSelectedImg(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('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });                         
                                    
        }    
        
    }
  
    
    async function onQRScanned(imgdata){
        let qtn=QRqtnData.qtn || {};
        let window=QRqtnData.window || {};
        let QR_withValidChars=imgdata!=null && imgdata!=''?imgdata.replace(/["']/g,''):'';
        let value=QR_withValidChars;//imgdata && imgdata[0] && imgdata[0].displayValue ? imgdata[0].displayValue :""
        setTextValue(value,qtn,window)
    }


    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.TgQuestionId==qtn.TgQuestionId);
       
        if(newqtnIndex>=0){
            let newqtn=allQtns[newqtnIndex];
            newqtn.showDatePicker=show;
            allQtns[newqtnIndex]=newqtn;
            window['TgQuestions']=allQtns;
            let allWindows=Windows;
            const winIndex=allWindows.findIndex(i=>i.TgQuestionId==window.TgQuestionId) || {};
            allWindows[winIndex]=window;
            setWindows(allWindows);
            setGlobalWindows(allWindows);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }
  
    async function openCamera(window,splitItem,splitItemIndex,type='1',cameraType='1',qtn={}){  
        setErrorField({});
        setError(false);
        let GridAllow=false;
        if(type=='1'){
            GridAllow = cameraType=='2' ?( type==='1' ? (qtn.TgqShowCamera1Grid === 'true' || qtn.TgqShowCamera1Grid==true): true):false
        }else{
            GridAllow = cameraType=='2' ?( type==='2' ? (qtn.TgqShowCamera2Grid === 'true' || qtn.TgqShowCamera2Grid==true): true):false
        }
        setGridValue(GridAllow);
        setGetImageProps({'window':window,'splitItem':splitItem,'splitItemIndex':splitItemIndex,'type':type,'cameraType':cameraType,'qtn':qtn}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }
   
    async function onSubmitData(){
        
        let isvalid=await validate();
      
        if(isvalid){
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        let d1n=new Date();
        let d3=moment(d1n).format('MM/DD/YYYY');
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;

            
            //  remove old data
            let isDeleted = await removePreviousData();
            console.log("isDeleted:",isDeleted);
            
            await db.transaction(async function (txn) {   
              
                // add data
                var values='',childV='',imageV='',stockV='';
              
                for (const wi in header_list){
                    const window=header_list[wi];
                    let TgQuestions=window.TgQuestions || [];
    
                    let VISICO_HEADER_ID='VISICOOL'+wi+(Math.floor(Math.random()*1000)+1);
                    let {TargetId,TargetTypeId,MenuId,TargetTypeName,ChildName}=window;


                    values+=values!=''?' , ':'';
                    values+=` ('${VISICO_HEADER_ID}','${MenuId}','${StoreId}','${d3}','${TargetId}','${TargetTypeName}','${TargetTypeId}','${ChildName}','1','1','${d3}') `;
                    

                        for(const qtnIndex in TgQuestions){
                            const qtn=TgQuestions[qtnIndex];
                            
                            let selansid='',selanswer='',selimg='',showImageTag1=false,showImageTag2=false;
                            let id_key=qtn.TgQuestionId+'_AnswerId'; 
                            let ans_key=qtn.TgQuestionId+'_Answer'; 
                            let multi_key=qtn.TgQuestionId+'_MultiOption';
                            let date_key=qtn.TgQuestionId+'_Date';
                            let img_key=qtn.TgQuestionId+'_ImagePath1';
                            let img_key2=qtn.TgQuestionId+'_ImagePath2';
                            let imgname_key1=qtn.TgQuestionId+'_ImageName1';
                            let imgname_key2=qtn.TgQuestionId+'_ImageName2';
                     
                            let rating_key=qtn.TgQuestionId+'_Rating'; 
                            let list_mcdata=[];
                            let isDisabled=qtn.isDisabled || false;

                            const wind = Object.keys(WindowData).length > 0 ? WindowData.find(i => i.TgQuestionId == qtn.TgQuestionId && i.TargetTypeId == qtn.TargetTypeId && i.TargetId==qtn.TargetId) : {};
                            let QD=(wind && wind.TgQA) || {};
                            
                            let {TgQuestionId,TgQuestionCode,QuestionType,TgqShowCamera1,TgqShowCamera2}=qtn
                            let answer=QD[ans_key] || '';
                            let answerId=QD[id_key]===0? 0 :(QD[id_key]|| '');
                            let multi_options_ids=QD[multi_key] || '';


                            if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date' || qtn.QuestionType=='TextSpc')
                            {
                                showImageTag1=(qtn.TgqShowCamera1==1 || qtn.TgqShowCamera1=='true');
                                showImageTag2=(qtn.TgqShowCamera2==1 || qtn.TgqShowCamera2=='true');
                            }
                            else 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.VAShowCamera=='true' || ansss.VAShowCamera==1);
                                        let isandImgAl1=(ansss.TgaShowCamera1=='true' || ansss.TgaShowCamera1==1);
                                        let isandImgAl2=(ansss.TgaShowCamera2=='true' || ansss.TgaShowCamera2==1);

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

                            let Image1=(showImageTag1==1 || showImageTag1==true) && QD[imgname_key1]!=null?QD[imgname_key1]:'';
                            let Image2=(showImageTag2==1 || showImageTag2==true) && QD[imgname_key2]!=null?QD[imgname_key2]:'';

                            childV+=childV!=''?' , ':'';
                            childV+=` ('${VISICO_HEADER_ID}','${StoreId}','${MenuId}','${d3}','${TargetTypeId}','${TgQuestionId}','${TgQuestionCode}','${QuestionType}','${answer}','${answerId||0}','${multi_options_ids}','${Image1}','${Image2}','${showImageTag1}','${showImageTag2}','${isDisabled}','${d3}') `;
                        }
                }
                
              
                let add_hdr_data=`INSERT INTO ${AppTables.VISICO_HDR_DATA} (VISICO_HEADER_ID ,MENU_ID ,STORE_ID ,VISIT_DATE ,TARGETID,TARGETTYPENAME ,TARGETTYPEID ,CHILD_NAME ,IS_PRESENT ,IS_UPDATED ,ADDED_DATE) VALUES ${values} `;
                let add_child_data=`INSERT INTO ${AppTables.VISICO_CHILD_DATA} (VISICO_HEADER_ID ,STORE_ID ,MENU_ID ,VISIT_DATE ,TARGETTYPEID ,TQQUESTIONID ,TQQUESTIONID_CODE ,QUESTION_TYPE ,ANSWER ,ANSWER_ID ,MULTI_OPTIONS_IDS ,IMAGE1 ,IMAGE2,IMAGE_ALLOW1,IMAGE_ALLOW2,TQA_QUESTION_DISABLE ,ADDED_DATE) VALUES ${childV} `;
                
                // setProcessing(false)
                         
                await txn.executeSql(add_hdr_data,[],async function (txn2, txnres) { 
                    var isChildAdded=true;
                  
                    if(childV!=''){
                        isChildAdded=await executeQuery(add_child_data);
                    }
                    
                    if(!isChildAdded){
                        setProcessing(false);notify('Cannot add visicooler questions data');
                    }
                    else{
                        // clear store data in local storage to avoiding re-set data for the store  
                        clear_item('storeData')
                        setProcessing(false);notify('Visicooler updated successfully');
                        props.navigation.goBack();
                    }

                       
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add visicooler data'); },);
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function removePreviousData(){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData;

        let {PSAllow}=currentMenu
        let deleteOnlyCatData=ShowCatWise && PSAllow &&  FilteredPromoValues.length>0;
            

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

            db.transaction(async function (txn) {   

                let sq=`Select * FROM ${AppTables.VISICO_HDR_DATA} WHERE STORE_ID='${StoreId}' and MENU_ID='${currentMenu.MenuId}' and VISIT_DATE='${d2}' `;
                
                await txn.executeSql(sq,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let arr=[];
                        let isHdrDel=false,isQtnsDel=false,isImagesDel=false,isStockDel=false;
                        for(let i=0;i<txnres.rows.length;i++){
                            let data=txnres.rows.item(i);
                            let {VISICO_HEADER_ID}=data;
                            arr.push(VISICO_HEADER_ID);
                            if(i==txnres.rows.length-1){
                                let AllHdrIds=`'${arr.join("','")}'`;

                                await txn.executeSql(`DELETE FROM ${AppTables.VISICO_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  and VISICO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window hdr data deleted');
                                    isHdrDel=true;
                                    if(isHdrDel && isQtnsDel ){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.VISICO_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and VISICO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window child data deleted');
                                    isQtnsDel=true;
                                    if(isHdrDel && isQtnsDel ){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);
                               
                            }
                        }
                    }
                    else{
                        resolve(true);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);

                
            });    

        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log('error:',err);
            return false;
        })
    }

    async function executeQuery(q){
        return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
            await 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 validate(){
        let isValid=true;

        function showError(obj,isErr){
            setErrorField(obj);
            setError(isErr);
        }
       
        return new Promise((resolve,reject)=>{
            for (const wi in header_list){
                const window=header_list[wi];
                let TgQuestions=window.TgQuestions || [];
                let errorobj = {'EF_Window':window};

                if(TgQuestions.length>0){
                    for(const qtnIndex in TgQuestions){
                        const qtn=TgQuestions[qtnIndex];
                        
                        let selansid='',selanswer='',selimg1='',selimg2='',selimg3='',selimg4='',showImageTag1=false,showImageTag2=false,showImageTag3=false,showImageTag4=false;
                        let id_key=qtn.TgQuestionId+'_AnswerId'; 
                        let ans_key=qtn.TgQuestionId+'_Answer'; 
                        let multi_key=qtn.TgQuestionId+'_MultiOption';
                        let date_key=qtn.TgQuestionId+'_Date';
                        let img_key1=qtn.TgQuestionId+'_ImagePath1';
                        let img_key2=qtn.TgQuestionId+'_ImagePath2';
                        // let img_key3=qtn.TgQuestionId+'_ImagePath3';
                        // let img_key4=qtn.TgQuestionId+'_ImagePath4';
                        let imgname_key=qtn.TgQuestionId+'_ImageName1';
                        let rating_key=qtn.TgQuestionId+'_Rating'; 

                        let isDisabled=qtn.isDisabled;


                        const wind=Object.keys(WindowData).length>0 ? WindowData.find(i=>i.TgQuestionId==qtn.TgQuestionId && i.TargetTypeId==qtn.TargetTypeId ):{};
                        let QD=(wind && wind.TgQA) || {};


                        let list_mcdata=[];
                        errorobj['EF_qtn']=qtn;

                        let isImgAllowed=(qtn.TgqShowCamera=='true' || qtn.TgqShowCamera==1);

              
                        let isImgAllowed1=(qtn.TgqShowCamera1==1 || qtn.TgqShowCamera1=='true')? true:false;
                        let isImgAllowed2=(qtn.TgqShowCamera2==1 || qtn.TgqShowCamera2=='true')? true:false;
                        let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating' || qtn.QuestionType=='QR' || qtn.QuestionType=='TextSpc') ;

                      
                        if(qtn.QuestionType=='Single choice list')
                        {
                            console.log("Single choice----",id_key,QD[id_key],qtn,"----",QD)
                            selansid=QD[id_key];
                        }
                        else if(qtn.QuestionType=='Multi choice list')
                        {
                            selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
                        }
                        
                        if(!isDisabled){

                            if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                                errorobj['EF_Qtn_MultiChoice']='Qtn_MultiChoice';
                                showError(errorobj,true);
                                notify(`${Pleaseselectoptionsfortherequiredfield} ${ST.In} ${qtn.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }
                            else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                                errorobj['EF_Qtn_Date']='Qtn_Date';
                                showError(errorobj,true);
                                let msg=( qtn.QuestionType=='Date'?`${ST.Pleasepickadatefortherequiredfield} ${ST.In} ${qtn.TgQuestionName}`:(qtn.QuestionType=='Rating'?`${Pleaseselectratingfortherequiredfield} ${ST.In} ${qtn.TgQuestionName}`:`${ST.Pleasefillalltherequiredfield} ${ST.In} ${qtn.TgQuestionName}`));
                                notify(msg,'SHORT');
                                resolve(false);return;
                            }
                            else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))){
                                errorobj['EF_Qtn_Input']='Qtn_Input';
                                showError(errorobj,true);
                                notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${qtn.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }
                            else if(isImgAllowed1 && (Object.keys(QD).indexOf(img_key1)<0 || (Object.keys(QD).indexOf(img_key1)>=0 && QD[img_key1]===''))){
                                errorobj['EF_Qtn_Image']='Qtn_Image';
                                showError(errorobj,true);
                                notify(`${ST.Pleaseaddimages} ${ST.In} ${qtn.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }else if(isImgAllowed2 && (Object.keys(QD).indexOf(img_key2)<0 || (Object.keys(QD).indexOf(img_key2)>=0 && QD[img_key2]===''))){
                                errorobj['EF_Qtn_Image']='Qtn_Image';
                                showError(errorobj,true);
                                notify(`${ST.Pleaseaddimages} ${ST.In} ${window.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }
                            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 isandImgAl1=(ansss.TgaShowCamera1=='true' || ansss.TgaShowCamera1==1);
                                        let isandImgAl2=(ansss.TgaShowCamera2=='true' || ansss.TgaShowCamera2==1);

                                        if(qtn.QuestionType=='Single choice list' && (isandImgAl1 && ansss.AnswerId==selansid)){
                                            showImageTag1=true;
                                        }
                                        else if(qtn.QuestionType=='Multi choice list' && (isandImgAl1 && selansid.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag1=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(showImageTag1 && (Object.keys(QD).indexOf(img_key1)<0 || (Object.keys(QD).indexOf(img_key1)>=0 && QD[img_key1]===''))){
                                
                                errorobj['EF_Qtn_Image']='Qtn_Image';
                                showError(errorobj,true);
                                notify(`${ST.Pleaseaddimages} ${ST.In} ${qtn.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }
                            if(showImageTag2 && (Object.keys(QD).indexOf(img_key2)<0 || (Object.keys(QD).indexOf(img_key2)>=0 && QD[img_key2]===''))){
                                errorobj['EF_Qtn_Image2']='Qtn_Image2';
                                showError(errorobj,true);
                                notify(`${ST.Pleaseaddimages} ${ST.In} ${qtn.TgQuestionName}`,'SHORT');
                                resolve(false);return;
                            }

                        }
                        
                    }
                }
                

                if(wi==(header_list.length-1)){
                    resolve(true);return;
                }
                
            }
            
        }).then((val)=>{
            return val
        })
        .catch((err)=>{console.log(err); return false});
    
    }



    async function onselectionChange(option,qtn,window){
        setErrorField({});
        setError(false);
        let allData=WindowData;
        
        let defData={'TgQuestionId':qtn.TgQuestionId,'TargetTypeId':qtn.TargetTypeId , 'TargetId':qtn.TargetId};
        
        // return
        const wind_index=allData.findIndex(i=>((i.TgQuestionId==qtn.TgQuestionId) && (i.TargetTypeId==qtn.TargetTypeId) && (i.TargetId==qtn.TargetId)  ));
        let wind=wind_index>=0?allData[wind_index]:defData;

       
        let data=wind.TgQA || {};
        let data2={...wind?.TgQA} || {};
        let id_key=qtn.TgQuestionId+'_AnswerId'; 
        let ans_key=qtn.TgQuestionId+'_Answer'; 
        data2[id_key]=option.value;
        data2[ans_key]=option.label;
        data2["TgaShowCamera1"]=option.TgaShowCamera1
        data2["TgaShowCamera2"]=option.TgaShowCamera2

        
        wind['TgQA']={...data2};
        wind_index>=0?(allData[wind_index]=wind):allData.push(wind);
        let objIndex = InputChange.findIndex(i=>i.TgQuestionId==window.TgQuestionId );
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
     
        setInputChange(winArr)
        WindowDataRef.current=allData
        setWindowData(allData);

        let aq_ans=qtn.Answers!=null?qtn.Answers:[];
        let ans_obj=aq_ans.find(i=>i.AnswerId==option.value) || {};
        let EQtns=ans_obj.TgaQuestionEnable!=null && ans_obj.TgaQuestionEnable!=''?ans_obj.TgaQuestionEnable.replace(' ','').split(','):[];
        let DQtns=ans_obj.TgaQuestionDisable!=null && ans_obj.TgaQuestionDisable!=''?ans_obj.TgaQuestionDisable.replace(' ','').split(','):[];
      
        let sqtns=window.TgQuestions || []

        if(EQtns.length>0){
           await enableQtns(sqtns,EQtns,DQtns,data,wind,wind_index,allData,window)
            setrerenderdata(!rerenderdata);
        }
        else if(DQtns.length>0){
           await disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            setrerenderdata(!rerenderdata);
        }
        else{
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }
        BgUnsavedChanges(true)
       
    }

    async function disableQtns(sqtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
       
        if(DQtns.length>0){
            await Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.TgQuestionId==qid) || {};
                    let s_qtn=sqtns[s_qtnindex];
                    if(s_qtn!=null){
                        s_qtn['isDisabled']=true
                        sqtns[s_qtnindex]=s_qtn;
                        let id_key=s_qtn.TgQuestionId+'_AnswerId'; 
                        let ans_key=s_qtn.TgQuestionId+'_Answer'; 
                        // data[id_key]=0;
                        // data[ans_key]='';

                        // wind['TgQA']=data;
                        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                        return false
                    }else{
                        return false
                    }
                })
            ).then(async (val)=>{

                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.TgQuestionId==window.TgQuestionId );
                if(windowIndex>=0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    WindowDataRef.current=allData
                    setWindowData(allData);
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
        await Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.TgQuestionId==qid) || {};
                let s_qtn=sqtns[s_qtnindex];
                if(s_qtn!=null){
                    s_qtn['isDisabled']=false
                    sqtns[s_qtnindex]=s_qtn;
                    return false
                }
                else{
                    return false
                }
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                await disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            }
            else{
                let allwindows=Windows;
           
                let windowIndex=allwindows.findIndex(i=>i.TgQuestionId==window.TgQuestionId)
                if(windowIndex>0){
                    window['TgQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
            }
        })
    }

    async function setMultiSelectValue(selectedItems=[],qtn={},window={}) {  
        setErrorField({});
        setError(false);
  
        let id_key=qtn.TgQuestionId+'_AnswerId'; 
        let ans_key=qtn.TgQuestionId+'_Answer'; 
        let multi_key=qtn.TgQuestionId+'_MultiOption';
       
        let allData=WindowData;
        let defData={'TgQuestionId':window.TgQuestionId};
        const wind_index=allData.findIndex(i=>i.TgQuestionId==window.TgQuestionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.TgQA || {};
        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);
        
        wind['TgQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.TgQuestionId==window.TgQuestionId );
        
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
    
        setInputChange(winArr)
        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value,qtn,window,type="") {   
        if(value!=''){
            let isValid=validateNumber(value,type);
            console.log("type:",type,isValid);
            if(!isValid){
                return;
            }
        }    

        setErrorField({});
        setError(false); 
        let id_key=qtn.TgQuestionId+'_AnswerId'; 
        let ans_key=qtn.TgQuestionId+'_Answer'; 

        let allData=WindowData;
        let defData={'TgQuestionId':qtn.TgQuestionId, 'TargetTypeId':qtn.TargetTypeId};
        const wind_index=allData.findIndex(i=>i.TgQuestionId==qtn.TgQuestionId && i.TargetTypeId==qtn.TargetTypeId && i.TargetId==qtn.TargetId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.TgQA || {};

        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.TgQuestionId+'_Date'; 
            let d=value!=null?new Date(value):new Date();
            let mfdate=moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn,window,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);
        wind['TgQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.TgQuestionId==window.TgQuestionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
   
        setInputChange(winArr)
        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.TgQuestionId==qtn.TgQuestionId);
       
        if(newqtnIndex>=0){
            let newqtn=allQtns[newqtnIndex];
            newqtn.showDatePicker=show;
            allQtns[newqtnIndex]=newqtn;
            window['WindowQuestions']=allQtns;
            let allWindows=Windows;
            const winIndex=allWindows.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId) || {};
            allWindows[winIndex]=window;
            setWindows(allWindows);
            setGlobalWindows(allwindows);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    function setRatingValue(data){
        setRatingOrder(data);
    }

    function onRatingCancel(){ 
        setShowRating(false);
    }

    function onRatingSave(){
        setShowRating(false);
        let qtn=RatingQtn;
        let window=RatingWindow;
        let id_key=qtn.TgQuestionId+'_AnswerId'; 
        let ans_key=qtn.TgQuestionId+'_Answer'; 
        let rating_key=qtn.TgQuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })

        let allData=WindowData;
        let defData={'VisibilityId':window.VisibilityId,'VisibilityDefinitionId':window.VisibilityDefinitionId};
        const wind_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.TgQA || {};

        obj[rating_key]=ids.join(',');
        obj[id_key]=0;
        obj[ans_key]=anss.join(',');
        
        wind['TgQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true

        setInputChange(winArr)
        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }
    
   
    function onChoiceSelect(item,val,key,animatedChoice){
        let win_index=InputChange.find(i=>i.VisibilityId==item.VisibilityId && i.VisibilityDefinitionId==item.VisibilityDefinitionId)
        let changeValue=win_index.Flag;
     
        if(changeValue){
            setIsPresentClean(val)
            setDataCleanAnim(animatedChoice)
            setDataCleanItem(item)
            setDataCleanModal(true)
            return
        }
        
        var val1=0;
        val==1?val1=1:'';
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onWindowDataChange(item,val,key)
    }

    function onWindowDataChange(item,val,key){
        let allData=WindowData;
        let defData={'VisibilityId':item.VisibilityId,'VisibilityDefinitionId':item.VisibilityDefinitionId};
        const win_index=allData.findIndex(i=>i.VisibilityId==item.VisibilityId && i.VisibilityDefinitionId==item.VisibilityDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

       
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        if(key!="isPresent"){
            let objIndex = InputChange.findIndex(i=>i.VisibilityId==item.VisibilityId && i.VisibilityDefinitionId==item.VisibilityDefinitionId);
            let winArr=[...InputChange]
            winArr[objIndex].Flag=true
            setInputChange(winArr)
        }

        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    
    async function setWindowStockVal(val,window,stockProd,key,type=''){
        setErrorField({});
        setError(false);
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify(ST.Pleaseenterwholenumbersonly,'SHORT');
                return;
            }
        }
        
        let allData=WindowData;
        let defData={'VisibilityId':window.VisibilityId,'VisibilityDefinitionId':window.VisibilityDefinitionId};
        const win_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        let sdIndex=WStocksData.findIndex(i=> i.ProductId==stockProd.VisibilityStockValue);
        let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.VisibilityStockValue,'Stock':''};
        sd[key]=val;
        sdIndex>=0?WStocksData[sdIndex]=sd:WStocksData.push(sd);
        wind['WStocksData']=WStocksData;
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        if(key=='isPVisPresent'){
            let isAllChecked = await verifyAllChecked(val,window,stockProd,key);
            wind['isAllSKUChecked']=isAllChecked;
        }
        
        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata4(!rerenderdata4);
    }


    async function verifyAllChecked(val,window,stockProd,key){
        return await new Promise((resolve,reject)=>{
            let WindowStocks=window.WindowStocks || [];
            let allData=WindowData;
            const win_index=allData.findIndex(i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId);
            let wind=win_index>=0?(allData[win_index] || defData) : defData;
            let WStocksData=wind['WStocksData'] || [];
            if(WindowStocks.length>0){
                let isAllChecked=1;
                for(var i=0;i<WindowStocks.length;i++){
                    let stockProd=WindowStocks[i];
                    
                    let sdIndex1=WStocksData.findIndex(a=> a.ProductId==stockProd.VisibilityStockValue);
                    let sd1=sdIndex1>=0?WStocksData[sdIndex1]:{};
                    let isPVisPresent=sd1.isPVisPresent;
                    if(isPVisPresent==null || isPVisPresent=='' || isPVisPresent==0 || isPVisPresent=='0'){
                        isAllChecked=0
                    }

                    if(i==WindowStocks.length-1){
                        resolve(isAllChecked);
                    }
                }
            }
            else{
                resolve(0);
            }
            
        }).catch((err)=>{
            console.log(err);
            return 0;
        });
    }

    function onWindowDataClean(){
        if(DataCleanAnim!=null){
            let anim=isPresentClean==1?1:'';
            Animated.timing(DataCleanAnim, {
                toValue:anim,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        let allData=WindowData;
        let WindowSplits =  [];
        for(var s=0;s<DataCleanItem.NoOfSplit;s++){
            let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':'',img1Required:true, img2Required:true};
            WindowSplits.push(obj);
        }

        // i=>i.VisibilityId==window.VisibilityId && i.VisibilityDefinitionId==window.VisibilityDefinitionId
        let defData={'VisibilityId':DataCleanItem.VisibilityId,'VisibilityDefinitionId':DataCleanItem.VisibilityDefinitionId,'isAllSKUChecked':0,'WindowSplits':WindowSplits,'TgQA':{},'WStocksData':[],isPresent:isPresentClean};
        const win_index=allData.findIndex(i=>i.VisibilityId==DataCleanItem.VisibilityId && i.VisibilityDefinitionId==DataCleanItem.VisibilityDefinitionId);
        allData[win_index]=defData

        let objIndex = InputChange.findIndex((obj => obj.VisibilityId == DataCleanItem.VisibilityId && obj.VisibilityDefinitionId==DataCleanItem.VisibilityDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=false
  
        setInputChange(winArr)
        WindowDataRef.current=allData
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setDataCleanModal(false)
        setrerenderdata(!rerenderdata);
    }


    function onSaveCancel(){
        setShowAlert(false);
    }

  

    function openImageRefView(windowIndex=0){
        setrefImageIndex(windowIndex);
        UpdateShow_zoomImageRef(true);
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        let arr=[];
        let newWindows=[];
        if(searchedQry!=null && searchedQry!=''){
            
            for(let i=0;i<globalWindows.length;i++){
                let item=globalWindows[i];
                let {VisibilityName}=item;
                if(VisibilityName.toLowerCase().includes(searchedQry)){
                    newWindows.push(item);
                }

                if(i==globalWindows.length-1){
                    arr=newWindows;
                }
            }
        }
        else{
          arr=globalWindows;
        }

        setWindows(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }

    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.TgQuestionId+'_AnswerId'; 
        let ans_key=qtn.TgQuestionId+'_Answer'; 
        let rating_key=qtn.TgQuestionId+'_Rating'; 
        
        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 render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        let window=selected_data.window || {};
        let isQtnDisabled=qtn.isDisabled!=null || qtn.isDisabled!=''?false:true;
        let allAnswers=qtn.Answers || [];
        
        allAnswers.map((item,index)=>{
            let obj={ key: index, label: item[label_key],value:item[value_key],TgaShowCamera1:item["TgaShowCamera1"],TgaShowCamera2:item["TgaShowCamera2"]  };
            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,window) }}
            overlayStyle={customStyle.addVisPickerOverlay}
            cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            optionStyle={customStyle.addvis_opStyle}
            optionTextStyle={customStyle.addvis_opTextStyle}
            optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            selectedKey={'1'}
            disabled={isQtnDisabled}
            >
            <Text style={[customStyle.WQPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-'+ST.select+'-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn,window){
        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,window)}}
            maximumDate={new Date(maxDate)}
            minimumDate={new Date(minDate)}
            />    
        );
    }

    async function OpenImgModal(imgPath,window,splitItem,splitItemIndex,cameraType){
        setSelectedImg(imgPath)
        setShowModal(true);
        if((imgPath!='' && imgPath!=null)){
            setShowImageSaveOp(false);
        }
        else{
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({window,splitItem,splitItemIndex,cameraType})
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)
        
      }

      function cancelImage(){
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
      }

    function _renderWindow(){
       
        
        return (
            <KeyboardAvoidingView  behavior="padding" enabled  >  
            
            <FlatList 
            data={header_list}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.Win_scroll} 
            // style={customStyle.Win_scrollO}
            initialNumToRender={5}
            listKey={(item, index) => `window_${index.toString()}`}
            renderItem={({item,index})=>{
                const window=item;

                const windowIndex=index;
                
                let isImage1=window.VisibilityImage1=='true' || window.VisibilityImage1==1?1:0;
                let isImage2=window.VisibilityImage2=='true' || window.VisibilityImage2==1?1:0;
                let isNAImageAvl=window.VisibilityNotExistCamera=='true' || window.VisibilityNotExistCamera==1?1:0;
                let isNAReasonEnable=window.VisibilityNotExistReasonEnable=='true' || window.VisibilityNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.VisibilityExistReasonEnable=='true' || window.VisibilityExistReasonEnable==1? 1:0;
                let isStockReq=window.VisibilityElementStockRequired=='true' || window.VisibilityElementStockRequired==1?1:0;
                let StockQtyRequired=window.StockQtyRequired=='true' || window.StockQtyRequired==1?1:0;
                let PromoTitleEnable=window.PromoDefinitionTitleEnable=='true' || window.PromoDefinitionTitleEnable==1? 1:0;
                let PromoTitle=window.PromoDefinitionTitle!=null && window.PromoDefinitionTitle!='undefined'? window.PromoDefinitionTitle:"";
                
                // let isStock_CheckAssrt=window.VisibilityElementCheckAssortment=='true' || window.VisibilityElementCheckAssortment==1?1:0;
                let TgQuestions=window.TgQuestions || [];

                
                let EF_Window=errorfield.EF_Window!=null ?errorfield.EF_Window:{};
                let show_errorhere=error==true && EF_Window.VisibilityId==window.VisibilityId && EF_Window.VisibilityDefinitionId==window.VisibilityDefinitionId;
                
                // if not Present fields

                // this will show error field in red (if window is present and exist reason is enabled and not filled ) or (if window is not present and Not exist reason is enabled and not filled ) 
                let EF_NExistReason=errorfield.EF_NExistReason || '';
                let EStyle_NExistReason=show_errorhere && EF_NExistReason=='NExistReason'?customStyle.stk_inptSTyle_error:{};
                
                let EF_NExistRemark=errorfield.EF_NExistRemark || '';
                let EStyle_NExistRemark=show_errorhere && EF_NExistRemark=='NExistRemark'?customStyle.stk_inptSTyle_error:{};
                
                let EF_NExistImage=errorfield.EF_NExistImage || '';
                let EStyle_NExistImage=show_errorhere && EF_NExistImage=='NExistImage'?customStyle.error_CatImage2:{};
                
                

                return(
                    <View style={customStyle.WItem_wrap} key={'window_'+index}>
                        <View style={customStyle.WItem_Hdr}>                            
                            <View style={customStyle.WItem_Hdrbg}>
                                <Text style={customStyle.WItem_HdrText}>{window.TargetTypeName}</Text>
                                {
                                    window && window.ChildName !="" && <Text style={[customStyle.WItem_Hdrname2]}>{window.ChildName}</Text>
                                }

                                <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={()=>{openImageRefView(index)}}>
                                    <Entypo name='image-inverted' size={24} color={PageTheme.$accent_color} />    
                                </TouchableOpacity>
                            </View>
                        </View>
                        
                        <View style={customStyle.WForm}>
                            <View style={[customStyle.openStk_prd_cols,customStyle.mt10]}>
                                <View>
                                    {(TgQuestions.length>0) && 
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{currentMenu.MenuName+' Questions'}</Text>
                                    </LinearGradient>
                                    { TgQuestions.map((item,index)=>{

                                        let qtn=item;  
                                        let qtnIndex=index;
                                        let selansid='',selanswer='',selimg1='',selimg2='',selimg3='',selimg4='',showImageTag1=false,showImageTag2=false,showImageTag3=false,showImageTag4=false;
                                        let id_key=qtn.TgQuestionId+'_AnswerId'; 
                                        let ans_key=qtn.TgQuestionId+'_Answer'; 
                                        let multi_key=qtn.TgQuestionId+'_MultiOption';
                                        let date_key=qtn.TgQuestionId+'_Date';
                                        let img_key=qtn.TgQuestionId+'_ImagePath1';
                                        let img_key2=qtn.TgQuestionId+'_ImagePath2';
                                       
                                        let imgname_key=qtn.TgQuestionId+'_ImageName1';
                                        let rating_key=qtn.TgQuestionId+'_Rating'; 
                                        
                                        let list_mcdata=[];
                                        let TgqDefaultQuestionEnable=qtn.TgqDefaultQuestionEnable=='true' || qtn.TgqDefaultQuestionEnable==1 || qtn.TgqDefaultQuestionEnable=='1'?true:false;
                                        let isDisabled=qtn.isDisabled;


                                        // =>i.TgQuestionId==qtn.TgQuestionId && i.TargetTypeId==window.TargetTypeId
                                        const wind=Object.keys(WindowData).length>0 ? WindowData.find(i=>(i.TgQuestionId==qtn.TgQuestionId && i.TargetTypeId==qtn.TargetTypeId && i.TargetId==qtn.TargetId)):{};
                                        let QuestionsData=(wind && wind.TgQA) || {};


                                        if(qtn.QuestionType=='Single choice list')
                                        {
                                            
                                            selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                                            selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                                            
                                            showImageTag1=((QuestionsData.TgaShowCamera1==1) || (QuestionsData.TgaShowCamera1=='true'))? true:false;
                                            showImageTag2=(QuestionsData.TgaShowCamera2==1 || QuestionsData.TgaShowCamera2=='true')? true:false;
                                        }
                                        else if(qtn.QuestionType=='Multi choice list')
                                        {
                                            if(qtn.Answers!=null){
                                                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' || qtn.QuestionType=='TextSpc' )
                                        {
                                            selansid=QuestionsData[ans_key]!=null && QuestionsData[ans_key]!=undefined? QuestionsData[ans_key]:"";
                                            selanswer=(qtn.QuestionType=='Date'  )?(QuestionsData[date_key] || moment().format('MM/DD/YYYY')):'';


                                            showImageTag1=(qtn.TgqShowCamera1==1 || qtn.TgqShowCamera1=='true');
                                            showImageTag2=(qtn.TgqShowCamera2==1 || qtn.TgqShowCamera2=='true');
                                        }
                                        else if(qtn.QuestionType=='Rating' || qtn.QuestionType=='QR'){
                                            selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                                        }
                                        

                                        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.VAShowCamera=='true' || ansss.VAShowCamera==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(showImageTag1){
                                            selimg1=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 EF_qtn=errorfield.EF_qtn!=null?errorfield.EF_qtn:{};
                                        let showQtnErrHere=EF_qtn.TgQuestionId==qtn.TgQuestionId;
                                        //Qtn_MultiChoice
                                        let EF_Qtn_MultiChoice=errorfield.EF_Qtn_MultiChoice || '';
                                        let EStyle_Qtn_MultiChoice=show_errorhere && showQtnErrHere && EF_Qtn_MultiChoice=='Qtn_MultiChoice'?customStyle.stk_MultiSSTyle_error:customStyle.wind_MultiSearchInputStyle;
                                        
                                        
                                        let EF_Qtn_Date=errorfield.EF_Qtn_Date || '';
                                        let EStyle_Qtn_Date=show_errorhere && showQtnErrHere && EF_Qtn_Date=='Qtn_Date'?customStyle.stk_inptSTyle_error:{};
                                        
                                        let EF_Qtn_Input=errorfield.EF_Qtn_Input || '';
                                        let EStyle_Qtn_Input=show_errorhere && showQtnErrHere && EF_Qtn_Input=='Qtn_Input'?customStyle.stk_inptSTyle_error:{};
                                        
                                        let EF_Qtn_Image=errorfield.EF_Qtn_Image || '';
                                        let EStyle_Qtn_Image=show_errorhere && showQtnErrHere && EF_Qtn_Image=='Qtn_Image'?customStyle.stk_inptSTyle_error:{};
                                        
                                        let EF_Qtn_Image2=errorfield.EF_Qtn_Image2 || '';
                                        let EStyle_Qtn_Image2=show_errorhere && showQtnErrHere && EF_Qtn_Image2=='Qtn_Image2'?customStyle.stk_inptSTyle_error:{};
                                        
                                        if(!isDisabled){
                                            return(
                                            <View style={[customStyle.sform_group2,]} key={'Qtn_'+qtnIndex} >
                                                <Text style={[customStyle.sform_label3]}>{qtn.TgQuestionName}</Text>                     
                                                {qtn.QuestionType=='Single choice list' && qtn.Answers && 
                                                    render_Picker('Answer','AnswerId',onselectionChange,{value:selanswer,qtn:qtn,window:window})
                                                }
                                                {qtn.QuestionType=='Multi choice list' && qtn.Answers &&
                                                    <MultiSelect
                                                        items={list_mcdata}
                                                        uniqueKey="AnswerId"
                                                        onSelectedItemsChange={(selectedItems)=>{ setMultiSelectValue(selectedItems,qtn,window) }} //setMultiSelectValue(selectedItems,qtn)
                                                        selectedItems={selansid}
                                                        selectText="Pick Items"
                                                        searchInputPlaceholderText={ST.SearchItems+"..."}
                                                        // 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}
                                                        itemTextColor={PageTheme.$text_color}
                                                        displayKey="Answer"
                                                        searchInputStyle={EStyle_Qtn_MultiChoice}
                                                        submitButtonColor={PageTheme.$primary_color}
                                                        submitButtonText={ST.Submit}
                                                    />
                                                }
                                               
                                                { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text' || qtn.QuestionType=='TextSpc') &&  
                                                    <TextInput 
                                                        style={[customStyle.WQ_InputStyle,EStyle_Qtn_Input]}
                                                        placeholder=""
                                                        autoComplete='off'
                                                        placeholderTextColor={PageTheme.$placeholder_color} 
                                                        // keyboardType={'ascii-capable'}
                                                        keyboardType={(qtn.QuestionType=='Decimal'?'decimal-pad':(qtn.QuestionType=='Text'?'default':qtn.QuestionType=='TextSpc' ?'default':'number-pad'))}
                                                        value={(selansid+'')}
                                                        onChange={(e)=>console.log("onchangeVal--",e.value)}
                                                        onChangeText={(val)=>{setTextValue(val,qtn,window,(qtn.QuestionType=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':qtn.QuestionType=='TextSpc'? 'TextSpc':'numeric')))}}
                                                    />
                                                }
                                                
                                                {
                                                    (qtn.QuestionType=='Date') && 
                                                    <View style={[customStyle.surveyQtn_datePicker_con,EStyle_Qtn_Date]}>
                                                        <Text style={customStyle.WQ_datePicker_text}>{selansid!=''?selansid:'MM/YYYY'}</Text>
                                                        <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setDateValue(selanswer);showQtnDatePicker(qtn,window,true)}}>
                                                            <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                                        </TouchableOpacity> 
                                                    </View>     
                                                }
                                                {
                                                    (qtn.QuestionType=='QR') && 
                                                    <View style={customStyle.surveyQtn_datePicker_con}>
                                                        {/* <Text style={customStyle.WQ_datePicker_text}>{selanswer!=''?selanswer:''}</Text> */}
                                                        <TextInput 
                                                        style={[customStyle.WQ_InputStyle,EStyle_Qtn_Input]}
                                                        placeholder=""
                                                        placeholderTextColor={PageTheme.$placeholder_color} 
                                                        keyboardType={'default'}
                                                        value={(selanswer+'')}
                                                        onChange={(e)=>console.log("onchangeVal--",e.value)}
                                                        onChangeText={(val)=>{setTextValue(val,qtn,window,'qrtext')}}
                                                    />
                                                        <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setQREnable(true);setQRqtnData({qtn,window});setShowQRCamera(true);}}>
                                                            <Ionicons name="camera" color={PageTheme.$accent_color} size={24}/>
                                                        </TouchableOpacity> 
                                                    </View>     
                                                }
                                                {   ((qtn.showDatePicker==true || qtn.showDatePicker=='true') && (qtn.QuestionType=='Date') ) && 
                                                    renderDatePicker(qtn,window)
                                                }  
                                                {
                                                    (qtn.QuestionType=='Rating') && 
                                                    <View style={customStyle.surveyQtn_datePicker_con}>
                                                        <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                        <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{setRatingQtn(qtn);setRatingWindow(window);setShowRating(true);}}>
                                                            <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag"/>
                                                        </TouchableOpacity> 
                                                    </View>    
                                                }
                                                {
                                                    showImageTag1==true && 
                                                    <View style={[customStyle.store_audit_img_con,EStyle_Qtn_Image]}>    
                                                        <Image source={(selimg1!='' && selimg1!=null )?{uri:selimg1}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg1!='' && selimg1!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>  
                                                        <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(window,{},0,'1','2',qtn)}}>
                                                            <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                                        </TouchableOpacity>
                                                    </View>
                                                }
                                                {
                                                    showImageTag2==true &&
                                                    <View style={[customStyle.store_audit_img_con,EStyle_Qtn_Image2]}>   
                                                        <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(window,{},0,'2','2',qtn)}}>
                                                            <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                                        </TouchableOpacity>
                                                    </View>
                                                }
                                            
                                            </View> 
                                            )
                                        }
                                        else{
                                            return null;
                                        }
                                    })}
                                    </View>
                                    }                                    
                                </View>
                                               
                            </View>
                        </View>
                    </View>
                );
            }}
            />

            </KeyboardAvoidingView>
        )
    }

    function _renderHeader(currentIndex){        
        return(
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{UpdateShow_zoomImageRef(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }

    const onCancelClean = () =>{
        setDataCleanModal(false)
    }
    const onclear = () => {
        onWindowDataClean(DataCleanItem)
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/> 
        {_OpenCaptureImage_Modal()}       
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,DataCleanModal,onCancelClean,onclear,'Your data will be clean',)}
        <CustomCamera cameraType={'back'} QRCodeEnable={QREnable} onImageCaptured={(imgData)=>{setShowQRCamera(false);onQRScanned(imgData)}} showCamera={showQRCamera} onHideCamera={()=>{setShowQRCamera(false);}}/>   
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} gridEnable={GridValue} 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.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                placeholder={ST.Searchby+' '+currentMenu.MenuName}
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                autoComplete='off'
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View>
          { Object.keys(storeData).length>0 && 
            <View style={customStyle.Windows_Wrap}>
                {_renderWindow()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl}  index={refImageIndex}
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }  
      </Container>   
    ); 
}
  

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