import React,{useState,useEffect,useRef, memo} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated, AppState, 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} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, Fontisto, 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 CameraImg from '../assets/performics/camera_front_image.svg'
import MultiSelect from 'react-native-multiple-select';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

const POSM=memo((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 [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 [dateValue, setDateValue] = useState('');
    const [WindowData, setWindowData] = useState([]);
    const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);
    const [globalWindows, setGlobalWindows] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showCamera, setShowCamera] = 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 [searchedItem, setSearchedItem]= useState('');
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [GridValue, setGridValue] = useState(false);
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [ItemsInView,setItemsInView] = useState([]);

    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 hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(WindowData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');

    const [isKPIPresent, setIsKPIPresent] = useState(0);
    const isKPIPresentAnim=useRef(new Animated.Value(0)).current;
    const isKPIPresentRef=useRef(isKPIPresent)

    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    
    
    const onViewableItemsChanged = ({ viewableItems,}) => {
        // Do stuff
        console.log("onViewableItemsChanged called:")
        setItemsInView(viewableItems);
    };

    const FlatLConfCallbackPairs=useRef([{viewabilityConfig:{itemVisiblePercentThreshold:50},onViewableItemsChanged}]);

    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 cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        
        let isAdhoc=params.isAdhoc || false;
        setStoreCameraAllow(cameraAllow);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1);

        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,
               StoreId1:StoreIdRef.current,
               visiteDate:d2,
               bgisKPIPresent:isKPIPresentRef.current
           }
           let WindowsStr= JSON.stringify(newData)
           
           await set_item('storeData',WindowsStr); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
        // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(WindowData,pro)});
        // AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(WindowData,pro)});
    }, [hasUnsavedChanges]);  
    
    // useEffect(() => {
    //     AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(WindowData,pro)});
    //     AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(WindowData,pro)});
    // }, [WindowData]); 
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [show_zoomImage]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else if(show_zoomImage==true){
            e.preventDefault();
            setShow_zoomImage(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 onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    

    async function getData(storeData1,menu1){        
        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 storeBGData1=[],bgStoreJson={},isBgDataExists=false;
            let windData = await get_item('storeData')
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,visiteDate,bgisKPIPresent }= StoreJson
                if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    isBgDataExists=true;
                    storeBGData1=storeBGData;
                    bgStoreJson=StoreJson
                    BgUnsavedChanges(true)
                    WindowDataRef.current=storeBGData
                    setWindowData(storeBGData);
                    onChoiceSelect_Global(bgisKPIPresent)
                }
            }

            let KPIPresentEnableIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
            let KPIPresentEnableObj=KPIPresentEnableIndex>=0?AllKPIFields[KPIPresentEnableIndex]:{};
            let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
                

            let StorePOSMDefaultReasonI=AllKPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMDefaultReason')
            let StorePOSMDefaultReasonObj=StorePOSMDefaultReasonI>=0?AllKPIFields[StorePOSMDefaultReasonI]:{};
            let StorePOSMDefaultReasonS=StorePOSMDefaultReasonI>=0?StorePOSMDefaultReasonObj['KPIFieldDisplayName']:"0";
            let StorePOSMDefaultReasonArr=StorePOSMDefaultReasonS!=null && StorePOSMDefaultReasonS!=''?StorePOSMDefaultReasonS.split(','):[];
            let StorePOSMDefaultReasonId=StorePOSMDefaultReasonArr.length>0?parseInt(StorePOSMDefaultReasonArr[0]):0;
                

            await db.transaction(async function (txn) {        
                

                let q3=`Select POSMReasonId as ReasonId,POSMReason as Reason,IsRemarkTaken From Master_POSMReason where POSMReasonId not in ('${StorePOSMDefaultReasonId}')`;
                
                await txn.executeSql(q3,[],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);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                setReasons_list(arr);
                            }                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);
                
                

                // check if data exists
                let selectlist=` w.STORE_ID as StoreId,w.POSM_HEADER_ID as posmHeaderId,wd.POSMDefinitionId,wd.PosmId,wd.POSMName,wd.PosmTypeId,wd.POSMTypeName,wd.POSMDefinitionTitle,wd.POSMDefinitionTitleEnable,wd.POSMTable,wd.POSMField,wd.POSMValue,wd.ChildName,wd.POSMRefImage,wd.POSMRefImagePopUp,w.IS_PRESENT as IsPresent,wd.POSMNotExistCamera,w.POSM_NA_IMAGE as POSMNAImage,w.POSM_IMAGE1 as Image1,w.POSM_IMAGE2 as Image2,wd.POSMExistReasonEnable,wd.POSMNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,wd.POSMImage1,wd.POSMImage2,wd.POSMImage1Lable,wd.POSMImage2Lable,wd.POSMImage1CameraGrid,wd.POSMImage2CameraGrid,w.SHOW_RSN_REMARK,w.REASON_REMARK`;
                let join=` inner join Master_POSMDefinition wd on w.POSM_DEFINITION_ID=wd.POSMDefinitionId `;
                let q=` Select ${selectlist} from ${AppTables.POSM_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  order by wd.PosmDefSequence`;

                // else pick data from masters
                let selectlist2=` s.StoreId,w.POSMDefinitionId,w.PosmId,w.POSMName,w.PosmTypeId,w.POSMTypeName,w.POSMDefinitionTitle,w.POSMDefinitionTitleEnable,w.POSMTable,w.POSMField,w.POSMValue,w.ChildName,w.POSMRefImage,w.POSMRefImagePopUp,'' as IsPresent,w.POSMNotExistCamera,'' as POSMNAImage,w.POSMExistReasonEnable,w.POSMNotExistReasonEnable,'' as ReasonId,'' as Reason,w.POSMImage1,w.POSMImage2,w.POSMImage1Lable,w.POSMImage2Lable,w.POSMImage1CameraGrid,w.POSMImage2CameraGrid`;
                let join2=` inner join Mapping_StorePOSM s on w.POSMDefinitionId=s.POSMDefinitionId  `;
                let q2=` Select ${selectlist2} from Master_POSMDefinition w  ${join2} where s.StoreId='${StoreId}' order by w.PosmDefSequence `;
                
                let anyPresent=0;
                await txn.executeSql(q,[],async function (txn2, txnres2) { 

                    if(txnres2.rows.length>0){
                        let arr=[];let images=[],allWindowsData=[],inputChangeFlag=[];
                    
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data=txnres2.rows.item(i);
                            let isPresent=data.IsPresent=='1' || data.IsPresent==1?1:0;
                            if(isBgDataExists){
                                let storeBgIndex=storeBGData1.findIndex(i=>i.POSMDefinitionId==data.POSMDefinitionId && i.PosmId==data.PosmId)
                                let storeBgObj=storeBgIndex>=0?storeBGData1[storeBgIndex]:{};
                                isPresent=storeBgObj.isPresent
                            }

                            // if(isBgDataExists){
                            //     let storeBgIndex=storeBGData1.findIndex(i=>i.PromoId==data.PromoId && i.PromoDefinitionId==data.PromoDefinitionId)
                            //     let storeBgObj=storeBgIndex>=0?storeBGData1[storeBgIndex]:{};
                            //     isPresent=HidePresentYesNoEnable?1:(storeBgObj.isPresent=='1' || storeBgObj.isPresent==1?1:0);
                            //     // let animatedChoice=new Animated.Value(isPresent);
                            //     // data.animatedChoice=animatedChoice;
                            // }

                            let animatedChoice=new Animated.Value(isPresent||0);
                            let animatedHeight = new Animated.Value(450);
                            data.animatedHeight=animatedHeight
                            data.animatedChoice=animatedChoice;

                            if(isPresent==1 || isPresent=='1'){
                                anyPresent=1;
                            }

                            let imgObj={imgIndex:(i+1),url: data.POSMRefImage, props: {}}
                            images.push(imgObj);

                            let WQr =  await getWindowQuestions(data,storeData1,isPresent,menu1);
                            let WindowQuestions = WQr['WindowQuestions'] || [];
                            let WindowQA= WQr['WindowQA'] || {};
                            

                            let isNAImageAvl=data.POSMNotExistCamera=='true' || data.POSMNotExistCamera==1?1:0;
                            let NAImage1=isNAImageAvl==1 && data.POSMNAImage!=null?data.POSMNAImage:'';
                            let NAImage1Path=NAImage1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+NAImage1:'';

                            let isImage1= data.POSMImage1=='true' || data.POSMImage1==1?1:0;
                            let Image1Name=isImage1==1 && data.Image1!=null?data.Image1:'';
                            let Image1=Image1Name!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+Image1Name:'';
                            console.log('IsPresent in save',data.IsPresent)
                            
                            let isImage2= data.POSMImage2=='true' || data.POSMImage2==1?1:0;
                            let Image2Name=isImage1==1 && data.Image2!=null?data.Image2:'';
                            let Image2=Image2Name!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+Image2Name:'';
                            let showRsnRemark=((data.SHOW_RSN_REMARK=='1' || data.SHOW_RSN_REMARK==1 )?true:false);

                            let windowDataObj={'PosmId':data.PosmId,'POSMDefinitionId':data.POSMDefinitionId,'WindowQA':WindowQA,'NAImage1':NAImage1,'NAImage1Path':NAImage1Path,'ReasonId':data.ReasonId,'Reason':data.Reason,'isPresent':isPresent,'Image1Name':Image1Name,'Image1':Image1,'Image2Name':Image2Name,'Image2':Image2,'showOtherText':showRsnRemark,'RemarkText':(data.REASON_REMARK || '')};
                            data['WindowQuestions']=WindowQuestions;
                            
                            let item_change_flag=KPIPresentEnable && data.ReasonId!=null && parseInt(data.ReasonId)==StorePOSMDefaultReasonId?false:true;
                            console.log('data.ReasonId',data.ReasonId,StorePOSMDefaultReasonId,item_change_flag);
                            let changesFlag = {PosmId:data.PosmId, POSMDefinitionId: data.POSMDefinitionId, Flag:item_change_flag}
                            inputChangeFlag.push(changesFlag)
                            
                            arr.push(data);
                            
                            allWindowsData.push(windowDataObj);
                            if(i==txnres2.rows.length-1){
                                let { menuName,StoreId1,visiteDate }=bgStoreJson
                                if(!isBgDataExists){
                                    WindowDataRef.current=allWindowsData
                                    setWindowData(allWindowsData);
                                }
                                if(KPIPresentEnable && anyPresent==1){
                                    onChoiceSelect_Global(1);
                                }
                                setInputChange(inputChangeFlag)
                                setWindows(arr);
                                setGlobalWindows(arr);
                                setZoomImageUrl(images);
                                setProcessing(false);
                            }                                
                        }
                    }
                    else{
                        await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                            
                            if(txnres2.rows.length>0){
                                let arr=[],images=[],allWindowsData=[],inputChangeFlag=[];
                                
                                for(var i=0;i<txnres2.rows.length;i++){
                                    let data=txnres2.rows.item(i);
                                    let isPresent=0;
                                    if(isBgDataExists){
                                        let storeBgIndex=storeBGData1.findIndex(i=>i.POSMDefinitionId==data.POSMDefinitionId && i.PosmId==data.PosmId)
                                        let storeBgObj=storeBgIndex>=0?storeBGData1[storeBgIndex]:{};
                                        isPresent=storeBgObj.isPresent
                                    }
        
                                    let animatedChoice=new Animated.Value(isPresent||0);
                                    let animatedHeight = new Animated.Value(450);
                                    data.animatedHeight=animatedHeight
                                    data.animatedChoice=animatedChoice;

                                    let imgObj={imgIndex:(i+1),url: data.POSMRefImage, props: {}}
                                    images.push(imgObj);

                                    let WQr =  await getWindowQuestions(data,storeData1,false,menu1);
                                    let WindowQuestions = WQr['WindowQuestions'] || [];
                                    let WindowQA= WQr['WindowQA'] || {};
                                    let WindowSplits =  [];
                                    for(var s=0;s<data.NoOfSplit;s++){
                                        let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':'',img1Required:true, img2Required:true};
                                        WindowSplits.push(obj);
                                    }

                                    let windowDataObj={'PosmId':data.PosmId,'POSMDefinitionId':data.POSMDefinitionId,'WindowQA':WindowQA, img1Required:true, img2Required:true};
                                    data['WindowQuestions']=WindowQuestions;

                                    let changesFlag = {PosmId:data.PosmId, POSMDefinitionId: data.POSMDefinitionId, Flag:false}
                                    inputChangeFlag.push(changesFlag)
                                    arr.push(data);
                                    allWindowsData.push(windowDataObj);
                                    if(i==txnres2.rows.length-1){   
                                        let { menuName,StoreId1,visiteDate }=bgStoreJson
                                        setInputChange(inputChangeFlag)
                                        if(!isBgDataExists){
                                            WindowDataRef.current=allWindowsData
                                            setWindowData(allWindowsData);
                                        }

                                        setWindows(arr);
                                        setGlobalWindows(arr);
                                        setZoomImageUrl(images);
                                        setProcessing(false);
                                    }                                
                                }
                            }
                            else{
                                setProcessing(false);
                            }
                        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
                    }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);

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

    async function getWindowQuestions(window,storeData1,isInserted=false,menu1){
        let obj={'WindowQA':{},'WindowQuestions':[]}
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                var q='',selectlist='',join='',join2='';
                if(isInserted==true){
                    selectlist=` DISTINCT  q.QUESTION_ID as POSMQuestionId,q.QUESTION_CODE as POSMQuestionCode,wq.POSMQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PAShowCamera,q.IMAGE1 as Image1  `;
                    join2=` inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId `;
                    join=` inner join Master_POSMQuestion wq on wq.POSMQuestionId=q.QUESTION_ID `;
                    q=`select ${selectlist} from ${AppTables.POSM_CHILD_DATA} q ${join} ${join2} where q.STORE_ID='${storeData1.StoreId}' and q.POSM_DEFINITION_ID='${window.POSMDefinitionId}' and q.POSM_ID='${window.PosmId}' order by wq.POSMQuestionSequence  `;
                }
                else{
                    selectlist=` DISTINCT  wq.POSMQuestionId,wq.POSMQuestionCode,wq.POSMQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable `;
                    join=` inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId `;
                    q=`select ${selectlist} from Master_POSMQuestion wq ${join} where mq.POSMDefinitionId='${window.POSMDefinitionId}' order by wq.POSMQuestionSequence  `;
                }
               
                await txn.executeSql(q,[],async function (txn2, txnres2) { 

                    if(txnres2.rows.length>0){
                        let arr=[];
                        let wqa_obj={};
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let answers=[];
                            data.PQDefaultQuestionEnable=data.PQDefaultQuestionEnable==1 || data.PQDefaultQuestionEnable=='true'?true:false;
                             
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  answers=await getWindowAnswers(data);
                                  if(data.QuestionType=='Rating'){
                                      data.showRating=false;
                                  }
                              }
                              else if(data.QuestionType=='Date'){
                                  data.showDatePicker=false;
                              }
                              data['Answers']=answers;
      
                              let id_key=data.POSMQuestionId+'_AnswerId'; 
                              let ans_key=data.POSMQuestionId+'_Answer'; 
                              let multi_key=data.POSMQuestionId+'_MultiOption';
                              let date_key=data.POSMQuestionId+'_Date';
                              let img_key=data.POSMQuestionId+'_ImagePath1';
                              let imgname_key=data.POSMQuestionId+'_ImageName1';
                              let rating_key=data.POSMQuestionId+'_Rating'; 
                              
      
                              let showImageTag=(data.PQShowCamera=='true' || data.PQShowCamera==1) ;
      
                              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!='' && 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=='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 isandImgAl=(ansss.PAShowCamera==1 || ansss.PAShowCamera=='true');
                                          if(data.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(data.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                              showImageTag=true;
                                          }
                                      }
                                  }
                              }
      
                              if(showImageTag && data.Answer!=null){
                                 
                                  let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image1;
                                  wqa_obj[imgname_key]=data.Image1;
                                  wqa_obj[img_key]=imgPath;
                              }

                             
      
                              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);
                            if(i==txnres2.rows.length-1){
                                obj['WindowQuestions']=arr;
                                obj['WindowQA']=wqa_obj;
                                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 getWindowAnswers(qtn){
        
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='';
                selectlist=` DISTINCT  POSMAnswerId as AnswerId,POSMAnswerName as Answer,PAShowCamera,PACameraMandatory,PAQuestionEnable,PAQuestionDisable `;
                q=`select ${selectlist} from  Master_POSMQuestion  where POSMQuestionId='${qtn.POSMQuestionId}'  order by PASequence  `;

                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);
                            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 getImage(imgdata){
        let type=getImageProps.type || '';
        let window=getImageProps.window || {};
        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+'_'+window.POSMDefinitionId+'_'+window.PosmId+'_'+(props.UserId || '')+'_POSMImg-'+calculate_tym_date_for_filename+'.jpg';
            
            let allData=WindowData;
            let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
            const wind_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId) ;
            let wind=wind_index>=0?allData[wind_index]:defData;
            
            let camera1Label=window.POSMImage1Lable || '';
            let camera2Label=window.POSMImage2Lable || '';
            let extraLabel='';

            if(cameraType=='2'){
                
                var QD=wind.WindowQA || {};
                var image_key=qtn.POSMQuestionId+'_ImageName1';
                var image_key_path=qtn.POSMQuestionId+'_ImagePath1';
                QD[image_key]=filename;
                extraLabel='Qtn Id: '+qtn.POSMQuestionId;
                
            }
            else if(cameraType=='3'){
                var image_key='NAImage1';
                var image_key_path='NAImage1Path';
                wind[image_key]=filename;
                extraLabel='Not Exist';
            }
            else{
                var image_key=type=='1'?'Image1Name':'Image2Name';
                var image_key_path=type=='1'?'Image1':'Image2';
                wind[image_key]=filename;
                extraLabel=type=='1'?camera1Label:camera2Label;
            }
            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | POSMName:'+window.POSMName+"("+window.POSMDefinitionId+")"+(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;
                console.log('image marker',uri);
                
                if(cameraType=='2'){
                    QD[image_key_path]=uri;
                    wind.WindowQA=QD;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata3(!rerenderdata3);
                }
                else{
                    wind[image_key_path]=uri;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                let objIndex = InputChange.findIndex((obj => obj.PosmId == window.PosmId && obj.POSMDefinitionId==window.POSMDefinitionId));
                let winArr=[...InputChange]
                winArr[objIndex].Flag=true
                setSelectedImg(uri)
                setInputChange(winArr)

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);

            })
            .catch(err => {
                console.log('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });   
        }        
    }
  
    async function openCamera(window,type='1',cameraType='1',qtn={}){ 
        setErrorField({});
        setError(false);
        let GridAllow = cameraType=='1' ? ( type==='1' ? (window.POSMImage1CameraGrid === 'true' || window.POSMImage1CameraGrid==true): (window.POSMImage2CameraGrid === 'true' || window.POSMImage2CameraGrid==true)):false
        setGridValue(GridAllow); 
        setGetImageProps({'window':window,'type':type,'cameraType':cameraType,'qtn':qtn}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

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

      function cancelImage(){
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
      }
   
    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData(){
        setErrorField({});
        setError(false);
        // 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;
            await db.transaction(async function (txn) {   

              //  remove old data
              await txn.executeSql(`DELETE FROM ${AppTables.POSM_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                  console.log('window hdr data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);
              await txn.executeSql(`DELETE FROM ${AppTables.POSM_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                  console.log('window child data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              
             
                // add data
                var values='',childV='';
                let KPIPresentEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
                let KPIPresentEnableObj=KPIPresentEnableIndex>=0?KPIFields[KPIPresentEnableIndex]:{};
                let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
                
                let StorePOSMDefaultReasonI=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMDefaultReason')
                let StorePOSMDefaultReasonObj=StorePOSMDefaultReasonI>=0?KPIFields[StorePOSMDefaultReasonI]:{};
                let StorePOSMDefaultReasonE=StorePOSMDefaultReasonI>=0?StorePOSMDefaultReasonObj['KPIFieldEnable']:true;
                let StorePOSMDefaultReasonS=StorePOSMDefaultReasonI>=0?StorePOSMDefaultReasonObj['KPIFieldDisplayName']:"0";
                let StorePOSMDefaultReasonArr=StorePOSMDefaultReasonS!=null && StorePOSMDefaultReasonS!=''?StorePOSMDefaultReasonS.split(','):[];
                let StorePOSMDefaultReasonId=StorePOSMDefaultReasonArr.length>0?parseInt(StorePOSMDefaultReasonArr[0]):0;
                let StorePOSMDefaultReason=StorePOSMDefaultReasonArr.length>1?StorePOSMDefaultReasonArr[1]:"";
                
                let showList=(KPIPresentEnable && isKPIPresent) || (KPIPresentEnable==false);

              
                for (const wi in Windows){
                    const window=Windows[wi];
                    let isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                    let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                    let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                    let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                    let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                    let WindowQuestions=window.WindowQuestions || [];
                    
                   
                    const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                    let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                    let ReasonId=wind.ReasonId!=null?wind.ReasonId:0;
                    let Reason=wind.Reason!=null?wind.Reason:'';
                    let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                    let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                    let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                    let Image1=wind.Image1!=null?wind.Image1:'';
                    let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                    let Image2=wind.Image2!=null?wind.Image2:'';
                   
                    let QD=wind.WindowQA || {};

                    let POSM_HEADER_ID='POSM'+wi+(Math.floor(Math.random()*1000)+1);
                    let {POSMDefinitionId,PosmId,POSMName,PosmTypeId,POSMTypeName,POSMTable,POSMField,POSMValue,ChildName}=window;
                    let showOtherText=wind.showOtherText==true || wind.showOtherText=='1' ?1:0;
                    let RemarkText=wind.RemarkText!=null?wind.RemarkText:'';

                    
                    values+=values!=''?' , ':'';
                    if(showList){
                        values+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMName}','${PosmTypeId}','${POSMTypeName}','${POSMTable}','${POSMField}','${POSMValue}','${ChildName}','${isPresent}','${NAImage1}','${Image1Name}','${Image2Name}','${ReasonId}','${Reason}','${showOtherText}','${RemarkText}','1','${d3}') `;
                    }
                    else{
                        values+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMName}','${PosmTypeId}','${POSMTypeName}','${POSMTable}','${POSMField}','${POSMValue}','${ChildName}','0','${NAImage1}','','','${StorePOSMDefaultReasonId}','${StorePOSMDefaultReason}','${showOtherText}','${RemarkText}','1','${d3}') `;
                    }

                    if(isPresent==1){
                        for(const qtnIndex in WindowQuestions){
                            const qtn=WindowQuestions[qtnIndex];
                            
                            let selansid='',selanswer='',selimg='',showImageTag=false;
                            let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                            let ans_key=qtn.POSMQuestionId+'_Answer'; 
                            let multi_key=qtn.POSMQuestionId+'_MultiOption';
                            let date_key=qtn.POSMQuestionId+'_Date';
                            let img_key=qtn.POSMQuestionId+'_ImagePath1';
                            let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                            let rating_key=qtn.POSMQuestionId+'_Rating'; 
                          

                            let {POSMQuestionId,POSMQuestionCode,QuestionType,PAShowCamera}=qtn
                            let answer=QD[ans_key] || '';
                            let answerId=QD[id_key] || 0;
                            let multi_options_ids=QD[multi_key] || '';
                            
                            if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                            {
                                showImageTag=(qtn.PQShowCamera==1 || qtn.PQShowCamera=='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.PAShowCamera=='true' || ansss.PAShowCamera==1);
                                       
                                        if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==answerId)){
                                            showImageTag=true;
                                        }
                                        else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && answerId.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag=true;
                                        }
                                        
                                    }
                                }
                            }

                            let Image1=showImageTag==1?QD[imgname_key]:'';
                          

                            childV+=childV!=''?' , ':'';
                            childV+=` ('${POSM_HEADER_ID}','${StoreId}','${d3}','${POSMDefinitionId}','${PosmId}','${POSMQuestionId}','${POSMQuestionCode}','${QuestionType}','${answer}','${answerId}','${multi_options_ids}','${Image1}','${(PAShowCamera=='true' || PAShowCamera==true?1:0)}','${d3}') `;
                        }
                    }
                }
              
               
                
                let add_hdr_data=`INSERT INTO ${AppTables.POSM_HDR_DATA} (POSM_HEADER_ID,STORE_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,POSM_NAME,POSM_TYPE_ID,POSM_TYPE_NAME,POSM_TABLE,POSM_FIELD,POSM_VALUE,CHILD_NAME,IS_PRESENT,POSM_NA_IMAGE,POSM_IMAGE1,POSM_IMAGE2,REASON_ID,REASON,SHOW_RSN_REMARK,REASON_REMARK,IS_UPDATED,ADDED_DATE) VALUES ${values} `;
                let add_child_data=`INSERT INTO ${AppTables.POSM_CHILD_DATA} (POSM_HEADER_ID,STORE_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE) VALUES ${childV} `;
                
                await txn.executeSql(add_hdr_data,[],async function (txn2, txnres) { 
                    console.log('posm header data added');
                    var isChildAdded=true;
                   
                    if(childV!=''){
                        isChildAdded=await executeQuery(add_child_data);
                    }

                    if(!isChildAdded){
                        setProcessing(false);notify(ST.Cannotaddposmquestionsdata);
                    }
                    else{
                        clear_item('storeData')
                        setProcessing(false);notify(ST.POSMdataupdatedsuccessfully);
                        props.navigation.goBack();
                    }
                       
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotaddPOSMdata); },);
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    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);
        }

        let KPIPresentEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
        let KPIPresentEnableObj=KPIPresentEnableIndex>=0?KPIFields[KPIPresentEnableIndex]:{};
        let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
        
        let StorePOSMDefaultReasonI=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMDefaultReason')
        let StorePOSMDefaultReasonObj=StorePOSMDefaultReasonI>=0?KPIFields[StorePOSMDefaultReasonI]:{};
        let StorePOSMDefaultReasonS=StorePOSMDefaultReasonI>=0?StorePOSMDefaultReasonObj['KPIFieldDisplayName']:"0";
        let StorePOSMDefaultReasonArr=StorePOSMDefaultReasonS!=null && StorePOSMDefaultReasonS!=''?StorePOSMDefaultReasonS.split(','):[];
        let StorePOSMDefaultReasonId=StorePOSMDefaultReasonArr.length>0?parseInt(StorePOSMDefaultReasonArr[0]):0;
                

        let showList=(KPIPresentEnable && isKPIPresent) || (KPIPresentEnable==false);
       
        if(showList){

        return new Promise((resolve,reject)=>{
            for (const [wi, window] of globalWindows.entries()) {
                let isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                let WindowQuestions=window.WindowQuestions || [];
                
               
                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                let Image2=wind.Image2!=null?wind.Image2:'';
                let QD=wind.WindowQA || {};
                let showOtherText=wind.showOtherText!=null?wind.showOtherText:false;

                let errorobj = {'EF_Window':window};

                if(isPresent=='1'){
                    if(isReasonEnable==true && ReasonId=='' ){
                        errorobj['EF_NExistReason']="NExistReason";
                        showError(errorobj,true);
                        notify(`${ST.Pleaseselectreasonfor} ${window.POSMName} `,'LONG');
                        resolve(false);return;
                    }
                    else{
                        if(StoreCameraAllow && isImage1==1 && Image1Name==''){
                            errorobj['EF_splitImage1']="splitImage1";
                            showError(errorobj,true);
                            notify(`${ST.Pleaseclickallimagesfor} ${window.POSMName}`,'LONG');
                            resolve(false);return;
                        }
                        else if(StoreCameraAllow && isImage2==1 && Image2Name==''){
                            errorobj['EF_splitImage1']="splitImage1";
                            showError(errorobj,true);
                            notify(`${ST.Pleaseclickallimagesfor} ${window.POSMName}`,'LONG');
                            resolve(false);return;
                        }
                        else if(WindowQuestions.length>0){
                            for(const qtnIndex in WindowQuestions){
                                const qtn=WindowQuestions[qtnIndex];
                                
                                let selansid='',selanswer='',selimg='',showImageTag=false;
                                let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                                let ans_key=qtn.POSMQuestionId+'_Answer'; 
                                let multi_key=qtn.POSMQuestionId+'_MultiOption';
                                let date_key=qtn.POSMQuestionId+'_Date';
                                let img_key=qtn.POSMQuestionId+'_ImagePath1';
                                let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                                let rating_key=qtn.POSMQuestionId+'_Rating'; 
                                let list_mcdata=[];
                                
                                errorobj['EF_qtn']=qtn;

                                let isImgAllowed=(qtn.PQShowCamera=='true' || qtn.PQShowCamera==1);
                                let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating') ;
                                if(qtn.QuestionType=='Single choice list')
                                {
                                    selansid=QD[id_key];
                                }
                                else if(qtn.QuestionType=='Multi choice list')
                                {
                                    selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
                                }
                                
                            
                                if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                                    errorobj['EF_Qtn_MultiChoice']='Qtn_MultiChoice';
                                    showError(errorobj,true);
                                    notify(`${ST.Pleaseselectoptionsfortherequiredfield} ${ST.In} ${window.POSMName}`,'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} ${window.POSMName}`:(qtn.QuestionType=='Rating'?`${ST.Pleaseselectratingfortherequiredfield} ${ST.In} ${window.POSMName}`:`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.POSMName}`));
                                    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]==='' || (QD[id_key]===0 && qtn.isDisabled===false) ))){
                                    errorobj['EF_Qtn_Input']='Qtn_Input';
                                    showError(errorobj,true);
                                    notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }
                                else if(StoreCameraAllow && isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                    errorobj['EF_Qtn_Image']='Qtn_Image';
                                    showError(errorobj,true);
                                    notify(`${ST.Pleaseaddimages} ${ST.In} ${window.POSMName}`,'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 isandImgAl=(ansss.PAShowCamera=='true' || ansss.PAShowCamera==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(StoreCameraAllow && showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                    errorobj['EF_Qtn_Image']='Qtn_Image';
                                    showError(errorobj,true);
                                    notify(`${ST.Pleaseaddimages} ${ST.In} ${window.POSMName}`,'SHORT');
                                    resolve(false);return;
                                }
                            }
                        }
                    }
                }
                else{
                    if(isNAReasonEnable==true && (ReasonId=='' || ReasonId==StorePOSMDefaultReasonId) ){
                        errorobj['EF_NExistReason']="NExistReason";
                        showError(errorobj,true);
                        notify(`${ST.Pleaseselectreasonfor} ${window.POSMName} `,'LONG');
                        resolve(false);return;
                    }
                    else if(isNAReasonEnable==true && showOtherText==true && (wind.RemarkText==null || wind.RemarkText=='') ){
                        errorobj['EF_NExistRemark']="NExistRemark";
                        showError(errorobj,true);
                        notify(`${ST.PleaseEnterRemarkFor} ${window.POSMName} `,'LONG');
                        resolve(false);return;
                    }
                    else if(StoreCameraAllow && isNAImageAvl==true && NAImage1=='' ){
                        errorobj['EF_NExistImage']="NExistImage";
                        showError(errorobj,true);
                        notify(`${ST.Pleaseclickimagefor} ${window.POSMName}`,'LONG');
                        resolve(false);return;
                    }
                }

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

        }
        else{
        return true;
        }
    }


    function onselectionChange(option,keyLbl,keyVal,otherData){
        setErrorField({});
        setError(false);
        let item=otherData.window;
        let allData=WindowData;
        let defData={'PosmId':item.PosmId,'POSMDefinitionId':item.POSMDefinitionId};
        const win_index=allData.findIndex(i=>i.PosmId==item.PosmId && i.POSMDefinitionId==item.POSMDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[keyVal]=option.value;
        wind[keyLbl]=option.label;

        if(keyLbl=='Reason'){
            let rsn_Index=reasons_list.findIndex(i=>i.ReasonId==option.value);
           
            if(rsn_Index>=0){
                let rsn=reasons_list[rsn_Index];
                let IsRemarkTaken=rsn.IsRemarkTaken==1 || rsn.IsRemarkTaken=='1'?true:false;
                
                if(IsRemarkTaken==true){
                    wind['showOtherText']=true;
                }
            }
        }

        win_index>=0?allData[win_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex((obj => obj.PosmId == item.PosmId && obj.POSMDefinitionId==item.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)

        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange2(option,qtn,window){
        setErrorField({});
        setError(false);
        let allData=WindowData;
        let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
        const wind_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let data=wind.WindowQA || {};
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        data[id_key]=option.value;
        data[ans_key]=option.label;
        

        wind['WindowQA']=data;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
      
        let objIndex = InputChange.findIndex((obj => obj.PosmId == window.PosmId && obj.POSMDefinitionId==window.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)
        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.WAQuestionEnable!=null && ans_obj.WAQuestionEnable!=''?ans_obj.WAQuestionEnable.replace(' ','').split(','):[];
        let DQtns=ans_obj.WAQuestionDisable!=null && ans_obj.WAQuestionDisable!=''?ans_obj.WAQuestionDisable.replace(' ','').split(','):[];
      
        let sqtns=window.WindowQuestions || []

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

    async function disableQtns(sqtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
       
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.POSMQuestionId==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.POSMQuestionId+'_AnswerId'; 
                        let ans_key=s_qtn.POSMQuestionId+'_Answer'; 
                        data[id_key]=0;
                        data[ans_key]='';

                        wind['WindowQA']=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.POSMDefinitionId==window.POSMDefinitionId && i.PosmId==window.PosmId)
                if(windowIndex>0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    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={}){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.POSMQuestionId==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){
                disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            }
            else{
                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.POSMDefinitionId==window.POSMDefinitionId && i.PosmId==window.PosmId)
                if(windowIndex>0){
                    window['WindowQuestions']=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.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let multi_key=qtn.POSMQuestionId+'_MultiOption';
       
        let allData=WindowData;
        let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
        const wind_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};
        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(',');
       
        
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex((obj => obj.PosmId == window.PosmId && obj.POSMDefinitionId==window.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value,qtn,window,type='') {  
        setErrorField({});
        setError(false);      
        if(value!=''){
            let isValid=validateNumber(value,type);
            if(!isValid){
                return;
            }
        }
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        
        let allData=WindowData;
        let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
        const wind_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};

        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.POSMQuestionId+'_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;
        }
        
    
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        // setInputChange([...InputChange,{PosmId:window.PosmId, Flag:true}])
        let objIndex = InputChange.findIndex((obj => obj.PosmId == window.PosmId && obj.POSMDefinitionId==window.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------1",winArr)
        setInputChange(winArr)
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.POSMQuestionId==qtn.POSMQuestionId);
       
        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.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId) || {};
            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.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let rating_key=qtn.POSMQuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })

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

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

        let objIndex = InputChange.findIndex((obj => obj.PosmId == window.PosmId && obj.POSMDefinitionId==window.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true
        console.log("changeValue---------7",winArr)

        setInputChange(winArr)
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }
    
   
    function onChoiceSelect(item,val,key,animatedChoice){
        let win_index=InputChange.find(i=> i.PosmId==item.PosmId && i.POSMDefinitionId==item.POSMDefinitionId)
        let changeValue=win_index.Flag;
        console.log("changeValue--------",changeValue,win_index,InputChange)
        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 onChoiceSelect_Global(val){
        console.log("onChoiceSelect_Global val:",val)
        Animated.timing(isKPIPresentAnim, {
            toValue: val,
            duration:400,
            useNativeDriver:false,
        }).start();
        isKPIPresentRef.current=val;
        hasUnsavedChangesRef.current=true
        setIsKPIPresent(val);
    }

    function onWindowDataChange(item,val,key,type=''){
        setErrorField({});
        setError(false);
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        let allData=WindowData;
        let defData={'PosmId':item.PosmId,'POSMDefinitionId':item.POSMDefinitionId};
        const win_index=allData.findIndex(i=>i.PosmId==item.PosmId && i.POSMDefinitionId==item.POSMDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

        if(key=='ReasonId'){
            let rsn=reasons_list.find(r=>r.ReasonId==val) || {};
            wind['Reason']=rsn.Reason || '';
        }

        win_index>=0?allData[win_index]=wind:allData.push(wind);

        if(key!="isPresent"){
            let objIndex = InputChange.findIndex((obj => obj.PosmId == item.PosmId && obj.POSMDefinitionId==item.POSMDefinitionId));
            let winArr=[...InputChange]
            winArr[objIndex].Flag=true
            setInputChange(winArr)
        }
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onWindowDataClean(){
        if(DataCleanAnim!=null){
            console.log("anim---")
            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':''};
            WindowSplits.push(obj);
        }

        console.log("isPresentClean-------",isPresentClean,"----",isPresentClean==1?0:1)
        let defData={'PosmId':DataCleanItem.PosmId,'POSMDefinitionId':DataCleanItem.POSMDefinitionId,'isAllSKUChecked':0,'WindowSplits':WindowSplits,'WindowQA':{},'WStocksData':[],isPresent:isPresentClean};
        const win_index=allData.findIndex(i=>i.PosmId==DataCleanItem.PosmId && i.POSMDefinitionId==DataCleanItem.POSMDefinitionId);
        allData[win_index]=defData

        let objIndex = InputChange.findIndex((obj => obj.PosmId == DataCleanItem.PosmId && obj.POSMDefinitionId==DataCleanItem.POSMDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=false
        console.log("changeValue---------7",winArr)
        setInputChange(winArr)
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setDataCleanModal(false)
        setrerenderdata(!rerenderdata);
    }

    function setWindowStockVal(val,window,stockProd){
        setErrorField({});
        setError(false);
        let allData=WindowData;
        let defData={'PosmId':window.PosmId,'POSMDefinitionId':window.POSMDefinitionId};
        const win_index=allData.findIndex(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        let sdIndex=WStocksData.findIndex(i=> i.ProductId==stockProd.WindowStockValue);
        let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.WindowStockValue,'Stock':''};
        sd['Stock']=val;
        sdIndex>=0?WStocksData[sdIndex]=sd:WStocksData.push(sd);
        wind['WStocksData']=WStocksData;
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        setWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata4(!rerenderdata4);
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

  

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


    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
        let ans_key=qtn.POSMQuestionId+'_Answer'; 
        let rating_key=qtn.POSMQuestionId+'_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] };
            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}
            cancelText={ST.Cancel}
            >
            <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)}
            />    
        );
    }

    function _renderKPIPresent(){
       
        let KPIPresentEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
        let KPIPresentEnableObj=KPIPresentEnableIndex>=0?KPIFields[KPIPresentEnableIndex]:{};
        let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
        let KPIPresentEnableDisName=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldDisplayName']:"Is Present";

        if(KPIPresentEnable==true){

            let xpos=0;
            xpos=isKPIPresentAnim.interpolate({
                inputRange:[0,1],
                outputRange:[0,-75],
            });
            

            return(
            <View style={[customStyle.addvis_pCon]}>
                <Text style={[customStyle.addvis_pText]}>{KPIPresentEnableDisName}</Text>
                <View style={customStyle.addvis_pChoiceBoxCon}>
                    <View style={[customStyle.openStk_prd_choiceBox,customStyle.addvis_pChoiceBoxbg]}>
                        <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isKPIPresent==1?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                        {
                            transform: [{
                                translateX:xpos
                            }],
                        }
                        ]}></Animated.View>
                        <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect_Global(1)}}>
                            <Text style={[customStyle.openStkCh_text,(isKPIPresent==1?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect_Global(0)}}>
                            <Text style={[customStyle.openStkCh_text,(isKPIPresent==0?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
            )
        }
        else{
            return null;
        }
    }

    function _renderWindow(){
        let KPIPresentEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
        let KPIPresentEnableObj=KPIPresentEnableIndex>=0?KPIFields[KPIPresentEnableIndex]:{};
        let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
        
        let showList=(KPIPresentEnable && isKPIPresent) || (KPIPresentEnable==false);
        if(showList){
        return (
            <FlatList 
            data={Windows}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.Win_scroll} 
            style={customStyle.Win_scrollO}
            viewabilityConfigCallbackPairs={
                FlatLConfCallbackPairs.current
            }
            listKey={(item, index) => `posm_${index.toString()}`}
            renderItem={({item,index})=>{
                const window=item;
                
                let isImage1=window.POSMImage1=='true' || window.POSMImage1==1?1:0;
                let isImage2=window.POSMImage2=='true' || window.POSMImage2==1?1:0;
                let isNAImageAvl=window.POSMNotExistCamera=='true' || window.POSMNotExistCamera==1?1:0;
                let isNAReasonEnable=window.POSMNotExistReasonEnable=='true' || window.POSMNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.POSMExistReasonEnable=='true' || window.POSMExistReasonEnable==1? 1:0;
                let POSMTitleEnable=window.POSMDefinitionTitleEnable=='true' || window.POSMDefinitionTitleEnable==1? 1:0;
                let POSMTitle=window.POSMDefinitionTitle!=null && window.POSMDefinitionTitle!='undefined'? window.POSMDefinitionTitle:"";
                let POSMRefImagePopUp=window.POSMRefImagePopUp=='true' || window.POSMRefImagePopUp==true? true:false;

                let RefImage=window.POSMRefImage;
                let camera1Label=window.POSMImage1Lable || '';
                let camera2Label=window.POSMImage2Lable || '';
                let WindowQuestions=window.WindowQuestions || [];

                let isVisible=Boolean(ItemsInView.find(({item:i,isViewable}) => i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId && isViewable))
                // console.log("RenderItemList ItemsInView2:",index,isVisible)

                const wind=WindowData.find(i=>i.PosmId==window.PosmId && i.POSMDefinitionId==window.POSMDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let showOtherText=wind.showOtherText!=null?wind.showOtherText:false;
                let RemarkText=wind.RemarkText!=null?wind.RemarkText:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let QuestionsData=wind.WindowQA || {};
                let Image1Name=wind.Image1Name!=null?wind.Image1Name:'';
                let Image1=wind.Image1!=null?wind.Image1:'';
                let Image2Name=wind.Image2Name!=null?wind.Image2Name:'';
                let Image2=wind.Image2!=null?wind.Image2:'';

                let isImg1mad=wind['img1Required'] || false;
                let isImg2mad=wind['img2Required'] || false;


                var xpos=isPresent=='1'||isPresent==1?-75:0;
                
                if(window.animatedChoice!=null ){
                    xpos=window.animatedChoice.interpolate({
                        inputRange:[0,1],
                        outputRange:[0,-75],
                    });
                }

                if(isVisible && window.animatedHeight!=null){
                    setTimeout(()=>{
                    Animated.timing(window.animatedHeight, {
                        toValue: 0,
                        duration: 800,
                        useNativeDriver: false,
                        }).start();
                    },(props.RefImagePopUpTime||0)*1000)
                }
             
                let EF_Window=errorfield.EF_Window!=null ?errorfield.EF_Window:{};
                let show_errorhere=error==true && EF_Window.PosmId==window.PosmId && EF_Window.POSMDefinitionId==window.POSMDefinitionId;
                
                // 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:{};
                

                // highlight slit image box 
                let EF_splitImage1=errorfield.EF_splitImage1 || '';
                let EStyle_splitImage1=show_errorhere && EF_splitImage1=='splitImage1'?customStyle.error_CatImage2:{};

                let EF_splitImage2=errorfield.EF_splitImage2 || '';
                let EStyle_splitImage2=show_errorhere && EF_splitImage2=='splitImage2'?customStyle.error_CatImage2:{};

                

                return(
                    <View style={customStyle.WItem_wrap} key={'window_'+index}>
                        <View style={customStyle.WItem_Hdr}>                            
                            {/* <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.WItem_Hdrbg}> */}
                            <View style={customStyle.WItem_Hdrbg}>
                                <Text style={customStyle.WItem_HdrText}>{window.POSMName}</Text>
                                {(POSMTitleEnable==1 && POSMTitle!=null && POSMTitle!='') && <Text style={customStyle.WItem_HdrSubTitleText}>{POSMTitle}</Text>}
                                <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={()=>{openImageRefView(index)}}>
                                    <Entypo name='image-inverted' size={24} color={PageTheme.$accent_color} />    
                                </TouchableOpacity>
                            </View>
                            {/* </LinearGradient> */}
                        </View>
                        { POSMRefImagePopUp && <Animated.View
                            style={[{
                                    backgroundColor: "#fff",
                                    width: "100%",
                                    // height: 300,
                                    height: window.animatedHeight,
                                    // borderRadius: 10,
                                    paddingBottom:10,
                                    // shadowColor: "#000",
                                    // elevation: 5
                                }]}
                            >
                            <Image  style={[{width:"100%",height:'100%'}]} resizeMode='contain' source={{uri:RefImage}} />
                            
                        </Animated.View>}
                        
                        <View style={customStyle.WForm}>
                            <View style={[customStyle.openStk_prd_cols,customStyle.mt10]}>
                                <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                    <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                                    <View style={customStyle.openStk_prd_choiceBoxCon}>
                                        <View style={customStyle.openStk_prd_choiceBox}>
                                            <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isPresent=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                            {   transform: [{   translateX:xpos }],  }]}></Animated.View>
                                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(window,1,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,(isPresent=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                            </TouchableOpacity>
                                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(window,0,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,(isPresent=='0'?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                                {((isPresent!='1' && isNAReasonEnable==true) || (isPresent=='1' && isReasonEnable==true)) &&
                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange} selected_data={{value:Reason,otherData:{window:window}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} ErrorStyle={EStyle_NExistReason} ShowError={error} />}
                                    </View>
                                }
                                {isPresent!='1' && showOtherText==true && 
                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.EnterRemark}</Text>
                                        <TextInput 
                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,EStyle_NExistRemark]}              
                                            placeholder=""    
                                            autoComplete='off'        
                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                            value={RemarkText}
                                            onChangeText={(val)=>{onWindowDataChange(window,val,'RemarkText','text')}}
                                        />
                                    </View>
                                }


                                {(isPresent!='1' && isNAImageAvl==true) && 
                                <View>
                                    <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}>{ST.CaptureImage}</Text>
                                    </LinearGradient>
                                    <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]}>
                                        <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                        { (NAImage1Path=='' || NAImage1Path==null) && 
                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin,EStyle_NExistImage]} onPress={()=>{openCamera(window,'1','3')}}>
                                                <CameraImg width={80} height={80} />                                     
                                            </TouchableOpacity>
                                        }
                                        { (NAImage1Path!='' && NAImage1Path!=null) && 
                                            <View style={customStyle.osCatImageView}>
                                                <Image style={customStyle.osCatImage} source={{uri:NAImage1Path}}/>
                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window,'1','3')}}>
                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                </TouchableOpacity>
                                            </View>                                    
                                        }   
                                        </View>
                                    </View>
                                    </View>
                                </View>
                                }



                                {(isPresent=='1') && 
                                <View>
                                    {(isImage1==1 || isImage2==1)&& 
                                    <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}>{ST.CaptureImage}</Text>
                                    </LinearGradient>
                                        <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]}>
                                        {isImage1==1 && 
                                            <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                            
                                            { (Image1=='' || Image1==null) ?
                                                <TouchableOpacity style={[EStyle_splitImage1]} onPress={()=>{openCamera(window,'1','1')}}>
                                                    <CameraImg5 width={50} height={50} />
                                                </TouchableOpacity> : (Image1!='' && Image1!=null)  ?
                                                <TouchableOpacity onPress={()=>{OpenImgModal(Image1,window,'1','1')}}>
                                                    <CameraImg3 width={50} height={50}  />
                                                </TouchableOpacity> : null
                                            }
                                            <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text>
                                            </View>
                                        }
                                        {isImage2==1 && 
                                            <View style={customStyle.openStkCameraCon}>
                                            
                                            { (Image2=='' || Image2==null) ?
                                                <TouchableOpacity style={[EStyle_splitImage2]}  onPress={()=>{openCamera(window,'2','1')}}>
                                                    <CameraImg5 width={50} height={50}  />
                                                </TouchableOpacity> : (Image2!='' && Image2!=null)  ?
                                                <TouchableOpacity onPress={()=>{OpenImgModal(Image2,window,'2','1')}}>
                                                    <CameraImg3 width={50} height={50} />
                                                </TouchableOpacity> : null
                                            }
                                            <Text style={customStyle.WSCameraLabel}>{camera2Label}</Text> 
                                            </View>  
                                        }          
                                        </View>
                                    </View>
                                    }
                                    
                                    {(WindowQuestions.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}>{ST.POSMQuestions}</Text>
                                    </LinearGradient>
                                    {WindowQuestions.map((item,index)=>{
                                        
                                        let qtn=item;  
                                        let qtnIndex=index;
                                        let selansid='',selanswer='',selimg='',showImageTag=false;
                                        let id_key=qtn.POSMQuestionId+'_AnswerId'; 
                                        let ans_key=qtn.POSMQuestionId+'_Answer'; 
                                        let multi_key=qtn.POSMQuestionId+'_MultiOption';
                                        let date_key=qtn.POSMQuestionId+'_Date';
                                        let img_key=qtn.POSMQuestionId+'_ImagePath1';
                                        let imgname_key=qtn.POSMQuestionId+'_ImageName1';
                                        let rating_key=qtn.POSMQuestionId+'_Rating'; 
                                        
                                        let list_mcdata=[];
                                        
                                        if(qtn.QuestionType=='Single choice list')
                                        {
                                            selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                                            selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                                        }
                                        else if(qtn.QuestionType=='Multi choice list')
                                        {
                                            if(qtn.Answers!=null){
                                                for(var i=0;i<qtn.Answers.length;i++){
                                                    let obj={'AnswerId':parseInt(qtn.Answers[i].AnswerId),'Answer':qtn.Answers[i].Answer};
                                                    list_mcdata.push(obj);
                                                }
                                            }
                                            selansid=QuestionsData[multi_key]!=null && QuestionsData[multi_key]!=''?QuestionsData[multi_key].split(','):[];
                                            // if(selansid!=null && selansid.length>0){
                                            //     let arr=[];
                                            //     for(var i=0;i<selansid.length;i++){
                                            //         arr.push(parseInt(selansid[i]));
                                            //     }
                                            //     selansid=arr;
                                            // }
                                        }
                                        else if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                                        {
                                            selansid=QuestionsData[ans_key];
                                            selanswer=(qtn.QuestionType=='Date'  )?(QuestionsData[date_key] || moment().format('MM/DD/YYYY')):'';
                                            showImageTag=(qtn.PQShowCamera==1 || qtn.PQShowCamera=='true');
                                        }
                                        else if(qtn.QuestionType=='Rating'){
                                            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.PAShowCamera=='true' || ansss.PAShowCamera==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(showImageTag){
                                            selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                                        }

                                        
                                        let EF_qtn=errorfield.EF_qtn!=null?errorfield.EF_qtn:{};
                                        let showQtnErrHere=EF_qtn.CategoryQuestionId==qtn.CategoryQuestionId;
                                        //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:{};
                                        

                                        return(
                                        <View style={[customStyle.sform_group2,]} key={'Qtn_'+qtnIndex} >
                                            <Text style={[customStyle.sform_label3]}>{qtn.POSMQuestionName}</Text>                     
                                            {qtn.QuestionType=='Single choice list' && qtn.Answers && 
                                                render_Picker('Answer','AnswerId',onselectionChange2,{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') &&  
                                                <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':'number-pad'))}
                                                    value={selansid}
                                                  //  onChangeText={(val)=>{setTextValue(val,qtn,window(qtn.QuestionType=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':'numeric')))}}
                                                    onChangeText={(val) => {
                                                           setTextValue(val, qtn, window, qtn.QuestionType == "Decimal" ? "decimal" : qtn.QuestionType == "Text" ? "text" : "numeric");
                                                         }}
                                                />
                                                
                                            }
                                           
                                            {
                                                (qtn.QuestionType=='Date') && 
                                                <View style={[customStyle.surveyQtn_datePicker_con,EStyle_Qtn_Date]}>
                                                    <Text style={customStyle.surveyQtn_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.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>    
                                            }

                                            {
                                                // (qtn.QuestionType=='Audio') && 
                                                // <View style={customStyle.surveyQtn_datePicker_con}>
                                                //     <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                //     <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{show_recorder(qtn);}}>
                                                //         <FontAwesome size={25} color={PageTheme.$accent_color} name="microphone"/>
                                                //     </TouchableOpacity> 
                                                // </View>    
                                            }
                                            
                                            {
                                                showImageTag &&
                                                <View style={[customStyle.store_audit_img_con,EStyle_Qtn_Image]}>                    
                                                    <Image source={(selimg!='' && selimg!=null )?{uri:selimg}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg!='' && selimg!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                                    <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(window,'1','2',qtn)}}>
                                                        <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                                    </TouchableOpacity>
                                                </View>
                                            }

                                           
                                        </View> 
                                        )
                                    })}
                                    </View>
                                    }
                                    
                                    
                                </View>
                                }
                                
                                                    
                                                    
                            </View>
                        </View>
                    </View>
                );
            }}
            />
        )
        }
        else{
        return null;
        }
    }

    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={()=>{setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2={};
        if(searchedQry!=null && searchedQry!=''){
            for(let i=0;i<globalWindows.length;i++){
                let item=globalWindows[i];
                arr2=Object.assign({'test':'1'} , item);
                if(item.POSMName.toLowerCase().includes(searchedQry)){
                    arr.push(arr2);
                }
            }
        }
        else{
          arr=globalWindows;
        }

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

    function getSearchBar(){
        let isSearchEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='SearchEnable')
        let isSearchEnableKPIObj=isSearchEnableIndex>=0?KPIFields[isSearchEnableIndex]:{};
        let isSearchEnable=isSearchEnableIndex>=0?isSearchEnableKPIObj['KPIFieldEnable']:true;

        let KPIPresentEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='StorePOSMPresent')
        let KPIPresentEnableObj=KPIPresentEnableIndex>=0?KPIFields[KPIPresentEnableIndex]:{};
        let KPIPresentEnable=KPIPresentEnableIndex>=0?KPIPresentEnableObj['KPIFieldEnable']:true;
        
        let showList=(KPIPresentEnable && isKPIPresent) || (KPIPresentEnable==false);
        if(isSearchEnable==true && showList){
            return (
                <View style={customStyle.storel_searchbar2}>
                  <TextInput 
                    style={[customStyle.storel_searchInput]}
                    placeholder={ST.Searchby+' '+currentMenu.MenuName}
                    autoComplete='off'
                    placeholderTextColor={PageTheme.$placeholder_color} 
                    value={searchedItem}
                    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>
            )
        }
        else{
            return(
                <View></View>
            )
        }
    }

    const onCancelClean = () =>{
        setDataCleanModal(false)
    }
    const onclear = () => {
        onWindowDataClean(DataCleanItem)
    }
  
    function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        
        let {window,type,cameraType,qtn}=reCapImgModalObj
        let camera2Label=(window && window.PromoImage2Lable) || '';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={currentMenu.MenuName+" Image"}
            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,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>
        )
      }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <View style={{zIndex: 10}}>
          <CustomHeader {...props}showaddstore={true}  title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>    
        </View>
        {_OpenCaptureImage_Modal()}    
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,DataCleanModal,onCancelClean,onclear,'Your data will be clean',)}
        <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]}>
          {_renderKPIPresent()}
          { getSearchBar()}
          { 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)(POSM);