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 } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, marktext1, marktext2 } 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, Fontisto, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import DateTimePicker from '@react-native-community/datetimepicker';


import CameraImg from '../assets/performics/camera_front_image.svg'
import MultiSelect from 'react-native-multiple-select';

function PaidVisibility(props) {
    const route = useRoute();

    // 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 [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [rerenderdata3, setrerenderdata3] = useState(0);
    const [rerenderdata4, setrerenderdata4] = useState(0);

    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

    const [WindowData, setWindowData] = useState([]);
    const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps, setGetImageProps] = useState({});
    const zoomView = useRef(null);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingWindow, setRatingWindow] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);

    const [Products, setProducts] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);

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


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

        let isAdhoc = params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        getData(storeData1, menu1);

        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

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

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

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

    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else {
            if (hasUnsavedChanges == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }
    function 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 getData(storeData1, menu1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

            await db.transaction(async function (txn) {


                let q3 = `Select * From Master_NonVisibility`;
                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                setReasons_list(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                // check if data exists
                let selectlist = ` w.STORE_ID as StoreId,w.WINDOW_HEADER_ID as windowHeaderId,wd.WindowDefinitionId,wd.WindowId,wd.WindowName,wd.WindowTable,wd.WindowField,wd.WindowValue,wd.ChildName,wd.WindowRefImage,wd.WindowElementCheckAssortment,wd.WindowElementStockRequired,w.IS_PRESENT as IsPresent,wd.WindowNotExistCamera,w.WINDOW_NA_IMAGE as WindowNAImage,wd.WindowExistReasonEnable,wd.WindowNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,wd.NoOfSplit,wd.WindowImage1,wd.WindowImage2,wd.WindowImage1Lable,wd.WindowImage2Lable,wd.WindowImage1CameraGrid,wd.WindowImage2CameraGrid`;
                let join = ` inner join Master_WindowDefinition wd on w.WINDOW_DEFINITION_ID=wd.WindowDefinitionId `;
                let q = ` Select ${selectlist} from ${AppTables.WINDOW_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;

                // else pick data from masters
                let selectlist2 = ` s.StoreId,w.WindowDefinitionId,w.WindowId,w.WindowName,w.WindowTable,w.WindowField,w.WindowValue,w.ChildName,w.WindowRefImage,w.WindowElementCheckAssortment,w.WindowElementStockRequired,'' as IsPresent,w.WindowNotExistCamera,'' as WindowNAImage,w.WindowExistReasonEnable,w.WindowNotExistReasonEnable,'' as ReasonId,'' as Reason,w.NoOfSplit,w.WindowImage1,w.WindowImage2,w.WindowImage1Lable,w.WindowImage2Lable,w.WindowImage1CameraGrid,w.WindowImage2CameraGrid`;
                let join2 = ` inner join Mapping_StoreWindow s on w.WindowDefinitionId=s.WindowDefinitionId  `;
                let q2 = ` Select ${selectlist2} from Master_WindowDefinition w  ${join2} where s.StoreId='${StoreId}'  `;

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = []; let images = [], allWindowsData = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let animatedChoice = new Animated.Value((data.IsPresent == '1' || data.IsPresent == 1 ? 1 : 0));
                            data.animatedChoice = animatedChoice;
                            data.NoOfSplit = parseInt(data.NoOfSplit);

                            let NoOfSplit = data.NoOfSplit;
                            let isPresent = data.IsPresent == '1' || data.IsPresent == 1 ? 1 : 0;
                            let isStockReq = data.WindowElementStockRequired == 'true' || data.WindowElementStockRequired == 1 ? 1 : 0;
                            let imgObj = { imgIndex: (i + 1), url: data.WindowRefImage, props: {} }
                            let WindowSplits = await getWindowSplits(NoOfSplit, data, storeData1, menu1);
                            let WQr = await getWindowQuestions(data, storeData1, isPresent, menu1);
                            let WindowQuestions = WQr['WindowQuestions'] || [];
                            let WindowQA = WQr['WindowQA'] || {};
                            let WSd = isStockReq == true ? await getWindowStockData(data, storeData1, isPresent) : { 'WStocks': [], 'WStocksData': [] };
                            let WStocks = WSd['WStocks'] || [];
                            let WStocksData = WSd['WStocksData'] || [];

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


                            let windowDataObj = { 'WindowId': data.WindowId, 'WindowDefinitionId': data.WindowDefinitionId, 'WindowSplits': WindowSplits, 'WindowQA': WindowQA, 'WStocksData': WStocksData, 'NAImage1': NAImage1, 'NAImage1Path': NAImage1Path, 'ReasonId': data.ReasonId, 'Reason': data.Reason, 'isPresent': isPresent };
                            data['WindowQuestions'] = WindowQuestions;
                            data['WindowStocks'] = WStocks;
                            arr.push(data);

                            allWindowsData.push(windowDataObj);
                            if (i == txnres2.rows.length - 1) {
                                setWindowData(allWindowsData);
                                setWindows(arr);
                                images.push(imgObj);
                                setZoomImageUrl(images);
                                setProcessing(false);
                            }
                        }
                    }
                    else {
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                let arr = [], images = [], allWindowsData = [];
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let animatedChoice = new Animated.Value(0);
                                    data.animatedChoice = animatedChoice;
                                    data.NoOfSplit = parseInt(data.NoOfSplit);

                                    let imgObj = { imgIndex: (i + 1), url: data.WindowRefImage, props: {} }
                                    let WindowSplits = [];
                                    for (var s = 0; s < data.NoOfSplit; s++) {
                                        let obj = { 'Image1Name': '', 'Image1': '', 'Image2Name': '', 'Image2': '' };
                                        WindowSplits.push(obj);
                                    }
                                    let WQr = await getWindowQuestions(data, storeData1, false, menu1);
                                    let WindowQuestions = WQr['WindowQuestions'] || [];
                                    let WindowQA = WQr['WindowQA'] || {};
                                    let WSd = await getWindowStockData(data, storeData1, false);
                                    let WStocks = WSd['WStocks'] || [];
                                    let WStocksData = WSd['WStocksData'] || [];

                                    let windowDataObj = { 'WindowId': data.WindowId, 'WindowDefinitionId': data.WindowDefinitionId, 'WindowSplits': WindowSplits, 'WindowQA': WindowQA, 'WStocksData': WStocksData };
                                    data['WindowQuestions'] = WindowQuestions;
                                    data['WindowStocks'] = WStocks;

                                    arr.push(data);
                                    allWindowsData.push(windowDataObj);
                                    if (i == txnres2.rows.length - 1) {
                                        setWindowData(allWindowsData);
                                        setWindows(arr);
                                        images.push(imgObj);
                                        setZoomImageUrl(images);
                                        setProcessing(false);
                                    }
                                }
                            }
                            else {
                                setProcessing(false);
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

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

    async function getWindowSplits(NoOfSplit, window, storeData1, menu1) {
        let WindowSplits_def = [];
        for (var s = 0; s < NoOfSplit; s++) {
            let obj = { 'Image1Name': '', 'Image1': '', 'Image2Name': '', 'Image2': '' };
            WindowSplits_def.push(obj);
        }
        return new Promise((resolve, reject) => {

            db.transaction(async function (txn) {

                let q = `select * from ${AppTables.WINDOW_IMAGES} where WINDOW_HEADER_ID='${window.windowHeaderId}' and  STORE_ID='${storeData1.StoreId}' `;

                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);
                            console.log(data.WINDOW_HEADER_ID)
                            let isImage1 = window.WindowImage1 == 'true' || window.WindowImage1 == 1 ? 1 : 0;
                            let isImage2 = window.WindowImage2 == 'true' || window.WindowImage2 == 1 ? 1 : 0;

                            let Image1 = isImage1 == 1 && data.IMAGE1 != null && data.IMAGE1 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + data.IMAGE1 : '';
                            let Image2 = isImage2 == 1 && data.IMAGE2 != null && data.IMAGE2 != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + data.IMAGE2 : '';
                            let obj = { 'Image1Name': data.IMAGE1, 'Image1': Image1, 'Image2Name': data.IMAGE2, 'Image2': Image2 };
                            arr.push(obj);

                            if (i == txnres2.rows.length - 1) {
                                resolve(arr)
                            }
                        }
                    }
                    else {
                        resolve(WindowSplits_def)
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(WindowSplits_def) },);
            });
        }).then((val) => {
            return val
        }).catch((err) => {
            console.log(err);
            return WindowSplits_def;
        });
    }

    async function getWindowQuestions(window, storeData1, isInserted = false, menu1) {
        let obj = { 'WindowQA': {}, 'WindowQuestions': [] }
        return new Promise((resolve, reject) => {

            db.transaction(async function (txn) {
                var q = '', selectlist = '', join = '', join2 = '';
                if (isInserted == true) {
                    selectlist = ` DISTINCT  q.QUESTION_ID as WindowQuestionId,q.QUESTION_CODE as WindowQuestionCode,wq.WindowQuestionName,wq.QuestionType,wq.WQShowCamera,wq.WQCameraMandatory,wq.WQLengthValidationRequired,wq.WQMinimumChar,wq.WQMaximumChar,wq.WQDecimalPoint,wq.WQDateRangeMin,wq.WQDateRangeMax,wq.WQVoiceLengthInMinutes,wq.WQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as WAShowCamera,q.IMAGE1 as Image1  `;
                    join2 = ` inner join Mapping_WindowQuestion mq on mq.WindowQuestionId=wq.WindowQuestionId `;
                    join = ` inner join Master_WindowQuestion wq on wq.WindowQuestionId=q.QUESTION_ID `;
                    q = `select ${selectlist} from ${AppTables.WINDOW_CHILD_DATA} q ${join} ${join2} where q.STORE_ID='${storeData1.StoreId}' and q.WINDOW_DEFINITION_ID='${window.WindowDefinitionId}' and q.WINDOW_ID='${window.WindowId}' order by wq.WindowQuestionSequence  `;
                }
                else {
                    selectlist = ` DISTINCT  wq.WindowQuestionId,wq.WindowQuestionCode,wq.WindowQuestionName,wq.QuestionType,wq.WQShowCamera,wq.WQCameraMandatory,wq.WQLengthValidationRequired,wq.WQMinimumChar,wq.WQMaximumChar,wq.WQDecimalPoint,wq.WQDateRangeMin,wq.WQDateRangeMax,wq.WQVoiceLengthInMinutes,wq.WQDefaultQuestionEnable `;
                    join = ` inner join Mapping_WindowQuestion mq on mq.WindowQuestionId=wq.WindowQuestionId `;
                    q = `select ${selectlist} from  Master_WindowQuestion wq  ${join} where mq.WindowDefinitionId='${window.WindowDefinitionId}' order by wq.WindowQuestionSequence  `;
                }

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        let wqa_obj = {};
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let answers = [];
                            data.WQDefaultQuestionEnable = data.WQDefaultQuestionEnable == 1 || data.WQDefaultQuestionEnable == 'true' ? true : false;

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

                            let id_key = data.WindowQuestionId + '_AnswerId';
                            let ans_key = data.WindowQuestionId + '_Answer';
                            let multi_key = data.WindowQuestionId + '_MultiOption';
                            let date_key = data.WindowQuestionId + '_Date';
                            let img_key = data.WindowQuestionId + '_ImagePath1';
                            let imgname_key = data.WindowQuestionId + '_ImageName1';
                            let rating_key = data.WindowQuestionId + '_Rating';


                            let showImageTag = (data.WQShowCamera == 'true' || data.WQShowCamera == 1);

                            data.AnswerId != null ? wqa_obj[id_key] = data.AnswerId : '';
                            data.Answer != null ? wqa_obj[ans_key] = data.Answer : '';


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

                            if ((data.QuestionType == 'Single choice list' || data.QuestionType == 'Multi choice list') && selansid != '' && selansid != null) {
                                if (data.Answers && data.Answers.length > 0) {
                                    for (var k = 0; k < data.Answers.length; k++) {
                                        let ansss = data.Answers[k];
                                        let isandImgAl = (ansss.WAShowCamera == 1 || ansss.WAShowCamera == 'true');
                                        if (data.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                            showImageTag = true;
                                        }
                                        else if (data.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                            showImageTag = true;
                                        }
                                    }
                                }
                            }

                            if (showImageTag && data.Answer != null) {
                                let imgPath = (Platform.OS == 'ios' ? 'file://' : '') + ImageFolderPath + menu1.ScreenName + "/" + data.Image1;
                                wqa_obj[imgname_key] = data.Image1;
                                wqa_obj[img_key] = imgPath;
                            }



                            if (data.QuestionType == 'Date' && data.Answer != null) {
                                let dayonly = moment().format('DD');
                                let actual_date = data.Answer ? data.Answer.split('/') : [];
                                let month = actual_date[0], year = actual_date[1];
                                let fulldate = month + '/' + dayonly + '/' + year;
                                wqa_obj[date_key] = fulldate;

                            }

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


    async function getWindowAnswers(qtn) {

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

            db.transaction(async function (txn) {
                var q = '', selectlist = '';
                selectlist = ` DISTINCT  WindowAnswerId as AnswerId,WindowAnswerName as Answer,WAShowCamera,WACameraMandatory,WAQuestionEnable,WAQuestionDisable `;
                q = `select ${selectlist} from  Master_WindowQuestion  where WindowQuestionId='${qtn.WindowQuestionId}'  order by WASequence  `;

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

    async function getWindowStockData(window, storeData1, isInserted = false) {
        let obj = { 'WStocks': [], 'WStocksData': [] }
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                var q = '', selectlist = '', join = '';
                let checkassrt = window.WindowElementCheckAssortment == 'true' || window.WindowElementCheckAssortment == 1 ? true : false;

                if (isInserted == true) {
                    if (checkassrt) {
                        join = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.WINDOW_STOCK_VALUE and a.StoreId='${storeData1.StoreId}'`;
                    }
                    selectlist = `  s.WINDOW_STOCK_DEFINITION_ID as WindowStockDefinitionId, s.WINDOW_DEFINITION_ID as WindowDefinitionId,s.WINDOW_STOCK_TABLE as WindowStockTable,s.WINDOW_STOCK_FIELD as WindowStockField,s.WINDOW_STOCK_VALUE as WindowStockValue,s.WINDOW_STOCK_MBQ as WindowStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock `;
                    q = `select ${selectlist} from  ${AppTables.WINDOW_STOCK_DATA} s ${join} where s.WINDOW_DEFINITION_ID='${window.WindowDefinitionId}' and s.STORE_ID='${storeData1.StoreId}'  `;
                } else {
                    if (checkassrt) {
                        join = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.WindowStockValue and a.StoreId='${storeData1.StoreId}'`;
                    }
                    selectlist = `  s.WindowStockDefinitionId, s.WindowDefinitionId,s.WindowStockTable,s.WindowStockField,s.WindowStockValue,s.WindowStockMBQ,s.ProductName `;
                    q = `select ${selectlist} from  Master_WindowStockDefinition s ${join} where s.WindowDefinitionId='${window.WindowDefinitionId}'   `;
                }
                if (checkassrt) {
                    q += ` and a.StoreId='${storeData1.StoreId}' `;
                }
                q += isInserted ? ` order by s.PRODUCT_NAME ` : ` order by s.ProductName `;



                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [], WStocksData = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            if (isInserted == true && data.Stock != null) {

                                let stockData_obj = { 'ProductId': data.WindowStockValue, 'Stock': data.Stock }
                                WStocksData.push(stockData_obj);
                            }
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                obj['WStocks'] = arr;
                                obj['WStocksData'] = WStocksData;
                                resolve(obj)
                            }
                        }
                    }
                    else {
                        resolve(obj)
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve(obj) },);
            });
        }).then((val) => {
            return val
        }).catch((err) => {
            console.log(err);
            return obj;
        });
    }





    async function getImage(imgdata) {
        let type = getImageProps.type || '';
        let window = getImageProps.window || {};
        let splitItem = getImageProps.splitItem || {};
        let splitItemIndex = getImageProps.splitItemIndex || 0;
        let qtn = getImageProps.qtn || {};
        let cameraType = getImageProps.cameraType != null ? getImageProps.cameraType : '1';

        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify('Camera unavailable');
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.height;
            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;

            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: Window' + ' | Date:' + calculate_tym_date_over_img;

            await marktext1(mark_text1, imgurl)
                .then((res) => {
                    if (res.success) {
                        let uri = res.uri;
                        marktext2(mark_text2, uri, imgWidth, imgHeight)
                            .then((res) => {
                                if (res.success) {
                                    let filename = storeData.StoreId + '_' + window.WindowDefinitionId + '_' + window.WindowId + '_' + (props.UserId || '') + '_WindowImg-' + calculate_tym_date_for_filename + '.jpg';
                                    let allData = WindowData;
                                    let defData = { 'WindowId': window.WindowId, 'WindowDefinitionId': window.WindowDefinitionId };
                                    const wind_index = allData.findIndex(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
                                    let wind = wind_index >= 0 ? allData[wind_index] : defData;

                                    if (cameraType == '2') {
                                        var QD = wind.WindowQA || {};
                                        var image_key = qtn.WindowQuestionId + '_ImageName1';
                                        var image_key_path = qtn.WindowQuestionId + '_ImagePath1';
                                        QD[image_key] = filename;
                                    }
                                    else if (cameraType == '3') {
                                        var image_key = 'NAImage1';
                                        var image_key_path = 'NAImage1Path';
                                        wind[image_key] = filename;
                                    }
                                    else {
                                        var WindowSplits = wind.WindowSplits || [];
                                        var image_key = type == '1' ? 'Image1Name' : 'Image2Name';
                                        var image_key_path = type == '1' ? 'Image1' : 'Image2';
                                        splitItem[image_key] = filename;
                                    }
                                    // renamefile
                                    let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;;
                                    RNFS.copyFile(res.uri, imagePath)
                                        .then(resn => {
                                            let uri = 'file://' + imagePath;
                                            console.log('image marker:', uri);

                                            if (cameraType == '2') {
                                                QD[image_key_path] = uri;
                                                wind.WindowQA = QD;
                                                wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                                                setWindowData(allData);
                                                setHasUnsavedChanges(true);
                                                setrerenderdata3(!rerenderdata3);
                                            }
                                            else if (cameraType == '3') {
                                                wind[image_key_path] = uri;
                                                wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                                                setWindowData(allData);
                                                setHasUnsavedChanges(true);
                                                setrerenderdata(!rerenderdata);
                                            }
                                            else {
                                                console.log('split image updated');
                                                splitItem[image_key_path] = uri;
                                                splitItemIndex >= 0 ? WindowSplits[splitItemIndex] = splitItem : WindowSplits.push(splitItem);
                                                wind.WindowSplits = WindowSplits;
                                                wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
                                                setWindowData(allData);
                                                setHasUnsavedChanges(true);
                                                setrerenderdata2(!rerenderdata2);
                                            }



                                        })
                                        .catch(err => {
                                            console.log('ERROR: image file write failed!!!');
                                            console.log(err.message, err.code);
                                        });

                                }
                                else {
                                    if (res.imagenotfound) {
                                        notify('Please capture a image');
                                    }
                                    else {
                                        notify(res.error);
                                    }
                                }
                            });
                    }
                    else {
                        if (res.imagenotfound) {
                            notify('Please capture a image');
                        }
                        else {
                            notify(res.error);
                        }
                    }
                });
        }
    }

    async function openCamera(window, splitItem, splitItemIndex, type = '1', cameraType = '1', qtn = {}) {
        setGetImageProps({ 'window': window, 'splitItem': splitItem, 'splitItemIndex': splitItemIndex, 'type': type, 'cameraType': cameraType, 'qtn': qtn });
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }


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

    async function saveData() {
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        let d1n = new Date();
        let d3 = moment(d1n).format('MM/DD/YYYY');
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {

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

                // add data
                var values = '', childV = '', imageV = '', stockV = '';

                for (const wi in Windows) {
                    const window = Windows[wi];
                    let isImage1 = window.WindowImage1 == 'true' || window.WindowImage1 == 1 ? 1 : 0;
                    let isImage2 = window.WindowImage2 == 'true' || window.WindowImage2 == 1 ? 1 : 0;
                    let isNAImageAvl = window.WindowNotExistCamera == 'true' || window.WindowNotExistCamera == 1 ? 1 : 0;
                    let isNAReasonEnable = window.WindowNotExistReasonEnable == 'true' || window.WindowNotExistReasonEnable == 1 ? 1 : 0;
                    let isReasonEnable = window.WindowExistReasonEnable == 'true' || window.WindowExistReasonEnable == 1 ? 1 : 0;
                    let isStockReq = window.WindowElementStockRequired == 'true' || window.WindowElementStockRequired == 1 ? 1 : 0;
                    let WindowQuestions = window.WindowQuestions || [];
                    let WindowStocks = window.WindowStocks || [];


                    const wind = WindowData.find(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
                    let isPresent = wind.isPresent != null && wind.isPresent != '' ? wind.isPresent : '0';
                    let ReasonId = wind.ReasonId != null ? wind.ReasonId : 0;
                    let Reason = wind.Reason != null ? wind.Reason : '';
                    let NAImage1 = wind.NAImage1 != null ? wind.NAImage1 : '';
                    let NAImage1Path = wind.NAImage1Path != null ? wind.NAImage1Path : '';
                    let WindowSplits = wind.WindowSplits || [];
                    let QD = wind.WindowQA || {};
                    let WStocksData = wind.WStocksData || [];

                    let WINDOW_HEADER_ID = 'WIND' + wi + (Math.floor(Math.random() * 1000) + 1);
                    let { WindowDefinitionId, WindowId, WindowName, WindowTable, WindowField, WindowValue, ChildName } = window;


                    values += values != '' ? ' , ' : '';
                    values += ` ('${WINDOW_HEADER_ID}','${StoreId}','${d3}','${WindowDefinitionId}','${WindowId}','${WindowName}','${WindowTable}','${WindowField}','${WindowValue}','${ChildName}','${isPresent}','${NAImage1}','${ReasonId}','${Reason}','${d3}') `;

                    if (isPresent == 1) {
                        for (const qtnIndex in WindowQuestions) {
                            const qtn = WindowQuestions[qtnIndex];

                            let selansid = '', selanswer = '', selimg = '', showImageTag = false;
                            let id_key = qtn.WindowQuestionId + '_AnswerId';
                            let ans_key = qtn.WindowQuestionId + '_Answer';
                            let multi_key = qtn.WindowQuestionId + '_MultiOption';
                            let date_key = qtn.WindowQuestionId + '_Date';
                            let img_key = qtn.WindowQuestionId + '_ImagePath1';
                            let imgname_key = qtn.WindowQuestionId + '_ImageName1';
                            let rating_key = qtn.WindowQuestionId + '_Rating';
                            let list_mcdata = [];

                            let { WindowQuestionId, WindowQuestionCode, QuestionType, WAShowCamera } = qtn
                            let answer = QD[ans_key] || 0;
                            let answerId = QD[id_key] || '';
                            let multi_options_ids = QD[multi_key] || '';
                            let isImage1All = WAShowCamera == 'true' || WAShowCamera == 1 ? 1 : 0;
                            let Image1 = isImage1All == 1 ? QD[imgname_key] : '';


                            childV += childV != '' ? ' , ' : '';
                            childV += ` ('${WINDOW_HEADER_ID}','${StoreId}','${d3}','${WindowDefinitionId}','${WindowId}','${WindowQuestionId}','${WindowQuestionCode}','${QuestionType}','${answer}','${answerId}','${multi_options_ids}','${Image1}','${isImage1All}','${d3}') `;
                        }
                        for (const splitItemIndex in WindowSplits) {
                            const splitItem = WindowSplits[splitItemIndex];
                            let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                            let Image2Name = splitItem['Image2Name'] != null && splitItem['Image2Name'] != '' ? splitItem['Image2Name'] : '';
                            Image1Name = isImage1 == 1 ? Image1Name : '';
                            Image2Name = isImage2 == 1 ? Image2Name : '';

                            imageV += imageV != '' ? ' , ' : '';
                            imageV += ` ('${WINDOW_HEADER_ID}','${StoreId}','${d3}','${WindowDefinitionId}','${WindowId}','${Image1Name}','${Image2Name}','${d3}') `;
                        }
                        for (const stockProdIndex in WindowStocks) {
                            const stockProd = WindowStocks[stockProdIndex];
                            let sd = WStocksData.find(i => i.ProductId == stockProd.WindowStockValue) || {};
                            let stock = sd.Stock != null ? sd.Stock : (sd.Stock == 0 ? sd.Stock : '');
                            let { WindowStockDefinitionId, WindowDefinitionId, WindowStockTable, WindowStockField, WindowStockValue, WindowStockMBQ, ProductName } = stockProd
                            stockV += stockV != '' ? ' , ' : '';
                            stockV += ` ('${WINDOW_HEADER_ID}','${StoreId}','${d3}','${WindowDefinitionId}','${WindowId}','${WindowStockDefinitionId}','${WindowStockTable}','${WindowStockField}','${WindowStockValue}','${WindowStockMBQ}','${ProductName}','${stock}','${d3}') `;
                        }

                    }
                }

                console.log('values:', values);


                let add_hdr_data = `INSERT INTO ${AppTables.WINDOW_HDR_DATA} (WINDOW_HEADER_ID,STORE_ID,VISIT_DATE,WINDOW_DEFINITION_ID,WINDOW_ID,WINDOW_NAME,WINDOW_TABLE,WINDOW_FIELD,WINDOW_VALUE,CHILD_NAME,IS_PRESENT,WINDOW_NA_IMAGE,REASON_ID,REASON,ADDED_DATE) VALUES ${values} `;
                let add_child_data = `INSERT INTO ${AppTables.WINDOW_CHILD_DATA} (WINDOW_HEADER_ID,STORE_ID,VISIT_DATE,WINDOW_DEFINITION_ID,WINDOW_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE) VALUES ${childV} `;
                let add_images_data = `INSERT INTO ${AppTables.WINDOW_IMAGES} (WINDOW_HEADER_ID,STORE_ID,VISIT_DATE,WINDOW_DEFINITION_ID,WINDOW_ID,IMAGE1,IMAGE2,ADDED_DATE) VALUES ${imageV} `;
                let add_stock_data = `INSERT INTO ${AppTables.WINDOW_STOCK_DATA} (WINDOW_HEADER_ID,STORE_ID,VISIT_DATE,WINDOW_DEFINITION_ID,WINDOW_ID,WINDOW_STOCK_DEFINITION_ID,WINDOW_STOCK_TABLE,WINDOW_STOCK_FIELD,WINDOW_STOCK_VALUE,WINDOW_STOCK_MBQ,PRODUCT_NAME,STOCK,ADDED_DATE) VALUES ${stockV} `;

                await txn.executeSql(add_hdr_data, [], async function (txn2, txnres) {
                    console.log('window header data added');
                    var isSplitImageAdded = true, isStockAdded = true, isChildAdded = true;
                    if (imageV != '') {
                        isSplitImageAdded = await executeQuery(add_images_data);
                    }
                    if (stockV != '') {
                        isStockAdded = await executeQuery(add_stock_data);
                    }
                    if (childV != '') {
                        isChildAdded = await executeQuery(add_child_data);
                    }

                    if (!isSplitImageAdded) {
                        setProcessing(false); notify('Cannot add split window images');
                    }
                    else if (!isStockAdded) {
                        setProcessing(false); notify('Cannot add window stock data');
                    }
                    else if (!isChildAdded) {
                        setProcessing(false); notify('Cannot add window questions data');
                    }
                    else {
                        setProcessing(false); notify('Window data updated successfully');
                        props.navigation.goBack();
                    }

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

    async function executeQuery(q) {
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    resolve(true);
                }, function (Etxn, txnerr) { console.log(txnerr); resolve(false) });
            });
        }).then((val) => {
            return val;
        }).catch((err) => {
            console.log(err);
            return false;
        })
    }



    async function validate() {
        let isValid = true;

        return new Promise((resolve, reject) => {
            for (const wi in Windows) {
                const window = Windows[wi];
                let isImage1 = window.WindowImage1 == 'true' || window.WindowImage1 == 1 ? 1 : 0;
                let isImage2 = window.WindowImage2 == 'true' || window.WindowImage2 == 1 ? 1 : 0;
                let isNAImageAvl = window.WindowNotExistCamera == 'true' || window.WindowNotExistCamera == 1 ? 1 : 0;
                let isNAReasonEnable = window.WindowNotExistReasonEnable == 'true' || window.WindowNotExistReasonEnable == 1 ? 1 : 0;
                let isReasonEnable = window.WindowExistReasonEnable == 'true' || window.WindowExistReasonEnable == 1 ? 1 : 0;
                let isStockReq = window.WindowElementStockRequired == 'true' || window.WindowElementStockRequired == 1 ? 1 : 0;
                let WindowQuestions = window.WindowQuestions || [];
                let WindowStocks = window.WindowStocks || [];


                const wind = WindowData.find(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
                let isPresent = wind.isPresent != null && wind.isPresent != '' ? wind.isPresent : '0';
                let ReasonId = wind.ReasonId != null ? wind.ReasonId : '';
                let Reason = wind.Reason != null ? wind.Reason : '';
                let NAImage1 = wind.NAImage1 != null ? wind.NAImage1 : '';
                let NAImage1Path = wind.NAImage1Path != null ? wind.NAImage1Path : '';
                let WindowSplits = wind.WindowSplits || [];
                let QD = wind.WindowQA || {};
                let WStocksData = wind.WStocksData || [];

                if (isPresent == '1') {
                    if (isReasonEnable == true && ReasonId == '') {
                        notify(`Please select reason for ${window.WindowName} `, 'LONG');
                        resolve(false); return;
                    }
                    else {
                        if (window.NoOfSplit > 0 && WindowSplits.length > 0 && (isImage1 == 1 || isImage2 == 1)) {
                            for (const splitItemIndex in WindowSplits) {
                                const splitItem = WindowSplits[splitItemIndex];
                                let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                                let Image2Name = splitItem['Image2Name'] != null && splitItem['Image2Name'] != '' ? splitItem['Image2Name'] : '';
                                console.log('Image2Name', Image2Name, isImage2);
                                if (isImage1 == 1 && Image1Name == '') {
                                    notify(`Please click all images for ${window.WindowName}`, 'LONG');
                                    resolve(false); return;
                                }
                                else if (isImage2 == 1 && Image2Name == '') {
                                    notify(`Please click all images for ${window.WindowName}`, 'LONG');
                                    resolve(false); return;
                                }
                            }
                        }

                        if (isStockReq == 1) {
                            for (const stockProdIndex in WindowStocks) {
                                const stockProd = WindowStocks[stockProdIndex];
                                let sd = WStocksData.find(i => i.ProductId == stockProd.WindowStockValue) || {};
                                let stock = sd.Stock != null ? sd.Stock : (sd.Stock == 0 ? sd.Stock : '');

                                if (stock == '') {
                                    notify(`Please enter stock for ${window.WindowName} ( ${stockProd.ProductName} ) `, 'LONG');
                                    resolve(false); return;
                                }
                            }
                        }

                        if (WindowQuestions.length > 0) {
                            for (const qtnIndex in WindowQuestions) {
                                const qtn = WindowQuestions[qtnIndex];

                                let selansid = '', selanswer = '', selimg = '', showImageTag = false;
                                let id_key = qtn.WindowQuestionId + '_AnswerId';
                                let ans_key = qtn.WindowQuestionId + '_Answer';
                                let multi_key = qtn.WindowQuestionId + '_MultiOption';
                                let date_key = qtn.WindowQuestionId + '_Date';
                                let img_key = qtn.WindowQuestionId + '_ImagePath1';
                                let imgname_key = qtn.WindowQuestionId + '_ImageName1';
                                let rating_key = qtn.WindowQuestionId + '_Rating';
                                let list_mcdata = [];

                                let isImgAllowed = (qtn.WQShowCamera == 'true' || qtn.WQShowCamera == 1);
                                let checkForAnsKey = (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'Date' || qtn.QuestionType == 'Rating');
                                if (qtn.QuestionType == 'Single choice list') {
                                    selansid = QD[id_key];
                                }
                                else if (qtn.QuestionType == 'Multi choice list') {
                                    selansid = QD[multi_key] != null && QD[multi_key] != '' ? QD[multi_key].split(',') : [];
                                }


                                if (qtn.QuestionType == 'Multi choice list' && selansid.length <= 0) {
                                    notify(`Please select options for the required field in ${window.WindowName}`, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (checkForAnsKey && (Object.keys(QD).indexOf(ans_key) < 0 || (Object.keys(QD).indexOf(ans_key) >= 0 && QD[ans_key] === ''))) {
                                    let msg = (qtn.QuestionType == 'Date' ? `Please pick a date for the required field in ${window.WindowName}` : (qtn.QuestionType == 'Rating' ? `Please select rating for the required field in ${window.WindowName}` : `Please fill all the required field in ${window.WindowName}`));
                                    notify(msg, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (Object.keys(QD).indexOf(id_key) < 0 || (Object.keys(QD).indexOf(id_key) >= 0 && (QD[id_key] === '' || (QD[id_key] === 0 && qtn.isDisabled === false)))) {
                                    notify(`Please fill all the required field in ${window.WindowName}`, 'SHORT');
                                    resolve(false); return;
                                }
                                else if (isImgAllowed && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                                    notify(`Please add images in ${window.WindowName}`, 'SHORT');
                                    resolve(false); return;
                                } else {
                                    console.log('no condition found');
                                }

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

                                if (showImageTag && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                                    notify(`Please add images in ${window.WindowName}`, 'SHORT');
                                    resolve(false); return;
                                }
                            }
                        }

                    }
                }
                else {
                    if (isNAReasonEnable == true && ReasonId == '') {
                        notify(`Please select reason for ${window.WindowName} `, 'LONG');
                        resolve(false); return;
                    }
                    else if (isNAImageAvl == true && NAImage1 == '') {
                        notify(`Please click image for ${window.WindowName}`, 'LONG');
                        resolve(false); return;
                    }
                }

                if (wi == (Windows.length - 1)) {
                    resolve(true); return;
                }

            }

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

    }


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

        win_index >= 0 ? allData[win_index] = wind : allData.push(wind);
        console.log('allData:', allData);
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

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


        wind['WindowQA'] = data;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

        setWindowData(allData);

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

        let sqtns = window.WindowQuestions || []

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

    }

    async function disableQtns(sqtns, DQtns, data, wind = {}, wind_index = -1, allData = [], window = {}) {

        if (DQtns.length > 0) {
            new Promise.all(
                DQtns.map((qid, q_index) => {
                    let s_qtnindex = sqtns.findIndex(i => i.WindowQuestionId == qid) || {};
                    let s_qtn = sqtns[s_qtnindex];
                    s_qtn['isDisabled'] = true
                    sqtns[s_qtnindex] = s_qtn;
                    let id_key = s_qtn.WindowQuestionId + '_AnswerId';
                    let ans_key = s_qtn.WindowQuestionId + '_Answer';
                    data[id_key] = 0;
                    data[ans_key] = '';

                    wind['WindowQA'] = data;
                    wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

                    return false
                })
            ).then(async (val) => {

                let allwindows = Windows;
                let windowIndex = allwindows.findIndex(i => i.WindowDefinitionId == window.WindowDefinitionId && i.WindowId == window.WindowId)
                if (windowIndex > 0) {
                    window['WindowQuestions'] = sqtns;
                    allwindows[windowIndex] = window;
                    setWindowData(allData);
                    setWindows(allwindows);
                    setHasUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                }

            })
        }
    }

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

    async function setMultiSelectValue(selectedItems = [], qtn = {}, window = {}) {
        console.log('setMultiSelectValue', selectedItems);
        let id_key = qtn.WindowQuestionId + '_AnswerId';
        let ans_key = qtn.WindowQuestionId + '_Answer';
        let multi_key = qtn.WindowQuestionId + '_MultiOption';

        let allData = WindowData;
        let defData = { 'WindowId': window.WindowId, 'WindowDefinitionId': window.WindowDefinitionId };
        const wind_index = allData.findIndex(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
        let wind = wind_index >= 0 ? allData[wind_index] : defData;
        let obj = wind.WindowQA || {};
        obj[id_key] = 0;
        obj[multi_key] = selectedItems.join(',');
        let anss = [];
        selectedItems.map((itemValue) => {
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue);
            if (ans.Answer) { anss.push(ans.Answer) }
        });
        obj[ans_key] = anss.join(',');
        console.log('obj:', obj);

        wind['WindowQA'] = obj;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value, qtn, window) {
        let id_key = qtn.WindowQuestionId + '_AnswerId';
        let ans_key = qtn.WindowQuestionId + '_Answer';

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

        if (qtn.QuestionType == 'Date') {
            let date_key = qtn.WindowQuestionId + '_Date';
            let d = value != null ? new Date(value) : new Date();
            let mfdate = moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn, window, false);
            obj[id_key] = 0;
            obj[ans_key] = mfdate;
            obj[date_key] = moment(d).format('MM/DD/YYYY');
        }
        else {
            obj[id_key] = 0;
            obj[ans_key] = value;
        }

        console.log(value, obj);
        wind['WindowQA'] = obj;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

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

    function showQtnDatePicker(qtn, window, show = false) {
        let allQtns = window.WindowQuestions || [];
        let newqtnIndex = allQtns.findIndex(q => q.WindowQuestionId == qtn.WindowQuestionId);

        if (newqtnIndex >= 0) {
            let newqtn = allQtns[newqtnIndex];
            newqtn.showDatePicker = show;
            allQtns[newqtnIndex] = newqtn;
            window['WindowQuestions'] = allQtns;
            let allWindows = Windows;
            const winIndex = allWindows.findIndex(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId) || {};
            allWindows[winIndex] = window;
            setWindows(allWindows);

            if (show == true) setrerenderdata(!rerenderdata);
        }
    }

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

    function onRatingCancel() {
        setShowRating(false);
    }

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

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

        obj[rating_key] = ids.join(',');
        obj[id_key] = 0;
        obj[ans_key] = anss.join(',');

        wind['WindowQA'] = obj;
        wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);

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


    function onChoiceSelect(item, val, key, animatedChoice) {
        console.log('onChoiceSelect', animatedChoice)
        var val1 = 0;
        val == 1 ? val1 = 1 : '';

        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        onWindowDataChange(item, val, key)
    }

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

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

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

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


    function setWindowStockVal(val, window, stockProd) {
        let allData = WindowData;
        let defData = { 'WindowId': window.WindowId, 'WindowDefinitionId': window.WindowDefinitionId };
        const win_index = allData.findIndex(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
        let wind = win_index >= 0 ? (allData[win_index] || defData) : defData;
        let WStocksData = wind['WStocksData'] || [];
        let sdIndex = WStocksData.findIndex(i => i.ProductId == stockProd.WindowStockValue);
        let sd = sdIndex >= 0 ? WStocksData[sdIndex] : { 'ProductId': stockProd.WindowStockValue, 'Stock': '' };
        sd['Stock'] = val;
        sdIndex >= 0 ? WStocksData[sdIndex] = sd : WStocksData.push(sd);
        wind['WStocksData'] = WStocksData;
        win_index >= 0 ? allData[win_index] = wind : allData.push(wind);

        setWindowData(allData);
        setHasUnsavedChanges(true);
        setrerenderdata4(!rerenderdata4);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }



    function openImageRefView(RefImage = '') {
        setShow_zoomImage(true);
    }

    function renderRatingView() {
        let qtn = RatingQtn;
        let Answers = qtn.Answers;
        let id_key = qtn.WindowQuestionId + '_AnswerId';
        let ans_key = qtn.WindowQuestionId + '_Answer';
        let rating_key = qtn.WindowQuestionId + '_Rating';

        let newarr = RatingOrder;
        if (RatingOrder.length <= 0) {
            newarr = Answers;
        }

        return (
            <View style={customStyle.RatingModal}>
                <View style={customStyle.RatingModalCon}>
                    <Text style={customStyle.VRModalHeding}>Drag Items In Order</Text>
                    <Text style={customStyle.VRSubHeding}>Press and hold to drag</Text>
                    <DraggableFlatList
                        data={newarr}
                        style={customStyle.RModal_list}
                        contentContainerStyle={customStyle.RModal_listInner}
                        onDragEnd={({ data }) => { setRatingValue(data) }}
                        keyExtractor={(item) => item.AnswerId}
                        renderItem={renderItem}
                    />
                    <View style={customStyle.RModal_Btns}>
                        <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={() => { onRatingCancel() }}>
                            <Text style={customStyle.RModal_BtnTextCancel}>Cancel</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={() => { onRatingSave() }}>
                            <Text style={customStyle.RModal_BtnTextsave}>Save</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }

    function render_Picker(label_key, value_key, onChange = () => { }, selected_data = {}) {
        var data = [];
        let qtn = selected_data.qtn || {};
        let window = selected_data.window || {};
        let isQtnDisabled = qtn.isDisabled != null || qtn.isDisabled != '' ? false : true;
        let allAnswers = qtn.Answers || [];

        allAnswers.map((item, index) => {
            let obj = { key: index, label: item[label_key], value: item[value_key] };
            if (selected_data.value == item[label_key])
                obj['component'] = <View style={customStyle.addvis_selectedOpStyle}><Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text></View>;
            data.push(obj);
        });

        return (
            <ModalSelector
                data={data}

                touchableActiveOpacity={0.8}

                style={customStyle.addVisPickerStyle}
                onChange={(option) => { onChange(option, qtn, window) }}
                overlayStyle={customStyle.addVisPickerOverlay}
                cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                optionStyle={customStyle.addvis_opStyle}
                optionTextStyle={customStyle.addvis_opTextStyle}
                optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                selectedKey={'1'}
                disabled={isQtnDisabled}
            >
                <Text style={[customStyle.WQPicker_InputStyle, (isQtnDisabled ? customStyle.addVisPicker_Dis_InputStyle : {})]}>{(selected_data.value != null && selected_data.value != '' ? selected_data.value : '-select-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn, window) {
        let qtnn = qtn;
        let DateRange = qtn.DateRange;
        let maxDate = moment().add(10, 'years').format('MM/DD/YYYY');
        let minDate = moment().subtract(10, 'years').format('MM/DD/YYYY');
        if (DateRange == 'RFD') {
            maxDate = moment().format('MM/DD/YYYY');
        }
        else if (DateRange == 'RPD') {
            minDate = moment().format('MM/DD/YYYY');
        }

        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={(dateValue != null && dateValue != '' ? new Date(dateValue) : new Date())}
                mode={'date'}
                display="default"
                onChange={(event, selectedDate) => { setTextValue(selectedDate, qtnn, window) }}
                maximumDate={new Date(maxDate)}
                minimumDate={new Date(minDate)}
            />
        );
    }

    function _renderWindow() {
        return (
            <FlatList
                data={Windows}
                extraData={rerenderdata}
                contentContainerStyle={customStyle.Win_scroll}
                style={customStyle.Win_scrollO}
                listKey={(item, index) => `window_${index.toString()}`}
                renderItem={({ item, index }) => {
                    const window = item;

                    let isImage1 = window.WindowImage1 == 'true' || window.WindowImage1 == 1 ? 1 : 0;
                    let isImage2 = window.WindowImage2 == 'true' || window.WindowImage2 == 1 ? 1 : 0;
                    let isNAImageAvl = window.WindowNotExistCamera == 'true' || window.WindowNotExistCamera == 1 ? 1 : 0;
                    let isNAReasonEnable = window.WindowNotExistReasonEnable == 'true' || window.WindowNotExistReasonEnable == 1 ? 1 : 0;
                    let isReasonEnable = window.WindowExistReasonEnable == 'true' || window.WindowExistReasonEnable == 1 ? 1 : 0;
                    let isStockReq = window.WindowElementStockRequired == 'tre' || window.WindowElementStockRequired == 1 ? 1 : 0;
                    // let isStock_CheckAssrt=window.WindowElementCheckAssortment=='true' || window.WindowElementCheckAssortment==1?1:0;
                    let RefImage = window.WindowRefImage;
                    let camera1Label = window.WindowImage1Lable || '';
                    let camera2Label = window.WindowImage2Lable || '';
                    let WindowQuestions = window.WindowQuestions || [];
                    let WindowStocks = window.WindowStocks || [];

                    const wind = WindowData.find(i => i.WindowId == window.WindowId && i.WindowDefinitionId == window.WindowDefinitionId);
                    let isPresent = wind.isPresent != null && wind.isPresent != '' ? wind.isPresent : '0';
                    let ReasonId = wind.ReasonId != null ? wind.ReasonId : '';
                    let Reason = wind.Reason != null ? wind.Reason : '';
                    let NAImage1 = wind.NAImage1 != null ? wind.NAImage1 : '';
                    let NAImage1Path = wind.NAImage1Path != null ? wind.NAImage1Path : '';
                    let WindowSplits = wind.WindowSplits || [];
                    let QuestionsData = wind.WindowQA || {};
                    let WStocksData = wind.WStocksData || [];

                    // console.log('camera2Label:',window.WindowId,window.WindowDefinitionId,camera2Label);


                    var xpos = isPresent == '1' ? -75 : 0;
                    if (window.animatedChoice != null) {
                        xpos = window.animatedChoice.interpolate({
                            inputRange: [0, 1],
                            outputRange: [0, -75],
                        });
                    }
                    return (
                        <View style={customStyle.WItem_wrap} key={'window_' + index}>
                            <View style={customStyle.WItem_Hdr}>
                                <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.WItem_Hdrbg}>
                                    <Text style={customStyle.WItem_HdrText}>{window.WindowName}</Text>
                                    <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={() => { openImageRefView(RefImage) }}>
                                        <Entypo name='image-inverted' size={24} color={'#1f7dbc'} />
                                    </TouchableOpacity>
                                </LinearGradient>
                            </View>

                            <View style={customStyle.WForm}>
                                <View style={[customStyle.openStk_prd_cols, customStyle.mt10]}>
                                    <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{'Is Present'}</Text>
                                        <View style={customStyle.openStk_prd_choiceBoxCon}>
                                            <View style={customStyle.openStk_prd_choiceBox}>
                                                <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isPresent == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                                                { transform: [{ translateX: xpos }], }]}></Animated.View>
                                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(window, 1, 'isPresent', window.animatedChoice) }}>
                                                    <Text style={[customStyle.openStkCh_text, (isPresent == '1' ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                                                </TouchableOpacity>
                                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(window, 0, 'isPresent', window.animatedChoice) }}>
                                                    <Text style={[customStyle.openStkCh_text, (isPresent == '0' ? customStyle.openStkCh_textactive : {})]}>No</Text>
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    </View>
                                    {((isPresent != '1' && isNAReasonEnable == true) || (isPresent == '1' && isReasonEnable == true)) &&
                                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>Select Reason</Text>
                                            {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange} selected_data={{ value: Reason, otherData: { window: window } }} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                                        </View>
                                    }


                                    {(isPresent != '1' && isNAImageAvl == true) &&
                                        <View>
                                            <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                                <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$bg_color, PageTheme.$fourth_color, PageTheme.$bg_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                                    <Text style={customStyle.windhdrText}>{'Capture Image'}</Text>
                                                </LinearGradient>


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



                                    {(isPresent == '1') &&
                                        <View>
                                            {(isStockReq == true && WindowStocks.length > 0) &&
                                                <View style={[customStyle.openStk_prd_borderT, customStyle.pt10]}>
                                                    <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$bg_color, PageTheme.$fourth_color, PageTheme.$bg_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                                        <Text style={customStyle.windhdrText}>{'Enter Stocks'}</Text>
                                                    </LinearGradient>
                                                    <FlatList
                                                        data={WindowStocks}
                                                        extraData={rerenderdata4}
                                                        listKey={(item, index) => `wstock_${index.toString()}`}
                                                        renderItem={({ item, index }) => {
                                                            let stockProd = item;
                                                            let stockProdIndex = index;
                                                            let sd = WStocksData.find(i => i.ProductId == stockProd.WindowStockValue) || {};
                                                            let stock = sd.Stock != null ? sd.Stock : '';
                                                            return (
                                                                <View style={[customStyle.WStkWrap]} key={'WSTock+' + stockProdIndex}>
                                                                    <Text style={[customStyle.WStkHdrText]}>{stockProd.ProductName}</Text>
                                                                    <View style={[customStyle.openStk_prd_colflex]} >
                                                                        <View style={[customStyle.openStk_prd_col50, customStyle.openStk_prd_col50_1]}>
                                                                            <Text style={customStyle.openStk_prd_flexlabel}>Stock</Text>
                                                                        </View>

                                                                        <View style={[customStyle.openStk_prd_col50, customStyle.openStk_prd_col50_2]}>
                                                                            <TextInput
                                                                                style={[customStyle.WStkInputStyle]}
                                                                                placeholder=""
                                                                                autoComplete='off'
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                keyboardType={'number-pad'}
                                                                                value={stock + ''}
                                                                                onChangeText={(val) => { setWindowStockVal(val, window, stockProd) }}
                                                                            />
                                                                        </View>

                                                                    </View>
                                                                </View>
                                                            );
                                                        }}
                                                    />
                                                </View>
                                            }
                                            {(window.NoOfSplit > 0 && WindowSplits.length > 0 && (isImage1 == 1 || isImage2 == 1)) &&
                                                <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                                    <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$bg_color, PageTheme.$fourth_color, PageTheme.$bg_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                                        <Text style={customStyle.windhdrText}>{'Capture Window Images'}</Text>
                                                    </LinearGradient>
                                                    <FlatList
                                                        data={WindowSplits}
                                                        extraData={rerenderdata2}
                                                        listKey={(item, index) => `spliItem_${index.toString()}`}
                                                        renderItem={({ item, index }) => {
                                                            let splitItem = item;
                                                            let splitItemIndex = index;
                                                            let Image1Name = splitItem['Image1Name'] != null && splitItem['Image1Name'] != '' ? splitItem['Image1Name'] : '';
                                                            let Image2Name = splitItem['Image2Name'] != null && splitItem['Image2Name'] != '' ? splitItem['Image2Name'] : '';
                                                            let Image1 = splitItem['Image1'] != null && splitItem['Image1'] != '' ? splitItem['Image1'] : '';
                                                            let Image2 = splitItem['Image2'] != null && splitItem['Image2'] != '' ? splitItem['Image2'] : '';

                                                            return (
                                                                <View style={[customStyle.openStk_prdCameras, customStyle.WSCameraWrap]} key={'SplitItem+' + splitItemIndex}>
                                                                    {isImage1 == 1 &&
                                                                        <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]}>
                                                                            {(Image1 == '' || Image1 == null) &&
                                                                                <TouchableOpacity style={[customStyle.osCat_action_openCam, customStyle.osCat_actn_margin]} onPress={() => { openCamera(window, splitItem, splitItemIndex, '1') }}>
                                                                                    <CameraImg width={80} height={80}  />
                                                                                </TouchableOpacity>
                                                                            }
                                                                            {(Image1 != '' && Image1 != null) &&
                                                                                <View style={customStyle.osCatImageView}>
                                                                                    <Image style={customStyle.osCatImage} source={{ uri: Image1 }} />
                                                                                    <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={() => { openCamera(window, splitItem, splitItemIndex, '1') }}>
                                                                                        <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color} />
                                                                                    </TouchableOpacity>
                                                                                </View>
                                                                            }
                                                                            <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text>
                                                                        </View>
                                                                    }
                                                                    {isImage2 == 1 &&
                                                                        <View style={customStyle.openStkCameraCon}>
                                                                            {(Image2 == '' || Image2 == null) &&
                                                                                <TouchableOpacity style={[customStyle.osCat_action_openCam, customStyle.osCat_actn_margin]} onPress={() => { openCamera(window, splitItem, splitItemIndex, '2') }}>
                                                                                    <CameraImg width={80} height={80}  />
                                                                                </TouchableOpacity>
                                                                            }
                                                                            {(Image2 != '' && Image2 != null) &&
                                                                                <View style={customStyle.osCatImageView}>
                                                                                    <Image style={customStyle.osCatImage} source={{ uri: Image2 }} />
                                                                                    <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={() => { openCamera(window, splitItem, splitItemIndex, '2') }}>
                                                                                        <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color} />
                                                                                    </TouchableOpacity>
                                                                                </View>
                                                                            }
                                                                            {console.log('camera2Label 2:', camera2Label)}
                                                                            <Text style={customStyle.WSCameraLabel}>{camera2Label}</Text>
                                                                        </View>
                                                                    }
                                                                </View>
                                                            );
                                                        }}
                                                    />
                                                </View>
                                            }

                                            {(WindowQuestions.length > 0) &&
                                                <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                                                    <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$bg_color, PageTheme.$fourth_color, PageTheme.$bg_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                                        <Text style={customStyle.windhdrText}>{'Window Questions'}</Text>
                                                    </LinearGradient>
                                                    {WindowQuestions.map((item, index) => {

                                                        let qtn = item;
                                                        let qtnIndex = index;
                                                        let selansid = '', selanswer = '', selimg = '', showImageTag = false;
                                                        let id_key = qtn.WindowQuestionId + '_AnswerId';
                                                        let ans_key = qtn.WindowQuestionId + '_Answer';
                                                        let multi_key = qtn.WindowQuestionId + '_MultiOption';
                                                        let date_key = qtn.WindowQuestionId + '_Date';
                                                        let img_key = qtn.WindowQuestionId + '_ImagePath1';
                                                        let imgname_key = qtn.WindowQuestionId + '_ImageName1';
                                                        let rating_key = qtn.WindowQuestionId + '_Rating';

                                                        let list_mcdata = [];

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


                                                        if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                                                            if (qtn.Answers && qtn.Answers.length > 0) {
                                                                for (var i = 0; i < qtn.Answers.length; i++) {
                                                                    let ansss = qtn.Answers[i];
                                                                    let isandImgAl = (ansss.WAShowCamera == 'true' || ansss.WAShowCamera == 1);

                                                                    if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                                                        showImageTag = true;
                                                                    }
                                                                    else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                                                        showImageTag = true;
                                                                    }

                                                                }
                                                            }
                                                        }

                                                        if (showImageTag) {
                                                            selimg = QuestionsData[img_key] != null && QuestionsData[img_key] != '' ? 'file://' + QuestionsData[img_key] : '';
                                                        }

                                                        return (
                                                            <View style={[customStyle.sform_group2,]} key={'Qtn_' + qtnIndex} >
                                                                <Text style={[customStyle.sform_label3]}>{qtn.WindowQuestionName}</Text>
                                                                {qtn.QuestionType == 'Single choice list' && qtn.Answers &&
                                                                    render_Picker('Answer', 'AnswerId', onselectionChange2, { value: selanswer, qtn: qtn, window: window })
                                                                }
                                                                {qtn.QuestionType == 'Multi choice list' && qtn.Answers &&
                                                                    <MultiSelect
                                                                        items={list_mcdata}
                                                                        uniqueKey="AnswerId"
                                                                        onSelectedItemsChange={(selectedItems) => { setMultiSelectValue(selectedItems, qtn, window) }} //setMultiSelectValue(selectedItems,qtn)
                                                                        selectedItems={selansid}
                                                                        selectText="Pick Items"
                                                                        searchInputPlaceholderText="Search Items..."
                                                                        // onChangeInput={ (text)=> console.log(text)}
                                                                        tagRemoveIconColor={PageTheme.$primary_color}
                                                                        tagBorderColor={PageTheme.$primary_color}
                                                                        tagTextColor={PageTheme.$primary_color}
                                                                        selectedItemTextColor={PageTheme.$primary_color}
                                                                        selectedItemIconColor={PageTheme.$primary_color}
                                                                        itemTextColor={PageTheme.$text_color}
                                                                        displayKey="Answer"
                                                                        searchInputStyle={{ color: '#CCC' }}
                                                                        submitButtonColor={PageTheme.$primary_color}
                                                                        submitButtonText="Submit"
                                                                    />
                                                                }
                                                                {(qtn.QuestionType == 'Number' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Text') &&
                                                                    <TextInput
                                                                        style={[customStyle.WQ_InputStyle]}
                                                                        placeholder=""
                                                                        autoComplete='off'
                                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                                        // keyboardType={'ascii-capable'}
                                                                        keyboardType={(qtn.QuestionType == 'Decimal' ? 'decimal-pad' : (qtn.QuestionType == 'Text' ? 'default' : 'number-pad'))}
                                                                        value={selansid}
                                                                        onChangeText={(val) => { setTextValue(val, qtn, window) }}
                                                                    />
                                                                }
                                                                {
                                                                    (qtn.QuestionType == 'Date') &&
                                                                    <View style={customStyle.surveyQtn_datePicker_con}>
                                                                        <Text style={customStyle.WQ_datePicker_text}>{selansid != '' ? selansid : 'MM/YYYY'}</Text>
                                                                        <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={() => { setDateValue(selanswer); showQtnDatePicker(qtn, window, true) }}>
                                                                            <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                                        </TouchableOpacity>
                                                                    </View>
                                                                }
                                                                {((qtn.showDatePicker == true || qtn.showDatePicker == 'true') && (qtn.QuestionType == 'Date')) &&
                                                                    renderDatePicker(qtn, window)
                                                                }
                                                                {
                                                                    (qtn.QuestionType == 'Rating') &&
                                                                    <View style={customStyle.surveyQtn_datePicker_con}>
                                                                        <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                                        <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={() => { setRatingQtn(qtn); setRatingWindow(window); setShowRating(true); }}>
                                                                            <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag" />
                                                                        </TouchableOpacity>
                                                                    </View>
                                                                }

                                                                {
                                                                    // (qtn.QuestionType=='Audio') && 
                                                                    // <View style={customStyle.surveyQtn_datePicker_con}>
                                                                    //     <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                                    //     <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{show_recorder(qtn);}}>
                                                                    //         <FontAwesome size={25} color={PageTheme.$accent_color} name="microphone"/>
                                                                    //     </TouchableOpacity> 
                                                                    // </View>    
                                                                }

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


                                                            </View>
                                                        )
                                                    })}
                                                </View>
                                            }


                                        </View>
                                    }



                                </View>
                            </View>
                        </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={() => { console.log('tsth'); setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#000'} 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}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            <CustomCamera cameraType={'back'} 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.Windows_Wrap}>
                            {_renderWindow()}
                        </View>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={'Save'} onPress={() => { onSubmitData() }} />
                    </View>
                </View>

            </LinearGradient>
            {showRating == true &&
                renderRatingView()
            }
            {show_zoomImage &&
                <View style={customStyle.album_ZOOM_wrap}>
                    <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl}
                        renderHeader={_renderHeader} renderIndicator={() => null}
                    />
                </View>
            }
        </Container>
    );
}



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