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, KeyboardAvoidingView, Alert, AppState, Keyboard } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { checkMDStockScreenExists, getDownloadJson, getKPIFields, getKPIFieldsWithSpecific, marktext1, marktext2, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, MaterialCommunityIcons } from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import { launchCamera, launchImageLibrary, CameraOptions } from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';

function ClosingStock(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [KPIFields, setKPIFields] = useState([]);
    const [KPIFieldsWithoutFilter, setKPIFieldsWithoutFilter] = useState([]);


    const [SKUStockData, setSKUStockData] = useState([]);
    const [IsMidDayStockScreen, setIsMidDayStockScreen] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

    const inputRefs = useRef({});
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SKUStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');

    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = 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);

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        getData(storeData1, menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(SKUStockData,pro)});  
            return unsubscribe;
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        console.log("app bg state change:", nextAppState, ScreenNameRef.current, hasUnsavedChangesRef.current)
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                visiteDate: d2
            }
            let WindowsStr = JSON.stringify(newData)
            await set_item('storeData', WindowsStr);
        }
    }

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

    // useEffect(() => {
    //     AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    //     AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    // }, [SKUStockData]); 

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

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

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

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

    async function getData(storeData1, menu1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData1;
            let allCats = [];
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            let AllKPIFieldsWithoutFilter = await getKPIFieldsWithSpecific();
            setKPIFieldsWithoutFilter(AllKPIFieldsWithoutFilter)

            let isMDSTOCKExists = await checkMDStockScreenExists(storeData1, 'MDSTOCK')
            setIsMidDayStockScreen(isMDSTOCKExists);

            let storeBGData1 = [], bgStoreJson = {};
            let windData = await get_item('storeData')
            // console.log("local storeData in getdata:",windData);
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, visiteDate } = StoreJson
                if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    // setSKUStockData(storeBGData);
                    BgUnsavedChanges(true)
                    BgWindowData(storeBGData);
                }
            }

            db.transaction(async function (txn) {

                let seletlist = `PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK,(OPENING_STOCK + MIDDAY_STOCK) as totalstock`;
                let skuCheck_q = `SELECT ${seletlist} FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and totalstock>0 `;


                let q = `select DISTINCT tbl1.CategoryId,tbl1.CategoryName from 
                ( SELECT DISTINCT p.ProductId,p.ProductName ,p.CategoryId,p.CategoryName,p.CategorySequence,(st.OPENING_STOCK+st.MIDDAY_STOCK) as totalStock from Product_Master p 
                INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId   
                INNER JOIN STOCK_DATA st on  p.ProductId=st.PRODUCT_ID and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'
                where mp.StoreId='${StoreId}' and totalStock>0  order by p.CategorySequence ) tbl1 order by tbl1.CategorySequence`;

                let q2 = `select DISTINCT tbl1.CategoryId,tbl1.CategoryName from 
                ( SELECT DISTINCT p.ProductId,p.ProductName ,p.CategoryId,p.CategoryName,p.CategorySequence,(st.OPENING_STOCK+st.MIDDAY_STOCK) as totalStock from Product_Master p 
                INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId   
                INNER JOIN STOCK_DATA st on  p.ProductId=st.PRODUCT_ID and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'
                where mp.StoreId='${StoreId}' order by p.CategorySequence ) tbl1 order by tbl1.CategorySequence`;

                // console.log('closing stock q:',q);
                // console.log('closing stock skuCheck_q:',skuCheck_q);
                txn.executeSql(skuCheck_q, [], async function (txn2, txnres) {
                    console.log("prod len with sum >0", txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        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) {
                                        // setBrandData(arr);
                                        getSKU(arr, storeData1, bgStoreJson, menu1, true);
                                    }
                                }

                            }
                        }, function (txnE, txnerr) { console.log(txnerr); });
                    }
                    else {
                        // console.log('closing stock q2:',q2);
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                let arr = [];
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    arr.push(data);
                                    if (i == txnres2.rows.length - 1) {
                                        // setBrandData(arr);
                                        getSKU(arr, storeData1, bgStoreJson, menu1, false);
                                    }
                                }
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); });
                    }
                }, function (txnE, txnerr) { console.log(txnerr); });
                // setProcessing(false);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function getSKU(brands = [], storeData1 = {}, bgStoreJson = {}, menu1 = {}, totalstockValidate = false) {

        try {
            let { StoreId, ChainId, StateId, StoreTypeId, ExpiryStock, StoreClassId, StoreCategoryId } = storeData1;

            let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
            let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
            let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;

            let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
            let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
            let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;

            let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
            let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
            let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;

            let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
            let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
            let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;

            let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
            let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
            let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;


            await db.transaction(async function (txn) {
                var allSKUData = [];
                await Promise.all(
                    brands.map(async (item, index) => {

                        // if there is no OPS and MDS available then show all mapped product in closing stock with filled value as 0 

                        let seletlist = `CLOSING_EXPIRYSTOCK1,ARTICLE_CODE,CLOSING_EXPIRYSTOCK2,CLOSING_EXPIRYSTOCK3,CLOSING_EXPIRYSTOCK4, MIDDAY_EXPIRYSTOCK1,MIDDAY_EXPIRYSTOCK2,MIDDAY_EXPIRYSTOCK3,MIDDAY_EXPIRYSTOCK4, EXPIRYSTOCK1,EXPIRYSTOCK2,EXPIRYSTOCK3,EXPIRYSTOCK4, PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK,(OPENING_STOCK + MIDDAY_STOCK) as totalstock,IsCompetitor`;
                        let sku_q = `SELECT ${seletlist} FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${item.CategoryId}' ${(totalstockValidate ? `and totalstock>0` : '')} ORDER BY MSL desc, IsCompetitor ASC, PRODUCT ASC`;
                        let { storeBGData, menuName, StoreId1, visiteDate } = bgStoreJson;


                        return await txn.executeSql(sku_q, [], async function (txn2, txnres) {
                            if (txnres.rows.length > 0) {
                                console.log('product found :', txnres.rows.length);
                                let arr = [];
                                for (var i = 0; i < txnres.rows.length; i++) {
                                    let data = txnres.rows.item(i);
                                    if (!isStockCalculateEnable) {
                                        inputRefs.current['input1_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    // if((isExpStockEnable && !isStockCalculateEnable)){
                                    //     inputRefs.current['input2_'+item.CategoryId+'_'+data.ProductId]='';
                                    // }
                                    if (isExpStock1Enable) {
                                        inputRefs.current['input2_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    if (isExpStock2Enable) {
                                        inputRefs.current['input3_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }

                                    if (isExpStock3Enable) {
                                        inputRefs.current['input4_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    if (isExpStock4Enable) {
                                        inputRefs.current['input5_' + item.CategoryId + '_' + data.ProductId] = '';
                                    }
                                    arr.push(data);

                                    let defData = { 'CategoryId': item.CategoryId, 'ProductId': data.ProductId, 'ClosingStock': (totalstockValidate ? data.CLOSING_STOCK : '0'), 'CLOSING_ExpiryStock1': data.CLOSING_EXPIRYSTOCK1, 'CLOSING_ExpiryStock2': data.CLOSING_EXPIRYSTOCK2, 'CLOSING_ExpiryStock3': data.CLOSING_EXPIRYSTOCK3, 'CLOSING_ExpiryStock4': data.CLOSING_EXPIRYSTOCK4 };
                                    // let defData={'CategoryId':item.CategoryId,'ProductId':data.ProductId,'ClosingStock':(totalstockValidate?data.CLOSING_STOCK:'0'),'CLOSING_ExpiryStock1':1,'CLOSING_ExpiryStock2':0,'CLOSING_ExpiryStock3':0,'CLOSING_ExpiryStock4':0};
                                    allSKUData.push(defData);
                                    if (i == txnres.rows.length - 1) {
                                        item['skulist'] = arr;
                                        brands[index] = item;
                                        if (index == brands.length - 1) {
                                            if (storeBGData != null && storeBGData != '' && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                                                if (storeBGData.length <= 0) {
                                                    // setSKUStockData(allSKUData);
                                                    BgWindowData(allSKUData);
                                                }
                                            } else {
                                                BgWindowData(allSKUData);
                                                // setSKUStockData(allSKUData);
                                            }
                                            // setSKUStockData(allSKUData);
                                            setBrandData(brands);
                                            setProcessing(false);
                                        }
                                        return item;
                                    }
                                }
                            }
                            else {
                                console.log('product not found return ');
                                item['skulist'] = [];
                                brands[index] = item;
                                setBrandData(brands);
                                setProcessing(false);
                                return item;
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        return item;
                    })
                );
            });
        } catch (err) {
            console.log(err);
        }
    }


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

    async function saveData() {

        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
        let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
        let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;

        let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
        let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
        let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;

        let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
        let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
        let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;

        let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
        let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
        let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;

        let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
        let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
        let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;

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

                let q = `SELECT DISTINCT KEY_ID,CATEGORY_ID FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`
                await txn.executeSql(q, [], async function (txn2, txnres) {

                    if (txnres.rows.length > 0) {
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let catdata = txnres.rows.item(i);
                            let c_index = i;
                            let q2 = `SELECT * FROM ${AppTables.STOCK_DATA} WHERE CATEGORY_ID='${catdata.CATEGORY_ID}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`

                            await txn.executeSql(q2, [], async function (txn2, txnres2) {
                                if (txnres2.rows.length > 0) {
                                    for (var j = 0; j < txnres2.rows.length; j++) {
                                        let skuData = txnres2.rows.item(j);
                                        let p_index = j;
                                        let new_q = '';
                                        let thisCatSkuData_i = SKUStockData.findIndex(ci => ci.CategoryId == catdata.CATEGORY_ID && ci.ProductId == skuData.PRODUCT_ID);
                                        let thisCatSkuData = thisCatSkuData_i >= 0 ? (SKUStockData[thisCatSkuData_i] || {}) : {};
                                        let closing_Stock = thisCatSkuData.ClosingStock != null ? thisCatSkuData.ClosingStock : '';
                                        let expStock1 = isExpStock1Enable == true ? (thisCatSkuData['CLOSING_ExpiryStock1'] != null ? thisCatSkuData['CLOSING_ExpiryStock1'] : '0') : '0';
                                        let expStock2 = isExpStock2Enable == true ? (thisCatSkuData['CLOSING_ExpiryStock2'] != null ? thisCatSkuData['CLOSING_ExpiryStock2'] : '0') : '0';
                                        let expStock3 = isExpStock3Enable == true ? (thisCatSkuData['CLOSING_ExpiryStock3'] != null ? thisCatSkuData['CLOSING_ExpiryStock3'] : '0') : '0';
                                        let expStock4 = isExpStock4Enable == true ? (thisCatSkuData['CLOSING_ExpiryStock4'] != null ? thisCatSkuData['CLOSING_ExpiryStock4'] : '0') : '0';

                                        if (isStockCalculateEnable) {
                                            let StockData = parseInt(expStock1) + parseInt(expStock2) + parseInt(expStock3) + parseInt(expStock4)
                                            new_q = `UPDATE ${AppTables.STOCK_DATA} SET CLOSING_STOCK='${(StockData || '0')}', CLOSING_EXPIRYSTOCK1=='${expStock1}',CLOSING_EXPIRYSTOCK2=='${expStock2}',CLOSING_EXPIRYSTOCK3=='${expStock3}',CLOSING_EXPIRYSTOCK4=='${expStock4}'  WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${catdata.CATEGORY_ID}' and PRODUCT_ID='${skuData.PRODUCT_ID}' `;
                                        } else {
                                            new_q = `UPDATE ${AppTables.STOCK_DATA} SET CLOSING_STOCK='${closing_Stock}'  WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${catdata.CATEGORY_ID}' and PRODUCT_ID='${skuData.PRODUCT_ID}' `;
                                        }

                                        await txn.executeSql(new_q, [], async function (txn2, txnres3) {
                                            console.log('updated closing stock', closing_Stock);
                                            if (c_index == txnres.rows.length - 1 && p_index == txnres2.rows.length - 1) {
                                                afterUpdate();
                                            }
                                        }, function (txnE, txnerr) { console.log(txnerr); notify('Oops! Error occur while updating Midday-Stock') },);
                                    }
                                } else {
                                    if (c_index == txnres.rows.length - 1) {
                                        setProcessing(false);
                                    }
                                }

                            }, function (txnE, txnerr) { console.log(txnerr); },);
                        }
                    }
                    else {
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

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

    async function focusToNext(cat, sku, type = '1') {

        let activeKey = '';
        let arr = Object.keys(inputRefs.current);

        activeKey = 'input' + type + '_' + cat.CategoryId + '_' + sku.ProductId;

        let activeIndex = arr.indexOf(activeKey);
        if (activeIndex < arr.length - 1) {
            let nextKey = arr[++activeIndex]
            let nextRef = inputRefs.current[nextKey];
            console.log("nextKey", nextKey, nextRef, inputRefs.current[nextKey])
            nextRef.focus();
        }
        else {
            return
        }
    }

    async function afterUpdate() {
        BgUnsavedChanges(false)
        setProcessing(false);
        // clear store data in local storage to avoiding re-set data for the store  
        clear_item('storeData')
        notify('Midday-Stock updated successfully');
        props.navigation.goBack();
    }


    async function validate() {
        let isValid = true;
        var i = 0, j = 0, error_Type = "";

        let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
        let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
        let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
        let isExpStock1DisplayName = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldDisplayName'] : "ExpStock 1";

        let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
        let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
        let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
        let isExpStock2DisplayName = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldDisplayName'] : "ExpStock 2";

        let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
        let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
        let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
        let isExpStock3DisplayName = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldDisplayName'] : "ExpStock 3";

        let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
        let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
        let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
        let isExpStock4DisplayName = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldDisplayName'] : "ExpStock 4";

        let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
        let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
        let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;


        await Promise.all(
            brandData.map(async (item, index) => {
                if (isValid) {
                    let catId = item.CategoryId;
                    let errorobj = { 'EF_brand': item };
                    let skulist = item.skulist || [];
                    console.log('skulist', skulist)
                    if (skulist.length > 0) {
                        await Promise.all(
                            skulist.map(async (skuItem, skuIndex) => {
                                if (isValid) {
                                    let skuData = SKUStockData.find(ci => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId) || {};
                                    let OS = skuItem.OPENING_STOCK || 0;
                                    let MDS = skuItem.MIDDAY_STOCK || 0;
                                    let maxClosingStock = IsMidDayStockScreen == true ? parseInt(OS) + parseInt(MDS) : parseInt(OS);
                                    // ExpiryStock1

                                    errorobj['EF_product'] = skuItem;
                                    let error_bid = item.CategoryId
                                    let error_pid = skuItem.ProductId
                                    let show_errorH = false, error_HInputKey = '', error_HInputKeyEx1 = '', error_HInputKeyEx2 = '', error_HInputKeyEx3 = '', error_HInputKeyEx4 = '';


                                    let OS_Exp1 = skuItem.EXPIRYSTOCK1 || 0;
                                    let OS_Exp2 = skuItem.EXPIRYSTOCK2 || 0;
                                    let OS_Exp3 = skuItem.EXPIRYSTOCK3 || 0;
                                    let OS_Exp4 = skuItem.EXPIRYSTOCK4 || 0;

                                    let MDS_Exp1 = skuItem.MIDDAY_EXPIRYSTOCK1 || 0;
                                    let MDS_Exp2 = skuItem.MIDDAY_EXPIRYSTOCK2 || 0;
                                    let MDS_Exp3 = skuItem.MIDDAY_EXPIRYSTOCK3 || 0;
                                    let MDS_Exp4 = skuItem.MIDDAY_EXPIRYSTOCK4 || 0;

                                    let maxClosingStockExp1 = IsMidDayStockScreen == true ? parseInt(OS_Exp1) + parseInt(MDS_Exp1) : parseInt(OS_Exp1);
                                    let maxClosingStockExp2 = IsMidDayStockScreen == true ? parseInt(OS_Exp2) + parseInt(MDS_Exp2) : parseInt(OS_Exp2);
                                    let maxClosingStockExp3 = IsMidDayStockScreen == true ? parseInt(OS_Exp3) + parseInt(MDS_Exp3) : parseInt(OS_Exp3);
                                    let maxClosingStockExp4 = IsMidDayStockScreen == true ? parseInt(OS_Exp4) + parseInt(MDS_Exp4) : parseInt(OS_Exp4);

                                    let ex_stock1 = skuData.CLOSING_ExpiryStock1 != null ? skuData.CLOSING_ExpiryStock1 : 0;
                                    let ex_stock2 = skuData.CLOSING_ExpiryStock2 != null ? skuData.CLOSING_ExpiryStock2 : 0;
                                    let ex_stock3 = skuData.CLOSING_ExpiryStock3 != null ? skuData.CLOSING_ExpiryStock3 : 0;
                                    let ex_stock4 = skuData.CLOSING_ExpiryStock4 != null ? skuData.CLOSING_ExpiryStock4 : 0;
                                    // console.log('closing_Stock',closing_Stock)


                                    let calVal = parseInt(ex_stock1 || 0) + parseInt(ex_stock2 || 0) + parseInt(ex_stock3 || 0) + parseInt(ex_stock4 || 0)

                                    if (isStockCalculateEnable == false && skuData.ClosingStock !== 0 && (skuData.ClosingStock == null || skuData.ClosingStock == '')) {
                                        notify('Please enter Closing-Stock for ' + skuItem.ProductName, 'SHORT');
                                        isValid = false;
                                        show_errorH = true, error_HInputKey = 'input1_', error_Type = 'input1_';
                                    } else if ((isExpStock1Enable == true) && skuData.CLOSING_ExpiryStock1 !== 0 && (skuData.CLOSING_ExpiryStock1 == null || skuData.CLOSING_ExpiryStock1 == '')) {
                                        notify('Please enter ' + isExpStock1DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx1 = 'input2_', error_Type = 'input2_';
                                    } else if ((isExpStock2Enable == true) && skuData.CLOSING_ExpiryStock2 !== 0 && (skuData.CLOSING_ExpiryStock2 == null || skuData.CLOSING_ExpiryStock2 == '')) {
                                        notify('Please enter ' + isExpStock2DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx2 = 'input3_', error_Type = 'input3_';
                                    } else if ((isExpStock3Enable == true) && skuData.CLOSING_ExpiryStock3 !== 0 && (skuData.CLOSING_ExpiryStock3 == null || skuData.CLOSING_ExpiryStock3 == '')) {
                                        notify('Please enter ' + isExpStock3DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx3 = 'input4_', error_Type = 'input4_';
                                    } else if ((isExpStock4Enable == true) && skuData.CLOSING_ExpiryStock4 !== 0 && (skuData.CLOSING_ExpiryStock4 == null || skuData.CLOSING_ExpiryStock4 == '')) {
                                        notify('Please enter ' + isExpStock4DisplayName + ' for ' + skuItem.ProductName, 'SHORT');
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx4 = 'input5_', error_Type = 'input5_';
                                    } else if (isStockCalculateEnable == false && parseInt(skuData.ClosingStock) > maxClosingStock) {
                                        IsMidDayStockScreen == true ? notify('Closing-Stock Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skuItem.ProductName);
                                        isValid = false;
                                        show_errorH = true, error_HInputKey = 'input1_', error_Type = 'input1_';
                                    } else if (parseInt(ex_stock1) > maxClosingStockExp1) {
                                        IsMidDayStockScreen == true ? notify(isExpStock1DisplayName + ' Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skuItem.ProductName);
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx1 = 'input2_', error_Type = 'input2_';
                                    } else if (parseInt(ex_stock2) > maxClosingStockExp2) {
                                        IsMidDayStockScreen == true ? notify(isExpStock2DisplayName + ' Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skuItem.ProductName);
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx2 = 'input3_', error_Type = 'input3_';
                                    } else if (parseInt(ex_stock3) > maxClosingStockExp3) {
                                        IsMidDayStockScreen == true ? notify(isExpStock3DisplayName + ' Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skuItem.ProductName);
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx3 = 'input4_', error_Type = 'input4_';
                                    } else if (parseInt(ex_stock4) > maxClosingStockExp4) {
                                        IsMidDayStockScreen == true ? notify(isExpStock4DisplayName + ' Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skuItem.ProductName);
                                        isValid = false;
                                        show_errorH = true, error_HInputKeyEx4 = 'input5_', error_Type = 'input5_';
                                    }




                                    if (show_errorH) {
                                        errorobj['EF_InputKey'] = error_HInputKey;
                                        errorobj['error_HInputKeyEx1'] = error_HInputKeyEx1;
                                        errorobj['error_HInputKeyEx2'] = error_HInputKeyEx2;
                                        errorobj['error_HInputKeyEx3'] = error_HInputKeyEx3;
                                        errorobj['error_HInputKeyEx4'] = error_HInputKeyEx4;

                                        setErrorField(errorobj)
                                        setError(true)
                                        let refIn1 = inputRefs.current[error_Type + error_bid + '_' + error_pid];
                                        refIn1.focus();
                                    }
                                }
                            })
                        );
                    }
                }
            })
        );

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

    async function onChangeValidate(cat, CategoryIndex, skus, ProductIndex) {
        let isValid = true;
        let d = { 'CategoryId': cat.CategoryId, 'CategoryIndex': CategoryIndex, 'ProductId': skus.ProductId, 'ProductIndex': ProductIndex };


        console.log('vdData', d);


        let skulist = skus || [];
        console.log('skulist', skulist)

        let skuData = SKUStockData.find(ci => ci.CategoryId == cat.CategoryId && ci.ProductId == skus.ProductId) || {};
        console.log('skuData', skuData)
        let OS = skulist.OPENING_STOCK || 0;
        console.log('OS', OS)
        let MDS = skulist.MIDDAY_STOCK || 0;
        console.log('MDS', MDS)
        let maxClosingStock = IsMidDayStockScreen == true ? parseInt(OS) + parseInt(MDS) : parseInt(OS);
        console.log('maxClosingStock', maxClosingStock)
        if (skuData.ClosingStock != null && skuData.ClosingStock != '') {
            if (skuData.ClosingStock !== 0 && skuData.ClosingStock !== '' && !validateNumber(skuData.ClosingStock, 'numeric', false)) {
                notify('Please enter whole numbers only for ' + skulist.ProductName + ' Closing-Stock', 'SHORT');
                isValid = false;
            } else if (parseInt(skuData.ClosingStock) > maxClosingStock) {
                IsMidDayStockScreen == true ? notify('Closing-Stock Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skulist.ProductName) : notify('Closing-Stock Should not be greater than the Opening-Stock for ' + skulist.ProductName);
                isValid = false;
            } else {

            }
        }
        else {

        }

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


    function onStockValChange(item, skuItem, val, key, type = '') {
        setError(false)
        setErrorField({})
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }

        let allSKUData = SKUStockData;
        let defData = { 'CategoryId': item.CategoryId, 'ProductId': skuItem.ProductId };
        const skud_index = allSKUData.findIndex(i => i.CategoryId == item.CategoryId && i.ProductId == skuItem.ProductId);
        const skud = skud_index >= 0 ? (allSKUData[skud_index] || defData) : defData;
        skud[key] = val;

        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        // setSKUStockData(allSKUData);
        BgWindowData(allSKUData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function _render_Alert() {
        return (
            <CustomModal
                style={customStyle.storelVisitM_Style}
                titleStyle={customStyle.storelVisitM_titleStyle}
                title={'Do you really want to save data?'}
                showModal={showAlert}
            >
                <View style={customStyle.storelVisitM_options}>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowAlert(false) }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { saveData() }}>
                        <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
                    </TouchableOpacity>
                </View>
            </CustomModal>
        )
    }

    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}`} />
            {_render_Alert()}
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    {Object.keys(storeData).length > 0 &&
                        <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior="position" enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -100)} >

                            <FlatList
                                data={brandData}
                                extraData={rerenderdata}
                                contentContainerStyle={customStyle.opening_Stock_scroll}
                                style={customStyle.opening_Stock_scrollOuter}
                                nestedScrollEnabled={true}
                                removeClippedSubviews={false}
                                scrollToOverflowEnabled={true}
                                legacyImplementation={true}
                                renderItem={({ item, index }) => {
                                    const cat = item;
                                    const cat_index = index;

                                    // get error field brand id
                                    let EF_brand = errorfield.EF_brand != null ? errorfield.EF_brand : {};
                                    let error_bid = EF_brand.CategoryId || '';

                                    let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
                                    let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
                                    let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
                                    let isExpStock1DisplayName = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldDisplayName'] : "ExpStock 1";

                                    let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
                                    let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
                                    let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
                                    let isExpStock2DisplayName = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldDisplayName'] : "ExpStock 2";

                                    let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
                                    let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
                                    let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
                                    let isExpStock3DisplayName = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldDisplayName'] : "ExpStock 3";

                                    let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
                                    let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
                                    let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
                                    let isExpStock4DisplayName = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldDisplayName'] : "ExpStock 4";

                                    let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
                                    let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
                                    let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;

                                    let isColor_MSLIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_MSL')
                                    let isColor_MSLObj = isColor_MSLIndex >= 0 ? KPIFieldsWithoutFilter[isColor_MSLIndex] : {};
                                    let isColor_MSLEnable = isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldEnable'] : false;
                                    let Color_MSL = isColor_MSLEnable && isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldDisplayName'] : ""

                                    let isColor_NONMSLIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_NONMSL')
                                    let isColor_NONMSLObj = isColor_NONMSLIndex >= 0 ? KPIFieldsWithoutFilter[isColor_NONMSLIndex] : {};
                                    let isColor_NONMSLEnable = isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldEnable'] : false;
                                    let Color_NONMSL = isColor_NONMSLEnable && isColor_NONMSLIndex >= 0 ? isColor_NONMSLObj['KPIFieldDisplayName'] : ""

                                    let isColor_CompetitionIndex = KPIFieldsWithoutFilter.findIndex(i => i.KPIFieldName == 'Color_Competition')
                                    let isColor_CompetitionObj = isColor_CompetitionIndex >= 0 ? KPIFieldsWithoutFilter[isColor_CompetitionIndex] : {};
                                    let isColor_CompetitionEnable = isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldEnable'] : false;
                                    let Color_Competition = isColor_CompetitionEnable && isColor_CompetitionIndex >= 0 ? isColor_CompetitionObj['KPIFieldDisplayName'] : ""
                                    console.log("Color_MSL----", Color_MSL, Color_NONMSL, Color_Competition)

                                    const getBackgroundStyle = (skus) => {
                                        if (skus?.MSL && skus?.MSL === 1 && skus?.IsCompetitor === 0 && Color_MSL !== "") {
                                            return { backgroundColor: Color_MSL };
                                        }
                                        if (skus?.MSL === 0 && skus?.IsCompetitor === 0 && Color_NONMSL !== "") {
                                            return { backgroundColor: Color_NONMSL };
                                        }
                                        if (skus?.IsCompetitor === 1 && Color_Competition !== "") {
                                            return { backgroundColor: Color_Competition };
                                        }

                                        return null;
                                    };

                                    return (
                                        <View style={customStyle.opening_Stock_wrap}>
                                            <View style={customStyle.opening_Stock_cat}>
                                                <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                                    <Text style={customStyle.opening_Stock_catText}>{item.CategoryName}</Text>
                                                </LinearGradient>

                                            </View>
                                            <View style={customStyle.opening_Stock_prds}>
                                                {<FlatList
                                                    data={item.skulist}
                                                    extraData={rerenderdata2}
                                                    nestedScrollEnabled={true}
                                                    removeClippedSubviews={false}
                                                    scrollToOverflowEnabled={true}
                                                    legacyImplementation={true}
                                                    renderItem={({ item, index }) => {
                                                        const skus = item;
                                                        const BrandId = item.BrandId;
                                                        const ProductId = item.ProductId;
                                                        const sku_index = index;
                                                        let calVal = 0;

                                                        let thisCatSkuData_i = SKUStockData.findIndex(i => i.CategoryId == cat.CategoryId && i.ProductId == skus.ProductId);
                                                        // console.log('thisCatSkuData_i',thisCatSkuData_i)

                                                        let thisCatSkuData = thisCatSkuData_i >= 0 ? (SKUStockData[thisCatSkuData_i] || {}) : {};
                                                        // console.log('thisCatSkuData',thisCatSkuData)
                                                        let categoryId = thisCatSkuData.CategoryId
                                                        let closing_Stock = thisCatSkuData.ClosingStock != null ? thisCatSkuData.ClosingStock : '';

                                                        let ex_stock1 = thisCatSkuData.CLOSING_ExpiryStock1 != null ? thisCatSkuData.CLOSING_ExpiryStock1 : '';
                                                        let ex_stock2 = thisCatSkuData.CLOSING_ExpiryStock2 != null ? thisCatSkuData.CLOSING_ExpiryStock2 : '';
                                                        let ex_stock3 = thisCatSkuData.CLOSING_ExpiryStock3 != null ? thisCatSkuData.CLOSING_ExpiryStock3 : '';
                                                        let ex_stock4 = thisCatSkuData.CLOSING_ExpiryStock4 != null ? thisCatSkuData.CLOSING_ExpiryStock4 : '';
                                                        // console.log('closing_Stock',closing_Stock)

                                                        if (isStockCalculateEnable) {
                                                            calVal = parseInt(ex_stock1 || 0) + parseInt(ex_stock2 || 0) + parseInt(ex_stock3 || 0) + parseInt(ex_stock4 || 0)
                                                        }

                                                        // get error field product id
                                                        let EF_product = errorfield.EF_product != null ? errorfield.EF_product : {};
                                                        let error_pid = EF_product.ProductId || '';
                                                        let EF_InputKey = errorfield.EF_InputKey;
                                                        let show_errorhere = error_bid == cat.CategoryId && error_pid == skus.ProductId;

                                                        let errorStyle_ST = (error && show_errorhere && EF_InputKey == 'input1_' ? customStyle.stk_inptSTyle_error : {});

                                                        let error_HInputKeyEx1 = (error && show_errorhere && errorfield.error_HInputKeyEx1 == 'input2_' ? customStyle.stk_inptSTyle_error : {});
                                                        let error_HInputKeyEx2 = (error && show_errorhere && errorfield.error_HInputKeyEx2 == 'input3_' ? customStyle.stk_inptSTyle_error : {});
                                                        let error_HInputKeyEx3 = (error && show_errorhere && errorfield.error_HInputKeyEx3 == 'input4_' ? customStyle.stk_inptSTyle_error : {});
                                                        let error_HInputKeyEx4 = (error && show_errorhere && errorfield.error_HInputKeyEx4 == 'input5_' ? customStyle.stk_inptSTyle_error : {});


                                                        return (
                                                            <View style={[customStyle.openStk_prd_Con, getBackgroundStyle(skus)]} key={sku_index}>
                                                                {/* <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text> */}
                                                                <Text style={customStyle.openStk_prd_name}>
                                                                    {skus.ArticleCode && skus.ArticleCode.trim() !== ""
                                                                        ? `${skus.ProductName} [${skus.ArticleCode}]`
                                                                        : skus.ARTICLE_CODE && skus.ARTICLE_CODE.trim() !== ""
                                                                            ? `${skus.ProductName} [${skus.ARTICLE_CODE}]`
                                                                            : skus.ProductName}
                                                                </Text>
                                                                <View style={[customStyle.openStk_prddetails, customStyle.openStk_prd_borderT, customStyle.openStk_prd_borderB]}>
                                                                    {IsMidDayStockScreen == true &&
                                                                        <View style={[customStyle.openStk_prdd_wrap]}>
                                                                            <Text style={customStyle.openStk_prdd_flabel}>{`Opening Stock + Midday Stock : (${skus.OPENING_STOCK} + ${skus.MIDDAY_STOCK}) :`}</Text>
                                                                            <Text style={customStyle.openStk_prdd_fvalue}>{(parseInt(skus.MIDDAY_STOCK || 0) + parseInt(skus.OPENING_STOCK || 0))}</Text>
                                                                        </View>
                                                                    }
                                                                    {IsMidDayStockScreen == false &&
                                                                        <View style={[customStyle.openStk_prdd_wrap]}>
                                                                            <Text style={customStyle.openStk_prdd_flabel}>{`Opening Stock : ${skus.OPENING_STOCK}`}</Text>
                                                                        </View>
                                                                    }
                                                                </View>
                                                                {isStockCalculateEnable == true &&
                                                                    <View style={[customStyle.openStk_prd_row, { marginBottom: 2, marginTop: 3 }]}>
                                                                        <View style={[customStyle.openStk_prd_colflex]}>
                                                                            <Text style={[customStyle.openStk_prd_label, customStyle.closeStk_prd_flexlabel]}>Closing Stock</Text>
                                                                            <TextInput
                                                                                editable={false}
                                                                                selectTextOnFocus={false}
                                                                                style={[customStyle.openStk_EXP_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2]}
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                value={(calVal == 0 ? "" : (calVal + '' || ''))}
                                                                                returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                maxLength={6}
                                                                                keyboardType='number-pad'
                                                                                blurOnSubmit={false}
                                                                            />
                                                                            <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: "1%" }]}>{"OpS+MdS"}</Text>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                {isStockCalculateEnable != true &&
                                                                    <View style={customStyle.openStk_prd_form}>
                                                                        <View style={customStyle.openStk_prd_row}>
                                                                            <View style={[customStyle.openStk_prd_colflex]}>
                                                                                <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>Closing Stock</Text>
                                                                                <TextInput
                                                                                    ref={(reff) => { inputRefs.current['input1_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                    style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, errorStyle_ST]}
                                                                                    placeholder=""
                                                                                    // onFocus={() =>validate() } 
                                                                                    onBlur={(e) => {
                                                                                        onChangeValidate(cat, cat_index, skus, sku_index)
                                                                                    }}
                                                                                    //  onSubmitEditing={validatedata(item,index)}        
                                                                                    placeholderTextColor={PageTheme.$placeholder_color}
                                                                                    returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                    blurOnSubmit={false}
                                                                                    value={(closing_Stock + '' || '')}
                                                                                    autoComplete='off'
                                                                                    maxLength={6}
                                                                                    keyboardType='number-pad'
                                                                                    onSubmitEditing={() => { focusToNext(cat, skus, '1') }}
                                                                                    onChangeText={(val) => { onStockValChange(cat, skus, val, 'ClosingStock', 'numeric') }}
                                                                                />
                                                                            </View>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                {isExpStock1Enable == true &&
                                                                    <View style={[customStyle.openStk_prd_row, { marginBottom: 3, marginTop: 4 }]}>
                                                                        <View style={[customStyle.openStk_prd_colflex]}>
                                                                            <Text style={[customStyle.openStk_prd_label, customStyle.closeStk_prd_flexlabel]}>{isExpStock1DisplayName}</Text>
                                                                            <TextInput
                                                                                ref={(reff) => { inputRefs.current['input2_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx1]}
                                                                                placeholder=""
                                                                                autoComplete='off'
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                value={(ex_stock1 + '' || '')}
                                                                                returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                maxLength={6}
                                                                                keyboardType='number-pad'
                                                                                blurOnSubmit={false}
                                                                                onChangeText={(val) => { onStockValChange(cat, skus, val, 'CLOSING_ExpiryStock1', 'numeric') }}
                                                                                onSubmitEditing={() => { focusToNext(cat, skus, '2') }}
                                                                            />
                                                                            <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: 20 }]}>{(parseInt(skus.MIDDAY_EXPIRYSTOCK1 || 0) + parseInt(skus.EXPIRYSTOCK1 || 0))}</Text>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                {isExpStock2Enable == true &&
                                                                    <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                        <View style={[customStyle.openStk_prd_colflex]}>
                                                                            <Text style={[customStyle.openStk_prd_label, customStyle.closeStk_prd_flexlabel]}>{isExpStock2DisplayName}</Text>
                                                                            <TextInput
                                                                                ref={(reff) => { inputRefs.current['input3_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx2]}
                                                                                placeholder=""
                                                                                autoComplete='off'
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                value={(ex_stock2 + '' || '')}
                                                                                returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                maxLength={6}
                                                                                keyboardType='number-pad'
                                                                                blurOnSubmit={false}
                                                                                onChangeText={(val) => { onStockValChange(cat, skus, val, 'CLOSING_ExpiryStock2', 'numeric') }}
                                                                                onSubmitEditing={() => { focusToNext(cat, skus, '3') }}
                                                                            />
                                                                            <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: 20 }]}>{(parseInt(skus.MIDDAY_EXPIRYSTOCK2 || 0) + parseInt(skus.EXPIRYSTOCK2 || 0))}</Text>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                {isExpStock3Enable == true &&
                                                                    <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                        <View style={[customStyle.openStk_prd_colflex]}>
                                                                            <Text style={[customStyle.openStk_prd_label, customStyle.closeStk_prd_flexlabel]}>{isExpStock3DisplayName}</Text>
                                                                            <TextInput
                                                                                ref={(reff) => { inputRefs.current['input4_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx3]}
                                                                                placeholder=""
                                                                                autoComplete='off'
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                value={(ex_stock3 + '' || '')}
                                                                                returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                maxLength={6}
                                                                                keyboardType='number-pad'
                                                                                blurOnSubmit={false}
                                                                                onChangeText={(val) => { onStockValChange(cat, skus, val, 'CLOSING_ExpiryStock3', 'numeric') }}
                                                                                onSubmitEditing={() => { focusToNext(cat, skus, '4') }}
                                                                            />
                                                                            <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: 20 }]}>{(parseInt(skus.MIDDAY_EXPIRYSTOCK3 || 0) + parseInt(skus.EXPIRYSTOCK3 || 0))}</Text>
                                                                        </View>
                                                                    </View>
                                                                }
                                                                {isExpStock4Enable == true &&
                                                                    <View style={[customStyle.openStk_prd_row, { marginBottom: 3 }]}>
                                                                        <View style={[customStyle.openStk_prd_colflex]}>
                                                                            <Text style={[customStyle.openStk_prd_label, customStyle.closeStk_prd_flexlabel]}>{isExpStock4DisplayName}</Text>
                                                                            <TextInput
                                                                                ref={(reff) => { inputRefs.current['input5_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, error_HInputKeyEx4]}
                                                                                placeholder=""
                                                                                autoComplete='off'
                                                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                                                value={(ex_stock4 + '' || '')}
                                                                                returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                maxLength={6}
                                                                                keyboardType='number-pad'
                                                                                blurOnSubmit={false}
                                                                                onChangeText={(val) => { onStockValChange(cat, skus, val, 'CLOSING_ExpiryStock4', 'numeric') }}
                                                                                onSubmitEditing={() => { focusToNext(cat, skus, '5') }}
                                                                            />
                                                                            <Text style={[customStyle.openStk_prdd_fvalue, { marginLeft: 20 }]}>{(parseInt(skus.MIDDAY_EXPIRYSTOCK4 || 0) + parseInt(skus.EXPIRYSTOCK4 || 0))}</Text>
                                                                        </View>
                                                                    </View>
                                                                }

                                                            </View>
                                                        )
                                                    }} />
                                                }
                                            </View>
                                        </View>
                                    );
                                }}
                            />
                        </KeyboardAvoidingView>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={'Save'} onPress={() => { submitOpeningStock() }} />
                    </View>
                </View>
            </LinearGradient>
        </Container>
    );
}



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