import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, FlatList, Alert, Animated, AppState, DeviceEventEmitter, 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 { UploadData2, 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 cameraImg from '../assets/performics/camera_front_image.svg'
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 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import DateTimePicker from '@react-native-community/datetimepicker';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import IRLogin from '../components/IRLogin';
import { SyncIRsessionsInKPI } from '../constants/uploadData';
import { METHODS, getMethodName } from '../constants/methodNames';
import ImageViewer from 'react-native-image-zoom-viewer';

function AdditionalVisibilityIR_Only(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const animatedChoice = useRef(new Animated.Value(0)).current;

    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);

    const [ShowDatePicker1, setShowDatePicker1] = useState(false);
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const showCameraRef = useRef(false);
    const [clickImageType, setClickImageType] = useState('1');
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [dateValue, setDateValue] = useState('');
    const [FromDate, setFromDate] = useState('');
    const [FromDate2, setFromDate2] = useState(new Date());

    const [ToDate, setToDate] = useState('');
    const [ToDate2, setToDate2] = useState(new Date());

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });

    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const zoomView = useRef(null);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(AddVisibility);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');

    const VisFormDataRef = React.useRef(AddVisFormData);
    const isAddVisPresentRef = React.useRef(isAddVisPresent);

    // AddVisibility,AddVisFormData,isAddVisPresent,pro

    // IR states or refs
    const [isDataExists, setisDataExists] = useState(false);
    const [isDataUploaded, setisDataUploaded] = useState("N");
    //  const [AddVisIRImages, setAddVisIRImages] = useState([]);
    //  const [GbTempSessionId, setGbTempSessionId] = useState("");
    const AddVisIRImages = useRef([]);
    const GbTempSessionId = useRef("");
    const GbTempSessionObj = useRef({});
    const sessionsToUpload = useRef([]);
    const sessionsToUploadDetails = useRef([]);
    const sessionsUploadedCount = useRef(0);
    const sessionsReceived = useRef(0);
    const [showRetakeModal, setshowRetakeModal] = useState(false);
    const [retakeMData, setretakeMData] = useState({});
    const [showUploadAlert, setshowUploadAlert] = useState(false);

    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;
        setStoreCameraAllow(cameraAllow);

        let isAdhoc = params.isAdhoc || false;

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        getData(storeData1, menu1);


        // console.log("storeData1,menu1",storeData1,menu1);
        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        const removeIRListener = DeviceEventEmitter.addListener('onIRImageUpload', (data) => { onIRImageUpload(data, storeData1, menu1) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);


        return function cleanup() {
            IRLogin.deRegisterReceiver();
            AppStateSubscription.remove();
            removeIRListener.remove();
            return unsubscribe;
        };
    }, []);


    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                AddFormData: VisFormDataRef.current,
                isVisPresent: isAddVisPresentRef.current,
                bg_GbTempSessionId: GbTempSessionId.current,
                bg_AddVisIRImages: AddVisIRImages.current,
                visiteDate: d2
            }
            let WindowsStr = await JSON.stringify(newData)
            await set_item('storeData', WindowsStr);
        }
    }

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


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

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

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

    function BgAddVisFormData(val) {
        VisFormDataRef.current = val
        setAddVisFormData(val);
    }

    function BgIsAddVisPresent(val) {
        isAddVisPresentRef.current = val
        setIsAddVisPresent(val);
    }


    function UpdateShowCameraRef(val) {
        showCameraRef.current = val
        setShowCamera(val);
    }


    function onBeforeRemove(e) {
        if (showCameraRef.current == true) {
            e.preventDefault();
            UpdateShowCameraRef(false);
        }
        else {
            if (hasUnsavedChangesRef.current == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }

    async function onIRImageUpload(data, storeData1, menu1) {
        console.log('onIRImageUpload on receive', data);
        let { message, sessionId, status } = data;
        let snum = sessionsReceived.current + 1;
        let su_num = sessionsUploadedCount.current;
        console.log('onreceive data', data);
        sessionsReceived.current = snum;
        let thisIR_SessObjIndex = sessionsToUploadDetails.current.findIndex(i => i.TEMP_SESSION_ID == sessionId);
        let thisIR_SessObj = sessionsToUploadDetails.current[thisIR_SessObjIndex];
        if (status != null && status == '200' && sessionId != null && sessionId != '') {

            let UnSessionId = await IRLogin.getDataIRSession(sessionId);
            if (UnSessionId != null && UnSessionId != '') {
                sessionsUploadedCount.current = ++su_num;
                let isUpdated = await UpdateIRUploadStatus(storeData1, menu1, sessionId, UnSessionId);
                let isUploaded = await LogImageUpload(storeData1, menu1, sessionId, UnSessionId, message, status, thisIR_SessObj);
                console.log("su_num:", su_num);
                if (isUploaded) {
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:" + sessionId);
                }
                else {
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:" + sessionId);
                }

            }
            else {
                console.log('OnReceived UnSessionId get', UnSessionId);
                notify("Cannot upload images for session:" + sessionId + ". Universal Id not found");
                let isUploaded = await LogImageUpload(storeData1, menu1, sessionId, "", message, status, thisIR_SessObj);
                if (isUploaded) {
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:" + sessionId);
                }
                else {
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:" + sessionId);
                }

            }

        }
        else {
            console.log('Cannot get OnReceived UnSessionId');
            notify((message != null && message != "" ? message + ". " : "") + "Cannot upload images for session:" + sessionId);
            let isUploaded = await LogImageUpload(storeData1, menu1, sessionId, "", message, status, thisIR_SessObj);
            if (isUploaded) {
                console.log('Image Uploaded');
                notify("Images Log uploaded for session:" + sessionId);
            }
            else {
                console.log('cannot Uploaded image');
                notify("cannot upload log for session:" + sessionId);
            }


        }

        console.log("check snum and su_num:", snum, su_num, sessionsToUpload.current.length);
        // if last broadcast received either uploaded or not update the processing status to false
        if (snum == sessionsToUpload.current.length) {
            setProcessing(false);
            console.log('Deregister event when last received');
            IRLogin.deRegisterReceiver();
        }

        // All IR Sessions with Images Uploaded : set DataUploaded Status to U (Fully Upload)
        if (su_num == sessionsToUpload.current.length) {
            setisDataUploaded("U");
            setProcessing(false);
            notify("All IR images uploaded!");
            console.log('set all uploaded true to U');
        }
        // Some Of IR Sessions with Images Uploaded but some are yet pending : set DataUploaded Status to P (Partial Upload)
        else if (su_num > 0 && su_num != sessionsToUpload.current.length) {
            // setProcessing(false);
            setisDataUploaded("P");
            notify("Some IR Images are still not uploaded!");
            console.log('set all uploaded true to P');
        }
    }


    function onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: ST.OK, onPress: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        // setHasUnsavedChanges(false);
                        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);


            let isFromDateIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
            let isFromDateKPIObj = isFromDateIndex >= 0 ? AllKPIFields[isFromDateIndex] : {};
            let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

            let isToDateIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
            let isToDateKPIObj = isToDateIndex >= 0 ? AllKPIFields[isToDateIndex] : {};
            let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;

            // let isKPIIREnableI=AllKPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
            // let isKPIIREnableObj=isKPIIREnableI>=0?AllKPIFields[isKPIIREnableI]:{};
            // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

            // console.log("isKPIIREnable:",isKPIIREnable)

            await db.transaction(async function (txn) {

                // await txn.executeSql(`UPDATE ${AppTables.ADDVIS_IRUPLOAD} set UPLOAD_STATUS='0' , SYNC_STATUS='' `,[],async function (txn2, txnres) { 
                //     console.log('AddVis IR Status data deleted');
                // },function (txnE,txnerr) { console.log(txnerr); },);


                let q = `Select Distinct p.CategoryId,p.CategoryName from Product_Master p where p.IsCompetitor='0' order by p.CategorySequence`;
                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) { setCategories(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                let q2 = `Select Distinct DisplayId,DisplayName from Master_Display where Additional='1'`;
                await txn.executeSql(q2, [], 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) { setDisplayList(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let storeBGData1 = [], bgStoreJson = {}, isBGDataExists = false;
                let windData = await get_item('storeData')
                if (windData != null && windData != '') {
                    let StoreJson = await JSON.parse(windData)
                    let { storeBGData, menuName, StoreId1, AddFormData, visiteDate, bg_AddVisIRImages, bg_GbTempSessionId, isVisPresent } = StoreJson
                    // Check if bg data exists for this Store and menu on today date
                    if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                        isBGDataExists = true;
                        BgUnsavedChanges(true)

                        // Check if isVisPresent data exists in bg data
                        let bgPresent = isVisPresent == 1 ? 1 : 0;
                        Animated.timing(animatedChoice, {
                            toValue: bgPresent,
                            duration: 400,
                            useNativeDriver: false,
                        }).start();
                        BgIsAddVisPresent(bgPresent);


                        // Check if added visibilities data exists in bg data
                        if (storeBGData.length > 0) {
                            storeBGData1 = storeBGData;
                            bgStoreJson = StoreJson
                            // setAddVisibility(storeBGData);
                            // setAddVisFormData(AddFormData)
                            // BgUnsavedChanges(true)
                            BgWindowData(storeBGData)
                            // BgAddVisFormData(AddFormData)
                        }
                        // console.log("AddFormData",AddFormData);
                        // Check if form data exists in bg data
                        if (AddFormData != null && Object.keys(AddFormData).length > 0) {
                            // BgUnsavedChanges(true)
                            let { CategoryId, SubCategoryId, FromDate, ToDate } = AddFormData;
                            // load subcategories if category exists 
                            if (CategoryId != null && CategoryId != '') {
                                loadData(CategoryId, 'SubCategories');
                            }
                            if (SubCategoryId != null && CategoryId != '') {
                                loadData(SubCategoryId, 'Brands');
                            }
                            if (FromDate != null && FromDate != '') {
                                setFromDate(FromDate);
                                setFromDate2(new Date(FromDate));
                            }
                            if (ToDate != null && ToDate != '') {
                                setToDate(ToDate);
                                setToDate2(new Date(ToDate));
                            }
                            BgAddVisFormData(AddFormData)
                        }

                        // Check if IR Images and session present in bg data 
                        if (bg_GbTempSessionId != null && bg_GbTempSessionId != '' && bg_AddVisIRImages != null && bg_AddVisIRImages.length > 0) {
                            AddVisIRImages.current = bg_AddVisIRImages;
                            GbTempSessionId.current = bg_GbTempSessionId;
                        }
                    }
                }

                let q3 = `Select * from ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        let isAddVisPr = false;
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { PRESENT, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE, FROM_DATE, TO_DATE, SHOWFROMDATE } = data;
                            let datan = { CategoryName: CATEGORY, CategoryId: CATEGORY_ID, SubCategoryName: SUB_CATEGORY, SubCategoryId: SUB_CATEGORY_ID, BrandName: BRAND, BrandId: BRAND_ID, DisplayName: DISPLAY, DisplayId: DISPLAY_ID, Remark: REMARK, Image1: IMAGE, FromDate: String(FROM_DATE), ToDate: String(TO_DATE), showFromDateFlag: SHOWFROMDATE }
                            datan.Image1Path = IMAGE != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + IMAGE : '';
                            PRESENT == 1 ? arr.push(datan) : '';
                            let isPresent = PRESENT;
                            if (i == 0) isAddVisPr = PRESENT;
                            if (i == txnres2.rows.length - 1) {
                                if (!isBGDataExists) { //set current data in list if bg data does not exists
                                    // setAddVisibility(arr);
                                    BgWindowData(arr);
                                    Animated.timing(animatedChoice, {
                                        toValue: isPresent,
                                        duration: 400,
                                        useNativeDriver: false,
                                    }).start();
                                    BgIsAddVisPresent(isPresent);
                                }


                                setisDataExists(true);
                                // isKPIIREnable &&
                                if (isAddVisPr) {
                                    let allIRImages = await getIRImages(storeData1, menu1);
                                    // setAddVisIRImages(allIRImages);
                                    AddVisIRImages.current = allIRImages;
                                    let isUpdated = await getUploadIRStatus(storeData1, menu1);
                                }
                                setProcessing(false);
                                setrerenderdata(!rerenderdata);
                            }
                        }
                    }
                    else {
                        setProcessing(false);
                        setrerenderdata(!rerenderdata);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

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


    async function getIRImages(storeData1, menu1) {
        let allImages = [];

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

            db.transaction(async function (txn) {

                let q = `select IMAGE1 as Image1 from ${AppTables.ADDVIS_IR_IMAGES} where STORE_ID='${storeData1.StoreId}' and VISIT_DATE='${d2}'`;

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    console.log('get IRImages count ', txnres2.rows.length);
                    if (txnres2.rows.length > 0) {
                        let arr2 = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let obj = { 'ImagePath': data.Image1 };
                            allImages.push(obj);

                            let imgObj = { imgIndex: (i + 1), url: data.Image1, props: {} }
                            arr2.push(imgObj);
                            if (i == txnres2.rows.length - 1) {
                                setZoomImageUrl(arr2);
                                resolve(allImages)
                            }
                        }
                    }
                    else {
                        resolve(allImages)
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(allImages) },);
            });
        }).then((val) => {
            return val
        }).catch((err) => {
            console.log(err);
            return allImages;
        });
    }

    async function getUploadIRStatus(storeData1, menu1) {
        let allImages = [];
        let { StoreId } = storeData1;
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {

                // Check If IR session uploaded or not 
                let q = ` SELECT Distinct TEMP_SESSION_ID as TempSessionId,UN_SESSION_ID as UploadSessionId,UPLOAD_STATUS as UploadStatus,SYNC_STATUS as SyncStatus,SESSION_STORECODE as Sess_StoreCode,SESSION_TASKNAME as Sess_TaskName,SESSION_CATNAME as Sess_CatName,SESSION_PHOTOTYPE as Sess_PhotoType FROM ${AppTables.ADDVIS_IRUPLOAD} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {

                        //No Loop required, As only one TempSessionId will be genrated for KPI
                        let data = txnres.rows.item(0);
                        let { Sess_StoreCode, Sess_TaskName, Sess_CatName, Sess_PhotoType } = data;
                        if (data.UploadStatus == '1' && isDataUploaded != 'P' && isDataUploaded != 'U') {
                            console.log('getUploadIRStatus success: U');
                            // Stop Upload and Editing both when fully uploaded
                            setisDataUploaded("U");
                        }
                        // setGbTempSessionId(data.TempSessionId);
                        GbTempSessionId.current = data.TempSessionId;
                        let obj = { Sess_StoreCode, Sess_TaskName, Sess_CatName, Sess_PhotoType };
                        GbTempSessionObj.current = obj;
                        resolve(true);
                    }
                    else {
                        resolve(true);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
            });
        }).catch((err) => {
            return false;
        })
    }



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

    }

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

    async function getImage(imgdata) {
        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('DD-MM-YYYY HH:mm:ss')
            ////change by jeevanp
            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);
            ////change by jeevanp
            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 + '_' + (props.UserId || '') + '_AddVisibilityImg-' + calculate_tym_date_for_filename + '.jpg';
            ////change by jeevanp
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Add. Visibility' + ' | Date:' + calculate_tym_date_over_img;

            let addvisdata = AddVisFormData;
            let image_key = 'Image1';
            let image_path_key = 'Image1Path';
            addvisdata[image_key] = filename;

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

                    setSelectedImg(uri)
                    BgAddVisFormData(addvisdata)
                    BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                    // 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);
                });

        }
    }

    function _OpenCaptureImage_Modal(img) {

        const isImageCap = (img != '' || img != null) ? true : false;
        let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"Additional Visibility 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('1') }}>
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>

                        {!showImageSaveOp &&
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        )
    }


    // IR functions start 

    function openRetakeOp(IRImgIndex, IRimgPath) {
        let data = { 'IRImgIndex': IRImgIndex, 'IRimgPath': IRimgPath };
        setretakeMData(data);
        setshowRetakeModal(true);
    }


    function closeRetakeOp() {
        setretakeMData({})
        setshowRetakeModal(false);
    }

    function setIRZoomImages(IRCamImages) {
        let z_images = [];
        for (let ci in IRCamImages) {
            let img = IRCamImages[ci];
            let img_obj = { imgIndex: (ci + 1), url: img.ImagePath, props: {} }
            z_images.push(img_obj);
            if (ci == IRCamImages.length - 1) {
                setZoomImageUrl(z_images);
            }
        }
    }

    async function StartCameraSession() {
        let IR_Creds = props.IR_Creds != null && props.IR_Creds != "" ? JSON.parse(props.IR_Creds) : [];
        let IR_CredsObj = IR_Creds.length > 0 ? IR_Creds[0] : {};

        let newStdata = storeData;
        if (IR_CredsObj.UseStoreCode != 1) {
            newStdata.StoreCode = newStdata.StoreId;
        }
        let obj = { "StoreData": newStdata };
        obj["category_name"] = "multi";
        obj["task_name"] = "additional-visibility-displays";
        obj["photo_type"] = "additional-visibility";

        let st1 = JSON.stringify(obj);
        let TempSessionId = await IRLogin.StartIRSession(st1);
        console.log('TempSessionId StartCameraSession:', TempSessionId, newStdata.StoreCode);
        if (TempSessionId != null) {
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let IRCamImages = await IRLogin.getImageURIFromIRSession(TempSessionId);
            console.log('Images from session :', IRCamImages);

            //set global IR images and session id if Camera is shown only once in header for KPI Screen
            // setGbTempSessionId(TempSessionId);
            GbTempSessionId.current = TempSessionId;
            let sessObj = {}
            sessObj['Sess_StoreCode'] = newStdata.StoreCode;
            sessObj['Sess_TaskName'] = obj["task_name"];
            sessObj['Sess_CatName'] = obj["category_name"];
            sessObj['Sess_PhotoType'] = obj["photo_type"];
            GbTempSessionObj.current = sessObj;
            AddVisIRImages.current = IRCamImages;
            setIRZoomImages(IRCamImages);

            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true);
            setrerenderdata(!rerenderdata);

            // stop image processing loader after all images get from sessionID
            setProcessing(false);
            setLoaderTitle('loading...');

        }
        else {
            notify('Cannot capture images as getting Session Null.');
        }

    }

    async function ResumeCameraSession() {
        // Resume Temp Session Id
        let TempSessionId = GbTempSessionId.current;
        console.log('TempSessionId :', TempSessionId);

        if (TempSessionId != null) {
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let retTempSessionId = await IRLogin.ResumeIRSession(TempSessionId);
            console.log('retTempSessionId :', retTempSessionId);
            if (retTempSessionId != null) {
                // start fetching images after capturing photos

                let IRCamImages = await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Images from session :', IRCamImages);
                // setAddVisIRImages(IRCamImages);
                AddVisIRImages.current = IRCamImages;
                setIRZoomImages(IRCamImages);

                BgUnsavedChanges(true);
                // setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);

                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
            }
            else {
                notify('Cannot capture images as getting Session Null.');
            }

        }
        else {
            notify('Cannot capture images as getting Session Null.');
        }

    }

    async function DeleteIRPhoto(type = '1', imgData = {}) {
        console.log('DeleteIRPhoto called');
        setshowRetakeModal(false);
        let deleteImgData = type == '2' ? imgData : retakeMData;
        let { IRImgIndex, IRimgPath } = deleteImgData;
        IRImgIndex = IRImgIndex != null ? IRImgIndex : '';
        IRimgPath = IRimgPath != null ? IRimgPath : '';


        let TempSessionId = GbTempSessionId.current;

        console.log('DeleteIRPhoto sessionID :', TempSessionId);
        if (TempSessionId != null || TempSessionId != '') {
            setLoaderTitle('Removing Image...');
            setProcessing(true);
            let isDeleted = await IRLogin.DeleteIRSessionPhoto(TempSessionId, IRimgPath);//"8099b819-0979-40d2-950e-489566041484";//
            console.log('DeleteIRPhoto isDeleted :', isDeleted);
            if (isDeleted) {
                setLoaderTitle('Processing Image...');

                let IRCamImages = await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Deleted, Images from session :', IRCamImages);
                // setAddVisIRImages(IRCamImages);
                AddVisIRImages.current = IRCamImages;
                setIRZoomImages(IRCamImages);

                BgUnsavedChanges(true);
                // setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);

                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
                return true;

            }
            else {
                notify('Cannot delete photo!.');
                return false;
            }

        }
        else {
            notify('Cannot delete photo! Found Null Session.');
            return false;
        }

    }

    async function RetakeIRPhoto() {
        setshowRetakeModal(false);
        let { IRImgIndex, IRimgPath } = retakeMData;

        IRImgIndex = IRImgIndex != null ? IRImgIndex : '';
        IRimgPath = IRimgPath != null ? IRimgPath : '';

        let TempSessionId = GbTempSessionId.current;

        console.log('Retake sessionID :', TempSessionId);
        if (TempSessionId != null || TempSessionId != '') {
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let isRetakeDone = await IRLogin.RetakeIRSessionPhoto(TempSessionId, IRimgPath);
            console.log('Retake isRetakeDone :', isRetakeDone);
            if (isRetakeDone) {
                setTimeout(async () => {
                    let IRCamImages = await IRLogin.getImageURIFromIRSession(TempSessionId);
                    console.log('Retake Images from session :', IRCamImages);
                    // setAddVisIRImages(IRCamImages);
                    AddVisIRImages.current = IRCamImages;
                    setIRZoomImages(IRCamImages);

                    BgUnsavedChanges(true);
                    // setHasUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);

                    // stop image processing loader after all images get from sessionID
                    setProcessing(false);
                    setLoaderTitle('loading...');
                }, 1000);

            }
            else {
                notify('Error occur while retaking photo!.');
            }

        }
        else {
            notify('Cannot start camera! Found Null Session.');
        }

    }

    // Start Upload for IR images 
    async function UploadIRSessions() {
        setshowUploadAlert(false);
        sessionsToUpload.current = [];
        sessionsReceived.current = 0;
        sessionsUploadedCount.current = 0;

        try {
            let { StoreId } = storeData;
            setLoaderTitle('Uploading Images...');
            setProcessing(true);

            // Global Upload function
            // Sync Status for IR images
            // From Infilect SDK 1.3.6 - The Images are uploading on realtime bases i.e. As the images are clicked by user the Images are getting uploaded to infilect server.
            // In this case call below func to check the status of images that is already being uploaded by Real Time processing
            let sync_result = await SyncIRsessionsInKPI(props, storeData, AppTables.ADDVIS_IRUPLOAD, AppTables.ADDVIS_IR_IMAGES);
            let { isUploadStarted, AllDataUploaded, noDataFound, success, sessionList, sessionListWithDetails } = sync_result;
            console.log("Sync Resp sync_result:", sync_result);
            if (!success) {
                notify('Cannot Upload Data! Something went wrong.');
                setProcessing(false);
            }
            else {
                if (noDataFound) {
                    notify('No session to upload!');
                    setisDataUploaded('U');
                    setProcessing(false);
                }
                else {
                    if (!isUploadStarted && AllDataUploaded) {
                        notify('All images synced! No session to upload.');
                        setisDataUploaded('U');
                        setProcessing(false);
                    } else if (isUploadStarted) {
                        sessionsToUpload.current = sessionList;
                        sessionsToUploadDetails.current = sessionListWithDetails;
                        console.log("UploadStarted");
                    }
                }
            }
        } catch (e) {
            console.log('Uploading Issue:', e);
            setProcessing(false);
        }


    }

    async function UpdateIRUploadStatus(storeData1, menu1, TempSessionId, UnSessionId) {
        console.log('UpdateIRUploadStatus');
        return new Promise((resolve, reject) => {

            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
            db.transaction(async function (txn) {
                // update upload status and sync status here : when files are uploaded and we have got the universal session id for that 
                let q = `Update ${AppTables.ADDVIS_IRUPLOAD} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                // console.log("update IR Upload q:",q);
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('Updated IR Upload Status');
                    // console.log("update IR Upload q2:",q2);
                    let q2 = `Update ${AppTables.ADDVIS_IR_IMAGES} set UN_SESSION_ID='${UnSessionId}' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        console.log('Updated IR Upload Images Status');
                        resolve(true);
                    }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
            });
        }).catch((Err) => {
            console.log('Error in UpdateIRUploadStatus:', Err);
            return false;
        })



    }

    // {"AddVisiAllow": "Y", "Address": "Blank", "CameraAllow": "true", "ChainId": 151, "ChainName": "RELIANCE RETAIL", "ChannelId": 1, "CheckInTime": "15:33:45", "CheckOutTime": "", "CityId": 133, "CityName": "Hyderabad", "ContactPerson": "NA", "DistributorId": null, "DistributorName": null, "Email": "", "EmpId": 1, "ExpiryStock": "N", "GSTno": "", "GeoFenceRadius": 500, "GeoTag": "Y", "InTime": "00:00:00", "JCP_TYPE": "Mapping_JourneyPlan", "Landmark": "Na", "LastVisitDate": "", "Latitude": "28.5275264", "Location": "NA", "Longitude": "77.2779835", "MID": 217939, "MTDMerchandised": 0, "MenuCount": 8, "MenuCountWithNonAvlbl": 8, "MenuDoneCount": 4, "MenuListLen": 8, "MinTimeTaken": 0, "Mobile": "NA", "OutTime": "00:00:00", "Phone": "NA", "Pincode": "0", "RegionId": 4, "Score": "0", "StateId": 25, "StateName": "Telangana", "StoreCategory": "NA", "StoreCategoryId": "1", "StoreClass": "NA", "StoreClassId": 1, "StoreCode": "ST4312", "StoreId": 4318, "StoreName": "Test Store-5", "StoreType": "Hyper", "StoreTypeId": 3, "TaxType": "NA", "UploadStatus": "I", "VisitDate": "06/02/2023", "allDone": false} ,
    // {"DataRowCount": 1, "GreyIcon": "Add-Free-Visibility-gray.png", "KPIAVBL": 1, "MenuId": 7, "MenuName": "Addl./free Visibility", "MenuPath": "https://perfetti1.parinaam.in/Download/Icon/", "MenuSequence": 7, "NormalIcon": "Add-Free-Visibility.png", "ScreenName": "ADDITIONALVISI", "StoreId": 4318, "TickIcon": "Add-Free-Visibility-tick.png", "isAvlbl": true, "isKPI_Done": true},'c2ae81f9-cf47-4887-aed6-78fe7cc2ad0c','','Failed','400'
    async function LogImageUpload(storeData1, menu1, TempSessionId, UnSessionId, message, status, thisIR_SessObj = {}) {
        let { StoreId, StoreName } = storeData1;
        const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
        const nowTime = moment().format('HH:mm:ss');
        let ImageCount = await getImageCount(storeData1, menu1, TempSessionId);
        let { SESSION_STORECODE, SESSION_TASKNAME, SESSION_CATNAME, SESSION_PHOTOTYPE } = thisIR_SessObj;


        ////Replaced special charecter and white space
        let storeTittle = StoreName.replace(`@!%&`, '').replace(' ', '-');
        console.log("storeTittle:", storeTittle, StoreName);

        let obj = {};
        obj['StoreId'] = StoreId;
        obj['Username'] = props.UserId;
        obj['VisitDate'] = d2;
        obj['InTime'] = nowTime;
        obj['TempSessionId'] = TempSessionId;
        obj['UnSessionId'] = UnSessionId;
        obj['Status'] = status;
        obj['Message'] = message;
        obj['ImageCount'] = ImageCount;
        obj['StoreTitle'] = storeTittle;
        obj['StoreCode'] = SESSION_STORECODE;
        obj['TaskName'] = SESSION_TASKNAME;
        obj['CategoryName'] = SESSION_CATNAME;
        obj['PhotoType'] = SESSION_PHOTOTYPE;
        obj['KPIType'] = currentMenu.MenuName;
        obj['ScreenName'] = currentMenu.ScreenName;
        obj['UploadType'] = "New";

        let postData = {};
        postData['MID'] = 0;
        postData['Keys'] = 'IR_UPLOAD_LOG_MSG';
        postData['JsonData'] = JSON.stringify(obj);
        postData['UserId'] = props.UserId;

        console.log('postData', postData);

        return await UploadData2(url, postData)
            .then((res) => {
                // console.log("log Uploaded:",res.UploadJsonResult);
                if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
                    return true;
                }
                return false;
            })
            .catch((err) => {
                console.log(err);
                return false;
            });
    }


    async function getImageCount(storeData1, menu1, TempSessionId) {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
        console.log('storeData in getImageCount', storeData1);
        return new Promise((resolve, reject) => {


            db.transaction(async function (txn) {

                let q = `select DISTINCT TEMP_SESSION_ID,count(IMAGE1) as ImageCount from ${AppTables.ADDVIS_IR_IMAGES}  where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}'  group by TEMP_SESSION_ID `;
                console.log('q', q);
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('ImageCount rows:', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        console.log('data:', data)
                        console.log('Image Count for TempSessionId:', data.ImageCount);
                        resolve(data.ImageCount);
                    }
                    else {
                        resolve(0);
                    }

                }, function (txnE, txnerr) { console.log(txnerr); resolve(0); },);
            });
        }).catch((Err) => {
            console.log('Error in getImageCount:', Err);
            return 0;
        })



    }



    // IR functions end

    async function openCamera(type = '1') {
        console.log('openCamera');
        setClickImageType(type);
        UpdateShowCameraRef(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

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

    async function saveData() {
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);

        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {

                let q = `DELETE FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                let q2 = `DELETE FROM ${AppTables.ADDVIS_IRUPLOAD} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                let q3 = `DELETE FROM ${AppTables.ADDVIS_IR_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

                //  remove old data
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('av data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);

                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    console.log('av IR status data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);

                await txn.executeSql(q3, [], async function (txn2, txnres) {
                    console.log('av IR Images data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);

                var values = '', IRStatusV = '', IRImageV = '';
                let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
                let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
                let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;


                // let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
                // let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
                // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;




                // if(isAddVisPresent==1 && AddVisibility.length>0){
                //     for(var i=0;i<AddVisibility.length;i++){
                //         let catIndex=i;
                //         let item=AddVisibility[catIndex];
                //         let {CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,DisplayName,DisplayId,Remark,Image1,Image1Path,FromDate,ToDate}=item;
                //         values+=values!=''?' , ':'';
                //         values+=` ('${StoreId}','${d2}','${isAddVisPresent}','${CategoryName}','${CategoryId}','${SubCategoryName}','${SubCategoryId}','${BrandName}','${BrandId}','${DisplayName}','${DisplayId}','${(Remark || '')}','${(Image1 || '')}','1','${(FromDate || '')}','${(ToDate || '')}','${isFromDateEnable}','${d2}') `;
                //     }
                // }
                // else{
                values += ` ('${StoreId}','${d2}','${isAddVisPresent}','','','','','','','','','','','1','','','false','${d2}') `;
                // if(isKPIIREnable){
                // if(AddVisIRImages.current.length>0){
                //     removeIRImage()
                // }
                // else{
                //     // setGbTempSessionId('');
                //     GbTempSessionId.current='';
                // }
                // }
                // }


                // isKPIIREnable &&
                if (isAddVisPresent == 1 && AddVisIRImages.current.length > 0) {
                    for (const IRImageIndex in AddVisIRImages.current) {
                        let IRImgObj = AddVisIRImages.current[IRImageIndex];
                        let Image1 = IRImgObj['ImagePath'] != null && IRImgObj['ImagePath'] != '' ? IRImgObj['ImagePath'] : '';

                        IRImageV += IRImageV != '' ? ' , ' : '';
                        IRImageV += ` ('${StoreId}','${d2}','${Image1}','${GbTempSessionId.current}','','${d2}') `;
                    }

                    let { Sess_StoreCode, Sess_TaskName, Sess_CatName, Sess_PhotoType } = GbTempSessionObj.current;
                    Sess_StoreCode = Sess_StoreCode || '';
                    Sess_TaskName = Sess_TaskName || '';
                    Sess_CatName = Sess_CatName || '';
                    Sess_PhotoType = Sess_PhotoType || '';
                    IRStatusV += IRStatusV != '' ? ' , ' : '';
                    IRStatusV += ` ('${StoreId}','${d2}','${GbTempSessionId.current}','','0','','${Sess_StoreCode}','${Sess_TaskName}','${Sess_CatName}','${Sess_PhotoType}','${d2}') `;

                }

                console.log('IRImageV additional_visibility:', IRImageV, IRStatusV);
                let add_data = `INSERT INTO ${AppTables.ADDITIONAL_VISIBILITY} (STORE_ID,VISIT_DATE,PRESENT,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,DISPLAY,DISPLAY_ID,REMARK,IMAGE,IS_UPDATED,FROM_DATE,TO_DATE,SHOWFROMDATE,ADDED_DATE) VALUES ${values} `;
                let add_IRImagesdata = `INSERT INTO ${AppTables.ADDVIS_IR_IMAGES} (STORE_ID,VISIT_DATE,IMAGE1,TEMP_SESSION_ID,UN_SESSION_ID,ADDED_DATE) VALUES ${IRImageV} `;
                let add_IRStatusdata = `INSERT INTO ${AppTables.ADDVIS_IRUPLOAD} (STORE_ID,VISIT_DATE,TEMP_SESSION_ID,UN_SESSION_ID,UPLOAD_STATUS,SYNC_STATUS,SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE,ADDED_DATE) VALUES ${IRStatusV} `;


                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    var isIRImageAdded = false, isIRStatusAdded = false;

                    if (IRImageV != '') {
                        console.log('execute IR image data');
                        isIRImageAdded = await executeQuery(add_IRImagesdata);
                    } else {
                        isIRImageAdded = true
                    }

                    if (IRStatusV != '') {
                        console.log('execute IR status data');
                        isIRStatusAdded = await executeQuery(add_IRStatusdata);
                    }
                    else {
                        isIRStatusAdded = true
                    }

                    console.log('isIRImageAdded:', isIRImageAdded, isIRStatusAdded);
                    if (!isIRImageAdded) {
                        setProcessing(false); notify('Cannot add Additional Visibility IR Images data');
                    }
                    else if (!isIRStatusAdded) {
                        setProcessing(false); notify('Cannot add Additional Visibility IR Status data');
                    }
                    else {
                        console.log('av added');
                        notify(ST.AdditionalVisibilityaddedsuccessfully, 'SHORT');
                        setProcessing(false);
                        setisDataExists(true);
                        // clear store data in local storage to avoiding re-set data for the store  
                        await clear_item('storeData')
                        BgUnsavedChanges(false);// when all data saved clear the unsaved changes flag 
                        props.navigation.goBack();// send back 
                        // if(isAddVisPresent){
                        //     setshowUploadAlert(true);
                        // }
                        // else{
                        //     props.navigation.goBack();
                        // }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Cannotaddadditionalvisibility) },);


            });
        } 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 isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
        // let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

        let isValid = true;

        // isKPIIREnable &&
        if (StoreCameraAllow && isAddVisPresent == 1 && (AddVisIRImages.current.length <= 0 || GbTempSessionId.current == '')) {
            isValid = false;
            notify("Please click images", 'SHORT');
        }

        console.log('isValid:', isValid);
        return isValid;
    }

    async function validateForm() {
        let isValid = true;
        let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path, FromDate, ToDate, showFromDateFlag } = AddVisFormData;

        let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
        let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
        let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

        let isToDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
        let isToDateKPIObj = isToDateIndex >= 0 ? KPIFields[isToDateIndex] : {};
        let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;

        // let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
        // let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;



        // if((CategoryName=='' || CategoryName==null )|| (CategoryId=='' || CategoryId==null)){
        //     isValid=false;
        //     notify(ST.PleaseSelectCategory,'SHORT');
        // }
        // else if((SubCategoryName=='' || SubCategoryName==null )|| (SubCategoryId=='' || SubCategoryId==null)){
        //     isValid=false;
        //     notify(ST.Pleaseselectsubcategory,'SHORT');
        // }
        // else if((BrandName=='' || BrandName==null )|| (BrandId=='' || BrandId==null)){
        //     isValid=false;
        //     notify(ST.Pleaseselectbrand,'SHORT');
        // }
        // else if((DisplayName=='' || DisplayName==null )|| (DisplayId=='' || DisplayId==null)){
        //     isValid=false;
        //     notify(ST.Pleaseselectdisplaytype,'SHORT');
        // }
        // // else if((Remark=='' || Remark==null )){
        // //     isValid=false;
        // //     notify('Please enter remark','SHORT');
        // // }
        // else if(isFromDateEnable==true && 
        //     !AddVisFormData.hasOwnProperty("FromDate") &&
        //      (FromDate=='' || FromDate==null )){
        //     isValid=false;
        //     notify('Please Select The From Date ','SHORT');
        // }else if(isToDateEnable==true &&
        //      !AddVisFormData.hasOwnProperty("ToDate") && 
        //      (ToDate=='' || ToDate==null )){
        //     isValid=false;
        //     notify('Please Select The To Date ','SHORT');
        // }
        // else if(StoreCameraAllow==true && !isKPIIREnable && (Image1=='' || Image1==null )){
        //     isValid=false;
        //     notify(ST.Pleaseclickimage,'SHORT');
        // }

        // console.log('isValid:',isValid);
        return isValid;
    }

    function onFormDataChange(val, key, type = '') {
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }

        let data = AddVisFormData;
        data[key] = val;
        // setAddVisFormData(data);
        // setHasUnsavedChanges(true);
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option, keyLbl, keyVal) {
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;

        CleanSelector(option, keyLbl, data)

        // setAddVisFormData(data);
        BgAddVisFormData(data)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);

    }

    function CleanSelector(option, keyLbl = '', data = {}) {

        if (keyLbl == 'CategoryName') {
            loadData(option.value, 'SubCategories');

            // clear subcategory and brand
            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';


            data['DisplayId'] = ''
            data['DisplayName'] = ''
            data['Remark'] = ''
            data['Image1Path'] = ''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
            // data['FromDate']='';
        }
        else if (keyLbl == 'SubCategoryName') {
            loadData(option.value, 'Brands');

            // clear brand
            data['BrandId'] = '';
            data['BrandName'] = '';

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        } else if (keyLbl == 'BrandName') {

            // clear brand

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        } else if (keyLbl == 'DisplayName') {

            // clear brand

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        }

    }
    async function loadData(qId, type) {
        try {
            await db.transaction(async function (txn) {
                let q = '';
                if (type == 'SubCategories') q = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where p.CategoryId='${qId}' and p.IsCompetitor='0' order by p.SubCategorySequence`;
                else if (type == 'Brands') q = `Select Distinct p.BrandName,p.BrandId from Product_Master p Where p.SubCategoryId='${qId}' and p.IsCompetitor='0' order by p.BrandSequence`;

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    // console.log('rowcount:,',type,':',txnres2.rows.length);
                    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) {
                                if (type == 'SubCategories') setSubCategories(arr);
                                else if (type == 'Brands') setBrands(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

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


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

    function onChoiceSelect(val, key) {
        let isDataPresent = AddVisibility.length > 0 || AddVisIRImages.current.length > 0;
        if (val == 0 && isDataPresent) {
            setShowRAllC_M(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        // setIsAddVisPresent(val);
        // setHasUnsavedChanges(true);
        BgIsAddVisPresent(val);
        BgUnsavedChanges(true)
        if (val == 0) {
            // setAddVisibility([]);
            // setAddVisFormData({});
            BgWindowData([])
            BgAddVisFormData({})
        }
    }

    function onConfirmRemoveAll() {
        // Remove all data 
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        // setIsAddVisPresent(0);
        // setHasUnsavedChanges(true);
        // setAddVisibility([]);
        // setAddVisFormData({});
        BgIsAddVisPresent(0);
        BgWindowData([])
        BgAddVisFormData({})
        setShowRAllC_M(false);

        // let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
        // let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

        // if(isKPIIREnable){
        //     if(AddVisIRImages.current.length>0){
        //         removeIRImage()
        //     }
        //     else{
        //         // setGbTempSessionId('');
        //         GbTempSessionId.current='';
        //     }
        // }

        BgUnsavedChanges(true)

    }

    async function removeIRImage() {
        // declare length of IRImages in starting as after deleteing IRphoto the length of refrence variable is also updated
        let AllIRImages = AddVisIRImages.current;
        let AllImageLen = AllIRImages.length;
        for (const IRImageIndex in AllIRImages) {
            let IRImgObj = AllIRImages[IRImageIndex];
            let Image1 = IRImgObj['ImagePath'] != null && IRImgObj['ImagePath'] != '' ? IRImgObj['ImagePath'] : '';

            let obj = { "IRImgIndex": IRImageIndex, "IRimgPath": Image1 };
            let isRemoved = await DeleteIRPhoto('2', obj);
            console.log("IR Image removed:", IRImageIndex, isRemoved);
            if (IRImageIndex == AllImageLen - 1) {
                console.log("do empty Session and images if all removed from IR session");
                // setGbTempSessionId('');
                GbTempSessionId.current = '';
                // setAddVisIRImages([]);
                AddVisIRImages.current = [];
            }

        }
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    async function Add_AddVis() {
        let isValid = await validateForm();
        console.log('isValid add:', isValid);
        if (isValid) {
            let arr = AddVisibility;
            let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = AddVisFormData;

            // let index=AddVisibility.findIndex(i=>i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId);
            // if(index>=0){
            //     notify(ST.Thisvisibilityhasalreadybeenadded,'LONG');
            // }
            // else{
            arr.push(AddVisFormData);
            // setAddVisibility(arr);
            // setHasUnsavedChanges(true);
            BgWindowData(arr)
            BgUnsavedChanges(true)
            notify(ST.AdditionalVisibilityaddedsuccessfully, 'LONG');
            setrerenderdata(!rerenderdata);

            // clear data
            setFromDate('');
            BgAddVisFormData({})
            setToDate('');
            // setAddVisFormData({});
            // }
        }

    }

    function showRemoveConfirm(item, index) {
        setToRemoveId(index);
        setToRemoveItem(item);
        setshowRemoveConfirm_M(true);
    }

    function Remove_AddVis() {
        let index = toRemoveId
        let item = toRemoveItem;
        let arr = AddVisibility;
        console.log('toRemoveId:', index);
        if (index >= 0 && index < arr.length) {
            arr.splice(index, 1);
            // setAddVisibility(AddVisibility);
            // setHasUnsavedChanges(true);
            BgWindowData(AddVisibility)
            BgUnsavedChanges(true)
            notify(ST.Visibilityremovedsuccessfully, 'LONG')
            setrerenderdata(!rerenderdata);
        }
        else {
            notify(ST.CannotremoveVisibilitynotfound, 'LONG')
        }
        setToRemoveId('');
        setToRemoveItem({});
        setshowRemoveConfirm_M(false);

    }


    function renderDatePicker(curDate, setTimeStamp, setDate, ColumnName, setShowDate) {
        // PODate2,setPODate2,setPODate,setShowDatePicker
        let today = new Date();
        console.log('renderDatePicker:', curDate, FromDate);
        let d1 = curDate != null && curDate != '' ? curDate : new Date();
        // let d1=new Date();
        console.log('d1 date:', d1);
        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={d1}
                mode={'date'}
                display="default"
                // maximumDate={today}
                onChange={(event, selectedDate) => {
                    console.log('onchange date', selectedDate);
                    if (selectedDate != null) {
                        console.log('change date', selectedDate);
                        let d2 = moment(selectedDate).format('DD/MM/YYYY');
                        let dateString = String(d2)
                        setShowDate(false);
                        setTimeStamp(selectedDate);
                        setDate(d2);
                        onFormDataChange(dateString, ColumnName)

                    }
                }}

            />
        );
    }



    function _render_RetakePopup() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={'If any image is blurred you can "Retake" or "Delete" the Image?'}
                showModal={showRetakeModal}
            >
                <View style={customStyle.IRretakeM_options}>
                    <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={() => { RetakeIRPhoto() }}>
                        <View style={customStyle.IRretakeM_optionsInn}>
                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$primary_color} />
                            <Text style={customStyle.IRretakeM_optionsBtnText}>Retake</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={() => { DeleteIRPhoto() }}>
                        <View style={customStyle.IRretakeM_optionsInn}>
                            <FontAwesome name='trash' size={20} color={PageTheme.$red} />
                            <Text style={customStyle.IRretakeM_optionsBtnText}>Delete</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={() => { closeRetakeOp() }}>
                        <View style={customStyle.IRretakeM_optionsInn}>
                            <Entypo name='cross' size={20} color={PageTheme.$red} />
                            <Text style={customStyle.IRretakeM_optionsBtnText}>Cancel</Text>
                        </View>
                    </TouchableOpacity>



                </View>
            </CustomModal>
        )
    }

    function _render_UploadAlert() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={'Upload IR Images! You cannot edit after images uploaded to the server!'}
                showModal={showUploadAlert}
            >
                <View style={customStyle.storelVisitM_options}>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setshowUploadAlert(false) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { UploadIRSessions() }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
                    </TouchableOpacity>
                </View>
            </CustomModal>
        )
    }

    function _renderIRCamera(IRImages, TempSessionId) {

        let isSaveDisabled = (isDataUploaded == 'U' || isDataUploaded == 'P');
        let isResumeDisabled = (TempSessionId == null || TempSessionId == '' || TempSessionId == 'undefined' || isSaveDisabled == true);

        return (
            <View style={customStyle.IRCamOnceWrap}>
                <View style={customStyle.SOSheadingsCon}>
                    <Text style={customStyle.SOSheadingsText}>{`Capture ${currentMenu.MenuName} Images`}</Text>
                </View>
                <View style={[customStyle.IRCamWrapper]}>
                    <View style={customStyle.IRCamImgWrap}>
                        {(IRImages != null && IRImages.length > 0) &&
                            IRImages.map((IRImg, IRImgIndex) => {
                                let IRimgPath = IRImg.ImagePath;
                                return (
                                    <TouchableOpacity style={customStyle.IRCamImageView} key={IRImgIndex} onPress={() => { openImageRefView(IRImgIndex) }}>
                                        {(IRimgPath != null && IRimgPath != '') && <Image style={customStyle.IRCamImage} source={{ uri: IRimgPath }} />}
                                        {(IRimgPath == null || IRimgPath == '') && <View style={customStyle.IRCamImage}></View>}
                                        <TouchableOpacity style={[customStyle.IRCamImage_OpBtn, isSaveDisabled ? { backgroundColor: PageTheme.$text_color_light } : {}]} disabled={isSaveDisabled} onPress={() => { openRetakeOp(IRImgIndex, IRimgPath) }}>
                                            <MaterialCommunityIcons name='camera-retake' size={15} color={PageTheme.$accent_color} />
                                        </TouchableOpacity>
                                    </TouchableOpacity>
                                );
                            })

                        }
                    </View>
                    <View style={[customStyle.IRCamCon, customStyle.IRCamConBG]}>
                        <TouchableOpacity style={[customStyle.IRCamBtns, customStyle.IRCamStartSess]} disabled={isSaveDisabled} onPress={() => { StartCameraSession() }}>
                            <AntDesign name='play' size={30} color={(isSaveDisabled ? PageTheme.$text_color_light : PageTheme.$primary_color)} />
                            <Text style={[customStyle.IRCamBtnsText, (isSaveDisabled ? { color: PageTheme.$text_color_light } : {})]}>Start Session</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={[customStyle.IRCamBtns, customStyle.IRCamStartSess]} disabled={isResumeDisabled} onPress={() => { ResumeCameraSession() }} >
                            <AntDesign name='pausecircle' size={30} color={(isResumeDisabled ? PageTheme.$text_color_light : PageTheme.$primary_color)} />
                            <Text style={[customStyle.IRCamBtnsText, (isResumeDisabled ? { color: PageTheme.$text_color_light } : {})]}>Resume Session</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }





    function _render_addVisFormTop() {
        let xpos = 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }

        // let isFromDateIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ShowFromDate');
        // let isFromDateKPIObj=isFromDateIndex>=0?KPIFields[isFromDateIndex]:{};
        // let isFromDateEnable=isFromDateIndex>=0?isFromDateKPIObj['KPIFieldEnable']:true;

        // let isToDateIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ShowToDate');
        // let isToDateKPIObj=isToDateIndex>=0?KPIFields[isToDateIndex]:{};
        // let isToDateEnable=isToDateIndex>=0?isToDateKPIObj['KPIFieldEnable']:true;

        // let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='KPIIREnable')
        // let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        // let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

        let isSaveDisabled = (isDataUploaded == 'U' || isDataUploaded == 'P');



        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                    <Text style={[customStyle.addvis_pText]}>{ST.IsPresent}</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, (isSaveDisabled ? customStyle.openStkCh_con_toggleDis : (isAddVisPresent == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red)),
                            {
                                transform: [{
                                    translateX: xpos
                                }],
                            }
                            ]}></Animated.View>
                            <TouchableOpacity style={customStyle.openStkCh_con1} disabled={isSaveDisabled} onPress={() => { onChoiceSelect(1, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isSaveDisabled && isAddVisPresent == 1 ? customStyle.openStkCh_con_toggleDisTxt : (isAddVisPresent == 1 ? customStyle.openStkCh_textactive : {}))]}>{ST.Yes}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} disabled={isSaveDisabled} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isSaveDisabled && isAddVisPresent == 0 ? customStyle.openStkCh_con_toggleDisTxt : (isAddVisPresent == 0 ? customStyle.openStkCh_textactive : {}))]}>{ST.No}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                </View>
                {
                    isAddVisPresent == 1 && (rerenderdata == rerenderdata) &&
                    <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                        <View style={customStyle.addVisForm}>
                            {/* isKPIIREnable &&  */}
                            {
                                _renderIRCamera(AddVisIRImages.current, GbTempSessionId.current)
                            }
                            {/* <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.Category}</Text>
                                {CustomPicker(props,Categories,'CategoryName','CategoryId','CategoryName','CategoryId',onselectionChange,{value:AddVisFormData.CategoryName},null,null,false,route)}
                                
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{'Sub Category'}</Text>
                                
                                {CustomPicker(props,SubCategories,'SubCategoryName','SubCategoryId','SubCategoryName','SubCategoryId',onselectionChange,{value:AddVisFormData.SubCategoryName},null,null,false,route)}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.Brands}</Text>
                                
                                {CustomPicker(props,Brands,'BrandName','BrandId','BrandName','BrandId',onselectionChange,{value:AddVisFormData.BrandName},null,null,false,route)}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.DisplayType}</Text>
                                {CustomPicker(props,DisplayList,'DisplayName','DisplayId','DisplayName','DisplayId',onselectionChange,{value:AddVisFormData.DisplayName},null,null,false,route)}
                            </View>
                        </View>
                        {isFromDateEnable==true &&
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={[customStyle.addVisFormGrp,{width:'100%'}]}>
                                <Text style={customStyle.addVisLabel}>{'From Date'}</Text>
                                <View style={[customStyle.AddStockM_col,customStyle.openStk_prd_date_inputCon,{width:'100%',paddingRight:5}]} >
                                    <Text style={customStyle.openStk_prd_dateInput}>{FromDate}</Text>
                                    <TouchableOpacity style={customStyle.openStk_prd_datePicker} onPress={()=>{setShowDatePicker1(true);}}>
                                        <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                    </TouchableOpacity>
                                </View>
                                {(ShowDatePicker1==true )&& 
                                    renderDatePicker(FromDate2,setFromDate2,setFromDate,'FromDate',setShowDatePicker1)
                                } 
                            </View>
                        </View>}
                        {isToDateEnable==true &&
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={[customStyle.addVisFormGrp,{width:'100%'}]}>
                                <Text style={customStyle.addVisLabel}>{'To Date'}</Text>
                                <View style={[customStyle.AddStockM_col,customStyle.openStk_prd_date_inputCon,{width:'100%',paddingLeft:5}]} >
                                    <Text style={customStyle.openStk_prd_dateInput}>{ToDate}</Text>
                                    <TouchableOpacity style={customStyle.openStk_prd_datePicker} onPress={()=>{setShowDatePicker(true);}}>
                                        <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                    </TouchableOpacity>
                                </View>
                                {(ShowDatePicker==true )&& 
                                    renderDatePicker(ToDate2,setToDate2,setToDate,"ToDate",setShowDatePicker)
                                } 
                            </View>
                        </View>}
                        
                        <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.Remark}</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                autoComplete='off'
                                value={(AddVisFormData.Remark || '')}
                                onChangeText={(val)=>{onFormDataChange(val,'Remark','text');}}
                                />
                            </View>
                        </View>
                        {!isKPIIREnable && 
                        <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{ST.Image}</Text>
                                <View style={customStyle.addVisCameras}>
                                    <View style={customStyle.openStkCameraCon}>
                                    { (AddVisFormData.Image1Path=='' || AddVisFormData.Image1Path==null) ?
                                        <TouchableOpacity onPress={()=>{openCamera('1')}}>
                                            <SvgXml width={50} height={50} xml={CameraImg5} />
                                        </TouchableOpacity> : (AddVisFormData.Image1Path!='' && AddVisFormData.Image1Path!=null) ?
                                        <TouchableOpacity onPress={()=>{OpenImgModal(AddVisFormData.Image1Path,'1')}}>
                                            <SvgXml width={50} height={50} xml={CameraImg3} />
                                        </TouchableOpacity> : null
                                    } 

                                    </View>
                                    
                                </View>
                            </View>
                        </View>
                        }
                        <View style={customStyle.addVis_btnWrap}>
                            <TouchableOpacity style={[customStyle.addVis_btn,(isSaveDisabled?{backgroundColor:PageTheme.$text_color_light}:{})]} disabled={isSaveDisabled} onPress={()=>{Add_AddVis()}}>
                                <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                            </TouchableOpacity>
                        </View>
                    </View> */}
                        </View>
                        {/* <View style={customStyle.addVis_list}>
                    <Text style={customStyle.addVis_listhdrText}>{ST.AddedVisibilities}</Text>
                    <View style={customStyle.addVis_listInner}>
                        {
                            AddVisibility.length>0 &&
                            AddVisibility.map((item,index)=>{
                                console.log(item);
                                return (
                                    <View key={index} style={customStyle.addVis_listItem}>
                                        <View style={customStyle.addVis_listI_row2}>
                                            <View style={[customStyle.addVis_listIcol1,(isKPIIREnable?{width:'100%'}:{})]}>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{ST.Category+' :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.CategoryName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{ST.SubCategory+' :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.SubCategoryName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{ST.Brands+' :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.BrandName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{ST.DisplayType+' :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.DisplayName}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listI_row]}>
                                                    <Text style={customStyle.addVis_listI_Label}>{ST.Remark+' :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.Remark}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listI_row]}>
                                                    <Text style={customStyle.addVis_listI_Label}>{'From Date :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.FromDate}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listI_row,customStyle.addVis_listI_lastrow]}>
                                                    <Text style={customStyle.addVis_listI_Label}>{'To Date :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.ToDate}</Text>
                                                </View>
                                            </View>
                                            {!isKPIIREnable && 
                                            <View style={customStyle.addVis_listIcol2}>
                                                <Text style={[customStyle.addVis_listI_Label2,customStyle.mb20]}>{ST.Image}</Text>
                                                {(item.Image1Path!=null && item.Image1Path!='') && <Image style={customStyle.addVis_listI_Image} source={{uri:item.Image1Path}} />}
                                            </View>}
                                            <TouchableOpacity style={[customStyle.addVis_btnRemove,(isSaveDisabled?{backgroundColor:PageTheme.$text_color_light}:{})]} disabled={isSaveDisabled} onPress={()=>{showRemoveConfirm(item,index)}}>
                                               <FontAwesome name='trash' size={20} color={(isSaveDisabled?'#000':'red')} />
                                            </TouchableOpacity>
                                        </View>
                                        
                                       
                                    </View>
                                );
                            })
                        }
                    </View>
                </View> */}
                    </ScrollView>
                }
            </View>
        )
    }

    function _renderBtns() {

        let isUploadDisabled = isDataUploaded == 'U';
        let isSaveDisabled = (isDataUploaded == 'U' || isDataUploaded == 'P');

        let colors1 = (isUploadDisabled ? [PageTheme.$tertiary_color, PageTheme.$tertiary_color] : [PageTheme.$secondary_color_light, PageTheme.$gradient2, PageTheme.$primary_color]);
        let colors2 = (isSaveDisabled ? [PageTheme.$tertiary_color, PageTheme.$tertiary_color] : [PageTheme.$secondary_color_light, PageTheme.$gradient2, PageTheme.$primary_color]);

        return (
            <View style={customStyle.opening_Stock_btnWrap}>
                <GradientButton {...props} title={'Save'} onPress={() => { onSubmitData() }} />
            </View>

        )
    }

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

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {_OpenCaptureImage_Modal()}
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, ST.Doyoureallywanttoremovethisvisibility)}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, ST.Doyoureallywanttoremoveallvisibilitydata)}
            {_render_RetakePopup()}
            {_render_UploadAlert()}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} onImageCaptured={(imgData) => { UpdateShowCameraRef(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { UpdateShowCameraRef(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]}>
                    {Object.keys(storeData).length > 0 &&
                        <View style={customStyle.addVis_Wrapper}>
                            {_render_addVisFormTop()}
                        </View>
                    }
                    {/* <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>   */}
                    {_renderBtns()}
                </View>

            </LinearGradient>
            {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)(AdditionalVisibilityIR_Only);