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 { AppState, StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, FlatList, Alert, Animated, KeyboardAvoidingView, Keyboard } from "react-native";
import { ReactReduxContext, connect, useSelector, useDispatch } from "react-redux";
import { mapStateToProps, mapDispatchToProps } from "../reducers/contextProvider";
import SQLite from "react-native-sqlite-2";
import { notify } from "../components/notify";
import moment from "moment";
import { getDownloadJson, getKPIFields, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber } from "../controller/functions";
import { get_item, set_item, clear_item } from "../components/localStorage";
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath, ImageFolderPath, HierarchyTbls } from "../constants/constants";
import CustomHeader from "../components/customHeader";
import { AntDesign, Entypo, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from "../components/icons";
import CustomLoader from "../components/CustomLoader";
import LinearGradient from "react-native-linear-gradient";
import { AppTables } from "../constants/tableConstants";

import * as RNFS from "react-native-fs";
import GradientButton from "../components/gradientButton";
import addImg from "../assets/performics/add_image.svg";
import CustomModal from "../components/CustomModal";
import { Q_getpaidvisibility } from "../constants/ConstantQueries";
import { Picker } from "@react-native-picker/picker";
import { ConfirmSaveAlert } from "../components/alert";
import ModalSelector from "react-native-modal-selector";
import { CustomPicker, CustomPicker2 } from "../components/CustomPicker";
import CustomCamera from "../components/Camera";
import ImageViewer from "react-native-image-zoom-viewer";
import DateTimePicker from "@react-native-community/datetimepicker";
import CheckBox from "@react-native-community/checkbox";

import cameraImg from "../assets/performics/camera_front_image.svg";
import MultiSelect from "react-native-multiple-select";
import CameraImg3 from "../assets/performics/camera_tick.svg";
import CameraImg2 from "../assets/performics/camera_icon.svg";
import CameraImg4 from "../assets/performics/camera_asterisk.svg";
import CameraImg5 from '../assets/image/astrickcamera.svg'

function WareHousePaidVi(props) {
  const route = useRoute();
  const ST = props.StaticText || {};

  // get all theme styles acc to current theme set
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const animatedChoice = useRef(new Animated.Value(0)).current;

  const [processing, setProcessing] = useState(true);
  const [loaderTitle, setLoaderTitle] = useState();
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [storeData, setStoreData] = useState({});
  const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
  const [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 [nonDeploymentReasonlist, setnonDeploymentReasonlist] = useState([]);

  const [DeploymentTypeHide, setDeploymentTypeHide] = useState(null);
  const [NoCameraHide, setNoCameraHide] = useState(null);

  const [Windows, setWindows] = useState([]);
  const [show_zoomImage, setShow_zoomImage] = useState(false);
  const Show_zoomImageRef = useRef(false);
  const [refImageIndex, setrefImageIndex] = useState(0);
  const [zoomImageIndex, setzoomImageIndex] = useState(0);
  const [showAlert, setShowAlert] = useState(false);
  const [zoomImageUrl, setZoomImageUrl] = useState([]);
  const [showCamera, setShowCamera] = useState(false);
  const [showQRCamera, setShowQRCamera] = 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 [searchedItem, setSearchedItem] = useState("");
  const [globalWindows, setGlobalWindows] = useState([]);
  const [KPIFields, setKPIFields] = useState([]);
  const [showSwitchCamera, setShowSwitchCamera] = useState(false);
  const [ImageAllow, setImageAllow] = useState(false);
  const [GridValue, setGridValue] = useState(false);
  const [QREnable, setQREnable] = useState(false);
  const [isOpen, setIsOpen] = useState(false);

  const [DataCleanModal, setDataCleanModal] = useState(false);
  const [DataCleanAnim, setDataCleanAnim] = useState("");
  const [DataCleanItem, setDataCleanItem] = useState({});
  const [isPresentClean, setIsPresentClean] = useState(0);

  const [InputChange, setInputChange] = useState([]);

  const [SelectedImg, setSelectedImg] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [reCapImgModalObj, setReCapImgModalObj] = useState({});
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });
  const [AppStatus, setAppStatus] = useState(AppState.currentState);
  const [QRqtnData, setQRqtnData] = useState({});
  //for Partial save
  const [FilteredPromoValues, setFilteredPromoValues] = useState([]);
  const [ShowCatWise, setShowCatWise] = useState(false);
  const [CatData, setCatData] = useState(false);
  const [ColId, setColId] = useState("");
  const [ColName, setColName] = useState("");

  const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
  const WindowDataRef = React.useRef(WindowData);
  const StoreIdRef = React.useRef(null);
  const ScreenNameRef = React.useRef({});
  const PSGroupData = React.useRef(""); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
  const BGPSAllow = React.useRef(false);



  // error field states
  const [errorfield, setErrorField] = useState({});
  const [error, setError] = useState(false);
  const [ImageLabel, setImageLabel] = useState([]);
  const [ImageMandtory,  setImageMandtory] = useState(false);
  const [ImageMandatoryNo, setImageMandatoryNo] = useState();
  const [KPIConfig, setKPIConfig] = useState({});


  const inputRefs = useRef({});

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

  const [ItemsInView, setItemsInView] = useState([]);

  const onViewableItemsChanged = ({ viewableItems }) => {
    // Do stuff
    setItemsInView(viewableItems);
  };

  // {
  //     viewabilityConfig: {
  //     //   minimumViewTime: (props.RefImagePopUpTime||0)*1000,
  //     viewAreaCoveragePercentThreshold: 50
  //     }
  const FlatLConfCallbackPairs = useRef([
    {
      viewabilityConfig: { itemVisiblePercentThreshold: 50 },
      onViewableItemsChanged,
    },
  ]);

  useEffect(() => {
    setLoaderTitle(ST.Loading + "...");
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let menu1 = params.menu || {};
    let ShowCatWise1 = params.ShowCatWise != null ? params.ShowCatWise : false;
    let CatData1 = params.CatData != null ? params.CatData : {};
    let isAdhoc = params.isAdhoc || false;
    let InnerScreenConfig=params?.menu?.InnerScreenConfig || ""

    const obj = {};
    InnerScreenConfig && InnerScreenConfig?.split(",")?.forEach((value, index) => {
      obj[value] = false;
    });


    setKPIConfig(obj)
    setIsAdhocScreen(isAdhoc);
    setShowCatWise(ShowCatWise1);
    setCatData(CatData1);
    setStoreData(storeData1);
    setCurrentMenu(menu1);

    let cameraAllow = storeData1.CameraAllow == "true" || storeData1.CameraAllow == 1 ? true : false;
    setStoreCameraAllow(cameraAllow);

    StoreIdRef.current = storeData1.StoreId;
    ScreenNameRef.current = {
      BgscreenName: menu1.ScreenName,
      BgMenuId: menu1.MenuId,
    };

    getData(storeData1, menu1, CatData1, ShowCatWise1,obj);

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

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

  const _handleAppStateChange = async (nextAppState) => {
    if (nextAppState == "background" && hasUnsavedChangesRef.current == true) {
      let newData = {
        storeBGData: WindowDataRef.current,
        menuName: ScreenNameRef.current && ScreenNameRef.current.BgscreenName,
        StoreId1: StoreIdRef.current,
        BgMenuID: ScreenNameRef.current && ScreenNameRef.current.BgMenuId,
        visiteDate: d2,
        BGPSAllow: BGPSAllow.current,
        PSGroupData: PSGroupData.current,
      };
      let WindowsStr = JSON.stringify(newData);

      await set_item("storeData", WindowsStr);
    }
  };

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

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

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

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

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

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

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

  function UpdateShow_zoomImageRef(val) {
    Show_zoomImageRef.current = val;
    setShow_zoomImage(val);
  }

  function onRemoveScreen(e) {
    Alert.alert("", ST.Doyoureallywanttoexitthescreen, [
      {
        text: ST.Cancel,
        onPress: () => { },
        style: "cancel",
      },
      {
        text: ST.OK,
        onPress: async () => {
          // setHasUnsavedChanges(false);
          BgUnsavedChanges(false);
          await clear_item("storeData");
          props.navigation.dispatch(e.data.action);
        },
      },
    ]);
  }

  function _OpenCaptureImage_Modal(img) {
    const isImageCap = img != "" || img != null ? true : false;
    let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj;
    let camera2Label = (window && window.PromoImage2Lable) || "";
    return (
      <CustomModal style={customStyle.PromoImgModal} title={currentMenu.MenuName} message={camera2Label} titleStyle={customStyle.PromoImgModal_title} messageStyle={customStyle.PromoImgModal_subtitle} showModal={showModal}>
        {isImageCap && (
          <View style={customStyle.PromoImgModalCon}>
            <View style={customStyle.PromoImgModal_ImgWrap}>
              <Image style={[customStyle.PromoImgModal_Img, Platform.OS == "ios" ? customStyle.android_flipIMageView : {}]} source={{ uri: SelectedImg }} />
            </View>
            <TouchableOpacity
              style={customStyle.PromoImgModal_CameraSmall}
              onPress={() => {
                openCamera(window, splitItem, splitItemIndex, null,cameraType);
              }}
            >
              <MaterialCommunityIcons name="camera-retake" size={30} color={PageTheme.$primary_color} />
            </TouchableOpacity>

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

  async function getData(storeData1, menu1, CatData1 = {}, ShowCatWise1 = false,objConfig={}) {
    try {
      let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

      let AllKPIFields = await getKPIFields(menu1);
      setKPIFields(AllKPIFields);

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


      let CameraAllow = AllKPIFields?.findIndex((i) => i.KPIFieldName == (objConfig?.ImageAllow==false? "PrimaryImageAllow":"ImageAllow"));
      let CameraAllowObj = CameraAllow >= 0 ? AllKPIFields[CameraAllow] : {};
      let CameraSplitNo=CameraAllowObj?.KPIFieldDisplayName || 0
      let CameraSplitArr=CameraAllowObj?.KPIType?.split(",") || []
      let CameraAllowI = CameraAllow >= 0 ? CameraAllowObj["KPIFieldEnable"] : false;
      setImageLabel(CameraSplitArr)
      setImageAllow(CameraAllowI);

      let DeploymentTypeH = AllKPIFields?.find((i) => i.KPIFieldName == "DeploymentTypeHide");

      let DeploymentTypeHArr = DeploymentTypeH?.KPIType?.split(":");
      let DeploymentTypeHMenu = DeploymentTypeHArr?.length >0? DeploymentTypeHArr[DeploymentTypeHArr?.length-1]:null;
      setDeploymentTypeHide(DeploymentTypeHMenu||null);

      let NoCameraHideH = AllKPIFields?.find((i) => i.KPIFieldName == "NoCameraHide");
      let NoCameraHideHArr = NoCameraHideH?.KPIType?.split(":");
      let NoCameraHideHMenu = NoCameraHideHArr?.length >0? NoCameraHideHArr[NoCameraHideHArr?.length-1]:null;
      setNoCameraHide(NoCameraHideHMenu||null);

      let DeploymentType = AllKPIFields?.find((i) => i.KPIFieldName == "DeploymentType");
      let DeploymentTypeArr = DeploymentType?.KPIType?.split(",");
      let DeploymentTypeArrObj=DeploymentTypeArr.map(item =>{return({"KPIType":item})})
      setReasons_list(DeploymentTypeArrObj||[]);


      let ImageMandatory = AllKPIFields?.find((i) => i.KPIFieldName == (objConfig?.ImageMandatory==false? "PrimaryImageMandatory" :"ImageMandatory"));
      let ImageMandatoryFlage = ImageMandatory?.KPIFieldEnable || false
      let ImageMandatoryNo = ImageMandatoryFlage ? ImageMandatory?.KPIFieldDisplayName : 0
      setImageMandtory(ImageMandatoryFlage);
      setImageMandatoryNo(ImageMandatoryNo)

      // let DeploymentTypeArr = DeploymentType?.KPIFieldEnable ||
      // let DeploymentTypeArrObj=DeploymentTypeArr.map(item =>{return({"KPIType":item})})
      // setReasons_list(DeploymentTypeArrObj||[]);

      let isSpecificMapIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='SpecificMapping')
      let isSpecificMapKPIObj=isSpecificMapIndex>=0?AllKPIFields[isSpecificMapIndex]:{};
      let isSpecificMappingEnable=isSpecificMapIndex>=0?isSpecificMapKPIObj['KPIFieldEnable']:false;


      let { PSAllow, PSTableName } = menu1;
      PSTableName = PSTableName != null ? PSTableName : "";
      PSAllow = PSAllow != null ? PSAllow : false;

      let idCol = "",
        nameCol = "";

      if (PSTableName.toLowerCase() == HierarchyTbls.Master_Category.toLowerCase()) {
        (idCol = "CategoryId"), (nameCol = "CategoryName");
      } else if (PSTableName.toLowerCase() == HierarchyTbls.Master_Brand.toLowerCase()) {
        (idCol = "BrandId"), (nameCol = "BrandName");
      } else {
        (idCol = "SubCategoryId"), (nameCol = "SubCategoryName");
      }
      let IdVal = CatData1[idCol];
      let NameVal = CatData1[nameCol];

      let FilteredIds=[];
      if(ShowCatWise1){
          FilteredIds=await getWindowFilterIds(idCol,IdVal,storeData1,false,menu1);
      }
      setFilteredPromoValues(FilteredIds);


      let inputChangeFlag = [],
        storeBGData1 = [],
        bgStoreJson = {},
        isBgDataExists = false;

      //storeBGData check
      let windData = await get_item("storeData");
      if (windData != null && windData != "") {
        let StoreJson = JSON.parse(windData);
        let { storeBGData, menuName, StoreId1, BgMenuID, visiteDate } = StoreJson;
        if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && menu1.MenuId == BgMenuID && visiteDate == d2) {
          isBgDataExists = true;
          storeBGData1 = storeBGData;
          bgStoreJson = StoreJson;
          WindowDataRef.current = storeBGData;
          setWindowData(storeBGData);
          BgUnsavedChanges(true);
        }
      }

      //  call this after storeBGData check
      if (PSAllow) {
        // if Partial save is allowed then add the currently active category or group in BG var
        BGPSAllow.current = true;
        PSGroupData.current = CatData1;
      }

      await db.transaction(async function (txn) {      
        let q3=`Select ReasonId,Reason,IsRemarkTaken From Master_WarehouseNonDeployReason WHERE MenuId='${menu1.MenuId}' `;
        console.log("reasoncheck---",q3)
        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){                     
                      setnonDeploymentReasonlist(arr);
                    }                                
                }
            }
        },function (txnE,txnerr) { console.log(txnerr); },);

        let selectlist2 = `Distinct wd.WAREHS_HEADER_ID as WHRESHeaderId,w.MeasureUnit,w.ItemId,w.ItemName,w.ItemCode,w.ItemCategoryId,w.ItemCategory,IFNULL(wd.IS_PRESENT,'') as IsPresent,IFNULL(wd.PVIS_NA_IMAGE,'') as PVisNAImage,IFNULL(wd.KPITYPE_ID,'') as KpiTypId,IFNULL(wd.KPITYPE,'') as KPIType,IFNULL(wd.REASON_ID,'') as ReasonId,IFNULL(wd.REASON,'') as Reason, IFNULL(wd.ITEM_QTY,'') as PosQty,${DeploymentTypeHMenu==menu1.MenuId?"wh.MappingType,":"wh.CampaignId,"} rh.StockInHand,rh.TodayDeploy - wd.TODAY_DEPLOY as TodayDeploy `;
        let join3 = ` Left Outer Join ${AppTables.WAREHOUSE_HDR_DATA} wd on w.ItemId=wd.ITEM_ID and wd.STORE_ID='${StoreId}' and wd.VISIT_DATE='${d2}'`;
        let join2 = `INNER JOIN ${ DeploymentTypeHMenu==menu1.MenuId ?"Mapping_WarehousePrimaryItem":"Mapping_WarehouseCampaignDeployment"} wh ON wh.ItemId=w.ItemId and wh.StoreId='${StoreId}' and wh.MenuId='${menu1.MenuId}' `;
        let join4 = `Left Outer Join Report_WarehouseStockInHand rh ON rh.ItemId=w.ItemId `;
        
        let q2 = `SELECT  ${selectlist2} FROM Master_WarehouseItem w ${join3} ${join2} ${join4}  WHERE wh.MenuId='${menu1.MenuId}' `;
        // let join2 = `INNER JOIN Mapping_WarehouseItem wh ON wh.ItemId = w.ItemId `;
        // let join4 = ` Left Outer Join Mapping_WarehouseCampaignDeployment wm on w.ItemId=wm.ItemId and wm.StoreId='${StoreId}' and wh.CampaignId=wm.CampaignId`;
        // let q2 = `SELECT  ${selectlist2} FROM Master_WarehouseItem w ${join3} ${join2}  WHERE wh.MenuId='${menu1.MenuId}' `;


        await txn.executeSql(
          q2,
          [],
          async function (txn2, txnres2) {
            console.log("Warehouse Visi added count", txnres2.rows.length);
            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 isPresent = (data.IsPresent == "1" || data.IsPresent == 1 || data.WhDisable== "true" ||data.WhDisable==1)? 1 : 0;
                let WhDisable = ( data.WhDisable== "true" ||data.WhDisable==1)  ? 1 : 0;

                if (isBgDataExists) {
                  let storeBgIndex = storeBGData1.findIndex((i) => i.ItemId == data.ItemId );
                  // && i.QuestionCategoryId == data.ItemCategoryId
                  let storeBgObj = storeBgIndex >= 0 ? storeBGData1[storeBgIndex] : {};
                  isPresent = storeBgObj.isPresent == "1" || storeBgObj.isPresent == 1 ? 1 : 0;
                }

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

                
                // data.NoOfSplit = parseInt(data.NoOfSplit);
                data.NoOfSplit = parseInt(CameraSplitNo);
                let NoOfSplit = Number(CameraSplitNo);

                let isStockReq = data.VisibilityElementStockRequired == "true" || data.VisibilityElementStockRequired == 1 ? 1 : 0;

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

                
                let WindowSplits = CameraAllowI ? await getWindowSplits(CameraSplitArr, data, storeData1, menu1,ImageMandatoryNo) :[];

                let WQr = await getWindowQuestions(data, storeData1, menu1);
                let WindowQuestions = WQr["WindowQuestions"] || [];
                console.log("WindowQuestions----",WindowQuestions)
                let WindowQA = WQr["WindowQA"] || {};
                let WSd = { WStocks: [], WStocksData: [] };
                let WStocks = WSd["WStocks"] || [];
                let WStocksData = WSd["WStocksData"] || [];
                let isAllChecked = WSd["isAllChecked"] != null ? WSd["isAllChecked"] : 0;

                let isNAImageAvl = data.VisibilityNotExistCamera == "true" || data.VisibilityNotExistCamera == 1 ? 1 : 0;
                let NAImage1 =  data.PVisNAImage != null ? data.PVisNAImage : "";
                let NAImage1Path = NAImage1 != "" ? "file://" + ImageFolderPath + menu1.ScreenName + "/" + NAImage1 : "";
                let showRsnRemark = data.SHOW_RSN_REMARK == "1" || data.SHOW_RSN_REMARK == 1 ? true : false;
                let windowDataObj = {
                  ItemId: data.ItemId,
                  ItemQuestionId: data.ItemQuestionId,
                  WindowSplits: WindowSplits,
                  WindowQA: WindowQA,
                  WStocksData: WStocksData,
                  NAImage1: NAImage1,
                  NAImage1Path: NAImage1Path,
                  KpiTypId: data.Id,
                  KPIType: data.KPIType,
                  ReasonId: data.ReasonId,
                  Reason: data.Reason,
                  PosQty: data.PosQty || "",
                  isPresent: isPresent,
                  WhDisable:WhDisable,
                  StockInHand:data?.StockInHand||0,
                  TodayDeploy:data?.TodayDeploy||0,
                  isAllSKUChecked: isAllChecked,
                  remark: data.Remark != null ? data.Remark : "",
                  showOtherText: showRsnRemark
                };
                data["WindowQuestions"] = WindowQuestions;
                data["WindowStocks"] = WStocks;
                let changesFlag = {
                  ItemId: data.ItemId,
                  ItemQuestionId: data.QuestionCategoryId,
                  Flag: data.WHRESHeaderId != null ? true : false,
                };
                inputChangeFlag.push(changesFlag);
                arr.push(data);

                allWindowsData.push(windowDataObj);

                if (i == txnres2.rows.length - 1) {
                  if (!isBgDataExists) {
                    BgWindowData(allWindowsData);
                  }
                  setInputChange(inputChangeFlag);
                  setWindows(arr);
                  setGlobalWindows(arr);
                  setZoomImageUrl(images);
                  setProcessing(false);
                }
              }
            } else {
              setProcessing(false);
              notify("No data found!");
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
            setProcessing(false);
          }
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  async function getWindowFilterIds(idCol, IdVal, storeData1, isSpecificMappingEnable, menu1 = {}) {
    let AllIds = [];
    let { StoreId } = storeData1;
    let { MenuId } = menu1;

    let tbname2 = isSpecificMappingEnable ? "Mapping_StoreVisibilitySpecific" : "Mapping_StoreVisibility";

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join = ` inner join ${tbname2} s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  `;
        let q = `Select w.* from Master_VisibilityDefinition w ${join} where s.StoreId='${StoreId}' and w.MenuId='${MenuId}' `;
        await txn.executeSql(
          q,
          [],
          async function (txn2, txnres) {
            if (txnres.rows.length > 0) {
              let Wind_data = txnres.rows.item(0);
              let { VisibilityTable } = Wind_data;
              VisibilityTable = VisibilityTable != null ? VisibilityTable : "";

              let filterIdsCol = "",
                filterNamesCol = "";
              if (VisibilityTable.toLowerCase() == HierarchyTbls.Master_Category.toLowerCase()) {
                (filterIdsCol = "CategoryId"), (filterNamesCol = "CategoryName");
              } else if (VisibilityTable.toLowerCase() == HierarchyTbls.Master_Brand.toLowerCase()) {
                (filterIdsCol = "BrandId"), (filterNamesCol = "BrandName");
              } else if (VisibilityTable.toLowerCase() == HierarchyTbls.Master_Product.toLowerCase()) {
                (filterIdsCol = "ProductId"), (filterNamesCol = "ProductName");
              } else {
                (filterIdsCol = "SubCategoryId"), (filterNamesCol = "SubCategoryName");
              }

              let FIdsQ = `Select distinct p.${filterIdsCol},p.${filterNamesCol} from Product_Master p where (p.${idCol}='${IdVal}' or p.${idCol}= ${IdVal}) `;

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

  async function getWindowSplits(NoOfSplit, window, storeData1, menu1,ImageMandatoryNo) {
    let WindowSplits_def = [];
    for (var s=0; s <NoOfSplit.length; s++) {
      let obj = {
        ImageName: "",
        Image: "",
        ImageLable: NoOfSplit[s],
        imgRequired: s < ImageMandatoryNo
      };

      // obj[`Image${s}Name`]=""
      // obj[`Image${s}`]=""
      WindowSplits_def.push(obj);
    }
    // console.log("window----",window)
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `select * from ${AppTables.WAREHOUSE_IMAGES} where WAREHS_HEADER_ID='${window.WHRESHeaderId}' 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);
                let isImage1 = window.VisibilityImage1 == "true" || window.VisibilityImage1 == 1 ? 1 : 0;
                let isImage2 = window.VisibilityImage2 == "true" || window.VisibilityImage2 == 1 ? 1 : 0;

                let Image1 =  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,
                //   img1Required: true,
                //   img2Required: true,
                // };
                let obj = {
                  ImageName: data.IMAGE1,
                  Image: Image1,
                  ImageLable: "",
                  ImageLable: NoOfSplit[i],
                  // imgRequired: s < ImageMandatoryNo
                  imgRequired: false
                };
                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, menu1) {
    // console.log("windowww", window)
    let obj = { WindowQA: {}, WindowQuestions: [] };
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        var q = "",
          selectlist = "",
          join = "",
          join2 = "";

        //get data from masters with saved data if any
        // selectlist=` DISTINCT  q.QUESTION_ID as ItemQuestionId,q.QUESTION_CODE as VisibilityQuestionCode,wq.VisibilityQuestionName,wq.QuestionType,wq.ItemShowCamera,wq.VQCameraMandatory,wq.VQLengthValidationRequired,wq.VQMinimumChar,wq.VQMaximumChar,wq.VQDecimalPoint,wq.VQDateRangeMin,wq.VQDateRangeMax,wq.VQVoiceLengthInMinutes,wq.VQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as VAShowCamera,q.IMAGE1 as Image1  `;
        // selectlist = ` DISTINCT  wq.ItemQuestionId,wq.ItemQuestionCode,wq.ItemQuestionName,wq.QuestionType,wq.ItemShowCamera,wq.ItemCameraMandatory,wq.ItemLengthValidationRequired,wq.ItemMinimumChar,wq.ItemMaximumChar,wq.ItemDecimalPoint,wq.ItemDateRangeMin,wq.ItemDateRangeMax,wq.ItemVoiceLengthInMinutes,wq.ItemDefaultQuestionEnable,(CASE WHEN q.QUESTION_ID is not null THEN 1 ELSE 0 END) isInserted,q.IS_DISABLED,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as VAShowCamera,q.IMAGE1 as Image1  `;

        // selectlist = ` DISTINCT  wq.ItemQuestionId,wq.ItemQuestionCode,wq.ItemQuestionName,wq.QuestionType,wq.ItemShowCamera,wq.ItemCameraMandatory,wq.ItemLengthValidationRequired,wq.ItemMinimumChar,wq.ItemMaximumChar,wq.ItemDecimalPoint,wq.ItemDateRangeMin,wq.ItemDateRangeMax,wq.ItemVoiceLengthInMinutes,wq.ItemDefaultQuestionEnable `;
        // // join2=` Left Outer Join ${AppTables.PAIDVIS_CHILD_DATA} q on wq.ItemQuestionId=q.QUESTION_ID and q.STORE_ID='${storeData1.StoreId}' and q.PVIS_DEFINITION_ID='${window.VisibilityDefinitionId}' and q.PVIS_ID='${window.VisibilityId}' and q.VISIT_DATE='${d2}'`;
        // join = ` inner join Mapping_WarehouseItemQuestion mq on mq.ItemQuestionId = wq.ItemQuestionId `;
        // q = `select ${selectlist} from Master_WarehouseItemQuestion wq  ${join} where wq.QuestionCategoryId='${window.ItemCategoryId}'`;
        // console.log("nnn", q)
        // q=`select ${selectlist} from Master_WarehouseItemQuestion wq  ${join} where mq.VisibilityDefinitionId='${window.VisibilityDefinitionId}' order by wq.VisibilityQuestionSequence`;

        selectlist = ` DISTINCT  wq.ItemQuestionId,wq.ItemQuestionCode,wq.ItemQuestionName,wq.QuestionType,wq.ItemAnswerShowCamera,wq.ItemAnswerCameraMandatory,wq.ItemLengthValidationRequired,wq.ItemMinimumChar,wq.ItemMaximumChar,wq.ItemDecimalPoint,wq.ItemDateRangeMin,wq.ItemDateRangeMax,wq.ItemVoiceLengthInMinutes,wq.ItemDefaultQuestionEnable,(CASE WHEN q.QUESTION_ID is not null THEN 1 ELSE 0 END) isInserted,q.IS_DISABLED,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as ItemAnswerShowCamera,q.IMAGE1 as Image1  `;
        join2 = ` Left Outer Join ${AppTables.WAREHOUSE_CHILD_DATA} q on wq.ItemQuestionId=q.QUESTION_ID and q.STORE_ID='${storeData1.StoreId}' and q.ITEM_ID='${window.ItemId}' and q.VISIT_DATE='${d2}'`;
        join = ` inner join Mapping_WarehouseItemQuestion mq on mq.ItemQuestionId=wq.ItemQuestionId and mq.StoreTypeId='${storeData1.StoreTypeId}' and mq.ItemId='${window.ItemId}' `;
        q = `select ${selectlist} from Master_WarehouseItemQuestion wq  ${join} ${join2} where wq.ItemQuestionId=mq.ItemQuestionId  `;

        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 { isInserted } = data;
                let answers = [];
                data.ItemDefaultQuestionEnable = data.ItemDefaultQuestionEnable == 1 || data.ItemDefaultQuestionEnable == "true" ? true : false;
                // data['isDisabled']=!data.ItemDefaultQuestionEnable;
                if (isInserted) {
                  data["isDisabled"] = data.IS_DISABLED == true || data.IS_DISABLED == "true" ? true : false;
                } else {
                  data["isDisabled"] = !data.ItemDefaultQuestionEnable;
                }
                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.ItemQuestionId + "_AnswerId";
                let ans_key = data.ItemQuestionId + "_Answer";
                let multi_key = data.ItemQuestionId + "_MultiOption";
                let date_key = data.ItemQuestionId + "_Date";
                let img_key = data.ItemQuestionId + "_ImagePath1";
                let imgname_key = data.ItemQuestionId + "_ImageName1";
                let rating_key = data.ItemQuestionId + "_Rating";

                let showImageTag = data.ItemShowCamera == "true" || data.ItemShowCamera == 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 != "" || selansid === 0) && 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.ItemAnswerShowCamera == 1 || ansss.ItemAnswerShowCamera == "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  ItemAnswerId as AnswerId,ItemAnswerName as Answer,ItemAnswerShowCamera,ItemAnswerCameraMandatory,ItemQuestionEnable,ItemQuestionDisable `;
        q = `select ${selectlist} from  Master_WarehouseItemQuestion  where ItemQuestionId='${qtn.ItemQuestionId}'  order by ItemAnswerSequence  `;

        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, AllKPIFields = []) {
    let obj = { WStocks: [], WStocksData: [], isAllChecked: 0 };
    let { StateId, ChainId, StoreTypeId, StoreId } = storeData1;

    let isSpecificMapIndex = AllKPIFields?.findIndex((i) => i.KPIFieldName == "SpecificMapping");
    let isSpecificMapKPIObj = isSpecificMapIndex >= 0 ? AllKPIFields[isSpecificMapIndex] : {};
    let isSpecificMappingEnable = isSpecificMapIndex >= 0 ? isSpecificMapKPIObj["KPIFieldEnable"] : false;

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let checkassrt = window.VisibilityElementCheckAssortment == "true" || window.VisibilityElementCheckAssortment == 1 ? true : false;
        let join = "",
          join2 = "",
          selectlist2 = "",
          q2 = "";

        //get data from masters with saved data if any
        if (checkassrt) {
          join2 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.VisibilityStockValue and a.StoreId='${StoreId}' `;
        }
        let join3 = "";
        if (isSpecificMappingEnable == true) {
          join3 = ` Left Outer Join ${AppTables.PAIDVIS_STOCK_DATA} ps on s.VisibilityValue=ps.PVIS_STOCK_VALUE and ps.PVIS_DEFINITION_ID='${window.VisibilityDefinitionId}' and ps.STORE_ID='${storeData1.StoreId}' `;
          selectlist2 = ` '0' as VisibilityStockDefinitionId, s.VisibilityDefinitionId,s.VisibilityTable as VisibilityStockTable,s.VisibilityField as VisibilityStockField,s.VisibilityValue as VisibilityStockValue,'' as VisibilityStockMBQ,s.ChildName as ProductName, ps.STOCK as Stock,IFNULL(ps.IS_PVIS_PRESENT,'') as isPVisPresent `;
          q2 = `select ${selectlist2} from  Mapping_StoreVisibilitySpecific s ${join2} ${join3} where s.VisibilityDefinitionId='${window.VisibilityDefinitionId}'  and s.StoreId='${StoreId}'   order by s.ChildName `;
        } else {
          join3 = ` Left Outer Join ${AppTables.PAIDVIS_STOCK_DATA} ps on s.VisibilityStockDefinitionId=ps.PVIS_STOCK_DEFINITION_ID and s.VisibilityStockValue=ps.PVIS_STOCK_VALUE and ps.PVIS_DEFINITION_ID='${window.VisibilityDefinitionId}' and ps.STORE_ID='${storeData1.StoreId}' `;
          selectlist2 = `  s.VisibilityStockDefinitionId, s.VisibilityDefinitionId,s.VisibilityStockTable,s.VisibilityStockField,s.VisibilityStockValue,s.VisibilityStockMBQ,s.ProductName, ps.STOCK as Stock,IFNULL(ps.IS_PVIS_PRESENT,'') as isPVisPresent `;
          q2 = `select ${selectlist2} from  Master_VisibilityStockDefinition s ${join2} ${join3} where s.VisibilityDefinitionId='${window.VisibilityDefinitionId}'   order by s.ProductName   `;
        }

        // console.log("isSpecificMappingEnable---",isSpecificMappingEnable,q2)
        await txn.executeSql(
          q2,
          [],
          async function (txn2, txnres2) {
            console.log("Stock qty added:", txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              let arr = [],
                WStocksData = [];
              let isAllChecked = 1;
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                // use index for refId instead of VisibilityStockDefinitionId as the condition does not work in case of isSpecificMappingEnable is true ( because all VisibilityStockDefinitionId are 0)
                let refId = "input1_" + data.VisibilityDefinitionId + "_" + i;

                inputRefs.current[refId] = "";
                if (data.Stock != null) {
                  let stockData_obj = {
                    ProductId: data.VisibilityStockValue,
                    Stock: data.Stock,
                    isPVisPresent: data.isPVisPresent != null ? data.isPVisPresent : 0,
                  };
                  WStocksData.push(stockData_obj);
                }
                if (data.isPVisPresent == null || data.isPVisPresent == 0 || data.isPVisPresent == "0" || data.isPVisPresent == "") {
                  isAllChecked = 0;
                }
                arr.push(data);
                if (i == txnres2.rows.length - 1) {
                  obj["WStocks"] = arr;
                  obj["WStocksData"] = WStocksData;
                  obj["isAllChecked"] = isAllChecked;
                  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 focusToNext(WindowStocks, windowIndex, stockProd, index) {
    console.log("focusToNext is call");
    console.log("WindowStocks", index + 1);

    if (index == WindowStocks.length - 1) {
      return;
    }

    try {
      // inputRefs.current['input1_'+data.VisibilityDefinitionId+"_"+data.VisibilityStockDefinitionId]='';
      // use (index+1) instead of WindowStocks[index+1].VisibilityStockDefinitionId as the condition does not work in case of isSpecificMappingEnable is true ( because all VisibilityStockDefinitionId are 0)
      console.log("next 1 call", "input1_" + WindowStocks[index + 1].VisibilityDefinitionId + "_" + (index + 1));
      let refIn2 = inputRefs.current["input1_" + WindowStocks[index + 1].VisibilityDefinitionId + "_" + (index + 1)];
      // let refIn2=inputRefs.current['input1_'+stockProd.WindowDefinitionId+'_'+stockProd.WindowStockDefinitionId];

      if (refIn2 != null) {
        refIn2.focus();
      }
    } catch (err) {
      console.log(err);
    }
  }

  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(ST.Cameraunavailable);
    }
    else if (typeof imgdata == 'object' && imgdata.uri != null) {
      const img = imgdata;
      const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
      let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
      let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();

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

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

      let filename = storeData.StoreId + '_' + window.ItemName + '_' + window.ItemId + '_' + (props.UserId || '') + '_STImg-' +calculate_tym_date_for_filename+ '.jpg';

      let allData = WindowData;
      let defData = { 'ItemId': window.ItemId, 'QuestionCategoryId': window.ItemQuestionId };
      const wind_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
      let wind = wind_index >= 0 ? allData[wind_index] : defData;


      let camera1Label = window.VisibilityImage1Lable || '';
      let camera2Label = window.VisibilityImage2Lable || '';
      let extraLabel = '';
      if (cameraType == '2') {
        var QD = wind.WindowQA || {};
        var image_key = qtn.ItemQuestionId + '_ImageName1';
        var image_key_path = qtn.ItemQuestionId + '_ImagePath1';
        QD[image_key] = filename;
        extraLabel = 'Qtn Id: ' + qtn.ItemQuestionId;
      }
      else if (cameraType == '3') {
        var image_key = 'NAImage1';
        var image_key_path = 'NAImage1Path';
        wind[image_key] = filename;
        extraLabel = 'Not Exist';
      } else if (cameraType == '4') {
        var WindowSplits = wind.WindowSplits || [];
        var image_key =  'ImageName' 
        var image_key_path = 'Image' 
        splitItem[image_key] = filename;
        extraLabel = splitItem?.ImageLable;
      }
      else {
        var WindowSplits = wind.WindowSplits || [];
        var image_key = type == '1' ? 'Image1Name' : 'Image2Name';
        var image_key_path = type == '1' ? 'Image1' : 'Image2';
        splitItem[image_key] = filename;
        extraLabel = type == '1' ? camera1Label : camera2Label;
      }

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | ItemId :' + window.ItemId + (extraLabel != '' ? ' (' + extraLabel + ')' : '') + ' | Image Type: ' + currentMenu.MenuName + ' | Date:' +calculate_tym_date_over_img;

      let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          console.log('image marker:', imgWidth, imgHeight, uri);

          if (cameraType == '2') {
            QD[image_key_path] = uri;
            wind.WindowQA = QD;
            wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
            WindowDataRef.current = allData
            setWindowData(allData);
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata3(!rerenderdata3);
          }
          else if (cameraType == '3') {
            wind[image_key_path] = uri;
            wind_index >= 0 ? allData[wind_index] = wind : allData.push(wind);
            WindowDataRef.current = allData
            setWindowData(allData);
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
          }
          else {
            console.log('split image updated',splitItemIndex >= 0);
            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);
            WindowDataRef.current = allData
            setWindowData(allData);
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata2(!rerenderdata2);
          }

          let objIndex = InputChange.findIndex(i => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
          let winArr = [...InputChange]
          winArr[objIndex].Flag = true
          setSelectedImg(uri)
          setInputChange(winArr)

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

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

  }

  async function onQRScanned(imgdata) {
    let qtn = QRqtnData.qtn || {};
    let window = QRqtnData.window || {};
    let QR_withValidChars = imgdata != null && imgdata != "" ? imgdata.replace(/["']/g, "") : "";
    let value = QR_withValidChars; //imgdata && imgdata[0] && imgdata[0].displayValue ? imgdata[0].displayValue :""
    setTextValue(value, qtn, window);
  }

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

    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.ItemId == window.ItemId && i.ItemQuestionId == window.QuestionCategoryId) || {};
      allWindows[winIndex] = window;
      setWindows(allWindows);
      setGlobalWindows(allwindows);
      if (show == true) setrerenderdata(!rerenderdata);
    }
  }

  async function openCamera(window, splitItem, splitItemIndex, type = "1", cameraType = "1", qtn = {}) {
    setErrorField({});
    setError(false);
    let GridAllow = false;
    if (type == "1") {
      // console.log("texxxt2..",window)
      GridAllow = cameraType == "1" ? (type === "1" ? window.VisibilityImage1CameraGrid === "true" || window.VisibilityImage1CameraGrid == true : window.VisibilityImage1CameraGrid === "true" || window.VisibilityImage1CameraGrid == true) : false;
    } else {
      GridAllow = cameraType == "1" ? (type === "2" ? window.VisibilityImage2CameraGrid === "true" || window.VisibilityImage2CameraGrid == true : window.VisibilityImage2CameraGrid === "true" || window.VisibilityImage2CameraGrid == true) : false;
    }
    setGridValue(GridAllow);
    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(currentMenu);

    if (isvalid) {
      Keyboard.dismiss();
      setShowAlert(true);
    }
  }

  async function saveData() {
    // setHasUnsavedChanges(false);
    BgUnsavedChanges(false);
    setShowAlert(false);
    setLoaderTitle(ST.SavingData + "...");
    setProcessing(true);
    let d1n = new Date();
    let d3 = moment(d1n).format("MM/DD/YYYY");
    try {
      let { StoreId,MenuId, ChainId, StateId, StoreTypeId } = storeData;

      //  remove old data
      let isDeleted = await removePreviousData();
      console.log("isDeleted:", isDeleted);

      await db.transaction(async function (txn) {
        // add data
        var values = "",
          childV = "",
          imageV = "";
        let updateQueries = [];

        for (const wi in globalWindows) {
          const window = globalWindows[wi];
          let isImage1 = window.VisibilityImage1 == "true" || window.VisibilityImage1 == 1 ? 1 : 0;
          let isImage2 = window.VisibilityImage2 == "true" || window.VisibilityImage2 == 1 ? 1 : 0;
          let isNAImageAvl = window.VisibilityNotExistCamera == "true" || window.VisibilityNotExistCamera == 1 ? 1 : 0;
          let isNAReasonEnable = window.VisibilityNotExistReasonEnable == "true" || window.VisibilityNotExistReasonEnable == 1 ? 1 : 0;
          let isReasonEnable = window.VisibilityExistReasonEnable == "true" || window.VisibilityExistReasonEnable == 1 ? 1 : 0;
          let isStockReq = window.VisibilityElementStockRequired == "true" || window.VisibilityElementStockRequired == 1 ? 1 : 0;
          let WindowQuestions = window.WindowQuestions || [];
          let WindowStocks = window.WindowStocks || [];
          let CampaignId = window.CampaignId

          const wind = WindowData.find(
            (i) => i.ItemId == window.ItemId
              &&
              i.QuestionCategoryId == window.ItemQuestionId,
          );
          let isPresent = wind.isPresent != null && wind.isPresent != "" ? wind.isPresent : "0";
          let WhDisable = wind.WhDisable != null && wind.WhDisable != "" ? wind.WhDisable : "0";
          let KpiTypId = wind.Id != null ? wind.Id : 0;
          let KPIType = wind.KPIType != null ? wind.KPIType : "";
          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 remark = wind.remark != null ? wind.remark : "";
          let WindowSplits = wind.WindowSplits || [];
          let QD = wind.WindowQA || {};
          let WStocksData = wind.WStocksData || [];

          let WAREHS_HEADER_ID = "WIND" + wi + (Math.floor(Math.random() * 1000) + 1);
          let { ItemId, ItemCode, ItemName, ItemCategoryId, ItemCategory,MappingType } = window;
          let showOtherText = wind.showOtherText == true || wind.showOtherText == "1" ? 1 : 0;
          let PosQty = wind.PosQty != null ? wind.PosQty : "";
          let TodayDeploy = wind.TodayDeploy != null && wind.TodayDeploy != "" ? wind.TodayDeploy : 0;

          console.log("CampaignId in savedata:", window);

          if(WhDisable!=1){
          values += values != "" ? " , " : "";
          values += `('${WAREHS_HEADER_ID}','${StoreId}','${d3}','${ItemId}','${ItemName}','${MappingType}','${ItemCode}','${ItemCategoryId}','${ItemCategory}','${PosQty||0}','${isPresent}','${KpiTypId}','${KPIType}','${ReasonId||0}','${Reason}','${currentMenu.MenuId}','${CampaignId}','${NAImage1}','${TodayDeploy}')`;

          if ( KPIConfig?.HidePresentYesNo==false ? true : isPresent == 1) {
            // updateQueries.push(`UPDATE Report_WarehouseStockInHand SET TodayDeploy='${PosQty || 0}' WHERE ItemId='${ItemId}'`);

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

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

              let { ItemQuestionId, ItemQuestionCode, QuestionType, ItemAnswerShowCamera } = qtn;
              let answer = QD[ans_key] || 0;
              let answerId = QD[id_key] === 0 ? 0 : QD[id_key] || "";
              let multi_options_ids = QD[multi_key] || "";

              if (qtn.QuestionType == "Number" || qtn.QuestionType == "Text" || qtn.QuestionType == "Decimal" || qtn.QuestionType == "Date") {
                showImageTag = qtn.ItemAnswerShowCamera == 1 || qtn.ItemAnswerShowCamera == "true";
              } else if (qtn.QuestionType == "Single choice list" || qtn.QuestionType == "Multi choice list") {
                if (qtn.Answers && qtn.Answers.length > 0) {
                  for (var i = 0; i < qtn.Answers.length; i++) {
                    let ansss = qtn.Answers[i];
                    let isandImgAl = ansss.ItemAnswerShowCamera == "true" || ansss.ItemAnswerShowCamera == 1;
                    if (qtn.QuestionType == "Single choice list" && isandImgAl && ansss.AnswerId == answerId) {
                      showImageTag = true;
                    } else if (qtn.QuestionType == "Multi choice list" && isandImgAl && answerId.indexOf(ansss.AnswerId) >= 0) {
                      showImageTag = true;
                    }
                  }
                }
              }

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

              childV += childV != "" ? " , " : "";
              childV += ` ('${WAREHS_HEADER_ID}','${StoreId}','${d3}','${ItemId}','${ItemQuestionId}','${ItemQuestionCode}','${QuestionType}','${answer}','${answerId}','${multi_options_ids}','${Image1}','${showImageTag}','${d3}','${isDisabled}') `;
            }
            for (const splitItemIndex in WindowSplits) {
              const splitItem = WindowSplits[splitItemIndex];
              let ImageName = splitItem["ImageName"] != null && splitItem["ImageName"] != "" ? splitItem["ImageName"] : "";
              let ImageLabel = splitItem["ImageLable"] != null && splitItem["ImageLable"] != "" ? splitItem["ImageLable"] : "";
              let Image2Name = splitItem["Image2Name"] != null && splitItem["Image2Name"] != "" ? splitItem["Image2Name"] : "";
            
              Image2Name = isImage2 == 1 ? Image2Name : "";

              imageV += imageV != "" ? " , " : "";
              imageV += ` ('${WAREHS_HEADER_ID}','${StoreId}','${d3}','${ItemId}','${ImageName}','${Image2Name}','${ImageLabel}','${d3}') `;
            }
           
          }else if(NoCameraHide==currentMenu?.MenuId){
            for (const splitItemIndex in WindowSplits) {
              const splitItem = WindowSplits[splitItemIndex];
              let ImageName = splitItem["ImageName"] != null && splitItem["ImageName"] != "" ? splitItem["ImageName"] : "";
              let ImageLabel = splitItem["ImageLable"] != null && splitItem["ImageLable"] != "" ? splitItem["ImageLable"] : "";
              let Image2Name = splitItem["Image2Name"] != null && splitItem["Image2Name"] != "" ? splitItem["Image2Name"] : "";
            
              Image2Name = isImage2 == 1 ? Image2Name : "";

              imageV += imageV != "" ? " , " : "";
              imageV += ` ('${WAREHS_HEADER_ID}','${StoreId}','${d3}','${ItemId}','${ImageName}','${Image2Name}','${ImageLabel}','${d3}') `;
            }
          }
        }
      }

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

        let add_hdr_data = `INSERT INTO ${AppTables.WAREHOUSE_HDR_DATA} (WAREHS_HEADER_ID,STORE_ID,VISIT_DATE,ITEM_ID,ITEM_NAME,MAPPING_TYPE,ITEM_CODE,ITEM_CATEGORY_ID,ITEM_CATEGORY,ITEM_QTY,IS_PRESENT,KPITYPE_ID,KPITYPE,REASON_ID,REASON,MENU_ID,CAMPAIGN_ID,PVIS_NA_IMAGE,TODAY_DEPLOY) VALUES ${values} `;
        let add_child_data = `INSERT INTO ${AppTables.WAREHOUSE_CHILD_DATA} (WAREHS_HEADER_ID,STORE_ID,VISIT_DATE,ITEM_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE,IS_DISABLED) VALUES ${childV} `;
        let add_images_data = `INSERT INTO ${AppTables.WAREHOUSE_IMAGES} (WAREHS_HEADER_ID,STORE_ID,VISIT_DATE,ITEM_ID,IMAGE1,IMAGE2,IMAGE_LABEL,ADDED_DATE) VALUES ${imageV} `;

        let combinedUpdateQuery = updateQueries.join('; ');
        // let updateReport=`Update Report_WarehouseStockInHand set TodayDeploy='${PosQty||0}' where ItemId='${StoreId}' `;
        await txn.executeSql(
          add_hdr_data,
          [],
          async function (txn2, txnres) {
            console.log("st header data added");
            var isSplitImageAdded = true,
              isStockAdded = true,
              isChildAdded = true,
              updatQ=true;

            if (imageV != "") {
              isSplitImageAdded = await executeQuery(add_images_data);
            }
            
            if (childV != "") {
              isChildAdded = await executeQuery(add_child_data);
            }

            if (combinedUpdateQuery != "") {
              updatQ = await executeQuery(combinedUpdateQuery);
            }

            if (!isSplitImageAdded) {
              setProcessing(false);
              notify("Cannot add warehouse images");
            } else if (!isChildAdded) {
              setProcessing(false);
              notify("Cannot add warehouse questions data");
            } else {
              // clear store data in local storage to avoiding re-set data for the store
              clear_item("storeData");
              setProcessing(false);
              notify(`${currentMenu.MenuName} updated successfully`);
              props.navigation.goBack();
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
            setProcessing(false);
            notify("Cannot add warehouse data");
          }
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  async function removePreviousData() {
    let { StoreId, ChainId, StateId, StoreTypeId } = storeData;

    let { PSAllow } = currentMenu;
    let deleteOnlyCatData = ShowCatWise && PSAllow && FilteredPromoValues.length > 0;

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let sq = `Select * FROM ${AppTables.WAREHOUSE_HDR_DATA} WHERE STORE_ID='${StoreId}' and MENU_ID='${currentMenu.MenuId}' and VISIT_DATE='${d2}' `;
        if (deleteOnlyCatData) {
          let FilterIdsJoin = FilteredPromoValues.join(",");
          sq += ` and PVIS_VALUE in (${FilterIdsJoin})  `;
        }
        await txn.executeSql(
          sq,
          [],
          async function (txn2, txnres) {
            if (txnres.rows.length > 0) {
              let arr = [];
              let isHdrDel = false,
                isQtnsDel = false,
                isImagesDel = false

              for (let i = 0; i < txnres.rows.length; i++) {
                let data = txnres.rows.item(i);
                let { WAREHS_HEADER_ID } = data;
                arr.push(WAREHS_HEADER_ID);
                if (i == txnres.rows.length - 1) {
                  let AllHdrIds = `'${arr.join("','")}'`;

                  await txn.executeSql(
                    `DELETE FROM ${AppTables.WAREHOUSE_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and WAREHS_HEADER_ID in (${AllHdrIds}) `,
                    [],
                    async function (txn2, txnres) {
                      console.log("window hdr data deleted");
                      isHdrDel = true;
                      if (isHdrDel && isHdrDel && isImagesDel ) {
                        resolve(true);
                      }
                    },
                    function (txnE, txnerr) {
                      console.log(txnerr);
                    }
                  );
                  await txn.executeSql(
                    `DELETE FROM ${AppTables.WAREHOUSE_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and WAREHS_HEADER_ID in (${AllHdrIds}) `,
                    [],
                    async function (txn2, txnres) {
                      console.log("window child data deleted");
                      isQtnsDel = true;
                      if (isHdrDel && isHdrDel && isImagesDel ) {
                        resolve(true);
                      }
                    },
                    function (txnE, txnerr) {
                      console.log(txnerr);
                    }
                  );
                  await txn.executeSql(
                    `DELETE FROM ${AppTables.WAREHOUSE_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and WAREHS_HEADER_ID in (${AllHdrIds}) `,
                    [],
                    async function (txn2, txnres) {
                      console.log("window images data deleted");
                      isImagesDel = true;
                      if (isHdrDel && isHdrDel && isImagesDel ) {
                        resolve(true);
                      }
                    },
                    function (txnE, txnerr) {
                      console.log(txnerr);
                    }
                  );
                 
                }
              }
            } else {
              resolve(true);
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
            resolve(false);
          }
        );
      });
    })
      .then((val) => {
        return val;
      })
      .catch((err) => {
        console.log("error:", err);
        return false;
      });
  }

  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(currentMenu) {
    let isValid = true;

    let isListedSKUIndex = KPIFields.findIndex((i) => i.KPIFieldName == "ListedSKUCheckbox");
    let isListedSKUKPIObj = isListedSKUIndex >= 0 ? KPIFields[isListedSKUIndex] : {};
    let isListedSKUEnable = isListedSKUIndex >= 0 ? isListedSKUKPIObj["KPIFieldEnable"] : true;

    let ReasonEnableIndex = KPIFields.findIndex((i) => i.ScreenName == "WAREHOUSEDEPLOY" && i.KPIFieldName == "ReasonEnable");
    let ReasonEnableKPIObj = ReasonEnableIndex >= 0 ? KPIFields[ReasonEnableIndex] : {};
    let ReasonEnable = ReasonEnableIndex >= 0 ? ReasonEnableKPIObj["KPIFieldEnable"] : false;

    let MenuIdFromConfig = ReasonEnableIndex >= 0 ? ReasonEnableKPIObj["KPIType"] : null;
    let menuId = MenuIdFromConfig && MenuIdFromConfig.split(":")[1]?.trim();


    function showError(obj, isErr) {
      setErrorField(obj);
      setError(isErr);
    }

    return new Promise((resolve, reject) => {
      for (const wi in globalWindows) {
        const window = globalWindows[wi];
        let isImage1 = window.VisibilityImage1 == "true" || window.VisibilityImage1 == 1 ? 1 : 0;
        let isImage2 = window.VisibilityImage2 == "true" || window.VisibilityImage2 == 1 ? 1 : 0;
        let isNAImageAvl = window.VisibilityNotExistCamera == "true" || window.VisibilityNotExistCamera == 1 ? 1 : 0;
        let isNAReasonEnable = window.VisibilityNotExistReasonEnable == "true" || window.VisibilityNotExistReasonEnable == 1 ? 1 : 0;
        let isReasonEnable = window.VisibilityExistReasonEnable == "true" || window.VisibilityExistReasonEnable == 1 ? 1 : 0;
        let isStockReq = window.VisibilityElementStockRequired == "true" || window.VisibilityElementStockRequired == 1 ? 1 : 0;
        let StockQtyRequired = window.StockQtyRequired == "true" || window.StockQtyRequired == 1 ? 1 : 0;
        let WindowQuestions = window.WindowQuestions || [];
        let WindowStocks = window.WindowStocks || [];

        const wind = WindowData.find((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
        let isPresent = KPIConfig?.HidePresentYesNo==false ? true : (wind.isPresent != null && wind.isPresent != "" ? wind.isPresent : "0");
        let WhDisable = wind.WhDisable != null && wind.WhDisable != "" ? wind.WhDisable : "0";
        let KpiTypId = wind.Id != null ? wind.Id : "";
        let KPIType = wind.KPIType != null ? wind.KPIType : "";
        
        let ReasonId = wind.ReasonId != null ? wind.ReasonId : "";
        let Reason = wind.Reason != null ? wind.Reason : "";

        let PosQty = wind.PosQty != null ? wind.PosQty : "";
        let NAImage1 = wind.NAImage1 != null ? wind.NAImage1 : "";
        let NAImage1Path = wind.NAImage1Path != null ? wind.NAImage1Path : "";
        let remark = wind.remark != null ? wind.remark : "";
        let WindowSplits = wind.WindowSplits || [];
        let QD = wind.WindowQA || {};
        let WStocksData = wind.WStocksData || [];
        let showOtherText = wind.showOtherText != null ? wind.showOtherText : false;
        let StockInHand = wind.StockInHand != null && wind.StockInHand != "" ? wind.StockInHand : 0;

        let errorobj = { EF_Window: window };
        if(WhDisable!=1){
          if (isPresent == "1") {
            if (isReasonEnable == true && KpiTypId == "") {
              errorobj["EF_NExistReason"] = "NExistReason";
              showError(errorobj, true);
              notify(`${ST.Pleaseselectreasonfor} ${window.ItemName} `, "LONG");
              resolve(false);
              return;
            }
            else if(KPIConfig?.DeploymentType==false ? false : KPIType==''){
                notify(`Please enter Deployment type for ${window.ItemName} `,'LONG');
                resolve(false);return;
            } 
            else if(StockInHand!=0 && PosQty=='' && KPIType!="Already Deployed"){
              notify(`Please enter Deploy Qty for ${window.ItemName} `,'LONG');
              resolve(false);return;
            }
            else {
              if (StoreCameraAllow && window.NoOfSplit > 0 && WindowSplits.length > 0) {
              
                for (const splitItemIndex in WindowSplits) {
                  const splitItem = WindowSplits[splitItemIndex];
  
                  let Image1Name = splitItem["Image"] != null && splitItem["Image"] != "" ? splitItem["Image"] : "";
                  let imgRequired = splitItem["imgRequired"] || false;
                  // console.log("Image2Name", Image2Name, isImage2);
                  if ( Image1Name == "" && imgRequired) {
                    errorobj["EF_splitImage1"] = "splitImage1";
                    errorobj["EF_splitItemIndex"] = splitItemIndex;
                    showError(errorobj, true);
                    notify(`${ST.Pleaseclickallimagesfor} ${window.ItemName}`, "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.ItemQuestionId + "_AnswerId";
                  let ans_key = qtn.ItemQuestionId + "_Answer";
                  let multi_key = qtn.ItemQuestionId + "_MultiOption";
                  let date_key = qtn.ItemQuestionId + "_Date";
                  let img_key = qtn.ItemQuestionId + "_ImagePath1";
                  let imgname_key = qtn.ItemQuestionId + "_ImageName1";
                  let rating_key = qtn.ItemQuestionId + "_Rating";

                  let isDisabled = qtn.isDisabled;

                  if (!isDisabled) {
                    let list_mcdata = [];
                    errorobj["EF_qtn"] = qtn;

                    let isImgAllowed = qtn.ItemAnswerShowCamera == "true" || qtn.ItemAnswerShowCamera == 1;
                    let checkForAnsKey = qtn.QuestionType == "Decimal" || qtn.QuestionType == "Number" || qtn.QuestionType == "Text" || qtn.QuestionType == "Date" || qtn.QuestionType == "Rating" || qtn.QuestionType == "QR";

                    if (qtn.QuestionType == "Single choice list") {
                      selansid = QD[id_key];
                    } else if (qtn.QuestionType == "Multi choice list") {
                      selansid = QD[multi_key] != null && QD[multi_key] != "" ? QD[multi_key].split(",") : [];
                    }

                    if (qtn.QuestionType == "Multi choice list" && selansid.length <= 0) {
                      errorobj["EF_Qtn_MultiChoice"] = "Qtn_MultiChoice";
                      showError(errorobj, true);
                      notify(`${ST.Pleaseselectoptionsfortherequiredfield} ${ST.In} ${window.ItemName}`, "SHORT");
                      resolve(false);
                      return;
                    } else if (checkForAnsKey && (Object.keys(QD).indexOf(ans_key) < 0 || (Object.keys(QD).indexOf(ans_key) >= 0 && QD[ans_key] === ""))) {
                      errorobj["EF_Qtn_Date"] = "Qtn_Date";
                      showError(errorobj, true);
                      let msg =
                        qtn.QuestionType == "Date"
                          ? `${ST.Pleasepickadatefortherequiredfield} ${ST.In} ${window.VisibilityName}`
                          : qtn.QuestionType == "Rating"
                            ? `${ST.Pleaseselectratingfortherequiredfield} ${ST.In} ${window.VisibilityName}`
                            : `${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.VisibilityName}`;
                      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] === "")) {
                      errorobj["EF_Qtn_Input"] = "Qtn_Input";
                      showError(errorobj, true);
                      notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.VisibilityName}`, "SHORT");
                      resolve(false);
                      return;
                    } else if (isImgAllowed && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ""))) {
                      errorobj["EF_Qtn_Image"] = "Qtn_Image";
                      showError(errorobj, true);
                      notify(`${ST.Pleaseaddimages} ${ST.In} ${window.ItemName}`, "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.ItemAnswerShowCamera == "true" || ansss.ItemAnswerShowCamera == 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] === ""))) {
                      errorobj["EF_Qtn_Image"] = "Qtn_Image";
                      showError(errorobj, true);
                      notify(`${ST.Pleaseaddimages} ${ST.In} ${window.ItemName}`, "SHORT");
                      resolve(false);
                      return;
                    }
                  }
                }
              }
            }
          } else {
            if (isNAReasonEnable == true && KpiTypId == "") {
              errorobj["EF_NExistReason"] = "NExistReason";
              showError(errorobj, true);
              notify(`${ST.Pleaseselectreasonfor} ${window.ItemName} `, "LONG");
              resolve(false);
              return;
            } 
            if (ReasonEnable == true && Reason == "" && menuId==currentMenu.MenuId) {
              errorobj["EF_NExistReason"] = "NExistReason";
              showError(errorobj, true);
              notify(`${ST.Pleaseselectreasonfor} ${window.ItemName} `, "LONG");
              resolve(false);
              return;
            }
            else if (isNAReasonEnable == true && showOtherText == true && (wind.PosQty == null || wind.PosQty == "")) {
              errorobj["EF_NExistRemark"] = "NExistRemark";
              showError(errorobj, true);
              notify(`${ST.PleaseEnterRemarkFor} ${window.ItemName} `, "LONG");
              resolve(false);
              return;
            } else if (StoreCameraAllow && isNAImageAvl == true && NAImage1 == "") {
              errorobj["EF_NExistImage"] = "NExistImage";
              showError(errorobj, true);
              notify(`${ST.Pleaseclickimagefor} ${window.VisibilityName}`, "LONG");
              resolve(false);
              return;
            }
          }

          if(NoCameraHide==currentMenu?.MenuId){
            if (StoreCameraAllow && window.NoOfSplit > 0 && WindowSplits.length > 0) {
              
              for (const splitItemIndex in WindowSplits) {
                const splitItem = WindowSplits[splitItemIndex];

                let Image1Name = splitItem["Image"] != null && splitItem["Image"] != "" ? splitItem["Image"] : "";
                let imgRequired = splitItem["imgRequired"] || false;
                // console.log("Image2Name", Image2Name, isImage2);
                if ( Image1Name == "" && imgRequired) {
                  errorobj["EF_splitImage1"] = "splitImage1";
                  errorobj["EF_splitItemIndex"] = splitItemIndex;
                  showError(errorobj, true);
                  notify(`${ST.Pleaseclickallimagesfor} ${window.ItemName}`, "LONG");
                  resolve(false);
                  return;
                }
              }
            }
          }
        }

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

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

    if (keyLbl == "KPIType") {
      let rsn_Index = reasons_list.findIndex((i) => i.Id == option.value);

      if (rsn_Index >= 0) {
        let rsn = reasons_list[rsn_Index];
        let IsRemarkTaken = rsn.IsRemarkTaken == 1 || rsn.IsRemarkTaken == "1" ? true : false;

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

    win_index >= 0 ? (allData[win_index] = wind) : allData.push(wind);
    // console.log("allData:", allData);
    let objIndex = InputChange.findIndex((i) => i.ItemId == item.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = true;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  async function onselectionChange(option, qtn, window) {
    setErrorField({});
    setError(false);
    let allData = WindowData;
    let defData = {
      ItemId: window.ItemId,
      QuestionCategoryId: window.ItemQuestionId,
    };
    const wind_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let wind = wind_index >= 0 ? allData[wind_index] : defData;
    let data = wind.WindowQA || {};
    let id_key = qtn.ItemQuestionId + "_AnswerId";
    let ans_key = qtn.ItemQuestionId + "_Answer";
    data[id_key] = option.value;
    data[ans_key] = option.label;

    wind["WindowQA"] = data;
    wind_index >= 0 ? (allData[wind_index] = wind) : allData.push(wind);
    let objIndex = InputChange.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = true;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    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.ItemQuestionEnable != null && ans_obj.ItemQuestionEnable != "" ? ans_obj.ItemQuestionEnable.replace(" ", "").split(",") : [];
    let DQtns = ans_obj.ItemQuestionDisable != null && ans_obj.ItemQuestionDisable != "" ? ans_obj.ItemQuestionDisable.replace(" ", "").split(",") : [];

    let sqtns = window.WindowQuestions || [];

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

  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.ItemQuestionId == qid) || {};
          let s_qtn = sqtns[s_qtnindex];
          if (s_qtn != null) {
            s_qtn["isDisabled"] = true;
            sqtns[s_qtnindex] = s_qtn;
            let id_key = s_qtn.ItemQuestionId + "_AnswerId";
            let ans_key = s_qtn.ItemQuestionId + "_Answer";
            data[id_key] = 0;
            data[ans_key] = "";

            wind["WindowQA"] = data;
            wind_index >= 0 ? (allData[wind_index] = wind) : allData.push(wind);
            return false;
          } else {
            return false;
          }
        })
      ).then(async (val) => {
        let allwindows = Windows;
        let windowIndex = allwindows.findIndex((i) => i.QuestionCategoryId == window.ItemQuestionId && i.ItemId == window.ItemId);
        if (windowIndex >= 0) {
          window["WindowQuestions"] = sqtns;
          allwindows[windowIndex] = window;
          WindowDataRef.current = allData;
          setWindowData(allData);
          setWindows(allwindows);
          setGlobalWindows(allwindows);
          // setHasUnsavedChanges(true);
          BgUnsavedChanges(true);
          setrerenderdata(!rerenderdata);
        }
      });
    }
  }

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

  async function setMultiSelectValue(selectedItems = [], qtn = {}, window = {}) {
    setErrorField({});
    setError(false);
    // console.log("setMultiSelectValue", selectedItems);
    let id_key = qtn.ItemQuestionId + "_AnswerId";
    let ans_key = qtn.ItemQuestionId + "_Answer";
    let multi_key = qtn.ItemQuestionId + "_MultiOption";

    let allData = WindowData;
    let defData = {
      ItemId: window.ItemId,
      QuestionCategoryId: window.ItemQuestionId,
    };
    const wind_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    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);

    let objIndex = InputChange.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = true;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  function setTextValue(value, qtn, window, type = "") {
    if (value != "") {
      let isValid = validateNumber(value, type);
      if (!isValid) {
        return;
      }
    }

    setErrorField({});
    setError(false);
    let id_key = qtn.ItemQuestionId + "_AnswerId";
    let ans_key = qtn.ItemQuestionId + "_Answer";

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

    if (qtn.QuestionType == "Date") {
      let date_key = qtn.ItemQuestionId + "_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);

    let objIndex = InputChange.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = true;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    console.log("tyeop-14");
    setrerenderdata(!rerenderdata);
  }

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

    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.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId) || {};
      allWindows[winIndex] = window;
      setWindows(allWindows);
      setGlobalWindows(allWindows);
      if (show == true) setrerenderdata(!rerenderdata);
    }
  }

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

  function onRatingCancel() {
    setShowRating(false);
  }

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

    let allData = WindowData;
    let defData = {
      ItemId: window.ItemId,
      QuestionCategoryId: window.ItemQuestionId,
    };

    const wind_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let wind = wind_index >= 0 ? allData[wind_index] : defData;
    let obj = wind.WindowQA || {};

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

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

    let objIndex = InputChange.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = true;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  function onChoiceSelect(item, val, key, animatedChoice) {
    let win_index = InputChange.find((i) => i.ItemId == item.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
    let changeValue = win_index.Flag;

    if (changeValue) {
      setIsPresentClean(val);
      setDataCleanAnim(animatedChoice);
      setDataCleanItem(item);
      setDataCleanModal(true);
      return;
    }

    var val1 = 0;
    val == 1 ? (val1 = 1) : "";

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

  function onWindowDataChange(item, val, key) {
    let allData = WindowData;

    let defData = {
      ItemId: item.ItemId,
      QuestionCategoryId: item.ItemQuestionId,
    };
    const win_index = allData.findIndex((i) => i.ItemId == item.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
    let wind = win_index >= 0 ? allData[win_index] || defData : defData;
    wind[key] = val;

    if (key == "Id") {
      let rsn = reasons_list.find((r) => r.Id == val) || {};
      wind["KPIType"] = rsn.KPIType || "";
    }

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

    if (key != "isPresent") {
      let objIndex = InputChange.findIndex((i) => i.ItemId == item.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
      let winArr = [...InputChange];
      winArr[objIndex].Flag = true;
      setInputChange(winArr);
    }

    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  async function setWindowStockVal(val, window, stockProd, key, type = "") {
    setErrorField({});
    setError(false);
    if (type == "numeric" && val != "") {
      const regex = new RegExp(/^\d+$/);
      let isNUmeric = regex.test(val);
      if (!isNUmeric) {
        notify(ST.Pleaseenterwholenumbersonly, "SHORT");
        return;
      }
    }

    let allData = WindowData;
    let defData = {
      ItemId: window.ItemId,
      QuestionCategoryId: window.ItemQuestionId,
    };
    const win_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
    let wind = win_index >= 0 ? allData[win_index] || defData : defData;
    let WStocksData = wind["WStocksData"] || [];
    let sdIndex = WStocksData.findIndex((i) => i.ProductId == stockProd.VisibilityStockValue);
    let sd = sdIndex >= 0 ? WStocksData[sdIndex] : { ProductId: stockProd.VisibilityStockValue, Stock: "" };
    sd[key] = val;
    sdIndex >= 0 ? (WStocksData[sdIndex] = sd) : WStocksData.push(sd);
    wind["WStocksData"] = WStocksData;
    win_index >= 0 ? (allData[win_index] = wind) : allData.push(wind);
    if (key == "isPVisPresent") {
      let isAllChecked = await verifyAllChecked(val, window, stockProd, key);
      wind["isAllSKUChecked"] = isAllChecked;
    }

    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata4(!rerenderdata4);
  }

  async function onCatTextChange(window, key, val,type="") {
    if (val != "") {
      let isValid = validateNumber(val, type);
      if (!isValid) {
        return;
      }
    }

    setErrorField({});
    setError(false);
    let item = window;
    let allData = WindowData;
    let defData = {
      ItemId: item.ItemId,
      QuestionCategoryId: item.ItemQuestionId,
    };
    const win_index = allData.findIndex((i) => i.ItemId == item.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
    let wind = win_index >= 0 ? allData[win_index] || defData : defData;
    wind[key] = val;

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

    WindowDataRef.current = allData;
    setWindowData(allData);

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

  async function verifyAllChecked(val, window, stockProd, key) {
    return await new Promise((resolve, reject) => {
      let WindowStocks = window.WindowStocks || [];
      let allData = WindowData;
      const win_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == item.ItemQuestionId);
      let wind = win_index >= 0 ? allData[win_index] || defData : defData;
      let WStocksData = wind["WStocksData"] || [];
      if (WindowStocks.length > 0) {
        let isAllChecked = 1;
        for (var i = 0; i < WindowStocks.length; i++) {
          let stockProd = WindowStocks[i];

          let sdIndex1 = WStocksData.findIndex((a) => a.ProductId == stockProd.VisibilityStockValue);
          let sd1 = sdIndex1 >= 0 ? WStocksData[sdIndex1] : {};
          let isPVisPresent = sd1.isPVisPresent;
          if (isPVisPresent == null || isPVisPresent == "" || isPVisPresent == 0 || isPVisPresent == "0") {
            isAllChecked = 0;
          }

          if (i == WindowStocks.length - 1) {
            resolve(isAllChecked);
          }
        }
      } else {
        resolve(0);
      }
    }).catch((err) => {
      console.log(err);
      return 0;
    });
  }

  function onWindowDataClean() {
    if (DataCleanAnim != null) {
      // console.log("anim---")
      let anim = isPresentClean == 1 ? 1 : "";
      Animated.timing(DataCleanAnim, {
        toValue: anim,
        duration: 400,
        useNativeDriver: false,
      }).start();
    }
    let ImageMandatory = KPIFields?.find((i) => i.KPIFieldName == (KPIConfig?.ImageMandatory==false? "PrimaryImageMandatory" :"ImageMandatory"));
    let ImageMandatoryFlage = ImageMandatory?.KPIFieldEnable || false
    let ImageMandatoryNo = ImageMandatoryFlage ? ImageMandatory?.KPIFieldDisplayName : 0

    let allData = WindowData;
    let WindowSplits = [];
    for (var s = 0; s < DataCleanItem.NoOfSplit; s++) {
      let obj = {
        ImageName: "",
        Image: "",
        ImageLable: ImageLabel[s],
        imgRequired: s < ImageMandatoryNo
      };
      WindowSplits.push(obj);
    }


    let defData = {
      ...DataCleanItem,
      ItemId: DataCleanItem.ItemId,
      ItemQuestionId: DataCleanItem.ItemQuestionId,
      isAllSKUChecked: 0,
      WindowSplits: WindowSplits,
      KPIType: "",
      PosQty: "",
      Reason:"",
      ReasonId:"",
      TodayDeploy:0,
      WindowQA: {},
      WStocksData: [],
      isPresent: isPresentClean,
    };
    const win_index = allData.findIndex((i) => i.ItemId == DataCleanItem.ItemId && i.QuestionCategoryId == DataCleanItem.ItemQuestionId);
    allData[win_index] = defData;



    let objIndex = InputChange.findIndex((obj) => obj.ItemId == DataCleanItem.ItemId && obj.QuestionCategoryId == DataCleanItem.ItemQuestionId);
    let winArr = [...InputChange];
    winArr[objIndex].Flag = false;

    setInputChange(winArr);
    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setDataCleanModal(false);
    setrerenderdata(!rerenderdata);
  }

  function checkAllSKUs(val, window) {
    let WindowStocks = window.WindowStocks || [];
    let allData = WindowData;
    let defData = {
      ItemId: window.ItemId,
      QuestionCategoryId: window.ItemQuestionId,
    };
    const win_index = allData.findIndex((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
    let wind = win_index >= 0 ? allData[win_index] || defData : defData;
    let WStocksData = wind["WStocksData"] || [];
    console.log("WStocksData before:", WStocksData);
    for (var i = 0; i < WindowStocks.length; i++) {
      let stockProd = WindowStocks[i];

      let sdIndex = WStocksData.findIndex((a) => a.ProductId == stockProd.VisibilityStockValue);
      let sd = sdIndex >= 0 ? WStocksData[sdIndex] : { ProductId: stockProd.VisibilityStockValue, Stock: "" };
      let isPVisPresent = val == 1 || val == "1" ? 1 : 0;
      sd["isPVisPresent"] = isPVisPresent;

      sdIndex >= 0 ? (WStocksData[sdIndex] = sd) : WStocksData.push(sd);
    }

    wind["WStocksData"] = WStocksData;
    wind["isAllSKUChecked"] = val == 1 ? 1 : 0;
    console.log("wind updated");
    win_index >= 0 ? (allData[win_index] = wind) : allData.push(wind);

    WindowDataRef.current = allData;
    setWindowData(allData);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  function onSaveCancel() {
    setShowAlert(false);
  }

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

  function FilterStores(searchedQry) {
    searchedQry = searchedQry.toLowerCase();
    console.log("searchedQry", searchedQry);
    let arr = [];
    let newWindows = [];
    if (searchedQry != null && searchedQry != "") {
      for (let i = 0; i < globalWindows.length; i++) {
        let item = globalWindows[i];
        let { ItemName } = item;
        if (ItemName.toLowerCase().includes(searchedQry)) {
          newWindows.push(item);
        }

        if (i == globalWindows.length - 1) {
          arr = newWindows;
        }
      }
    } else {
      arr = globalWindows;
    }

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

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

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

    return (
      <View style={customStyle.RatingModal}>
        <View style={customStyle.RatingModalCon}>
          <Text style={customStyle.VRModalHeding}>{ST.DragItemsInOrder}</Text>
          <Text style={customStyle.VRSubHeding}>{ST.Pressandholdtodrag}</Text>
          <DraggableFlatList
            data={newarr}
            style={customStyle.RModal_list}
            contentContainerStyle={customStyle.RModal_listInner}
            onDragEnd={({ data }) => {
              setRatingValue(data);
            }}
            keyExtractor={(item) => item.AnswerId}
            renderItem={renderItem}
          />
          <View style={customStyle.RModal_Btns}>
            <TouchableOpacity
              style={customStyle.RModal_BtnCancel}
              onPress={() => {
                onRatingCancel();
              }}
            >
              <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={customStyle.RModal_Btnsave}
              onPress={() => {
                onRatingSave();
              }}
            >
              <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

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

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

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

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

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

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

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

  function _renderWindow(currentMenu) {
    let RemarkEnableIndex = KPIFields.findIndex((i) => i.ScreenName == "WAREHOUSEDEPLOY" && i.KPIFieldName == "DeployQty");
    let RemarkEnableKPIObj = RemarkEnableIndex >= 0 ? KPIFields[RemarkEnableIndex] : {};
    let RemarkEnable = RemarkEnableIndex >= 0 ? RemarkEnableKPIObj["KPIFieldEnable"] : false;
    let DeployQtyTextLength = RemarkEnableIndex >= 0 ? Number(RemarkEnableKPIObj["KPIType"]) : null;

    let DeploymentTypEnableIndex = KPIFields.findIndex((i) => i.ScreenName == "WAREHOUSEDEPLOY" && i.KPIFieldName == "DeploymentType");
    let DeploymentTypKPIObj = DeploymentTypEnableIndex >= 0 ? KPIFields[DeploymentTypEnableIndex] : {};
    let DeploymentTypEnable = DeploymentTypEnableIndex >= 0 ? DeploymentTypKPIObj["KPIFieldEnable"] : false;

    let isListedSKUIndex = KPIFields.findIndex((i) => i.KPIFieldName == "ListedSKUCheckbox");
    let isListedSKUKPIObj = isListedSKUIndex >= 0 ? KPIFields[isListedSKUIndex] : {};
    let isListedSKUEnable = isListedSKUIndex >= 0 ? isListedSKUKPIObj["KPIFieldEnable"] : true;

    let ReasonEnableIndex = KPIFields.findIndex((i) => i.ScreenName == "WAREHOUSEDEPLOY" && i.KPIFieldName == "ReasonEnable");
    let ReasonEnableKPIObj = ReasonEnableIndex >= 0 ? KPIFields[ReasonEnableIndex] : {};
    let ReasonEnable = ReasonEnableIndex >= 0 ? ReasonEnableKPIObj["KPIFieldEnable"] : false;
    let MenuIdFromConfig = ReasonEnableIndex >= 0 ? ReasonEnableKPIObj["KPIType"] : null;
    let menuId = MenuIdFromConfig && MenuIdFromConfig.split(":")[1]?.trim();
 
    return (
      <KeyboardAvoidingView behavior="padding" enabled>
        <FlatList
          data={Windows}
          extraData={rerenderdata}
          contentContainerStyle={customStyle.Win_scroll}
          // style={customStyle.Win_scrollO}
          initialNumToRender={5}
          viewabilityConfigCallbackPairs={FlatLConfCallbackPairs.current}
          listKey={(item, index) => `window_${index.toString()}`}
          renderItem={({ item, index }) => {
            const window = item;
            const windowIndex = index;
            let isVisible = Boolean(ItemsInView.find(({ item: i, isViewable }) => i.ItemId == window.ItemId && i.ItemQuestionId == window.QuestionCategoryId && isViewable));
            // console.log("RenderItemList ItemsInView2:",index,isVisible)

            let isImage1 = window.VisibilityImage1 == "true" || window.VisibilityImage1 == 1 ? 1 : 0;
            let isImage2 = window.VisibilityImage2 == "true" || window.VisibilityImage2 == 1 ? 1 : 0;
            let isNAImageAvl = window.VisibilityNotExistCamera == "true" || window.VisibilityNotExistCamera == 1 ? 1 : 0;
            let isNAReasonEnable = window.VisibilityNotExistReasonEnable == "true" || window.VisibilityNotExistReasonEnable == 1 ? 1 : 0;
            let VisibilityRefImagePopUp = window.VisibilityRefImagePopUp == "true" || window.VisibilityRefImagePopUp == true ? true : false;
            let isReasonEnable = window.VisibilityExistReasonEnable == "true" || window.VisibilityExistReasonEnable == 1 ? 1 : 0;
            let isStockReq = window.VisibilityElementStockRequired == "true" || window.VisibilityElementStockRequired == 1 ? 1 : 0;
            let StockQtyRequired = window.StockQtyRequired == "true" || window.StockQtyRequired == 1 ? 1 : 0;
            let PromoTitleEnable = window.PromoDefinitionTitleEnable == "true" || window.PromoDefinitionTitleEnable == 1 ? 1 : 0;
            let PromoTitle = window.PromoDefinitionTitle != null && window.PromoDefinitionTitle != "undefined" ? window.PromoDefinitionTitle : "";

            // let isStock_CheckAssrt=window.VisibilityElementCheckAssortment=='true' || window.VisibilityElementCheckAssortment==1?1:0;
            let RefImage = window.VisibilityRefImage;
            let camera1Label = window.VisibilityImage1Lable || "";
            let camera2Label = window.VisibilityImage2Lable || "";
            let WindowQuestions = window.WindowQuestions || [];
            let WindowStocks = window.WindowStocks || [];

            const wind = WindowData.find((i) => i.ItemId == window.ItemId && i.QuestionCategoryId == window.ItemQuestionId);
            let isPresent = KPIConfig?.HidePresentYesNo==false ? true : (wind.isPresent != null && wind.isPresent != "" ? wind.isPresent : "0");
            let WhDisable = wind.WhDisable != null && wind.WhDisable != "" ? wind.WhDisable : "0";
            
            let StockInHand = wind.StockInHand != null && wind.StockInHand != "" ? wind.StockInHand : 0;
            let TodayDeploy = wind.TodayDeploy != null && wind.TodayDeploy != "" ? wind.TodayDeploy : 0;
            let FinalStock = Number(StockInHand)-Number(TodayDeploy)
            let KpiTypId = wind.Id != null ? wind.Id : "";
            let Reason = wind.Reason != null ? wind.Reason : '';
            let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
            let KPIType = wind.KPIType != null ? wind.KPIType : "";
            let NAImage1 = wind.NAImage1 != null ? wind.NAImage1 : "";
            let NAImage1Path = wind.NAImage1Path != null ? wind.NAImage1Path : "";
            let remark = wind.remark != null ? wind.remark : "";
            // let PosQty = wind && wind.PosQty != null ? wind.PosQty : "";
            let PosQty = wind.PosQty != null ? wind.PosQty.toString() : "0";



            let showOtherText = wind.showOtherText != null ? wind.showOtherText : false;
            let WindowSplits = wind.WindowSplits || [];
            let QuestionsData = wind.WindowQA || {};
            let WStocksData = wind.WStocksData || [];
            let isAllSKUChecked = wind.isAllSKUChecked == 1 || wind.isAllSKUChecked == "1";

            // console.log('RefImage:',RefImage);

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

            if (isVisible && window.animatedHeight != null) {
              setTimeout(() => {
                Animated.timing(window.animatedHeight, {
                  toValue: 0,
                  duration: 800,
                  useNativeDriver: false,
                }).start();
                // animHight=window.animatedHeight.interpolate({
                //     inputRange:[100,0],
                //     outputRange:["100%","0%"],
                // });
              }, (props.RefImagePopUpTime || 0) * 1000);
            }

            let EF_Window = errorfield.EF_Window != null ? errorfield.EF_Window : {};
            let show_errorhere = error == true && EF_Window.ItemId == window.ItemId && EF_Window.QuestionCategoryId == window.ItemQuestionId;

            // if not Present fields

            // this will show error field in red (if window is present and exist reason is enabled and not filled ) or (if window is not present and Not exist reason is enabled and not filled )
            let EF_NExistReason = errorfield.EF_NExistReason || "";
            let EStyle_NExistReason = show_errorhere && EF_NExistReason == "NExistReason" ? customStyle.stk_inptSTyle_error : {};

            let EF_NExistRemark = errorfield.EF_NExistRemark || "";
            let EStyle_NExistRemark = show_errorhere && EF_NExistRemark == "NExistRemark" ? customStyle.stk_inptSTyle_error : {};

            let EF_NExistImage = errorfield.EF_NExistImage || "";
            let EStyle_NExistImage = show_errorhere && EF_NExistImage == "NExistImage" ? customStyle.error_CatImage2 : {};

            return (
              <View style={customStyle.WItem_wrap} key={"window_" + index}>
                <View style={customStyle.WItem_Hdr}>
                  <View style={[customStyle.WItem_Hdrbg,(WhDisable==1 && {backgroundColor:"#7ca0bc"})]}>
                    <Text style={customStyle.WItem_HdrText}>{window.ItemCategory}</Text>
                    {/* {window && window.ChildName != "" && <Text style={[customStyle.WItem_Hdrname2]}>{window.ItemName+" - "+window.MappingType}</Text>} */}
                    { window && window.ChildName !== "" && ( <Text style={[customStyle.WItem_Hdrname2]}>
                    {window.ItemName + (menuId == currentMenu.MenuId ? " - " + window.MappingType : "")}</Text> )}
                    {PromoTitleEnable == 1 && PromoTitle != null && PromoTitle != "" && <Text style={customStyle.WItem_HdrSubTitleText}>{PromoTitle}</Text>}
                    <TouchableOpacity
                      style={customStyle.WItem_RefImgBtn}
                      onPress={() => {
                        openImageRefView(index);
                      }}
                    >
                      <Entypo name="image-inverted" size={24} color={PageTheme.$accent_color} />
                    </TouchableOpacity>
                  </View>
                </View>
                {VisibilityRefImagePopUp && (
                  <Animated.View
                    style={[
                      {
                        backgroundColor: "#fff",
                        width: "100%",
                        // height: 300,
                        height: window.animatedHeight,
                        // borderRadius: 10,
                        paddingBottom: 10,
                        // shadowColor: "#000",
                        // elevation: 5
                      },
                    ]}
                  >
                    <Image style={[{ width: "100%", height: "100%" }]} resizeMode="contain" source={{ uri: RefImage }} />
                  </Animated.View>
                )}

                <View style={customStyle.WForm}>
                  <View style={[customStyle.openStk_prd_cols, customStyle.mt10]}>
                  { (KPIConfig?.HidePresentYesNo==false ? false : true ) && 
                    <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                      <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                      <View style={customStyle.openStk_prd_choiceBoxCon}>
                        <View style={customStyle.openStk_prd_choiceBox}>
                          <Animated.View
                            style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, isPresent == "1" || isPresent == 1 ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red, (WhDisable==1 && {backgroundColor:"#c4c6c6"}),{ transform: [{ translateX: xpos }] }]}
                          ></Animated.View>
                          <TouchableOpacity
                            style={customStyle.openStkCh_con1}
                            onPress={() => {
                              if(WhDisable==1){
                                notify(`You have already Deployed`, "LONG");
                                return
                              }
                              onChoiceSelect(window, 1, "isPresent", window.animatedChoice);
                            }}
                          >
                            <Text style={[customStyle.openStkCh_text, isPresent == "1" || isPresent == 1 ? customStyle.openStkCh_textactive : {}]}>{ST.Yes}</Text>
                          </TouchableOpacity>
                          <TouchableOpacity
                            style={[customStyle.openStkCh_con1]}
                            onPress={() => {
                              if(WhDisable==1){
                                notify(`You have already Deployed`, "LONG");
                                return
                              }
                              onChoiceSelect(window, 0, "isPresent", window.animatedChoice);
                            }}
                          >
                            <Text style={[customStyle.openStkCh_text, isPresent == "0" || isPresent == 0 ? customStyle.openStkCh_textactive : {}]}>{ST.No}</Text>
                          </TouchableOpacity>
                        </View>
                      </View>
                    </View>
                  }
                    {/* {((isPresent != "1" && isNAReasonEnable == true) || (isPresent == "1" && isReasonEnable == true)) && WhDisable=="0"  && ( */}
                    {((isPresent != "1" && ReasonEnable == true && menuId==currentMenu.MenuId)) && WhDisable=="0"  && (
                      <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                        {
                          <CustomPicker2
                            {...props}
                            Pickerdata={nonDeploymentReasonlist}
                            label_key={"Reason"}
                            value_key={"ReasonId"}
                            onchangeKeyLbl={"Reason"}
                            onchangeKey={"ReasonId"}
                            onChange={onselectionChange3}
                            selected_data={{
                              value: Reason,
                              otherData: { window: window },
                            }}
                            InputStyle={customStyle.PV_selectInputStyle}
                            selectStyle={customStyle.PV_selectStyle}
                            ErrorStyle={EStyle_NExistReason}
                            ShowError={error}
                          />
                        }
                      </View>
                    )}

                    {/* {(NoCameraHide==currentMenu?.MenuId ?true:(isPresent != "1")) && isNAImageAvl == true && WhDisable=="0"  && ( */}
                    {/* {(NoCameraHide==currentMenu?.MenuId) && WhDisable=="0"  && (
                      <View>
                        <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                          <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$fourth_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                            <Text style={customStyle.windhdrText}>{ST.CaptureImage}</Text>
                          </LinearGradient>

                          <View style={[customStyle.openStk_prdCameras, customStyle.WSCameraWrap]}>
                            <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]}>
                              {(NAImage1Path == "" || NAImage1Path == null) && (
                                <TouchableOpacity
                                  style={[customStyle.osCat_action_openCam, customStyle.osCat_actn_margin, EStyle_NExistImage]}
                                  onPress={() => {
                                    openCamera(window, {}, 0, "1", "3");
                                  }}
                                >
                                  <SvgXml width={80} height={80} xml={cameraImg} />
                                </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" && RemarkEnable == true && WhDisable=="0" && (KPIConfig?.DeploymentType==false ? false : 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]}>{"Deployment Type"}</Text>
                        {
                          <CustomPicker2
                            {...props}
                            Pickerdata={reasons_list}
                            label_key={"KPIType"}
                            value_key={"KPIType"}
                            onchangeKeyLbl={"KPIType"}
                            onchangeKey={"KPIType"}
                            onChange={onselectionChange3}
                            selected_data={{
                              value: KPIType,
                              otherData: { window: window },
                            }}
                            InputStyle={customStyle.PV_selectInputStyle}
                            selectStyle={customStyle.PV_selectStyle}
                            ErrorStyle={EStyle_NExistReason}
                            ShowError={error}
                          />
                        }
                      </View>
                    )}
                    {isPresent == "1" && RemarkEnable == true && WhDisable=="0" && (KPIConfig?.DeployQty==false ? false : true ) && (
                      <View style={[customStyle.openStk_prd_colflex, customStyle.pt10]}>
                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{`Deploy Qty ${item?.MeasureUnit?`(${item?.MeasureUnit})`:""} \n( Stock Avbl. ${StockInHand} )`}</Text>
                        <TextInput
                          style={[customStyle.openStk_prd_inputStyle1, customStyle.openStk_prd_flex_inputStyle1, EStyle_NExistRemark,((!Boolean(FinalStock) || KPIType=="Already Deployed" )&& {backgroundColor:"#dbdbd9"} )]}
                          placeholder=""
                          autoComplete="off"
                          keyboardType="numeric"
                          maxLength={DeployQtyTextLength}
                          placeholderTextColor={PageTheme.$placeholder_color}
                          editable={(KPIType=="Already Deployed") ? false:Boolean(FinalStock)}
                          textAlign="center"
                          value={PosQty}
                          onChangeText={(val) => {
                            // onCatTextChange(window, 'RemarkText', val, 'text');
                            // let stockEnt=KPIType=="Already Deployed" ? true :val<=FinalStock
                            let stockEnt=KPIType=="Already Deployed" ? true :(val<=FinalStock && (val===""? true :val>0) )
                            if(stockEnt){
                              onCatTextChange(window, "PosQty", val, "numeric");
                            }else{
                              notify(`Please fill the value less than Stock In Hand and Greater than 0 `, "LONG");
                            }
                          }}
                        />
                      </View>
                    )}

                    
                      <View>
                        {isPresent == "1" && WhDisable=="0" && isStockReq == true  && WindowStocks.length > 0 && (
                          <View style={[customStyle.openStk_prd_borderT, customStyle.pt10]}>
                            <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$fourth_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                              <Text style={customStyle.windhdrText}>{isListedSKUEnable == true ? ST.SelectProducts : "Enter Stocks"}</Text>
                            </LinearGradient>
                            {isListedSKUEnable == true && (
                              <View style={customStyle.windhdr_checkAllBtnCon}>
                                <TouchableOpacity
                                  style={customStyle.windhdr_checkAllBtn}
                                  onPress={() => {
                                    checkAllSKUs(isAllSKUChecked == 1 ? 0 : 1, window);
                                  }}
                                >
                                  <CheckBox
                                    boxType="square"
                                    value={isAllSKUChecked}
                                    onValueChange={(val) => {
                                      let val1 = val == true ? 1 : 0;
                                      checkAllSKUs(val1, window);
                                    }}
                                    style={[customStyle.WStkHdr_checkbox, Platform.OS == "ios" ? { height: 20, width: 20, marginLeft: 5 } : {}]}
                                    tintColors={{
                                      true: PageTheme.$primary_color,
                                      false: PageTheme.$text_color_light,
                                    }}
                                  />
                                  <Text style={customStyle.windhdr_checkAllBtnText}>{ST.SelectAll}</Text>
                                </TouchableOpacity>
                              </View>
                            )}

                          </View>
                        )}




                        {((NoCameraHide==currentMenu?.MenuId) ? true :(isPresent == "1" && WhDisable=="0")) && WindowSplits?.length > 0 && (
                          <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10,customStyle.mt20]}>
                            <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$fourth_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                              <Text style={customStyle.windhdrText}>{currentMenu.MenuName + " Images"}</Text>
                            </LinearGradient>
                            <FlatList
                              data={WindowSplits}
                              extraData={rerenderdata2}
                              listKey={(item, index) => `spliItem_${index.toString()}`}
                              style={{flexWrap:"wrap", flexDirection:"row", justifyContent:"space-between",marginHorizontal:"25%"}}
                              renderItem={({ item, index }) => {
                                let splitItem = item;
                                let splitItemIndex = index;
                                let Img = item?.Image
                                let imgRequired = item?.imgRequired
                                let ImageLable = item?.ImageLable
                                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"] : "";
                                let isImg1mad = splitItem["img1Required"] || false;
                                let isImg2mad = splitItem["img2Required"] || false;

                                // highlight slit image box
                                let EF_splitItemIndex = errorfield.EF_splitItemIndex || "";
                                let showSplitItemErrHere = EF_splitItemIndex == splitItemIndex;

                                let EF_splitImage1 = errorfield.EF_splitImage1 || "";
                                let EStyle_splitImage1 = show_errorhere && showSplitItemErrHere && EF_splitImage1 == "splitImage1" ? customStyle.error_CatImage2 : {};

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

                               
                                return (
                                  <View style={[customStyle.openStk_prdCameras, customStyle.WSCameraWrap,{width:"50%"}]} key={"SplitItem+" + splitItemIndex}>
                                    
                                      <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]}>
                                        {!Img && imgRequired ? (
                                          <TouchableOpacity
                                            style={[EStyle_splitImage1]}
                                            onPress={() => {
                                              openCamera(window, splitItem, splitItemIndex, "4","4");
                                            }}
                                          >
                                            <CameraImg5 width={50} height={50} />
                                          </TouchableOpacity>
                                        ) : !Img ? (
                                          <TouchableOpacity
                                            style={[EStyle_splitImage1]}
                                            onPress={() => {
                                              openCamera(window, splitItem, splitItemIndex, "4","4");
                                            }}
                                          >
                                            <CameraImg2 width={50} height={50}/>
                                          </TouchableOpacity>
                                        ) : Img && (
                                          <TouchableOpacity
                                            onPress={() => {
                                              OpenImgModal(Img, window, splitItem, splitItemIndex, "4","4");
                                            }}
                                          >
                                            <CameraImg3 width={50} height={50} />
                                          </TouchableOpacity>
                                        ) }
                                        <Text style={customStyle.WSCameraLabel}>{ImageLable}</Text>
                                      </View>
                                    
                                  </View>
                                );
                              }}
                            />
                          </View>
                        )}

                        {WindowQuestions.length > 0 && (
                          <View style={[customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10,customStyle.mt10]}>
                            <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$fourth_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                              <Text style={customStyle.windhdrText}>{currentMenu.MenuName + " Questions"}</Text>
                            </LinearGradient>
                            {WindowQuestions.map((item, index) => {
                              {/* console.log("Question...:", item, "Index:", index); */ }
                              let qtn = item;
                              let qtnIndex = index;
                              let selansid = "",
                                selanswer = "",
                                selimg = "",
                                showImageTag = false;
                              let id_key = qtn.ItemQuestionId + "_AnswerId";
                              let ans_key = qtn.ItemQuestionId + "_Answer";
                              let multi_key = qtn.ItemQuestionId + "_MultiOption";
                              let date_key = qtn.ItemQuestionId + "_Date";
                              let img_key = qtn.ItemQuestionId + "_ImagePath1";
                              let imgname_key = qtn.ItemQuestionId + "_ImageName1";
                              let rating_key = qtn.ItemQuestionId + "_Rating";

                              let list_mcdata = [];
                              let ItemDefaultQuestionEnable = qtn.ItemDefaultQuestionEnable == "true" || qtn.ItemDefaultQuestionEnable == 1 || qtn.ItemDefaultQuestionEnable == "1" ? true : false;
                              let isDisabled = qtn.isDisabled;
                              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] != null && QuestionsData[ans_key] != undefined ? QuestionsData[ans_key] : "";
                                selanswer = qtn.QuestionType == "Date" ? QuestionsData[date_key] || moment().format("MM/DD/YYYY") : "";
                                showImageTag = qtn.ItemAnswerShowCamera == 1 || qtn.ItemAnswerShowCamera == "true";
                              } else if (qtn.QuestionType == "Rating" || qtn.QuestionType == "QR") {
                                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.ItemAnswerShowCamera == "true" || ansss.ItemAnswerShowCamera == 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] : ""; */ }

                                selimg = QuestionsData[img_key] != null && QuestionsData[img_key] !== "" ? "file://" + QuestionsData[img_key] : "";
                              }

                              let EF_qtn = errorfield.EF_qtn != null ? errorfield.EF_qtn : {};
                              let showQtnErrHere = EF_qtn.ItemQuestionId == qtn.ItemQuestionId;
                              //Qtn_MultiChoice
                              let EF_Qtn_MultiChoice = errorfield.EF_Qtn_MultiChoice || "";
                              let EStyle_Qtn_MultiChoice = show_errorhere && showQtnErrHere && EF_Qtn_MultiChoice == "Qtn_MultiChoice" ? customStyle.stk_MultiSSTyle_error : {};

                              let EF_Qtn_Date = errorfield.EF_Qtn_Date || "";
                              let EStyle_Qtn_Date = show_errorhere && showQtnErrHere && EF_Qtn_Date == "Qtn_Date" ? customStyle.stk_inptSTyle_error : {};

                              let EF_Qtn_Input = errorfield.EF_Qtn_Input || "";
                              let EStyle_Qtn_Input = show_errorhere && showQtnErrHere && EF_Qtn_Input == "Qtn_Input" ? customStyle.stk_inptSTyle_error : {};

                              let EF_Qtn_Image = errorfield.EF_Qtn_Image || "";
                              let EStyle_Qtn_Image = show_errorhere && showQtnErrHere && EF_Qtn_Image == "Qtn_Image" ? customStyle.stk_inptSTyle_error : {};

                              if (!isDisabled) {
                                return (
                                  <View style={[customStyle.sform_group2]} key={"Qtn_" + qtnIndex}>
                                    <Text style={[customStyle.sform_label3]}>{qtn.ItemQuestionName}</Text>
                                    {qtn.QuestionType == "Single choice list" &&
                                      qtn.Answers &&
                                      render_Picker("Answer", "AnswerId", onselectionChange, {
                                        value: selanswer,
                                        qtn: qtn,
                                        window: window,
                                      })}
                                    {qtn.QuestionType == "Multi choice list" && qtn.Answers && (
                                      <MultiSelect
                                        items={list_mcdata}
                                        uniqueKey="AnswerId"
                                        onSelectedItemsChange={(selectedItems) => {
                                          setMultiSelectValue(selectedItems, qtn, window);
                                        }} //setMultiSelectValue(selectedItems,qtn)
                                        selectedItems={selansid}
                                        selectText="Pick Items"
                                        searchInputPlaceholderText={ST.SearchItems + "..."}
                                        // onChangeInput={ (text)=> console.log(text)}
                                        tagRemoveIconColor={PageTheme.$primary_color}
                                        tagBorderColor={PageTheme.$primary_color}
                                        tagTextColor={PageTheme.$primary_color}
                                        selectedItemTextColor={PageTheme.$primary_color}
                                        selectedItemIconColor={PageTheme.$primary_color}
                                        itemTextColor={PageTheme.$text_color}
                                        displayKey="Answer"
                                        searchInputStyle={customStyle.wind_MultiSearchInputStyle}
                                        styleMainWrapper={EStyle_Qtn_MultiChoice}
                                        submitButtonColor={PageTheme.$primary_color}
                                        submitButtonText={ST.Submit}
                                      />
                                    )}
                                    {(qtn.QuestionType == "Number" || qtn.QuestionType == "Decimal" || qtn.QuestionType == "Text") && (
                                      <TextInput
                                        style={[customStyle.WQ_InputStyle, EStyle_Qtn_Input]}
                                        placeholder=""
                                        autoComplete="off"
                                        placeholderTextColor={PageTheme.$placeholder_color}
                                        // keyboardType={'ascii-capable'}
                                        keyboardType={qtn.QuestionType == "Decimal" ? "decimal-pad" : qtn.QuestionType == "Text" ? "default" : "number-pad"}
                                        value={selansid + ""}
                                        onChange={(e) => console.log("onchangeVal--", e.value)}
                                        onChangeText={(val) => {
                                          setTextValue(val, qtn, window, qtn.QuestionType == "Decimal" ? "decimal" : qtn.QuestionType == "Text" ? "text" : "numeric");
                                        }}
                                      />
                                    )}
                                    {qtn.QuestionType == "Date" && (
                                      <View style={[customStyle.surveyQtn_datePicker_con, EStyle_Qtn_Date]}>
                                        <Text style={customStyle.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.QuestionType == "QR" && (
                                      <View style={customStyle.surveyQtn_datePicker_con}>
                                        <Text style={customStyle.WQ_datePicker_text}>{selanswer != "" ? selanswer : ""}</Text>
                                        <TouchableOpacity
                                          style={[customStyle.surveyQtn_datePicker]}
                                          onPress={() => {
                                            setQREnable(true);
                                            setQRqtnData({ qtn, window });
                                            setShowQRCamera(true);
                                          }}
                                        >
                                          {/* <Fontisto size={20} color={PageTheme.$accent_color} name="date"/> */}
                                          <Ionicons name="camera" color={PageTheme.$accent_color} size={24} />
                                        </TouchableOpacity>
                                      </View>
                                    )}
                                    {(qtn.showDatePicker == true || qtn.showDatePicker == "true") && qtn.QuestionType == "Date" && renderDatePicker(qtn, window)}
                                    {qtn.QuestionType == "Rating" && (
                                      <View style={customStyle.surveyQtn_datePicker_con}>
                                        <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                        <TouchableOpacity
                                          style={[customStyle.surveyQtnRatingIcon]}
                                          onPress={() => {
                                            setRatingQtn(qtn);
                                            setRatingWindow(window);
                                            setShowRating(true);
                                          }}
                                        >
                                          <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag" />
                                        </TouchableOpacity>
                                      </View>
                                    )}

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

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

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

  const onCancelClean = () => {
    setDataCleanModal(false);
  };
  const onclear = () => {
    onWindowDataClean(DataCleanItem);
  };

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS == "ios" ? true : false}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
      {_OpenCaptureImage_Modal()}
      {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
      {ConfirmSaveAlert(props, DataCleanModal, onCancelClean, onclear, "Your data will be clean")}
      <CustomCamera
        cameraType={"back"}
        QRCodeEnable={QREnable}
        onImageCaptured={(imgData) => {
          console.log("QRRec:", imgData);
          setShowQRCamera(false);
          onQRScanned(imgData);
        }}
        showCamera={showQRCamera}
        onHideCamera={() => {
          setShowQRCamera(false);
        }}
      />
      <CustomCamera
        cameraType={"back"}
        BottomText={"Store Name:" + storeData.StoreName + " | Store Id:" + storeData.StoreId + " | User Id:" + storeData.EmpId + " | Image Type: " + currentMenu.MenuName}
        enableCameraFlip={showSwitchCamera}
        gridEnable={GridValue}
        onImageCaptured={(imgData) => {
          setShowCamera(false);
          getImage(imgData);
        }}
        showCamera={showCamera}
        onHideCamera={() => {
          setShowCamera(false);
        }}
      />

      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper, customStyle.zIndex0]}>
        <View style={[customStyle.pageContentWrapper]}>
          <View style={customStyle.storel_searchbar}>
            <TextInput
              style={[customStyle.storel_searchInput]}
              placeholder={ST.Searchby + " " + currentMenu.MenuName}
              placeholderTextColor={PageTheme.$placeholder_color}
              value={searchedItem}
              autoComplete="off"
              onChangeText={(val) => {
                setSearchedItem(val);
                FilterStores(val);
              }}
            />
            <TouchableOpacity
              style={customStyle.storel_searchBtn}
              onPress={() => {
                FilterStores(searchedItem);
              }}
            >
              <AntDesign style={customStyle.storel_searchBtnIcon} name="search1" size={20} color={PageTheme.$accent_color} />
            </TouchableOpacity>
          </View>

          {Object.keys(storeData).length > 0 && <View style={customStyle.Windows_Wrap}>{_renderWindow(currentMenu)}</View>}
          <View style={[customStyle.opening_Stock_btnWrap, customStyle.pb10]}>
            <GradientButton
              {...props}
              title={ST.Save}
              onPress={() => {
                onSubmitData();
              }}
            />
          </View>
        </View>
      </LinearGradient>
      {showRating == true && renderRatingView()}
      {show_zoomImage && (
        <View style={customStyle.album_ZOOM_wrap}>
          <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} index={refImageIndex} renderHeader={_renderHeader} renderIndicator={() => null} />
        </View>
      )}
    </Container>
  );
}

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