import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert,BackHandler, Animated} 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, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, 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 CameraImg from '../assets/performics/camera_front_image.svg'
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import { Picker } from '@react-native-picker/picker';
import ImageViewer from 'react-native-image-zoom-viewer';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import { ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';

function PaidVisibility(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [globalBrandData, setGlobalBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [reasons_list, setReasons_list] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [searchedItem, setSearchedItem]= useState('');

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    const zoomView=useRef(null);
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            return unsubscribe;
        };
    }, []);   

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }

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

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          let allCats=[];
          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);


          await db.transaction(async function (txn) {  
            let q2=Q_getpaidvisibility(storeData1);
            let q=`Select * From Master_NonVisibility`;
            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){
                            setReasons_list(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);

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


    async function getSKU(brands=[],storeData1={}){
        
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData1;     
        
          await db.transaction(async function (txn) { 
            let allSKUData=[];
            let completed_tasks=0;
            await Promise.all(
                brands.map(async (item,index) => {
                    let seletlist=`p.DISPLAY_ID as DisplayId,p.DISPLAY as DisplayName,p.VISIBILITY_PRESENT,p.IMAGE1,p.IMAGE2,p.REASON_ID,p.REASON,md.RefImage,p.SHOW_RSN_REMARK,p.REASON_REMARK`;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} p INNER join Master_Display md on md.DisplayId=p.DISPLAY_ID WHERE p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' and  p.SUB_CATEGORY_ID='${item.SubCategoryId}' `;
                    
                    let join=`  INNER JOIN Mapping_Visibility v on p.SubCategoryId=v.SubCategoryId `;
                    let join2=` INNER join Master_Display md on md.DisplayId=v.DisplayId `;
                    let sku_q2=`SELECT DISTINCT md.DisplayId,md.DisplayName,md.RefImage from Product_Master p  ${join} ${join2} where v.StoreId='${StoreId}' and (p.SubCategoryId='${item.SubCategoryId}' or p.SubCategoryId= ${item.SubCategoryId})`;
                    
                    let cindex=index;
                    return await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                        if(txnres.rows.length>0){
                            let arr=[];
                           
                            for(var i=0;i<txnres.rows.length;i++){
                                let data =txnres.rows.item(i);
                                
                                let ancval=data.VISIBILITY_PRESENT==1?1:0;
                                let animatedChoice=new Animated.Value(ancval);
                                let cj_index=i;
                                data.animatedChoice=animatedChoice;
                                let displayCheckList_obj=await getDisplayCheckList(data.DisplayId,item.SubCategoryId,storeData1);
                                let displayCheckList=displayCheckList_obj.Results || [];
                                data['displayCheckList']=displayCheckList;
                                arr.push(data);
                                
                                let defchecklistd=[];
                                if(displayCheckList.length>0){
                                    for(var k=0;k<displayCheckList.length;k++){
                                        let dcItem=displayCheckList[k];
                                       
                                        let obj={'ChecklistId':dcItem.ChecklistId,'ChecklistName':dcItem.ChecklistName,'AnswerId':dcItem.REASON_ID,'Answer':dcItem.REASON};
                                        defchecklistd.push(obj);
                                    }
                                }
                                let showRsnRemark=((data.SHOW_RSN_REMARK=='1' || data.SHOW_RSN_REMARK==1)?true:false);
                                let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':data.DisplayId,'isPresent':(data.VISIBILITY_PRESENT),'ReasonId':data.REASON_ID,'Reason':data.REASON,'showOtherText':showRsnRemark,'RemarkText':data.REASON_REMARK,'Image1':(data.IMAGE1 || ''),'Image2':(data.IMAGE2 || ''),'Checklist':defchecklistd};
                                
                                allSKUData.push(defData);

                                if(cj_index==txnres.rows.length-1){
                                    item['skulist']=arr;
                                    brands[index]=item;
                                    if(completed_tasks==brands.length-1){
                                        setSKUStockData(allSKUData);
                                        setBrandData(brands);
                                        setGlobalBrandData(brands);
                                        let images=[];
                                        let imgObj={imgIndex:1,url: 'https://th.parinaam.in/Download/Icon/pos_stock.png', props: {}}
                                        images.push(imgObj);
                                        
                                        setZoomImageUrl(images);
                                        setProcessing(false);
                                        
                                    }
                                    completed_tasks++;
                                    return item;
                                }
                            }
                            
                        }
                        else{
                            return await txn.executeSql(sku_q2,[],async function (txn2, txnres2) { 
                                if(txnres2.rows.length>0){
                                    let arr=[];
                                    
                                    for(var i=0;i<txnres2.rows.length;i++){
                                        let data =txnres2.rows.item(i);
                                        let cj_index=i;
                                        let animatedChoice=new Animated.Value(0);
                                        data.animatedChoice=animatedChoice;
                                        
                                        let displayCheckList_obj=await getDisplayCheckList(data.DisplayId,item.SubCategoryId,storeData1);
                                        let displayCheckList=displayCheckList_obj.Results || [];
                                        data['displayCheckList']=displayCheckList;
                                        arr.push(data);
                                        
                                        let defchecklistd=[];
                                        if(displayCheckList.length>0){
                                            for(var k=0;k<displayCheckList.length;k++){
                                                let dcItem=displayCheckList[k];
                                                let obj={'ChecklistId':dcItem.ChecklistId,'ChecklistName':dcItem.ChecklistName,'AnswerId':'0','Answer':''};
                                                defchecklistd.push(obj);
                                            }
                                        }
                                        let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':data.DisplayId,'isPresent':0,'ReasonId':0,'Reason':'','Image1':'','Image2':'','Checklist':defchecklistd};
                                        allSKUData.push(defData);
                                        
                                        
                                        if(cj_index==(txnres2.rows.length-1)){  
                                            item['skulist']=arr;
                                            brands[index]=item;
                                            if(completed_tasks==brands.length-1){
                                                setSKUStockData(allSKUData);
                                                setBrandData(brands);
                                                setGlobalBrandData(brands);
                                                let images=[];
                                                let imgObj={imgIndex:1,url: 'https://th.parinaam.in/Download/Icon/pos_stock.png', props: {}}
                                                images.push(imgObj);
                                                setZoomImageUrl(images);
                                                setProcessing(false);
                                            }
                                            completed_tasks++;
                                            return item;
                                        }               
                                    }
                                }
                                else{
                                    return item;
                                }
                                
                            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        }
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); return item; },);
                  return item;
                })
            ) .then((res)=>{
                
            });          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getDisplayCheckList(DisplayId,SubCategoryId,storeData1={}){
        var result=await new Promise((resolve, reject) => {
            db.transaction(async function (txn) { 
            
            let {StoreId}=storeData1;
            let join=`Inner join Mapping_DisplayChecklist v on p.ChecklistId=v.ChecklistId`;
            let join2=`Left join (Select * From ${AppTables.PAID_VIS_CHECKLIST} Where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SUB_CATEGORY_ID='${SubCategoryId}' and DISPLAY_ID='${DisplayId}') as T on p.ChecklistId=T.CHECKLIST_iD `;
            let q=`Select Distinct p.ChecklistId as ChecklistId,p.ChecklistName as ChecklistName ,ifnull(T.REASON,'')as REASON,ifnull(T.REASON_ID,0)as REASON_ID from Master_Checklist p ${join} ${join2} Where v.DisplayId ='${DisplayId}'`;
            
            await txn.executeSql(q,[],async function (txn2, txnres) { 
                
                if(txnres.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres.rows.length;i++){
                        let data=txnres.rows.item(i);
                        arr.push(data);
                    }
                    resolve(arr);
                }
                else{
                    resolve([]);
                }
            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); resolve([])},);

        });
        }).then((val)=>{
            return {'Results':val};
        }).catch((err)=>{
            return {'Error':err};
        });
        return result;
    }
    

    async function getImage(imgdata){
        let cat=getImageProps.cat || '';
        let skuItem=getImageProps.skuItem || '';
        let type=getImageProps.type || '';
        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.height;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

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

           console.log("time", picture_clicked_time);
           console.log("time1", picture_clicked_time_for_pic_name);
           let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
           let calculate_tym_date_over_img = picture_clicked_time;
 
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Paid Visibility'+' | Date:'+calculate_tym_date_over_img;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                           
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_PaidVisibilityImg-'+calculate_tym_date_for_filename+'.jpg';
                            
                            let allData=SKUStockData;
                            let defData={'SubCategoryId':cat.SubCategoryId,'DisplayId':skuItem.DisplayId};
                            const cindex=allData.findIndex(ci=>ci.SubCategoryId==cat.SubCategoryId && ci.DisplayId==skuItem.DisplayId);
                            const imgData=cindex>=0?(allData[cindex] || defData):defData;
                            let image_key=type=='2'?'Image2':'Image1';
                            let image_path_key=type=='2'?'Image2Path':'Image1Path';
                            imgData[image_key]=filename;
                            
                            // renamefile
                            let imagePath='file://'+`${ImageFolderPath+currentMenu.ScreenName}/`+filename;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri=imagePath;
                                console.log('image marker',uri);
                                imgData[image_path_key]=uri; 
                                cindex>=0?allData[cindex]=imgData:allData.push(imgData);
                                
                                setSKUStockData(allData);
                                setHasUnsavedChanges(true);
                                setrerenderdata2(!rerenderdata2);
                            })
                            .catch(err => {
                                    console.log(ST.Errorimagefilewritefailed+'!!!');
                                    console.log(err.message, err.code);
                            });
                                          
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(cat,skuItem,type='1'){  
        setGetImageProps({'cat':cat,'skuItem':skuItem,'type':type}); 
        setShowCamera(true);
    }

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

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   

              let q=`DELETE FROM ${AppTables.PAID_VISIBILITY_HEADER_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q2=`DELETE FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q3=`DELETE FROM ${AppTables.PAID_VIS_CHECKLIST} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('paid vis hdr data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

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

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

              let seq_q=` select seq from sqlite_sequence where name="${AppTables.PAID_VISIBILITY_HEADER_DATA}" `;
              await txn.executeSql(seq_q,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let data=txnres.rows.item(0);
                    let seq=data.seq;
                    insertData(seq);
                }
                else{
                    insertData(0);
                }
              },function (txnE,txnerr) { console.log(txnerr); insertData(0); },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function insertData(seq=0){
        try {   
            console.log(seq);
            let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData;

            await db.transaction(async function (txn) {
              var values='',child_values='',checklist_values='';
              let isChecklistExists=false;
              for(var i=0;i<brandData.length;i++){
                seq++;
                let catIndex=i;
                let item=brandData[catIndex];
                values+=values!=''?' , ':'';
                values+=` ('${StoreId}','${d2}','${item.SubCategoryName}','${item.SubCategoryId}','${d2}') `;
               
                let skulist=item['skulist'] || [];
               
                for(var j=0;j<skulist.length;j++){
                    let skuItem=skulist[j];
                    let displayCheckList=skuItem['displayCheckList'] || [];
                    child_values+=child_values!=''?' , ':'';
                    let allSKUData=SKUStockData;
                    const skud_index=allSKUData.findIndex(ci=>ci.SubCategoryId==item.SubCategoryId && ci.DisplayId==skuItem.DisplayId);
                    const skud=skud_index>=0?(allSKUData[skud_index] || {}) : {};
                    let RemarkText=skud.RemarkText!=null?skud.RemarkText:'';
                    let showOtherText=skud.showOtherText==true || skud.showOtherText=='1' ?1:0;
                    let checklist=skud['Checklist'] || [];
                    
                    child_values+=` ('${seq}','${StoreId}','${d2}','${item.SubCategoryName}','${item.SubCategoryId}','${skud.isPresent}','${skuItem.DisplayId}','${skuItem.DisplayName}','${(skud.Image1 || '')}','${(skud.Image2 || '')}','${skud.Reason}','${skud.ReasonId}','${showOtherText}','${RemarkText}','1','${d2}') `;
                    
                    if(displayCheckList.length>0 && skud.isPresent==1){
                        for(var k=0;k<displayCheckList.length;k++){
                            let dcItem=displayCheckList[k];
                            const checkeItem=checklist.find(ci=>ci.ChecklistId==dcItem.ChecklistId) || {};

                            checklist_values+=checklist_values!=''?' , ':'';
                            
                            checklist_values+=` ('${seq}','${StoreId}','${d2}','${item.SubCategoryId}','${skuItem.DisplayId}','${dcItem.ChecklistName}','${dcItem.ChecklistId}','${checkeItem.Answer}','${checkeItem.AnswerId}','${d2}') `;
                            
                            isChecklistExists=true;
                        }
                    }
                }
              }

              let add_HdrData=`INSERT INTO ${AppTables.PAID_VISIBILITY_HEADER_DATA} (STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,ADDED_DATE) VALUES ${values} `;
              let add_ChildData=`INSERT INTO ${AppTables.PAID_VISIBILITY_CHILD_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,VISIBILITY_PRESENT,DISPLAY_ID,DISPLAY,IMAGE1,IMAGE2,REASON,REASON_ID,SHOW_RSN_REMARK,REASON_REMARK,IS_UPDATED,ADDED_DATE) VALUES ${child_values} `;
              let add_Checklist=`INSERT INTO ${AppTables.PAID_VIS_CHECKLIST} (COMMON_ID,STORE_ID,VISIT_DATE,SUB_CATEGORY_ID,DISPLAY_ID,CHECKLIST,CHECKLIST_ID,REASON,REASON_ID,ADDED_DATE) VALUES ${checklist_values} `;
                
             
            
              await txn.executeSql(add_HdrData,[],async function (txn2, txnres) { 
                console.log('pv header added');
                await txn.executeSql(add_ChildData,[],async function (txn2, txnres) { 
                    console.log('pv child added');
                    if(isChecklistExists){
                        await txn.executeSql(add_Checklist,[],async function (txn2, txnres) { 
                            console.log('pv checklist added');
                            notify(ST.PaidVisibilityupdatedsuccessfully);
                            setProcessing(false);
                            props.navigation.goBack();
                        },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddpaidvisibility) },);
                    }
                    else{
                        notify(ST.PaidVisibilityupdatedsuccessfully);
                        setProcessing(false);
                        props.navigation.goBack();
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddpaidvisibility) },);
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddpaidvisibility) },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


    async function validate(){
        
        let isValid=true;
        var i=0,j=0;
        
        await Promise.all(
            brandData.map(async (item,index) => {
            if(isValid){
                
                let skulist=item.skulist || [];
                if(skulist.length>0){
                    await Promise.all(
                        skulist.map(async (skuItem,skuIndex) => {
                            if(isValid){
                                
                                let skuData=SKUStockData.find(ci=>ci.SubCategoryId==item.SubCategoryId && ci.DisplayId==skuItem.DisplayId) || {};
                                let displayCheckList=skuItem['displayCheckList'] || [];

                                let showOtherText=skuData.showOtherText!=null?skuData.showOtherText:false;
                                
                                let isCamera1EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera1Enable')
                                let isCamera1EnableKPIObj=isCamera1EnableIndex>=0?KPIFields[isCamera1EnableIndex]:{};
                                let isCamera1Enable=isCamera1EnableIndex>=0?isCamera1EnableKPIObj['KPIFieldEnable']:true;
                                
                                let isCamera2EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera2Enable')
                                let isCamera2EnableKPIObj=isCamera2EnableIndex>=0?KPIFields[isCamera2EnableIndex]:{};
                                let isCamera2Enable=isCamera2EnableIndex>=0?isCamera2EnableKPIObj['KPIFieldEnable']:true;

                                let isCamera1MandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera1Mandatory')
                                let isCamera1MandKPIObj=isCamera1MandIndex>=0?KPIFields[isCamera1MandIndex]:{};
                                let isCamera1Mand=isCamera1MandIndex>=0?isCamera1MandKPIObj['KPIFieldEnable']:true;

                                let isCamera2MandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera2Mandatory')
                                let isCamera2MandKPIObj=isCamera2MandIndex>=0?KPIFields[isCamera2MandIndex]:{};
                                let isCamera2Mand=isCamera2MandIndex>=0?isCamera2MandKPIObj['KPIFieldEnable']:true;

                                
                               
                                console.log('isCamera1Mand:',isCamera1Mand,',isCamera2Mand:',isCamera2Mand)


                                if(skuData.isPresent!=0 && (skuData.isPresent==null || skuData.isPresent=='')){
                                    notify(ST.Pleaseselectifvisiblitypresentornotfor+' '+item.SubCategoryName+' '+skuItem.DisplayName,'SHORT');
                                    isValid=false;
                                }
                                else if(skuData.isPresent==0 && (skuData.ReasonId==null || skuData.ReasonId=='')){
                                    notify(ST.Pleaseselectreasonfor+' '+item.SubCategoryName+' '+skuItem.DisplayName,'SHORT');
                                    isValid=false;
                                }
                                else if(skuData.isPresent==0 && showOtherText==true && ( skuData.RemarkText==null || skuData.RemarkText=='')){
                                    notify(ST.PleaseEnterRemarkFor+' '+item.SubCategoryName+' '+skuItem.DisplayName,'SHORT');
                                    isValid=false;
                                }
                                else if(skuData.isPresent==1 && (((isCamera1Enable==1 || isCamera1Enable=='true') && (isCamera1Mand==1 || isCamera1Mand=='true') && (skuData.Image1==null || skuData.Image1=='') )|| ((isCamera2Enable==1 || isCamera2Enable=='true') && (isCamera2Mand==1 || isCamera2Mand=='true') && (skuData.Image2==null || skuData.Image2=='')))){
                                    notify(ST.Pleaseclickallimagesfor+' '+item.SubCategoryName+' '+skuItem.DisplayName,'SHORT');
                                    isValid=false;
                                }else if(skuData.isPresent==1){
                                    if(displayCheckList.length>0){
                                        await Promise.all(
                                            displayCheckList.map(async (dclistItem,dcIndex) => {
                                                if(isValid){
                                                    const skud_ckecklist=skuData['Checklist'] || [];
                                                    let checkedItem=skud_ckecklist.find(c=>c.ChecklistId==dclistItem.ChecklistId) || {};
                                                    
                                                    if(checkedItem['AnswerId']!=0 && (checkedItem['AnswerId']==null || checkedItem['AnswerId']=='')){
                                                        isValid=false;
                                                        notify(ST.Pleaseselectreasonfor+' '+item.SubCategoryName+' '+skuItem.DisplayName+' '+dclistItem.ChecklistName,'SHORT');
                                                    }
                                                }
                                            })
                                        );
                                    }
                                }
                            }
                        })
                    );
                }
                    
                
            }
            })
        );

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

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

        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':skuItem.DisplayId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && i.DisplayId==skuItem.DisplayId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;
        if(key=='ReasonId'){
            let rsn=reasons_list.find(r=>r.ReasonId==val) || {};
            skud['Reason']=rsn.Reason || '';
        }
        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    

    function onChoiceSelect(item,skuItem,val,key,animatedChoice){
        console.log('onChoiceSelect',animatedChoice)
       
        var val1=0;
        if(val==1){
            val1=1;
        }
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onStockValChange(item,skuItem,val,key)
    }

    function onselectionChange(option,keyLbl,keyVal,otherData){
        let skuItem=otherData.skus,item=otherData.cat;
        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':skuItem.DisplayId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && i.DisplayId==skuItem.DisplayId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[keyVal]=option.value;
        skud[keyLbl]=option.label;

        
        if(keyLbl=='Reason'){
            let rsn_Index=reasons_list.findIndex(i=>i.ReasonId==option.value);
          
            if(rsn_Index>=0){
                let rsn=reasons_list[rsn_Index];
                let IsRemarkTaken=rsn.IsRemarkTaken==1 || rsn.IsRemarkTaken=='1'?true:false;
                console.log('on reason change IsRemarkTaken :',IsRemarkTaken);
                if(IsRemarkTaken==true){
                    skud['showOtherText']=true;
                }
                else{
                    skud['showOtherText']=false;
                }
            }
        }

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        console.log('allSKUData:',allSKUData);
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onStockCheckListChange(option,keyLbl,keyVal,otherData){
        let skuItem=otherData.skus,item=otherData.cat,dclistItem=otherData.dclist;
        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':skuItem.DisplayId,'Checklist':[]};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && i.DisplayId==skuItem.DisplayId);
        let skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        let skud_ckecklist=skud['Checklist'] || [];
        let defCheckedItem={"ChecklistId": dclistItem.ChecklistId, "ChecklistName": dclistItem.ChecklistName};
        let checkedItem_index=skud_ckecklist.findIndex(c=>c.ChecklistId==dclistItem.ChecklistId);
        let checkedItem=checkedItem_index>=0?(skud_ckecklist[checkedItem_index] || defCheckedItem):defCheckedItem;
        
        checkedItem['AnswerId']=option.value;
        checkedItem['Answer']=option.label;
        
        
        checkedItem_index>=0?skud_ckecklist[checkedItem_index]=checkedItem:skud_ckecklist.push(checkedItem);
        skud['Checklist']=skud_ckecklist;

        skud_index>=0?allSKUData[skud]=checkedItem:allSKUData.push(skud);
        console.log('allSKUData:',allSKUData);
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

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

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2=[];
        if(searchedQry!=null && searchedQry!=''){
            // globalBrandData.map((item,index)=>{
            for(let i=0;i<globalBrandData.length;i++){
                let item=globalBrandData[i];
                let skulist=item.skulist || [];
                arr2={ 'SubCategoryName':item.SubCategoryName,'SubCategoryId':item.SubCategoryId};
                let newSkulist=[];
                let isCatFound=false;
                if(item.SubCategoryName.toLowerCase().includes(searchedQry)){
                    isCatFound=true;
                }
                // skulist.map((sku,j)=>{
                for(let j=0;j<skulist.length;j++){
                    let sku=skulist[j];
                    let {DisplayName}=sku;
                    if(DisplayName.toLowerCase().includes(searchedQry)){
                        newSkulist.push(sku);
                    }
                    
                    if(j==skulist.length-1){
                        arr2.skulist=newSkulist;
                        if(isCatFound==true){
                            arr2.skulist=skulist;
                            arr.push(arr2);
                        }
                        else if(arr2.skulist.length>0){
                            arr.push(arr2);
                        }
                    }
                }

                
            }
        }
        else{
          arr=globalBrandData;
        }

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

    function _render_Alert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={ST.Doyoureallywanttosavedata}
            showModal={showAlert}
          >
            <View style={customStyle.storelVisitM_options}>
             <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowAlert(false)}}>
                <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{saveData()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>{ST.Yes}</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
      }

    function _renderHeader(currentIndex){        
        return(
            <View style={customStyle.album_ZOOM_topBar}>
                {/* <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text> */}
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{console.log('tsth');setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#000'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true}  title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_render_Alert()}
        <CustomCamera cameraType={'back'} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                autoComplete='off'
                placeholder={ST.SearchbyDisplayNameorSubCategoryName}
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                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 &&            
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            initialNumToRender={4}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                const cindex=catImages.findIndex(i=>i.SubCategoryId==item.SubCategoryId);
                const cimgName=cindex>=0?(catImages[cindex]?catImages[cindex].ImageName:''):'';
                const cimgPath=cindex>=0?(catImages[cindex]?catImages[cindex].ImagePath:''):'';
                const showIMg=cimgPath!='' && cimgPath!=null;
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={customStyle.opening_Stock_catText}>{item.SubCategoryName}</Text>
                        
                            </LinearGradient>
                            
                        </View>
                        <View style={customStyle.opening_Stock_prds}>
                            {
                                
                                <FlatList 
                                data={item.skulist}
                                extraData={rerenderdata2}
                                renderItem={({item,index})=>{
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.SubCategoryId==cat.SubCategoryId && i.DisplayId==skus.DisplayId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let ReasonId=thisCatSkuData.ReasonId!=null?thisCatSkuData.ReasonId:'';
                                    let Reason=thisCatSkuData.Reason!=null?thisCatSkuData.Reason:'';
                                    let isPresent=thisCatSkuData.isPresent!=null?thisCatSkuData.isPresent:'0';
                                    let showOtherText=thisCatSkuData.showOtherText!=null?thisCatSkuData.showOtherText:false;
                                    let RemarkText=thisCatSkuData.RemarkText!=null?thisCatSkuData.RemarkText:'';
                                    let Image1=(thisCatSkuData.Image1!=null && thisCatSkuData.Image1!='')?'file://'+`${ImageFolderPath+currentMenu.ScreenName}/`+thisCatSkuData.Image1:'';
                                    let Image2=(thisCatSkuData.Image2!=null && thisCatSkuData.Image2!='')?'file://'+`${ImageFolderPath+currentMenu.ScreenName}/`+thisCatSkuData.Image2:'';
                                    let RefImage=skus.RefImage;
                                    let displayCheckList=item.displayCheckList || [];

                                    let isCamera1EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera1Enable')
                                    let isCamera1EnableKPIObj=isCamera1EnableIndex>=0?KPIFields[isCamera1EnableIndex]:{};
                                    let isCamera1Enable=isCamera1EnableIndex>=0?isCamera1EnableKPIObj['KPIFieldEnable']:true;
                                    
                                    let isCamera2EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera2Enable')
                                    let isCamera2EnableKPIObj=isCamera2EnableIndex>=0?KPIFields[isCamera2EnableIndex]:{};
                                    let isCamera2Enable=isCamera2EnableIndex>=0?isCamera2EnableKPIObj['KPIFieldEnable']:true;
                                    
                                   
                                    var xpos=isPresent==1?-75:0;
                                    if(skus.animatedChoice!=null ){
                                        xpos=skus.animatedChoice.interpolate({
                                            inputRange:[0,1],
                                            outputRange:[0,-75],
                                        });
                                    }

                                    
                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={[customStyle.openStk_prd_name]}>{skus.DisplayName}</Text>
                                            
                                            <View style={customStyle.openStk_prd_form}>
                                                
                                                <View style={[customStyle.openStk_prd_cols,customStyle.openStk_prd_borderT,customStyle.mt10,customStyle.pt10]}>
                                                    <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'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                                                {
                                                                    transform: [{
                                                                        translateX:xpos
                                                                    }],
                                                                }
                                                                ]}></Animated.View>
                                                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(cat,skus,1,'isPresent',skus.animatedChoice)}}>
                                                                    <Text style={[customStyle.openStkCh_text,(isPresent=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                                                </TouchableOpacity>
                                                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(cat,skus,0,'isPresent',skus.animatedChoice)}}>
                                                                    <Text style={[customStyle.openStkCh_text,(isPresent=='0'?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                                                </TouchableOpacity>
                                                            </View>
                                                        </View>
                                                    </View>
                                                    {isPresent!='1' && 
                                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                                                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange} selected_data={{value:Reason,otherData:{cat:cat,skus:skus}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                                                    </View>
                                                    }
                                                    {isPresent!='1' && showOtherText==true && 
                                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.EnterRemark}</Text>
                                                        <TextInput 
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                                            placeholder=""  
                                                            autoComplete='off'          
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={RemarkText}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'RemarkText','text')}}
                                                        />
                                                    </View>
                                                    }
                                                    {(isPresent=='1' && displayCheckList.length>0) && 
                                                    displayCheckList.map((dclist_Item,dclist_index)=>{
                                                        const dclist=dclist_Item;
                                                        
                                                        const skud=SKUStockData.find(ci=>ci.SubCategoryId==cat.SubCategoryId && ci.DisplayId==skus.DisplayId) || {};
                                                        const skud_ckecklist=skud['Checklist'] || [];
                                                        let checkedItem=skud_ckecklist.find(c=>c.ChecklistId==dclist.ChecklistId) || {};
                                                        
                                                        let dclist_answerid=checkedItem['AnswerId'] || '0';
                                                        let dclist_answer=checkedItem['Answer'] || '';
                                                        const dclist_options=[{'dcItem':'No','dcItemId':'0'},{'dcItem':'Yes','dcItemId':'1'}];
                                                        return(
                                                        <View key={dclist_index} style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                                            <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{dclist.ChecklistName}</Text>
                                                            {<CustomPicker2 {...props} Pickerdata={dclist_options} label_key={'dcItem'} value_key={'dcItemId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onStockCheckListChange} selected_data={{value:dclist_answer,otherData:{cat:cat,skus:skus,dclist:dclist}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                                                        </View>
                                                        );
                                                    })
                                                    
                                                    }
                                                    {(isPresent=='1' && ( (isCamera1Enable=='true' || isCamera1Enable==1) || (isCamera2Enable=='true' || isCamera2Enable==1) )) && 
                                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                                        <Text style={[customStyle.openStk_prd_label]}>{ST.CaptureImage}</Text>
                                                        <View style={customStyle.openStk_prdCameras}>
                                                            { (isCamera1Enable=='true' || isCamera1Enable==1)  &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                { (Image1=='' || Image1==null) && 
                                                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(cat,skus,'1')}}>
                                                                        <CameraImg width={80} height={80} />                                     
                                                                    </TouchableOpacity>
                                                                }
                                                                { (Image1!='' && Image1!=null) && 
                                                                    <View style={customStyle.osCatImageView}>
                                                                        <Image style={customStyle.osCatImage} source={{uri:Image1}}/>
                                                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(cat,skus,'1')}}>
                                                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                                        </TouchableOpacity>
                                                                    </View>                                    
                                                                }       
                                                                </View>
                                                            }
                                                            { (isCamera2Enable=='true' || isCamera2Enable==1)  &&
                                                                <View style={customStyle.openStkCameraCon}>
                                                                { (Image2=='' || Image2==null) && 
                                                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(cat,skus,'2')}}>
                                                                        <CameraImg width={80} height={80} />                                     
                                                                    </TouchableOpacity>
                                                                }
                                                                { (Image2!='' && Image2!=null)  && 
                                                                    <View style={customStyle.osCatImageView}>
                                                                        <Image style={customStyle.osCatImage} source={{uri:Image2}}/>
                                                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(cat,skus,'2')}}>
                                                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                                        </TouchableOpacity>
                                                                    </View>                                    
                                                                }       
                                                                </View>
                                                            }  
                                                                              
                                                        </View>
                                                    </View>
                                                    }
                                                    
                                                </View>
                                            
                                            </View>
                                            <TouchableOpacity style={customStyle.openStk_refImageBtn} onPress={()=>{openImageRefView(RefImage)}}>
                                                <Entypo name='image-inverted' size={24} color={'#1f7dbc'} />    
                                            </TouchableOpacity>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} 
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }  
      </Container>   
    ); 
}
  
  

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