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, Keyboard } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, getKPIFields, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, FontAwesome, MaterialCommunityIcons, MaterialIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';

import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import Camera_icon_grey from '../assets/performics/camera_icon_grey.svg';

import SamplingHeaderTab from '../components/SamplingHeaderTab';
import GradientButton from '../components/gradientButton';


function SamplingView(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('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);

    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderAll, setrerenderAll] = useState(false);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [Refresh1, setRefresh1] = useState(0);

    // const [AddVisFormData, setAddVisFormData] = useState({});
    const [AddVisFormData, setAddVisFormData] = useState({});

    const [removeAllTabsData, setRemoveAllTabsData] = useState(false);
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [showSaveAlert, setShowSaveAlert] = useState(false);
    const [Companies, setCompanies] = useState([]);
    const [SamplingData, setSamplingData] = useState({});
    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 [getImageProps, setGetImageProps] = useState({});
    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 [showSwitchCamera, setShowSwitchCamera] = useState(false);

    const [showRAllC_MData, setShowRAllC_MData] = useState({});

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });
    const [SamplingTabObj, setSamplingTabObj1] = useState({});
    const [isLunchTime, setIsLunchTime] = useState(false);
    const [saveModalDObj, setSaveModalDObj] = useState({});
    const [reasons_list, setReasons_list] = useState([]);

    const [reason, setReason] = useState({});

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


    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');

    const animatedChoice = useRef(new Animated.Value(0)).current;
    const animatedChoice2 = useRef(new Animated.Value(0)).current;
    const SamplingTabObjRef = React.useRef(SamplingTabObj);
    const rerenderdata2Ref = React.useRef(rerenderdata2);


    useEffect(() => {
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};

        let isAdhoc = params.isAdhoc || false;
        let isBeat = params.isBeat != null ? params.isBeat : false;
        let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
        let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;

        let SamplingDataItem = params.SamplingData

        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setIsNonMerchan(isNonMerchan1);
        setIsNonProg(isNonProgam)

        setStoreData(storeData1);
        setCurrentMenu(menu1);

        setSamplingData(SamplingDataItem);


        getData(storeData1, menu1, SamplingDataItem);

        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log("refresh data")
            getData(storeData1, menu1, SamplingDataItem);

        });

        return function cleanup() {
            willFocusSubscription();
            return unsubscribe;
        };
    }, []);



    async function saveDataOnRefresh() {
        if (AddVisFormData.SamplingIsPresent == true) {
            let AllDataIsFilled = await CheckIfSamlingCompleted();
            console.log("AllDataIsFilled:", AllDataIsFilled);
            if (AllDataIsFilled) {
                onSubmitData();
            }
        }
    }

    function SamplingTabObjUpdate(val) {
        SamplingTabObjRef.current = val
        setSamplingTabObj1(val);
    }

    function rerenderdata2Update(val) {
        rerenderdata2Ref.current = val
        setrerenderdata2(val)
        // setSamplingTabObj1(val);
    }

    useEffect(() => {
        checkFilledData()
    });


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

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

    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else {
            if (hasUnsavedChanges == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }

    async function checkFilledData() {
        if (AddVisFormData.SamplingIsPresent == true || AddVisFormData.SamplingIsPresent == 1) {
            let AllDataIsFilled = await CheckIfSamlingCompleted();
            if (AllDataIsFilled == false) {
                updateTblSampling();
            }
        }

    }

    async function updateTblSampling(e) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            db.transaction(async function (txn) {
                let { SamplingDefinitionId } = SamplingData;
                let KioskSetupPresent = SamplingData.KioskSetup == '1' || SamplingData.KioskSetup == 'true' || SamplingData.KioskSetup == true ? true : false;

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

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


    function onRemoveScreen(e) {
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
                {
                    text: "Cancel",
                    onPress: () => { },
                    style: "cancel"
                },
                { text: "OK", onPress: () => { setHasUnsavedChanges(false); props.navigation.dispatch(e.data.action); } }
            ]
        );
    }


    async function OpenImgModal(imgPath, keyName, ImageLabel) {
        setSelectedImg(imgPath)
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        }
        else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ keyName, ImageLabel })
    }

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


    async function getData(storeData1, menu1, SamplingDataItem1) {
        setLoaderTitle("Loading...");
        setProcessing(true);
        try {
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);

            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SwitchingCamera');
            let SwitchingCameraObj = SwitchingCameraI >= 0 ? AllKPIFields[SwitchingCameraI] : {};
            let SwitchingCamera = SwitchingCameraI >= 0 ? SwitchingCameraObj['KPIFieldEnable'] : false;

            let isSaleDependIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'SaleDependOnStock')
            let isSaleDependPIObj = isSaleDependIndex >= 0 ? AllKPIFields[isSaleDependIndex] : {};
            let isSaleDependEnable = isSaleDependIndex >= 0 ? isSaleDependPIObj['KPIFieldEnable'] : true;

            setShowSwitchCamera(SwitchingCamera);



            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

            let InventoryRequired = SamplingDataItem1.InventoryRequired == true || SamplingDataItem1.InventoryRequired == "true" ? 1 : 0;
            let CustomerTrackingRequired = SamplingDataItem1.CustomerTrackingRequired == true || SamplingDataItem1.CustomerTrackingRequired == "true" ? 1 : 0;
            let CustomerConversionRequired = SamplingDataItem1.CustomerConversionRequired == true || SamplingDataItem1.CustomerConversionRequired == "true" ? 1 : 0;
            let LunchTimeRequired = SamplingDataItem1.LunchTimeRequired == true || SamplingDataItem1.LunchTimeRequired == "true" ? 1 : 0;
            let SaleRequired = SamplingDataItem1.SaleRequired == true || SamplingDataItem1.SaleRequired == "true" ? 1 : 0;
            let StockRequird = SamplingDataItem1.StockRequird == true || SamplingDataItem1.StockRequird == "true" ? 1 : 0;

            await db.transaction(async function (txn) {
                let StockAvil = false;

                // get done count for stock // -- add available only if product available 
                if (StockRequird) {

                    let q6 = `Select * FROM ${AppTables.SAMPLING_STOCK_DATA} T WHERE T.SAMPLING_DEFINITION_ID='${SamplingDataItem1.SamplingDefinitionId}'`;

                    await txn.executeSql(q6, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;
                        if (txnres2.rows.length > 0) {
                            console.log("StockAvil------")
                            StockAvil = true
                            alldata['StockAvil'] = true;
                        } else {
                            StockAvil = false
                            alldata['StockAvil'] = false;
                        }

                        SamplingTabObjUpdate(alldata)
                        console.log("alldata---", alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current)
                    }, function (txnE, txnerr) { console.log(txnerr); },);


                    let selectlist4 = ` DISTINCT T.SamplingStockValue, count(T.SamplingDefinitionId) as QtnAvlblCount,count(T1.SAMPLING_DEFINITION_ID) as QtnDoneCount`;
                    let join4 = ` LEFT OUTER JOIN ${AppTables.SAMPLING_STOCK_DATA} T1 on T.SamplingDefinitionId=T1.SAMPLING_DEFINITION_ID And T.SamplingStockValue=T1.SAMPLING_STOCK_VALUE AND T1.STORE_ID='${StoreId}'  AND T1.VISIT_DATE='${d2}'`;
                    let q4 = `Select ${selectlist4} FROM Master_SamplingStockDefinition T ${join4} WHERE T.SamplingDefinitionId='${SamplingDataItem1.SamplingDefinitionId}'`;


                    // let q4=`SELECT count(c.STOCK) as StockQtnCount from ${AppTables.SAMPLING_STOCK_DATA} c where c.SAMPLING_DEFINITION_ID='${SamplingDataItem1.SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' AND c.VISIT_DATE='${d2}' And c.STOCK is not null and  c.STOCK!=""`;  

                    await txn.executeSql(q4, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;
                        if (txnres2.rows.length > 0) {
                            let checkOut = txnres2.rows.item(0);
                            alldata["StockIsDone"] = checkOut && checkOut.QtnDoneCount > 0 ? true : false;
                            alldata["StockIsAvlbl"] = checkOut && checkOut.QtnAvlblCount > 0 ? true : false;

                        } else {
                            alldata["StockIsAvlbl"] = false
                        }

                        SamplingTabObjUpdate(alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current)
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }

                let q3 = `Select SamplingReasonId as ReasonId,SamplingReason as Reason From Master_SamplingReason`;
                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];

                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                console.log('Master_SamplingReason-----', arr)
                                setReasons_list(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                // get Available and done count for inventory
                if (InventoryRequired) {
                    let selectlist = ` DISTINCT T.QuestionCategoryId, count(T.SamplingQuestionId) as QtnAvlblCount,count(T1.QUESTION_ID) as QtnDoneCount`;
                    let join2 = ` LEFT OUTER JOIN ${AppTables.SAMPLING_INVENTORY} T1 on T.QuestionCategoryId=T1.CATEGORY_ID And T.SamplingQuestionId=T1.QUESTION_ID AND T1.STORE_ID='${StoreId}'  AND T1.VISIT_DATE='${d2}'`;
                    let join3 = ` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId `
                    let q2 = `Select ${selectlist} FROM Master_SamplingQuestion T ${join2} ${join3} WHERE T.QuestionCategoryId='${SamplingDataItem1.InventoryQuestionCategoryId}' `;
                    q2 += ` ORDER BY T.SamplingQuestionSequence `;

                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;
                        console.log("Inventory count:", txnres2.rows.length, q2);
                        if (txnres2.rows.length > 0) {
                            let data = txnres2.rows.item(0);
                            console.log("Inventory data:", data, SamplingDataItem1.InventoryQuestionCategoryId);
                            alldata["inventoryIsDone"] = data && data.QtnDoneCount > 0 ? true : false;
                            alldata["inventoryIsAvlbl"] = data && data.QtnAvlblCount > 0 ? true : false;
                        } else {
                            alldata["inventoryIsAvlbl"] = false;
                        }
                        SamplingTabObjUpdate(alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current);
                    }, function (txnE, txnerr) { console.log("error 404-", txnerr); },);
                }

                // get done count for customer tracking
                if (CustomerTrackingRequired) {

                    let selectlist = ` DISTINCT T.QuestionCategoryId, count(T.SamplingQuestionId) as QtnAvlblCount,count(T1.QUESTION_ID) as QtnDoneCount`;
                    let join3 = ` LEFT OUTER JOIN ${AppTables.SAMPLING_CUST_TRACK} T1 on T.QuestionCategoryId=T1.CATEGORY_ID And T.SamplingQuestionId=T1.QUESTION_ID AND T1.STORE_ID='${StoreId}' AND T1.SAMPLING_DEFINITION_ID='${SamplingDataItem1.SamplingDefinitionId}'  AND T1.VISIT_DATE='${d2}'`;
                    let join9 = ` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId `
                    let q3 = `Select ${selectlist} FROM Master_SamplingQuestion T ${join3} ${join9} WHERE T.QuestionCategoryId=='${SamplingDataItem1.CustomerTrackingQuestionCategoryId}' `;
                    q3 += ` ORDER BY T.SamplingQuestionSequence `;

                    // let q3=`Select * from ${AppTables.SAMPLING_CUST_TRACK} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND CATEGORY_ID='${SamplingDataItem1.CustomerTrackingQuestionCategoryId}' `;
                    await txn.executeSql(q3, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;

                        if (txnres2.rows.length > 0) {
                            let data1 = txnres2.rows.item(0);
                            alldata["trackIsAvlbl"] = data1 && data1.QtnAvlblCount > 0 ? true : false;
                            alldata["trackIsDone"] = data1 && data1.QtnDoneCount > 0 ? true : false;
                        } else {
                            alldata["trackIsAvlbl"] = false
                        }

                        SamplingTabObjUpdate(alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current)
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }

                // get done count for customer tracking
                if (CustomerConversionRequired) {

                    let q3 = `Select * from ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' and SAMPLING_DEFINITION_ID='${SamplingDataItem1.SamplingDefinitionId}' and VISIT_DATE='${d2}' AND SCREEN_TYPE='SamplingContactConversion' `;
                    await txn.executeSql(q3, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;
                        if (txnres2.rows.length > 0) {
                            alldata["ContactIsDone"] = true
                        } else {
                            alldata["ContactIsDone"] = false
                        }

                        SamplingTabObjUpdate(alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current)
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }

                // get done count for sale // -- add available only if product available 
                if (SaleRequired) {
                    let selectlist5 = ` DISTINCT T.SamplingStockValue, count(T.SamplingDefinitionId) as QtnAvlblCount,count(T1.SAMPLING_DEFINITION_ID) as QtnDoneCount`;
                    let join5 = ` LEFT OUTER JOIN ${AppTables.SAMPLING_SALE_DATA} T1 on T.SamplingDefinitionId=T1.SAMPLING_DEFINITION_ID And T.SamplingStockValue=T1.SAMPLING_STOCK_VALUE AND T1.STORE_ID='${StoreId}'  AND T1.VISIT_DATE='${d2}'`;
                    let q5 = `Select ${selectlist5} FROM Master_SamplingStockDefinition T ${join5} WHERE T.SamplingDefinitionId='${SamplingDataItem1.SamplingDefinitionId}'`;

                    await txn.executeSql(q5, [], async function (txn2, txnres2) {
                        let alldata = SamplingTabObjRef.current;
                        if (txnres2.rows.length > 0) {
                            let checkOut = txnres2.rows.item(0);
                            alldata["SaleIsDone"] = checkOut && checkOut.QtnDoneCount > 0 ? true : false;
                            alldata["SaleIsAvlbl"] = checkOut && checkOut.QtnAvlblCount > 0 ? true : false;
                        } else {
                            alldata['SaleIsAvlbl'] = false;
                        }

                        SamplingTabObjUpdate(alldata)
                        rerenderdata2Update(!rerenderdata2Ref.current)
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }

                let sample_q = `SELECT * FROM ${AppTables.SAMPLING_LIST} WHERE STORE_ID='${StoreId}' and SAMPLING_DEFINITION_ID='${SamplingDataItem1.SamplingDefinitionId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(sample_q, [], async function (txn2, txnres2) {
                    console.log("sampling data len:", txnres2.rows.length);
                    if (txnres2.rows.length > 0) {
                        let data1 = txnres2.rows.item(0);
                        let addvisFormdata = AddVisFormData;
                        console.log("sampling data:", data1);

                        let imagePath = `file://${ImageFolderPath + menu1.ScreenName}/`;
                        let isSamplingPresent = data1.SAMPLING_PRESENT == 1 ? 1 : 0;
                        let isReasonId = data1.REASONID != null ? data1.REASONID : 0;
                        let isReason = data1?.REASON != null ? data1?.REASON : '';
                        let isKiosksetupPresent = data1.KIOSKSETUP == 1 ? 1 : 0;
                        if (isSamplingPresent == 0) {
                            setReason({ "label": isReason, "value": isReasonId })
                        }

                        addvisFormdata["SamplingIsPresent"] = isSamplingPresent;
                        addvisFormdata["ReasonId"] = isReasonId;
                        addvisFormdata["Reason"] = isReason;
                        addvisFormdata["KioskIsPresent"] = isKiosksetupPresent;

                        Animated.timing(animatedChoice, {
                            toValue: isSamplingPresent,
                            duration: 400,
                            useNativeDriver: false,
                        }).start();

                        Animated.timing(animatedChoice2, {
                            toValue: isKiosksetupPresent,
                            duration: 400,
                            useNativeDriver: false,
                        }).start();


                        // if(data1.START_IMAGE1!=''){
                        //     let alldata=SamplingTabObj;
                        //     alldata["allTabDisable"]=false

                        //     SamplingTabObjUpdate(alldata)
                        //     rerenderdata2Update(!rerenderdata2Ref.current)
                        // }

                        addvisFormdata["StartLunchStamp"] = data1.START_LUNCH
                        addvisFormdata["EndLunchStamp"] = data1.END_LUNCH

                        addvisFormdata["StartTimeImage1"] = data1.START_IMAGE1
                        addvisFormdata["StartTimeImage2"] = data1.START_IMAGE2
                        addvisFormdata["EndTimeImage1"] = data1.END_IMAGE1
                        addvisFormdata["EndTimeImage2"] = data1.END_IMAGE2

                        addvisFormdata["StartTimeImage1path"] = data1.START_IMAGE1 != '' ? imagePath + data1.START_IMAGE1 : ""
                        addvisFormdata["StartTimeImage2path"] = data1.START_IMAGE2 != '' ? imagePath + data1.START_IMAGE2 : ""
                        addvisFormdata["EndTimeImage1path"] = data1.END_IMAGE1 != "" ? imagePath + data1.END_IMAGE1 : ''
                        addvisFormdata["EndTimeImage2path"] = data1.END_IMAGE2 != "" ? imagePath + data1.END_IMAGE2 : ''

                        addvisFormdata["StartTimeImage1stamp"] = data1.START_IMG_TIME
                        addvisFormdata["EndTimeImage1stamp"] = data1.END_IMG_TIME

                        //Lunch started but not ended yet 
                        if (data1.START_LUNCH != null && data1.START_LUNCH != '' && (data1.END_LUNCH == null || data1.END_LUNCH == '')) {
                            setIsLunchTime(true);
                        }

                        setAddVisFormData(addvisFormdata);
                        setrerenderdata(!rerenderdata)
                        setProcessing(false);
                    }
                    else {
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

                let alldata2 = SamplingTabObjRef.current;
                alldata2['isSaleDependEnable'] = isSaleDependEnable;
                SamplingTabObjUpdate(alldata2)
                rerenderdata2Update(!rerenderdata2Ref.current)

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


    async function StartLunch() {
        let addvisdata = AddVisFormData;
        let { StartLunchStamp } = addvisdata;
        if (StartLunchStamp == null || StartLunchStamp == '') {
            let picture_clicked_STamp = moment(new Date()).format('HH:mm:ss');
            addvisdata["StartLunchStamp"] = picture_clicked_STamp;
            // let alldata=SamplingTabObj;
            // alldata["allTabDisable"]=true

            // setSamplingTabObj1(alldata)
            // SamplingTabObjUpdate(alldata)

            setAddVisFormData(addvisdata);
            setIsLunchTime(true);
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
            rerenderdata2Update(!rerenderdata2Ref.current);
        } else {
            notify('You have already started lunch', 'SHORT');
        }
    }

    async function EndLunch() {
        let addvisdata = AddVisFormData;
        let { EndLunchStamp } = addvisdata;
        if (EndLunchStamp == null || EndLunchStamp == '') {
            let picture_clicked_STamp = moment(new Date()).format('HH:mm:ss');
            addvisdata["EndLunchStamp"] = picture_clicked_STamp

            // let alldata=SamplingTabObj;
            // alldata["allTabDisable"]=false

            // setSamplingTabObj1(alldata)
            // SamplingTabObjUpdate(alldata)
            setAddVisFormData(addvisdata);
            setIsLunchTime(false);
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
            rerenderdata2Update(!rerenderdata2Ref.current);
        } else {
            notify('You have already end lunch', 'SHORT');
        }
    }

    async function getImage(imgdata) {
        let type = getImageProps.type || '';
        let keyName = getImageProps.keyName || '';

        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify('Camera unavailable');
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();

            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')


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

            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_SamplingImg-' + calculate_tym_date_for_filename + '.jpg';

            const mark_text1 = calculate_tym_date_over_img;

            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | SampleDef Id:' + SamplingData.SamplingDefinitionId + ' | Image Type: ' + currentMenu.MenuName + ' | Date:' + calculate_tym_date_over_img;

            let picture_clicked_STamp = moment(picture_clickedd).format('HH:mm:ss');

            let addvisdata = AddVisFormData;
            let image_key = keyName;
            let image_path_key = keyName + "path";
            let imgTime = keyName + "stamp"
            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;
                    addvisdata[imgTime] = picture_clicked_STamp

                    setSelectedImg(uri)
                    setAddVisFormData(addvisdata);
                    setHasUnsavedChanges(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 { keyName, ImageLabel } = reCapImgModalObj
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={currentMenu.MenuName + " Image"}
                message={ImageLabel}
                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(keyName) }}>
                            <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>
        )
    }


    async function openCamera(keyName = '') {
        // stop user to lock by adding end image if all the fields are not done  
        let isValid = true;
        if (keyName == 'EndTimeImage1') {
            isValid = await CheckIfSamlingCompleted(true, false);
        }
        console.log("openCamera isValid:", isValid, keyName);
        if (isValid) {
            setGetImageProps({ keyName: keyName });
            setShowCamera(true);
        }
    }

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


    async function saveData() {
        let { screenName, params } = saveModalDObj;
        setShowAlert(false);
        setShowSaveAlert(false)
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {
                let { SamplingDefinitionId } = SamplingData;
                let KioskSetupPresent = SamplingData.KioskSetup == '1' || SamplingData.KioskSetup == 'true' || SamplingData.KioskSetup == true ? true : false;


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

                //remove All tabs Data
                if (removeAllTabsData) {
                    let q1 = `DELETE FROM ${AppTables.SAMPLING_INVENTORY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  `;
                    await txn.executeSql(q1, [], async function (txn2, txnres) {
                        console.log('SAMPLING_INVENTORY data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    let q2 = `DELETE FROM ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' and SCREEN_TYPE='SamplingContactConversion' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  `;
                    await txn.executeSql(q2, [], async function (txn2, txnres) {
                        console.log('SamplingContactConversion data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    let q3 = `DELETE FROM ${AppTables.SAMPLING_STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  `;
                    await txn.executeSql(q3, [], async function (txn2, txnres) {
                        console.log('Sampling stock data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    let q4 = `DELETE FROM ${AppTables.SAMPLING_SALE_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  `;
                    await txn.executeSql(q4, [], async function (txn2, txnres) {
                        console.log('Sampling Sale data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);

                    let q5 = `DELETE FROM ${AppTables.SAMPLING_CUST_TRACK} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' `;
                    await txn.executeSql(q5, [], async function (txn2, txnres) {
                        console.log('Sampling customer tracking data deleted');
                    }, function (txnE, txnerr) { console.log(txnerr); },);
                }


                let AllDataIsFilled = await CheckIfSamlingCompleted();
                console.log("AllDataIsFilled:", AllDataIsFilled);

                var values = '', add_data = '';
                let { SamplingIsPresent, KioskIsPresent, StartTimeImage1, StartTimeImage2, EndTimeImage1, EndTimeImage2, StartLunchStamp, EndLunchStamp, StartTimeImage1stamp, EndTimeImage1stamp } = AddVisFormData;
                let samplinPres = SamplingIsPresent == 1 || SamplingIsPresent == '1' ? 1 : 0;
                let kioskPres = KioskIsPresent == 1 || KioskIsPresent == '1' ? 1 : 0;

                let ReasonId = reason?.value != null ? reason?.value : 0;
                let Reason = reason?.label != null ? reason?.label : '';

                let item = AddVisFormData
                let goBackOnSave = false;
                if (samplinPres == 1 && ((KioskSetupPresent && kioskPres == 1) || !KioskSetupPresent)) {
                    //STORE_ID,VISIT_DATE,SAMPLING_PRESENT, KIOSKSETUP,SAMPLING_DEFINITION_ID,START_IMAGE1,START_IMAGE2,END_IMAGE1,END_IMAGE2,START_LUNCH,END_LUNCH,START_IMG_TIME,END_IMG_TIME,ISFILLED,ADDED_DATE
                    values += ` ('${StoreId}','${d2}','${samplinPres}','${kioskPres}','${SamplingDefinitionId}','${StartTimeImage1 || ''}','${StartTimeImage2 || ''}','${EndTimeImage1 || ''}','${EndTimeImage2 || ''}','${StartLunchStamp || ''}','${EndLunchStamp || ''}','${StartTimeImage1stamp || ''}','${EndTimeImage1stamp || ''}','${AllDataIsFilled ? 1 : 0}','${d2}','${ReasonId}','${Reason}') `;
                    goBackOnSave = AllDataIsFilled;
                }
                else {
                    values += ` ('${StoreId}','${d2}','${samplinPres}','${kioskPres}','${SamplingDefinitionId}','','','','','','','','','1','${d2}','${ReasonId}','${Reason}') `;
                    goBackOnSave = true;
                }

                console.log('sampling data to save:', values);
                // if(DataExist==true){
                //     add_data=`UPDATE ${AppTables.SAMPLING_LIST} SET SAMPLING_PRESENT='${samplinPres}',KIOSKSETUP='${kioskPres}',START_IMAGE1='${StartTimeImage1||""}',START_IMAGE2='${StartTimeImage2||""}',END_IMAGE1='${EndTimeImage1||""}',END_IMAGE2='${EndTimeImage2||""}',START_LUNCH='${StartLunchStamp||""}',END_LUNCH='${EndLunchStamp||""}',START_IMG_TIME='${StartTimeImage1stamp||""}',END_IMG_TIME='${EndTimeImage1stamp||""}', ISFILLED='${AllDataIsFilled?1:0}' WHERE STORE_ID='${StoreId}' and SAMPLING_DEFINITION_ID='${SamplingData.SamplingDefinitionId}' and VISIT_DATE='${d2}' `;
                // }else{
                add_data = `INSERT INTO ${AppTables.SAMPLING_LIST} (STORE_ID,VISIT_DATE,SAMPLING_PRESENT, KIOSKSETUP,SAMPLING_DEFINITION_ID,START_IMAGE1,START_IMAGE2,END_IMAGE1,END_IMAGE2,START_LUNCH,END_LUNCH,START_IMG_TIME,END_IMG_TIME,ISFILLED,ADDED_DATE,REASONID,REASON) VALUES ${values} `;
                // }


                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('sampling added');
                    notify('Sampling added successfully', 'SHORT');
                    setProcessing(false);
                    setHasUnsavedChanges(false);
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')
                    if (goBackOnSave) {
                        props.navigation.goBack();
                    }
                    if (Object.keys(saveModalDObj).length > 0 && screenName != null && screenName != '') {
                        props.navigation.navigate(screenName, params);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add sampling data') },);


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

    // useEffect(()=>{
    //     validateDis()
    // },[Refresh1])

    // async function validateDis(){

    //     let isValid=false;
    //     let alldata=SamplingTabObj;

    //     // if(AddVisFormData && (AddVisFormData.SamplingIsPresent==1) && (AddVisFormData.KioskIsPresent==1)){
    //         // console.log("testvalidate----------1",AddVisFormData)

    //         // || ( (SamplingData.StartTimeImage2==true || SamplingData.StartTimeImage2=="true" ) && (!AddVisFormData.hasOwnProperty('StartTimeImage2path') || AddVisFormData.StartTimeImage2path=='' || AddVisFormData.StartTimeImage2path==null))

    //         if( (Object.keys(AddVisFormData).length == 0) || (AddVisFormData && ( ( (SamplingData.StartTimeImage1==true || SamplingData.StartTimeImage1=="true" ) && (!AddVisFormData.hasOwnProperty('StartTimeImage1path') || AddVisFormData.StartTimeImage1path=='' || AddVisFormData.StartTimeImage1path==null) )))){
    //             isValid=true;
    //         }else if( AddVisFormData && (  (AddVisFormData.StartLunchStamp!= undefined && AddVisFormData.StartLunchStamp!='' && AddVisFormData.StartLunchStamp!=null ) && (AddVisFormData.EndLunchStamp== undefined || AddVisFormData.EndLunchStamp=='' || AddVisFormData.EndLunchStamp==null) )){
    //             isValid=true;
    //             console.log("allTabDisable isValid--start-",isValid,AddVisFormData.StartLunchStamp , (AddVisFormData.StartLunchStamp!= undefined || AddVisFormData.StartLunchStamp!='' || AddVisFormData.StartLunchStamp!=null ),"&&",(AddVisFormData.EndLunchStamp== undefined || AddVisFormData.EndLunchStamp=='' || AddVisFormData.EndLunchStamp==null))
    //             // notify('Please capture end time image','SHORT'); 
    //         }
    //     // }

    //     alldata["allTabDisable"]=isValid
    //     console.log("allTabDisable isValid---4",alldata,AddVisFormData)
    //     SamplingTabObjUpdate(alldata)
    //     rerenderdata2Update(!rerenderdata2Ref.current);
    // }   


    async function validate() {
        let isValid = true;
        let KioskSetupPresent = SamplingData.KioskSetup == '1' || SamplingData.KioskSetup == 'true' || SamplingData.KioskSetup == true ? true : false;
        let StartTimeImage1 = SamplingData.StartTimeImage1 == '1' || SamplingData.StartTimeImage1 == 'true' || SamplingData.StartTimeImage1 == true ? true : false;
        let StartTimeImage2 = SamplingData.StartTimeImage2 == '1' || SamplingData.StartTimeImage2 == 'true' || SamplingData.StartTimeImage2 == true ? true : false;

        let { SamplingIsPresent, KioskIsPresent, StartTimeImage1path, StartTimeImage2path, EndTimeImage1path, EndTimeImage2path, StartLunchStamp, EndLunchStamp } = AddVisFormData;
        SamplingIsPresent = SamplingIsPresent == 1 || SamplingIsPresent == '1' ? 1 : 0;
        KioskIsPresent = KioskIsPresent == 1 || KioskIsPresent == '1' ? 1 : 0;

        if (SamplingIsPresent && ((KioskSetupPresent && KioskIsPresent == 1) || !KioskSetupPresent)) {
            if (StartTimeImage1 && (StartTimeImage1path == null || StartTimeImage1path == '')) {
                isValid = false;
                notify('Please capture start time image', 'SHORT');
            }
        } else if (SamplingIsPresent == 0 && (reason?.label == "" || reason?.label == null)) {
            isValid = false;
            notify('Please select reason', 'SHORT');
        }

        return isValid;
    }

    async function CheckIfSamlingCompleted(showNotif = false, EndImageValid = true) {

        let isValid = true;

        let KioskSetupPresent = SamplingData.KioskSetup == '1' || SamplingData.KioskSetup == 'true' || SamplingData.KioskSetup == true ? true : false;
        let StartTimeImage1 = SamplingData.StartTimeImage1 == '1' || SamplingData.StartTimeImage1 == 'true' || SamplingData.StartTimeImage1 == true ? true : false;
        let StartTimeImage2 = SamplingData.StartTimeImage2 == '1' || SamplingData.StartTimeImage2 == 'true' || SamplingData.StartTimeImage2 == true ? true : false;
        let EndTimeImage1 = SamplingData.EndTimeImage1 == '1' || SamplingData.EndTimeImage1 == 'true' || SamplingData.EndTimeImage1 == true ? true : false;
        let EndTimeImage2 = SamplingData.EndTimeImage2 == '1' || SamplingData.EndTimeImage2 == 'true' || SamplingData.EndTimeImage2 == true ? true : false;
        let InventoryRequired = SamplingData.InventoryRequired == true || SamplingData.InventoryRequired == "true" ? 1 : 0;
        let CustomerTrackingRequired = SamplingData.CustomerTrackingRequired == true || SamplingData.CustomerTrackingRequired == "true" ? 1 : 0;
        let CustomerConversionRequired = SamplingData.CustomerConversionRequired == true || SamplingData.CustomerConversionRequired == "true" ? 1 : 0;
        let LunchTimeRequired = SamplingData.LunchTimeRequired == true || SamplingData.LunchTimeRequired == "true" ? 1 : 0;
        let SaleRequired = SamplingData.SaleRequired == true || SamplingData.SaleRequired == "true" ? 1 : 0;
        let StockRequird = SamplingData.StockRequird == true || SamplingData.StockRequird == "true" ? 1 : 0;
        let StartTimeImageLabel = SamplingData.StartTimeImageLabel != null ? SamplingData.StartTimeImageLabel : "Start Time Image";
        let EndTimeImageLabel = SamplingData.EndTimeImageLabel != null ? SamplingData.EndTimeImageLabel : "End Time Image";


        let { SamplingIsPresent, KioskIsPresent, StartTimeImage1path, StartTimeImage2path, EndTimeImage1path, EndTimeImage2path, StartLunchStamp, EndLunchStamp } = AddVisFormData;
        SamplingIsPresent = SamplingIsPresent == 1 || SamplingIsPresent == '1' ? 1 : 0;
        KioskIsPresent = KioskIsPresent == 1 || KioskIsPresent == '1' ? 1 : 0;

        let { inventoryIsDone, inventoryIsAvlbl, trackIsDone, trackIsAvlbl, ContactIsDone, StockIsDone, StockIsAvlbl, SaleIsDone, SaleIsAvlbl } = SamplingTabObj

        if (SamplingIsPresent && ((KioskSetupPresent && KioskIsPresent == 1) || !KioskSetupPresent)) {
            console.log("CustomerTrackingRequired  ", CustomerTrackingRequired, trackIsAvlbl, trackIsDone)

            if (StartTimeImage1 && (StartTimeImage1path == null || StartTimeImage1path == '')) {
                isValid = false;
                showNotif ? notify("Please click " + StartTimeImageLabel) : '';
            } else if (EndImageValid && EndTimeImage1 && (EndTimeImage1path == null || EndTimeImage1path == '')) {
                isValid = false;
                showNotif ? notify("Please click " + EndTimeImageLabel) : '';
            } else if (InventoryRequired && inventoryIsAvlbl && (inventoryIsDone == null || inventoryIsDone == '' || inventoryIsDone == false)) {
                isValid = false;
                showNotif ? notify("Please fill data for Inventory") : '';
            } else if (CustomerTrackingRequired && trackIsAvlbl && (trackIsDone == null || trackIsDone == '' || trackIsDone == false)) {
                isValid = false;
                showNotif ? notify("Please fill data for Customer Tracking") : '';
            } else if (CustomerConversionRequired && (ContactIsDone == null || ContactIsDone == '' || ContactIsDone == false)) {
                isValid = false;
                showNotif ? notify("Please fill data for Contact Conversion") : '';
            } else if (SaleRequired && SaleIsAvlbl && (SaleIsDone == null || SaleIsDone == '' || SaleIsDone == false)) {
                isValid = false;
                showNotif ? notify("Please fill data for Sale") : '';
            } else if (StockRequird && StockIsAvlbl && (StockIsDone == null || StockIsDone == '' || StockIsDone == false)) {
                isValid = false;
                showNotif ? notify("Please fill data for Stock") : '';
            } else if (LunchTimeRequired && (StartLunchStamp == null || StartLunchStamp == '')) {
                isValid = false;
                showNotif ? notify("Please add Lunch Start Timing") : '';
            }
            else if (LunchTimeRequired && (EndLunchStamp == null || EndLunchStamp == '')) {
                isValid = false;
                showNotif ? notify("Please add Lunch End Timing") : '';
            }
        }
        return isValid;
    }

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

        if ((Company == '' || Company == null) || (CompanyId == '' || CompanyId == null)) {
            isValid = false;
            notify('Please select company', 'SHORT');
        }
        else if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
            isValid = false;
            notify('Please select category', 'SHORT');
        }
        else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
            isValid = false;
            notify('Please select sub category', 'SHORT');
        }
        else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
            isValid = false;
            notify('Please select brand', 'SHORT');
        }
        else if ((DisplayName == '' || DisplayName == null) || (DisplayId == '' || DisplayId == null)) {
            isValid = false;
            notify('Please select display type', 'SHORT');
        }
        else if ((Remark == '' || Remark == null)) {
            isValid = false;
            notify('Please enter remark', 'SHORT');
        }
        else if ((Image1 == '' || Image1 == null)) {
            isValid = false;
            notify('Please click image', 'SHORT');
        }



        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);
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option, keyLbl, keyVal, otherData) {
        let CompanyId = otherData.CompanyId != null ? otherData.CompanyId : '';
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        setAddVisFormData(data);
        setHasUnsavedChanges(true);
        if (keyLbl == 'Company') {
            loadData(option.value, 'Categories');

            data['CategoryId'] = '';
            data['CategoryName'] = '';
            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';
        }
        else if (keyLbl == 'CategoryName') {

            loadData(option.value, 'SubCategories', CompanyId);

            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';
        }
        else if (keyLbl == 'SubCategoryName') {
            loadData(option.value, 'Brands', CompanyId);

            data['BrandId'] = '';
            data['BrandName'] = '';
        }
        setrerenderdata(!rerenderdata);


    }

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

                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) {
                                if (type == 'Categories') setCategories(arr);
                                else if (type == 'SubCategories') setSubCategories(arr);
                                else if (type == 'Brands') setBrands(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

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


    function onChoiceSelect(val, key, animatedChoice, type) {
        console.log("reason?.la------", Boolean(reason?.label), reason)
        if (val == 0 || (Boolean(reason?.label))) {
            setShowRAllC_MData({ val, key, animatedChoice, type })
            setShowRAllC_M(true)
        } else {
            var val1 = val == 1 ? 1 : 0;
            let data = AddVisFormData;
            data[key] = val;
            if (animatedChoice != null) {
                Animated.timing(animatedChoice, {
                    toValue: val1,
                    duration: 400,
                    useNativeDriver: false,
                }).start();
            }
            setAddVisFormData(data);
            setrerenderdata(!rerenderdata)
        }

        setHasUnsavedChanges(true);
    }

    async function onConfirmRemoveAll() {


        let data1 = AddVisFormData;

        console.log("showRAllC_MData.key----", showRAllC_MData.key == "SamplingIsPresent", showRAllC_MData)
        if (showRAllC_MData.key == "SamplingIsPresent") {
            // data1["SamplingIsPresent"]=0;
            data1["SamplingIsPresent"] = showRAllC_MData?.val || 0;
            data1["KioskIsPresent"] = 0;
            setReason({})
            if (animatedChoice != null) {
                Animated.timing(animatedChoice, {
                    toValue: showRAllC_MData?.val || 0,
                    // toValue: 0,
                    duration: 400,
                    useNativeDriver: false,
                }).start();
            }

            if (animatedChoice2 != null) {
                Animated.timing(animatedChoice2, {
                    toValue: 0,
                    duration: 400,
                    useNativeDriver: false,
                }).start();
            }

        } else {
            if (animatedChoice2 != null) {
                Animated.timing(animatedChoice2, {
                    toValue: 0,
                    duration: 400,
                    useNativeDriver: false,
                }).start();
            }
            data1["KioskIsPresent"] = 0;
        }

        setRemoveAllTabsData(true);
        setAddVisFormData(data1)
        setHasUnsavedChanges(true);
        // getData(storeData,currentMenu,SamplingData,"reload");
        // setAddVisFormData({});
        setrerenderdata(!rerenderdata)
        setShowRAllC_M(false);
    }



    function onSaveCancel() {
        setShowAlert(false);
        setShowSaveAlert(false);
    }

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

            let index = AddVisFormData.findIndex(i => i.CompanyId == CompanyId && i.CategoryId == CategoryId && i.SubCategoryId == SubCategoryId && i.BrandId == BrandId && i.DisplayId == DisplayId);
            if (index >= 0) {
                notify('This visibility has already been added', 'LONG');
            }
            else {
                arr.push(AddVisFormData);
                setAddVisFormData(arr);
                setHasUnsavedChanges(true);
                notify('Visibility added successfully', 'LONG');
                setrerenderdata(!rerenderdata);

                // clear data
                setAddVisFormData({});
            }
        }

    }

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

    async function Remove_AddVis() {

        let index = toRemoveId
        let item = toRemoveItem;
        let arr = AddVisFormData;

        if (index >= 0 && index < arr.length) {
            arr.splice(index, 1);
            setAddVisFormData(arr);
            setHasUnsavedChanges(true);
            notify('Sampling removed successfully', 'LONG')
            setrerenderdata(!rerenderdata);
        }
        else {
            notify('Cannot remove! Sampling not found', 'LONG')
        }
        setReason({});
        setToRemoveId('');
        setToRemoveItem({});
        setshowRemoveConfirm_M(false);
    }

    function onselectionChange3(option, keyLbl, keyVal, otherData) {
        let item = otherData.window;
        let index = otherData.index;
        setReason(option)
        console.log("option------", option)
        // let allData=WindowData;
        // let wind = item; 
        // wind[keyVal]=option.value;
        // wind[keyLbl]=option.label;

        // let objIndex = InputChange.findIndex(i=>i.WindowId==item.WindowId);
        // let winArr=[...InputChange]
        // winArr[objIndex].Flag=true
        // setInputChange(winArr);


        // index>=0?allData[index]=wind:'';
        // console.log('windowallData',allData)

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

    }




    const _render_addVisFormTop = () => {
        let StartTimeImageLabel = SamplingData.StartTimeImageLabel != null ? SamplingData.StartTimeImageLabel : "Start Time";
        let EndTimeImageLabel = SamplingData.EndTimeImageLabel != null ? SamplingData.EndTimeImageLabel : "End Time";
        let SamplingPresentLabel = (SamplingData && SamplingData.SamplingPresentLabel) || ""
        let KioskSetupLabel = (SamplingData && SamplingData.KioskSetupLabel) || ""
        // let SamplingPresent=SamplingData && SamplingData.SamplingPresent!=null? SamplingData.SamplingPresent : false;
        let KioskSetupPresent = SamplingData.KioskSetup == '1' || SamplingData.KioskSetup == 'true' || SamplingData.KioskSetup == true ? true : false;
        let StartTimeImage1 = SamplingData.StartTimeImage1 == '1' || SamplingData.StartTimeImage1 == 'true' || SamplingData.StartTimeImage1 == true ? true : false;
        let StartTimeImage2 = SamplingData.StartTimeImage2 == '1' || SamplingData.StartTimeImage2 == 'true' || SamplingData.StartTimeImage2 == true ? true : false;
        let EndTimeImage1 = SamplingData.EndTimeImage1 == '1' || SamplingData.EndTimeImage1 == 'true' || SamplingData.EndTimeImage1 == true ? true : false;
        let EndTimeImage2 = SamplingData.EndTimeImage2 == '1' || SamplingData.EndTimeImage2 == 'true' || SamplingData.EndTimeImage2 == true ? true : false;


        // let InventoryRequired=SamplingData.InventoryRequired==true || SamplingData.InventoryRequired=="true"?1:0;
        // let CustomerTrackingRequired=SamplingData.CustomerTrackingRequired==true || SamplingData.CustomerTrackingRequired=="true"?1:0;
        // let CustomerConversionRequired=SamplingData.CustomerConversionRequired==true || SamplingData.CustomerConversionRequired=="true"?1:0;
        let LunchTimeRequired = SamplingData.LunchTimeRequired == true || SamplingData.LunchTimeRequired == "true" ? 1 : 0;
        // let SaleRequired=SamplingData.SaleRequired==true || SamplingData.SaleRequired=="true"?1:0;
        // let StockRequird=SamplingData.StockRequird==true || SamplingData.StockRequird=="true"?1:0;


        let { SamplingIsPresent, KioskIsPresent, StartTimeImage1path, StartTimeImage2path, EndTimeImage1path, EndTimeImage2path, StartLunchStamp, EndLunchStamp } = AddVisFormData;
        SamplingIsPresent = SamplingIsPresent == 1 || SamplingIsPresent == '1' ? 1 : 0;
        KioskIsPresent = KioskIsPresent == 1 || KioskIsPresent == '1' ? 1 : 0;


        let isEndImgCaptured = (EndTimeImage1path != null && EndTimeImage1path != '') ? true : false;
        let isStartImgCaptured = StartTimeImage1 ? ((StartTimeImage1path != null && StartTimeImage1path != '') ? true : false) : true;
        // let tabdisable= (SamplingTabObj &&  SamplingTabObj.allTabDisable==true );
        // let lunchStarted=AddVisFormData && SamplingTabObj && SamplingTabObj.allTabDisable==false && ( AddVisFormData.StartLunchStamp!='' && AddVisFormData.StartLunchStamp!=null)
        // let EnableEndLunch= (AddVisFormData.EndLunchStamp!='' && AddVisFormData.EndLunchStamp!=null)? false:  (AddVisFormData && (AddVisFormData.StartLunchStamp== undefined || AddVisFormData.StartLunchStamp=='' || AddVisFormData.StartLunchStamp==null)) ? (!tabdisable && lunchStarted):true
        // let startImgDis= (Object.keys(AddVisFormData).length==0 ||(AddVisFormData.StartTimeImage1path!= undefined && AddVisFormData.StartTimeImage1path!='' && AddVisFormData.StartTimeImage1path!=null) )? true: (!AddVisFormData.hasOwnProperty('StartLunchStamp') &&(AddVisFormData.StartLunchStamp== undefined || AddVisFormData.StartLunchStamp=='' || AddVisFormData.StartLunchStamp==null)) && SamplingTabObj.allTabDisable==true ? true: SamplingTabObj.allTabDisable==false? true: false
        // let EnableStartLunch= (AddVisFormData.StartLunchStamp!='' && AddVisFormData.StartLunchStamp!=null) ? false: ((SamplingTabObj && SamplingTabObj.allTabDisable==false) &&(AddVisFormData && (AddVisFormData.StartLunchStamp== undefined || AddVisFormData.StartLunchStamp=='' || AddVisFormData.StartLunchStamp==null) )) ? true : false
        let isLunchDone = EndLunchStamp != null && EndLunchStamp != '' && EndLunchStamp != 'undefined' ? true : false;
        let startImgDis = isLunchTime == true || isEndImgCaptured ? true : false;
        let endImgDis = (isLunchTime == true || !isStartImgCaptured) ? true : false;
        let EnableStartLunch = !isLunchTime && !isLunchDone && isStartImgCaptured && !isEndImgCaptured ? true : false;
        let EnableEndLunch = isLunchTime && isStartImgCaptured && !isEndImgCaptured ? true : false;
        let AllTabDisabled = isLunchTime || !isStartImgCaptured || isEndImgCaptured ? true : false;


        let xpos = AddVisFormData.SamplingIsPresent == 1 ? -75 : 0;
        let xpos2 = AddVisFormData.KioskIsPresent == 1 ? -75 : 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }
        if (animatedChoice2 != null) {
            xpos2 = animatedChoice2.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }


        if (rerenderdata == rerenderdata) {
            return (
                <View style={[customStyle.addvisCon]}>
                    <View style={[customStyle.Sampling_pCon]}>
                        <Text style={[customStyle.addvis_pText]}>{SamplingPresentLabel}</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, ((SamplingIsPresent == '1' || SamplingIsPresent == 1) ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                                {
                                    transform: [{
                                        translateX: xpos
                                    }],
                                }
                                ]}></Animated.View>
                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1, 'SamplingIsPresent', animatedChoice, 1) }}>
                                    <Text style={[customStyle.openStkCh_text, ((SamplingIsPresent == '1' || SamplingIsPresent == 1) ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'SamplingIsPresent', animatedChoice, 1) }}>
                                    <Text style={[customStyle.openStkCh_text, ((SamplingIsPresent == '0' || SamplingIsPresent == 0) ? customStyle.openStkCh_textactive : {})]}>No</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>

                    {SamplingIsPresent != '1' &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel1]}>{ST.SelectReason}</Text>
                            {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange3}
                                selected_data={{ value: reason?.label }}
                                InputStyle={customStyle.PV_selectInputStyle1}
                                selectStyle={customStyle.PV_selectStyle} ErrorStyle={{}} ShowError={error} />}
                        </View>
                    }


                    {(SamplingIsPresent == 1 || SamplingIsPresent == '1') &&
                        <View>
                            {KioskSetupPresent &&
                                <View style={[customStyle.Sampling_pCon, customStyle.Samling_borderB, customStyle.mb10]}>
                                    <Text style={[customStyle.addvis_pText]}>{KioskSetupLabel}</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, ((KioskIsPresent == '1' || KioskIsPresent == 1) ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                                            {
                                                transform: [{
                                                    translateX: xpos2
                                                }],
                                            }
                                            ]}></Animated.View>
                                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1, 'KioskIsPresent', animatedChoice2, 2) }}>
                                                <Text style={[customStyle.openStkCh_text, ((KioskIsPresent == '1' || KioskIsPresent == 1) ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                                            </TouchableOpacity>
                                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'KioskIsPresent', animatedChoice2, 2) }}>
                                                <Text style={[customStyle.openStkCh_text, ((KioskIsPresent == '0' || KioskIsPresent == 0) ? customStyle.openStkCh_textactive : {})]}>No</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            }
                            {((KioskSetupPresent && KioskIsPresent == 1) || !KioskSetupPresent) && (rerenderdata == rerenderdata) &&
                                <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                                    <View style={[customStyle.addVisForm, customStyle.Samling_borderB, customStyle.mb10]}>
                                        <View style={customStyle.addVisRow}>
                                            {(StartTimeImage1 || StartTimeImage2) &&
                                                <View style={[customStyle.addVisCol100]}>
                                                    <View style={[customStyle.addVisFormGrp, { flexDirection: 'row' }]}>
                                                        <Text style={[customStyle.Sampling_pText]}>{StartTimeImageLabel}</Text>
                                                        <View style={[customStyle.addVisCameras, customStyle.sampling_CameraWrap]}>
                                                            {StartTimeImage1 &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                    {(startImgDis) &&
                                                                        (
                                                                            <TouchableOpacity onPress={() => { }} disabled={true}>
                                                                                <Camera_icon_grey width={50} height={50}  />
                                                                                {(StartTimeImage1path != null && StartTimeImage1path != '') &&
                                                                                    <View style={customStyle.sampling_disable_Tick}>
                                                                                        <AntDesign color={PageTheme.$text_color_light} size={15} name='checkcircle' />
                                                                                    </View>
                                                                                }
                                                                            </TouchableOpacity>
                                                                        )
                                                                    }
                                                                    {!startImgDis &&
                                                                        (((StartTimeImage1path == null || StartTimeImage1path == '')) ?
                                                                            <TouchableOpacity onPress={() => { openCamera("StartTimeImage1") }}>
                                                                                <CameraImg5 width={50} height={50}  />
                                                                            </TouchableOpacity> : (StartTimeImage1path != null && StartTimeImage1path != '') ?
                                                                                <TouchableOpacity onPress={() => { OpenImgModal(StartTimeImage1path, 'StartTimeImage1', StartTimeImageLabel) }}>
                                                                                    <CameraImg3 width={50} height={50}/>
                                                                                </TouchableOpacity> :
                                                                                null
                                                                        )
                                                                    }
                                                                </View>
                                                            }
                                                            {StartTimeImage2 &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                    {(startImgDis) &&
                                                                        <TouchableOpacity onPress={() => { }} disabled={true}>
                                                                            <Camera_icon_grey width={50} height={50} />
                                                                            {(StartTimeImage2path != null && StartTimeImage2path != '') &&
                                                                                <View style={customStyle.sampling_disable_Tick}>
                                                                                    <AntDesign color={PageTheme.$text_color_light} size={15} name='checkcircle' />
                                                                                </View>
                                                                            }
                                                                        </TouchableOpacity>
                                                                    }
                                                                    {!startImgDis &&
                                                                        (((StartTimeImage2path == null || StartTimeImage2path == '') ?
                                                                            <TouchableOpacity onPress={() => { openCamera('StartTimeImage2') }}>
                                                                                <CameraImg2 width={50} height={50}  />
                                                                            </TouchableOpacity> : (StartTimeImage2path != null && StartTimeImage2path != '') ?
                                                                                <TouchableOpacity onPress={() => { OpenImgModal(StartTimeImage2path, 'StartTimeImage2', StartTimeImageLabel) }}>
                                                                                    <CameraImg3 width={50} height={50}  />
                                                                                </TouchableOpacity> : null)
                                                                        )
                                                                    }
                                                                </View>
                                                            }
                                                            <Text style={[customStyle.Sampling_pTextTime]}>{AddVisFormData.StartTimeImage1stamp}</Text>
                                                        </View>
                                                    </View>
                                                </View>
                                            }
                                            {(EndTimeImage1 || EndTimeImage2) &&
                                                <View style={[customStyle.addVisCol100]}>
                                                    <View style={[customStyle.addVisFormGrp, { flexDirection: 'row' }]}>
                                                        <Text style={[customStyle.Sampling_pText]}>{'End Time Image'}</Text>
                                                        <View style={[customStyle.addVisCameras, customStyle.sampling_CameraWrap]}>
                                                            {EndTimeImage1 &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                    {endImgDis &&
                                                                        <TouchableOpacity onPress={() => { }} disabled={true}>
                                                                            <Camera_icon_grey width={50} height={50}  />
                                                                            {(EndTimeImage1path != null && EndTimeImage1path != '') &&
                                                                                <View style={customStyle.sampling_disable_Tick}>
                                                                                    <AntDesign color={PageTheme.$text_color_light} size={15} name='checkcircle' />
                                                                                </View>
                                                                            }
                                                                        </TouchableOpacity>
                                                                    }
                                                                    {!endImgDis &&
                                                                        ((EndTimeImage1path == null || EndTimeImage1path == '') ?
                                                                            <TouchableOpacity onPress={() => { openCamera('EndTimeImage1') }}>
                                                                                <CameraImg5 width={50} height={50}  />
                                                                            </TouchableOpacity> : (EndTimeImage1path != '' && EndTimeImage1path != null) ?
                                                                                <TouchableOpacity onPress={() => { OpenImgModal(EndTimeImage1path, 'EndTimeImage1', EndTimeImageLabel) }}>
                                                                                    <CameraImg3 width={50} height={50}  />
                                                                                </TouchableOpacity> : null
                                                                        )
                                                                    }
                                                                </View>
                                                            }
                                                            {EndTimeImage2 &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                    {endImgDis &&
                                                                        <TouchableOpacity onPress={() => { }} disabled={true}>
                                                                            <Camera_icon_grey width={50} height={50}  />
                                                                            {(EndTimeImage2path != null && EndTimeImage2path != '') &&
                                                                                <View style={customStyle.sampling_disable_Tick}>
                                                                                    <AntDesign color={PageTheme.$text_color_light} size={15} name='checkcircle' />
                                                                                </View>
                                                                            }
                                                                        </TouchableOpacity>
                                                                    }
                                                                    {!endImgDis &&
                                                                        ((EndTimeImage2path == null || EndTimeImage2path == '') ?
                                                                            <TouchableOpacity onPress={() => { openCamera('EndTimeImage2') }}>
                                                                                <CameraImg2 width={50} height={50} />
                                                                            </TouchableOpacity> : (EndTimeImage2path != '' && EndTimeImage2path != null) ?
                                                                                <TouchableOpacity onPress={() => { OpenImgModal(EndTimeImage2path, 'EndTimeImage2', EndTimeImageLabel) }}>
                                                                                    <CameraImg3 width={50} height={50} />
                                                                                </TouchableOpacity> : null
                                                                        )
                                                                    }
                                                                </View>
                                                            }
                                                            <Text style={[customStyle.Sampling_pTextTime]}>{AddVisFormData.EndTimeImage1stamp}</Text>
                                                        </View>
                                                    </View>
                                                </View>
                                            }
                                        </View>
                                    </View>
                                    {
                                        rerenderdata2 == rerenderdata2 &&
                                        // (rerenderdata2Ref.current== rerenderdata2Ref.current) &&
                                        // <SamplingHeaderTab {...props} currentMenu={currentMenu} SamplingData={SamplingData} storeData={storeData} SamplingTabObj={SamplingTabObjRef.current} hasUnsavedChanges={hasUnsavedChanges} setShowAlert={setShowSaveAlert}/>  
                                        <SamplingHeaderTab {...props} currentMenu={currentMenu} SamplingData={SamplingData} storeData={storeData} SamplingTabObj={SamplingTabObjRef.current} AllTabDisabled={AllTabDisabled} hasUnsavedChanges={hasUnsavedChanges} setShowAlert={setShowSaveAlert} setSaveModalDObj={setSaveModalDObj} />
                                    }
                                    {LunchTimeRequired == true &&
                                        <View>
                                            <View style={[customStyle.Sampling_pCon]}>
                                                <Text style={[customStyle.Sampling_pText]}>{'Start Lunch'}</Text>
                                                <View style={customStyle.openStkCameraCon}>
                                                    <TouchableOpacity activeOpacity={0.6} disabled={!EnableStartLunch} style={[customStyle.SamplingCat_action_reCap, (EnableStartLunch ? { backgroundColor: PageTheme.$primary_color } : {})]} onPress={() => { StartLunch() }}>
                                                        <MaterialIcons name='timer' size={20} color={(EnableStartLunch ? PageTheme.$accent_color : PageTheme.$text_color)} />
                                                    </TouchableOpacity>
                                                </View>
                                                {StartLunchStamp != null && StartLunchStamp != '' && StartLunchStamp != 'undefined' &&
                                                    <Text style={[customStyle.Sampling_LunchText]}>{StartLunchStamp}</Text>
                                                }
                                            </View>

                                            <View style={[customStyle.Sampling_pCon2]}>
                                                <Text style={[customStyle.Sampling_pText]}>{'End Lunch'}</Text>
                                                <View style={customStyle.openStkCameraCon}>
                                                    <TouchableOpacity activeOpacity={0.6} disabled={!EnableEndLunch} style={[customStyle.SamplingCat_action_reCap, (EnableEndLunch ? { backgroundColor: PageTheme.$primary_color } : {})]} onPress={() => { EndLunch() }}>
                                                        <MaterialIcons name='timer-off' size={20} color={(EnableEndLunch ? PageTheme.$accent_color : PageTheme.$text_color)} />
                                                    </TouchableOpacity>
                                                </View>
                                                {EndLunchStamp != null && EndLunchStamp != '' && EndLunchStamp != 'undefined' &&
                                                    <Text style={[customStyle.Sampling_LunchText]}>{EndLunchStamp}</Text>
                                                }
                                            </View>
                                        </View>
                                    }

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

    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, showSaveAlert, onSaveCancel, saveData, 'Please save your data before change tab')}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, 'Do you really want to remove this sampling?')}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, 'Do you really want to remove all data?')}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper, customStyle.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={'Save'} onPress={() => { onSubmitData() }} />
                    </View>
                </View>

            </LinearGradient>

        </Container>
    );
}



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