import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated, AppState, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2,resizeImage,restore_ImageWithMetaData,validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, FontAwesome, MaterialCommunityIcons} 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 CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

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

    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Companies, setCompanies] = useState([]);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [Products, setProducts] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [toRemoveId,setToRemoveId]= useState('');
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);
    const [showRAllC_M,setShowRAllC_M]= useState(false);

    
    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(AddVisibility);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');


    const VisFormDataRef=React.useRef(AddVisFormData);
    const isAddVisPresentRef=React.useRef(isAddVisPresent);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();
            return unsubscribe;
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               AddFormData:VisFormDataRef.current,
               isVisPresent:isAddVisPresentRef.current,
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
        // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(AddVisibility,AddVisFormData,isAddVisPresent,pro)});
        // AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(AddVisibility,AddVisFormData,isAddVisPresent,pro)});
    }, [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 BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

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

    function BgAddVisFormData(val){
        VisFormDataRef.current=val
        setAddVisFormData(val);
    }

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

    async function getData(storeData1,menu1){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=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 storeBGData1=[],bgStoreJson={},isBgDataExists=false;
            let windData = await get_item('storeData')
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,AddFormData,visiteDate,isVisPresent }= StoreJson
                if(menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    isBgDataExists=true;

                    // Check if isVisPresent data exists in bg data
                    let bgPresent=isVisPresent==1?1:0;
                    Animated.timing(animatedChoice, {
                        toValue: bgPresent,
                        duration:400,
                        useNativeDriver:false,
                    }).start();
                    BgIsAddVisPresent(bgPresent);

                    // Check if added visibilities data exists in bg data
                    if(storeBGData.length>0){
                        storeBGData1=storeBGData;
                        bgStoreJson=StoreJson
                        BgWindowData(storeBGData)
                        BgAddVisFormData(AddFormData)
                    }

                    // Check if form data exists in bg data
                    if(AddFormData!=null && Object.keys(AddFormData).length>0){
                        let {CategoryId,SubCategoryId,CompanyId,BrandId}=AddFormData;
                        // load categories if company exists 
                        if(CompanyId!=null && CompanyId!=''){
                            loadData(CompanyId,'Categories');
                        }
                        // load subcategories if category exists 
                        if(CategoryId!=null && CategoryId!=''){
                            loadData(CategoryId,'SubCategories','','',CompanyId);
                        }
                        // load brands if subcategory exists 
                        if(SubCategoryId!=null && CategoryId!=''){
                            loadData(SubCategoryId,'Brands',CategoryId,'',CompanyId);
                        }
                        // load products if brand exists 
                        if(BrandId!=null && BrandId!=''){
                            loadData(BrandId,'Products',CategoryId,SubCategoryId,CompanyId);
                        }

                        BgAddVisFormData(AddFormData)
                    }
                    BgUnsavedChanges(true)
                }
            }
            
            await db.transaction(async function (txn) {        
                
                let q4=`Select distinct CompanyId,Company from Master_Competitor order by Company`;
                await txn.executeSql(q4,[],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){setCompanies(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                let q2=`SELECT * from Master_PromoType order by PromoType`;
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    console.log('displays',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){setDisplayList(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                
                let q3=`Select * from ${AppTables.COMPETITION_PROMOTION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                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);
                            let {PRESENT,COMPANY,COMPANY_ID,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,PROMO_TYPE,PROMO_TYPE_ID,PRODUCT,PRODUCT_ID,PROMO_DETAILS,MRP,SELLING_PRICE,GRAMMAGE,DISCOUNT_PERCENT,IMAGE,IMAGE2,IMAGE3,KEY_ID}=data;
                            
                            let datan={Company:COMPANY,CompanyId:COMPANY_ID,CategoryName:CATEGORY,CategoryId:CATEGORY_ID,SubCategoryName:SUB_CATEGORY,SubCategoryId:SUB_CATEGORY_ID,BrandName:BRAND,BrandId:BRAND_ID,PromoType:PROMO_TYPE,PromoTypeId:PROMO_TYPE_ID,ProductName:PRODUCT,ProductId:PRODUCT_ID,Remark:PROMO_DETAILS,MRP:MRP,SPrice:SELLING_PRICE,Grammage:GRAMMAGE,DiscountPercent:DISCOUNT_PERCENT,Image1:IMAGE,Image2:IMAGE2,Image3:IMAGE3,keyId:KEY_ID}
                            datan.Image1Path="file://"+ImageFolderPath+menu1.ScreenName+"/"+IMAGE;
                            datan.Image2Path=IMAGE2!="" && IMAGE2!=null && IMAGE2!="undefined" ?"file://"+ImageFolderPath+menu1.ScreenName+"/"+IMAGE2:"";
                            datan.Image3Path=IMAGE3!="" && IMAGE3!=null && IMAGE3!="undefined" ?"file://"+ImageFolderPath+menu1.ScreenName+"/"+IMAGE3:"";
                            PRESENT==1? arr.push(datan):'';
                            let isPresent=PRESENT;
                            if(i==txnres2.rows.length-1){
                                let { menuName,StoreId1,isVisPresent,visiteDate}=bgStoreJson
                                if(!isBgDataExists){
                                    BgWindowData(arr);
                                    Animated.timing(animatedChoice, {
                                        toValue: isPresent,
                                        duration:400,
                                        useNativeDriver:false,
                                    }).start();
                                    BgIsAddVisPresent(isPresent);
                                }
                                setProcessing(false);
                            }                                
                        }
                    }else{
                        
                        setProcessing(false);
                    }
                },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);

               

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



    async function getImage(imgdata){
        let type=getImageProps.type || '';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
            let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

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

            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_CompPromoImg-'+calculate_tym_date_for_filename+'.jpg';
            console.log(filename,"file_name");
        
            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: Comp. Promotion'+' | Date:'+calculate_tym_date_over_img;
            
            let addvisdata=AddVisFormData;
            let image_key=`Image${type}`;
            let image_path_key=`Image${type}Path`;
            addvisdata[image_key]=filename;
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            // file resized now rename file
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                addvisdata[image_path_key]=uri; 

                BgAddVisFormData(addvisdata)
                BgUnsavedChanges(true)
                setrerenderdata2(!rerenderdata2);

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
            })
            .catch(err => {
                console.log('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });        
        } 
        
    }
  
    async function openCamera(type='1'){  
        setGetImageProps({'type':type}); 
        setShowCamera(true);
    }

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

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

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

              var values='';
              if(isAddVisPresent==1 && AddVisibility.length>0){
                for(var i=0;i<AddVisibility.length;i++){
                    let catIndex=i;
                    let item=AddVisibility[catIndex];
                    let {Company,CompanyId,CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,PromoType,PromoTypeId,ProductId,ProductName,Remark,MRP,SPrice,Image1,Image1Path,DiscountPercent,Grammage,Image2,Image2Path,Image3,Image3Path}=item;
                    values+=values!=''?' , ':'';
                    values+=` ('${StoreId}','${d2}','${isAddVisPresent}','${Company}','${CompanyId}','${CategoryName}','${CategoryId}','${SubCategoryName}','${SubCategoryId}','${BrandName}','${BrandId}','${(PromoType || '')}','${(PromoTypeId || '')}','${(ProductName || '')}','${(ProductId || '')}','${Remark}','${MRP}','${SPrice}','${DiscountPercent}','${Grammage}','${Image1}','${Image2}','${Image3}','${d2}') `;
                    
                }
              }
              else{
                values+=` ('${StoreId}','${d2}','${isAddVisPresent}','','','','','','','','','','','','','','','','','','','','','${d2}') `;
              }
              
              console.log('values:',values);
              let add_data=`INSERT INTO ${AppTables.COMPETITION_PROMOTION} (STORE_ID,VISIT_DATE,PRESENT,COMPANY,COMPANY_ID,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,PROMO_TYPE,PROMO_TYPE_ID,PRODUCT,PRODUCT_ID,PROMO_DETAILS,MRP,SELLING_PRICE,DISCOUNT_PERCENT,GRAMMAGE,IMAGE,IMAGE2,IMAGE3,ADDED_DATE) VALUES ${values} `;
             
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('cp added');
                notify('Competition Promotion added successfully','SHORT');
                setProcessing(false);
                 // clear store data in local storage to avoiding re-set data for the store  
                clear_item('storeData')
                props.navigation.goBack();
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add competition Promotion') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    


    async function validate(){
        let isValid=true;
        if(isAddVisPresent==1 && AddVisibility.length<=0){
            isValid=false;
            notify('Please add first','SHORT');
        }

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

    async function validateForm(){
        let isValid=true;
        let {Company,CompanyId,CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,PromoType,PromoTypeId,ProductName,ProductId,Remark,Image1,Image1Path,MRP,SPrice,DiscountPercent,Grammage,Image2,Image2Path,Image3,Image3Path}=AddVisFormData;
        
        let CompPromoSellingPriceI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoSellingPrice');
        let CompPromoSellingPriceObj=CompPromoSellingPriceI>=0?KPIFields[CompPromoSellingPriceI]:{};
        let CompPromoSellingPrice=CompPromoSellingPriceI>=0?CompPromoSellingPriceObj['KPIFieldEnable']:true;
        let CompPromoSellingPriceLabel=CompPromoSellingPriceI>=0?CompPromoSellingPriceObj['KPIFieldDisplayName']:"Selling Price";

        let CompPromoGrammageI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoGrammage');
        let CompPromoGrammageObj=CompPromoGrammageI>=0?KPIFields[CompPromoGrammageI]:{};
        let CompPromoGrammage=CompPromoGrammageI>=0?CompPromoGrammageObj['KPIFieldEnable']:false;
        let CompPromoGrammageLabel=CompPromoGrammageI>=0?CompPromoGrammageObj['KPIFieldDisplayName']:"Grammage";

        let CompPromoDPerI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoDiscountPercent');
        let CompPromoDPerObj=CompPromoDPerI>=0?KPIFields[CompPromoDPerI]:{};
        let CompPromoDPer=CompPromoDPerI>=0?CompPromoDPerObj['KPIFieldEnable']:false;
        let CompPromoDPerLabel=CompPromoDPerI>=0?CompPromoDPerObj['KPIFieldDisplayName']:"Discount %";

        let CompPromoShowImage1I=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage1');
        let CompPromoShowImage1Obj=CompPromoShowImage1I>=0?KPIFields[CompPromoShowImage1I]:{};
        let CompPromoShowImage1=CompPromoShowImage1I>=0?CompPromoShowImage1Obj['KPIFieldEnable']:true;
        let CompPromoShowImage1Label=CompPromoShowImage1I>=0?CompPromoShowImage1Obj['KPIFieldDisplayName']:"Image";
      
        let CompPromoShowImage2I=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage2');
        let CompPromoShowImage2Obj=CompPromoShowImage2I>=0?KPIFields[CompPromoShowImage2I]:{};
        let CompPromoShowImage2=CompPromoShowImage2I>=0?CompPromoShowImage2Obj['KPIFieldEnable']:false;
        let CompPromoShowImage2Label=CompPromoShowImage2I>=0?CompPromoShowImage2Obj['KPIFieldDisplayName']:"Image";
        
        let CompPromoGramImageI=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage3');
        let CompPromoGramImageObj=CompPromoGramImageI>=0?KPIFields[CompPromoGramImageI]:{};
        let CompPromoGramImage=CompPromoGramImageI>=0?CompPromoGramImageObj['KPIFieldEnable']:false;
        let CompPromoGramImageLabel=CompPromoGramImageI>=0?CompPromoGramImageObj['KPIFieldDisplayName']:"Grammage Image";
        

        if((Company=='' || Company==null )|| (CompanyId=='' || CompanyId==null)){
            isValid=false;
            notify('Please select company','SHORT');
        }
        else if((CategoryName=='' || CategoryName==null )|| (CategoryId=='' || CategoryId==null)){
            isValid=false;
            notify('Please select category','SHORT');
        }
        else if((SubCategoryName=='' || SubCategoryName==null )|| (SubCategoryId=='' || SubCategoryId==null)){
            isValid=false;
            notify('Please select sub category','SHORT');
        }
        else if((BrandName=='' || BrandName==null )|| (BrandId=='' || BrandId==null)){
            isValid=false;
            notify('Please select brand','SHORT');
        }
        else if((ProductId=='' || ProductId==null )|| (ProductId=='' || ProductId==null)){
            isValid=false;
            notify('Please select product','SHORT');
        }
        else if(CompPromoGrammage && (Grammage=='' || Grammage==null || (Grammage!=null && parseInt(Grammage)<=0))){
            isValid=false;
            notify('Please enter '+CompPromoGrammageLabel,'SHORT');
        }
        else if((PromoTypeId=='' || PromoTypeId==null ) || (PromoType=='' || PromoType==null)){
            isValid=false;
            notify('Please select promotion type','SHORT');
        }
        else if(CompPromoDPer && DiscountPercent!==0 && (DiscountPercent=='' || DiscountPercent==null)){
            isValid=false;
            notify('Please enter '+CompPromoDPerLabel,'SHORT');
        }
        else if((MRP=='' || MRP==null || (SPrice!=null && parseInt(SPrice<=0)) )){
            isValid=false;
            notify('Please enter MRP','SHORT');
        }
        else if(CompPromoSellingPrice && (SPrice=='' || SPrice==null || (SPrice!=null && parseInt(SPrice)<=0))){
            isValid=false;
            notify('Please enter '+CompPromoSellingPriceLabel,'SHORT');
        }
        else if(CompPromoSellingPrice && parseInt(SPrice)>parseInt(MRP)){
            isValid=false;
            notify('Selling price should not be greater than MRP','SHORT');
        }
        else if((Remark=='' || Remark==null )){
            isValid=false;
            notify('Please enter remark','SHORT');
        }
        else if(StoreCameraAllow && CompPromoShowImage1 && (Image1=='' || Image1==null )){
            isValid=false;
            notify('Please click '+CompPromoShowImage1Label,'SHORT');
        }
        else if(StoreCameraAllow && CompPromoShowImage2 && (Image2=='' || Image2==null )){
            isValid=false;
            notify('Please click '+CompPromoShowImage2Label,'SHORT');
        }
        else if(StoreCameraAllow && CompPromoGramImage && (Image3=='' || Image3==null )){
            isValid=false;
            notify('Please click '+CompPromoGramImageLabel,'SHORT');
        }

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

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

        let data=AddVisFormData;
        data[key]=val;
        // setAddVisFormData(data);
        // setHasUnsavedChanges(true);
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option,keyLbl,keyVal){
        
        let data=AddVisFormData;
        data[keyVal]=option.value;
        data[keyLbl]=option.label;
        // setAddVisFormData(data);
        // setHasUnsavedChanges(true);
       
        if(keyLbl=='Company'){
            loadData(option.value,'Categories');

            let newObj={};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;
        }
        else if(keyLbl=='CategoryName'){
            loadData(option.value,'SubCategories','','',AddVisFormData.CompanyId);

            
            let newObj={"CompanyId":AddVisFormData.CompanyId,"Company":AddVisFormData.Company};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;
        }
        else if(keyLbl=='SubCategoryName'){
            loadData(option.value,'Brands',AddVisFormData.CategoryId,'',AddVisFormData.CompanyId);

            
            let newObj={"CompanyId":AddVisFormData.CompanyId,"Company":AddVisFormData.Company,"CategoryId":AddVisFormData.CategoryId,"CategoryName":AddVisFormData.CategoryName};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;

        }
        else if(keyLbl=='BrandName'){
            loadData(option.value,'Products',AddVisFormData.CategoryId,AddVisFormData.SubCategoryId,AddVisFormData.CompanyId);

            
            let newObj={"CompanyId":AddVisFormData.CompanyId,"Company":AddVisFormData.Company,"CategoryId":AddVisFormData.CategoryId,"CategoryName":AddVisFormData.CategoryName,"SubCategoryId":AddVisFormData.SubCategoryId,"SubCategoryName":AddVisFormData.SubCategoryName};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;

        }
        else if(keyLbl=='ProductName'){
            let newObj={"CompanyId":AddVisFormData.CompanyId,"Company":AddVisFormData.Company,"CategoryId":AddVisFormData.CategoryId,"CategoryName":AddVisFormData.CategoryName,"SubCategoryId":AddVisFormData.SubCategoryId,"SubCategoryName":AddVisFormData.SubCategoryName,"BrandId":AddVisFormData.BrandId,"BrandName":AddVisFormData.BrandName};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;
        }
        else if(keyLbl=='PromoType'){
            let newObj={"CompanyId":AddVisFormData.CompanyId,"Company":AddVisFormData.Company,"CategoryId":AddVisFormData.CategoryId,"CategoryName":AddVisFormData.CategoryName,"SubCategoryId":AddVisFormData.SubCategoryId,"SubCategoryName":AddVisFormData.SubCategoryName,"BrandId":AddVisFormData.BrandId,"BrandName":AddVisFormData.BrandName,"ProductId":AddVisFormData.ProductId,"ProductName":AddVisFormData.ProductName,"Grammage":(AddVisFormData.Grammage!=null?AddVisFormData.Grammage:'')};
            newObj[keyVal]=option.value;
            newObj[keyLbl]=option.label;
            data=newObj;
        }
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);

        
    }

    async function loadData(qId,type,CatId,SubCatId,CompanyId){
        try {   
        await db.transaction(async function (txn) { 
            let q=''; 
            if(type=='Categories') q=`select distinct CategoryId,CategoryName from Master_Competitor where (CompanyId ='${qId}' or CompanyId = ${qId}) order by CategoryName`;
            else if(type=='SubCategories') q=`Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where (p.CategoryId='${qId}' or p.CategoryId=${qId}) and (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) order by p.SubCategorySequence`;
            else if(type=='Brands') q=`Select Distinct p.BrandName,p.BrandId from Product_Master p Where (p.SubCategoryId='${qId}' or p.SubCategoryId=${qId}) and (CategoryId='${CatId}' or CategoryId= ${CatId}) and (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) order by p.BrandSequence`;
            else if(type=='Products') q=`select distinct ProductId,ProductName from Product_Master where (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) and (CategoryId='${CatId}' or CategoryId= ${CatId}) and  (SubCategoryId='${SubCatId}' or SubCategoryId= ${SubCatId}) and (BrandId='${qId}' or BrandId=${qId}) order by ProductSequence`;
           
        
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                
                if(txnres2.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            if(type=='Categories') setCategories(arr);
                            else if(type=='SubCategories')setSubCategories(arr);
                            else if(type=='Brands')setBrands(arr);
                            else if(type=='Products')setProducts(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
           
          });          
        } catch (err) {
          console.log(err);          
        }
    }

  
   
    function onChoiceSelect(val,key){
        if(val==0 && AddVisibility.length>0){
            setShowRAllC_M(true);
            return ;
        }
        var val1=val==1?1:0;
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        // setIsAddVisPresent(val);
        // setHasUnsavedChanges(true);
        BgIsAddVisPresent(val);
        BgUnsavedChanges(true)
        if(val==0){
            setAddVisibility([]);
            setAddVisFormData({});
        }
    }

    function onConfirmRemoveAll(){
        // Remove all data 
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        // setIsAddVisPresent(0);
        // setHasUnsavedChanges(true);
        BgIsAddVisPresent(0);
        BgUnsavedChanges(true)
        // setAddVisibility([]);
        // setAddVisFormData({});
        BgWindowData([])
        BgAddVisFormData({})
        setShowRAllC_M(false);
    }


    function onSaveCancel(){
        setShowAlert(false);
    }

    async function Add_AddVis(){
        let isValid=await validateForm();
        console.log('isValid add:',isValid);
        if(isValid){
            let arr=AddVisibility;
            let {Company,CompanyId,CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,PromoType,PromoTypeId,ProductName,ProductId,Remark,DisplayId}=AddVisFormData;
            console.log(AddVisFormData);
            // let index=AddVisibility.findIndex(i=> i.CompanyId==CompanyId && i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId && i.PromoTypeId==PromoTypeId && i.ProductId==ProductId);
            // if(index>=0){
            //     notify('This promotion has already been added','LONG');
            // }
            // else{
                arr.push(AddVisFormData);
                // setAddVisibility(arr);
                // setHasUnsavedChanges(true);
                BgWindowData(arr)
                BgUnsavedChanges(true)
                notify('Promotion added successfully','LONG');
                setrerenderdata(!rerenderdata);
                
                // clear data
                // setAddVisFormData({});
                BgAddVisFormData({})
            // }
        } 
        
    }

    function showRemoveConfirm(item,index){
        // setToRemoveId(index);
        // setToRemoveItem(item);
        // setshowRemoveConfirm_M(true);
        if(item.keyId>0){
            setToRemoveId(item.keyId);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
        else{
            setToRemoveId(index);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
    }

    // function Remove_AddVis(){
    //     let index=toRemoveId
    //     let item=toRemoveItem;
    //     let arr=AddVisibility;
    //     console.log('toRemoveId:',index);
    //     if(index>=0 && index<arr.length){
    //         arr.splice(index,1);
    //         // setAddVisibility(arr);
    //         // setHasUnsavedChanges(true);
    //         BgWindowData(arr)
    //         BgUnsavedChanges(true)
    //         notify('Promotion removed successfully','LONG')
    //         setrerenderdata(!rerenderdata);
    //     }
    //     else{
    //         notify('Cannot remove! Promotion not found','LONG')
    //     }
        
    //     setToRemoveId('');
    //     setToRemoveItem({});
    //     setshowRemoveConfirm_M(false);
    // }
   

    async function Remove_AddVis() {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
        let { MenuId } = currentMenu;
      
        db.transaction(async function (txn) {          
                let index = toRemoveId;
                console.log("indexxx----",index)
                let item = toRemoveItem;
                let arr = AddVisibility;
                if (item.keyId!=null && item.keyId!='undefined' && index>0) {
                        console.log("check-keyId-",index)               
                        let deleteQuery=`DELETE FROM ${AppTables.COMPETITION_PROMOTION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND KEY_ID='${index}' `;

                            txn.executeSql(deleteQuery, [], function (txn3, txnres) {
                                console.log('Promotion data deleted', item.keyId,+""+index);
                                let updatedVisibility = AddVisibility.filter(item => item.keyId !== index);
                                setAddVisibility(updatedVisibility);
                                setHasUnsavedChanges(true);  
                                notify('Promotion removed successfully', 'LONG'); 
                                setrerenderdata(!rerenderdata);
                                setToRemoveId('');
                                setToRemoveItem({});
                                setshowRemoveConfirm_M(false);
                                                          
                            }, function (txnE, txnerr) {
                                console.log('Error deleting survey data:', txnerr);
                            });                        
                                                               
                } 
                else {
                    let index=toRemoveId
                    let item=toRemoveItem;
                    let arr=AddVisibility;
                    console.log('toRemoveId:',index);
                    if(index>=0 && index<arr.length){
                        arr.splice(index,1);
                        setAddVisibility(arr);
                        setHasUnsavedChanges(true);
                        notify('Promotion removed successfully','LONG')
                        setrerenderdata(!rerenderdata);
                    }
                    else{
                        notify('Cannot remove! Promotion not found','LONG')
                    }
                    setToRemoveId('');
                    setToRemoveItem({});
                    setshowRemoveConfirm_M(false);
                }
           
        });
    }

    function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let {window,splitItem,splitItemIndex,cameraType}=reCapImgModalObj
        let camera2Label=(window && window.PromoImage2Lable) || '';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={currentMenu.MenuName+" Image"}
            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('1')}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }
  

    async function 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 _render_addVisFormTop(){

        let CompPromoSellingPriceI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoSellingPrice');
        let CompPromoSellingPriceObj=CompPromoSellingPriceI>=0?KPIFields[CompPromoSellingPriceI]:{};
        let CompPromoSellingPrice=CompPromoSellingPriceI>=0?CompPromoSellingPriceObj['KPIFieldEnable']:true;
        let CompPromoSellingPriceLabel=CompPromoSellingPriceI>=0?CompPromoSellingPriceObj['KPIFieldDisplayName']:"Selling Price";

        let CompPromoGrammageI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoGrammage');
        let CompPromoGrammageObj=CompPromoGrammageI>=0?KPIFields[CompPromoGrammageI]:{};
        let CompPromoGrammage=CompPromoGrammageI>=0?CompPromoGrammageObj['KPIFieldEnable']:false;
        let CompPromoGrammageLabel=CompPromoGrammageI>=0?CompPromoGrammageObj['KPIFieldDisplayName']:"Grammage";

        let CompPromoDPerI=KPIFields.findIndex(i=>i.KPIFieldName=='CompPromoDiscountPercent');
        let CompPromoDPerObj=CompPromoDPerI>=0?KPIFields[CompPromoDPerI]:{};
        let CompPromoDPer=CompPromoDPerI>=0?CompPromoDPerObj['KPIFieldEnable']:false;
        let CompPromoDPerLabel=CompPromoDPerI>=0?CompPromoDPerObj['KPIFieldDisplayName']:"Discount %";

        let CompPromoShowImage1I=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage1');
        let CompPromoShowImage1Obj=CompPromoShowImage1I>=0?KPIFields[CompPromoShowImage1I]:{};
        let CompPromoShowImage1=CompPromoShowImage1I>=0?CompPromoShowImage1Obj['KPIFieldEnable']:true;
        let CompPromoShowImage1Label=CompPromoShowImage1I>=0?CompPromoShowImage1Obj['KPIFieldDisplayName']:"Image";
      
        let CompPromoShowImage2I=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage2');
        let CompPromoShowImage2Obj=CompPromoShowImage2I>=0?KPIFields[CompPromoShowImage2I]:{};
        let CompPromoShowImage2=CompPromoShowImage2I>=0?CompPromoShowImage2Obj['KPIFieldEnable']:false;
        let CompPromoShowImage2Label=CompPromoShowImage2I>=0?CompPromoShowImage2Obj['KPIFieldDisplayName']:"Image";
        
        let CompPromoGramImageI=KPIFields.findIndex(i=>i.KPIFieldName=='ShowImage3');
        let CompPromoGramImageObj=CompPromoGramImageI>=0?KPIFields[CompPromoGramImageI]:{};
        let CompPromoGramImage=CompPromoGramImageI>=0?CompPromoGramImageObj['KPIFieldEnable']:false;
        let CompPromoGramImageLabel=CompPromoGramImageI>=0?CompPromoGramImageObj['KPIFieldDisplayName']:"Image";
        

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


        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                        <Text style={[customStyle.addvis_pText]}>{'Is Present'}</Text>
                        <View style={customStyle.addvis_pChoiceBoxCon}>
                            <View style={[customStyle.openStk_prd_choiceBox,customStyle.addvis_pChoiceBoxbg]}>
                                <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isAddVisPresent=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                {
                                    transform: [{
                                        translateX:xpos
                                    }],
                                }
                                ]}></Animated.View>
                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(1,'isPresent')}}>
                                    <Text style={[customStyle.openStkCh_text,(isAddVisPresent==1?customStyle.openStkCh_textactive:{})]}>Yes</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(0,'isPresent')}}>
                                    <Text style={[customStyle.openStkCh_text,(isAddVisPresent==0?customStyle.openStkCh_textactive:{})]}>No</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        
                </View>
                {
                isAddVisPresent==1 && (rerenderdata== rerenderdata) && 
                <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                <View style={customStyle.addVisForm}>
                   
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Company</Text>
                                {CustomPicker(props,Companies,'Company','CompanyId','Company','CompanyId',onselectionChange,{value:AddVisFormData.Company})}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Category</Text>
                                {CustomPicker(props,Categories,'CategoryName','CategoryId','CategoryName','CategoryId',onselectionChange,{value:AddVisFormData.CategoryName})}
                                
                            </View>
                        </View>
                    </View>
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Sub Category</Text>
                                
                                {CustomPicker(props,SubCategories,'SubCategoryName','SubCategoryId','SubCategoryName','SubCategoryId',onselectionChange,{value:AddVisFormData.SubCategoryName})}
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Brands</Text>
                                
                                {CustomPicker(props,Brands,'BrandName','BrandId','BrandName','BrandId',onselectionChange,{value:AddVisFormData.BrandName})}
                            </View>
                        </View>
                    </View>
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Product</Text>
                                {CustomPicker(props,Products,'ProductName','ProductId','ProductName','ProductId',onselectionChange,{value:AddVisFormData.ProductName})}
                            </View>
                        </View>
                        {CompPromoGrammage && 
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{CompPromoGrammageLabel}</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.Grammage || '')}
                                keyboardType={'number-pad'}
                                autoComplete='off'
                                onChangeText={(val)=>{onFormDataChange(val,'Grammage','decimal');}}
                                />
                            </View>
                        </View>}
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Promotion Type</Text>
                                {CustomPicker(props,DisplayList,'PromoType','PromoTypeId','PromoType','PromoTypeId',onselectionChange,{value:AddVisFormData.PromoType})}
                            </View>
                        </View>
                        {CompPromoDPer && 
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{CompPromoDPerLabel}</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.DiscountPercent || '')}
                                keyboardType={'number-pad'}
                                autoComplete='off'
                                onChangeText={(val)=>{onFormDataChange(val,'DiscountPercent','decimal');}}
                                />
                            </View>
                        </View>}
                    </View>
                    <View style={[CompPromoSellingPrice?customStyle.addVisRow:customStyle.addVisRow2]}>
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol1]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>MRP</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.MRP || '')}
                                keyboardType={'number-pad'}
                                autoComplete='off'
                                onChangeText={(val)=>{onFormDataChange(val,'MRP','numeric');}}
                                />
                            </View>
                        </View>
                        {CompPromoSellingPrice && 
                        <View style={[customStyle.addVisCol50,customStyle.addVisCol2]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{CompPromoSellingPriceLabel}</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.SPrice || '')}
                                keyboardType={'number-pad'}
                                autoComplete='off'
                                onChangeText={(val)=>{onFormDataChange(val,'SPrice','numeric');}}
                                />
                            </View>
                        </View>}
                    </View>
                    <View style={customStyle.addVisRow}>
                        <View style={[customStyle.addVisCol100,customStyle.addVisColspace]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Promotion Details</Text>
                                <TextInput  
                                style={customStyle.addVisInputStyle} 
                                value={(AddVisFormData.Remark || '')}
                                autoComplete='off'
                                onChangeText={(val)=>{onFormDataChange(val,'Remark','text');}}
                                />
                            </View>
                        </View>
                        <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>Image</Text>
                                <View style={customStyle.addVisCameras}>
                                    {CompPromoShowImage1 &&
                                    <View style={customStyle.openStkCameraCon2}>
                                        { (AddVisFormData.Image1Path=='' || AddVisFormData.Image1Path==null) ?
                                            <TouchableOpacity onPress={()=>{openCamera('1')}}>
                                                <CameraImg5 width={50} height={50} />
                                            </TouchableOpacity> : (AddVisFormData.Image1Path!='' && AddVisFormData.Image1Path!=null) ?
                                            <TouchableOpacity onPress={()=>{OpenImgModal(AddVisFormData.Image1Path,'1')}}>
                                                <CameraImg3 width={50} height={50} />
                                            </TouchableOpacity> : null
                                            }
                                        <Text style={customStyle.WSCameraLabel}>{CompPromoShowImage1Label}</Text>
                                    </View> }
                                    {CompPromoShowImage2 &&
                                    <View style={customStyle.openStkCameraCon2}>
                                        {   (AddVisFormData.Image2Path=='' || AddVisFormData.Image2Path==null) ?
                                            <TouchableOpacity onPress={()=>{openCamera('2')}}>
                                                <CameraImg5 width={50} height={50}/>
                                            </TouchableOpacity> : (AddVisFormData.Image2Path!='' && AddVisFormData.Image2Path!=null) ?
                                            <TouchableOpacity onPress={()=>{OpenImgModal(AddVisFormData.Image2Path,'2')}}>
                                                <CameraImg3 width={50} height={50}  />
                                            </TouchableOpacity> : null
                                            }
                                        <Text style={customStyle.WSCameraLabel}>{CompPromoShowImage2Label}</Text>
                                    </View> }
                                    {CompPromoGramImage &&
                                    <View style={customStyle.openStkCameraCon2}>
                                        {   (AddVisFormData.Image3Path=='' || AddVisFormData.Image3Path==null) ?
                                            <TouchableOpacity onPress={()=>{openCamera('3')}}>
                                                <CameraImg5 width={50} height={50} />
                                            </TouchableOpacity> : (AddVisFormData.Image3Path!='' && AddVisFormData.Image3Path!=null) ?
                                            <TouchableOpacity onPress={()=>{OpenImgModal(AddVisFormData.Image3Path,'3')}}>
                                                <CameraImg3 width={50} height={50} />
                                            </TouchableOpacity> : null
                                            }
                                        <Text style={customStyle.WSCameraLabel}>{CompPromoGramImageLabel}</Text>
                                    </View>}
                                    
                                </View>
                            </View>
                        </View>
                        
                    </View>
                    <View style={[customStyle.addVis_btnWrap]}>
                            <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{Add_AddVis()}}>
                                <Text style={customStyle.addVisBtnText}>Add</Text>
                            </TouchableOpacity>
                    </View>
                </View>
                <View style={customStyle.addVis_list}>
                    <Text style={customStyle.addVis_listhdrText}>Added Promotions</Text>
                    <View style={customStyle.addVis_listInner}>
                        {
                            AddVisibility.length>0 &&
                            AddVisibility.map((item,index)=>{
                                console.log(item);
                                return (
                                    <View key={index} style={customStyle.addVis_listItem}>
                                        <View style={customStyle.addVis_listI_row2}>
                                            <View style={customStyle.addVis_listIcol1}>
                                            <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Company :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.Company}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Category :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.CategoryName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Sub Category :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.SubCategoryName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Brand :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.BrandName}</Text>
                                                </View>
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Product :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.ProductName}</Text>
                                                </View>
                                                { CompPromoGrammage &&
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{CompPromoGrammageLabel+" :"}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.Grammage}</Text>
                                                </View>}
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>Promo Type :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.PromoType}</Text>
                                                </View>
                                                {CompPromoDPer &&
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{CompPromoDPerLabel+" :"}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.DiscountPercent}</Text>
                                                </View>}
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>MRP :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.MRP}</Text>
                                                </View>
                                                { CompPromoSellingPrice && 
                                                <View style={customStyle.addVis_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{CompPromoSellingPriceLabel+" :"}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.SPrice}</Text>
                                                </View>
                                                }
                                                
                                                <View style={[customStyle.addVis_listI_row,customStyle.addVis_listI_lastrow]}>
                                                    <Text style={customStyle.addVis_listI_Label}>Remark :</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.Remark}</Text>
                                                </View>
                                            </View>
                                            <View style={customStyle.addVis_listIcol2}>
                                                
                                            
                                                {CompPromoShowImage1 && 
                                                <>
                                                {/* <View style={[customStyle.addVis_listI_row]}> */}
                                                    <Text style={[customStyle.addVis_listI_Label2,customStyle.mb20]}>{CompPromoShowImage1Label}</Text>
                                                    {(item.Image1Path!=null && item.Image1Path!='') && <Image style={customStyle.addVis_listI_Image} source={{uri:item.Image1Path}} />}
                                                {/* </View> */}
                                                </>
                                                }
                                                {CompPromoShowImage2 &&
                                                <>
                                                    <Text style={[customStyle.addVis_listI_Label2,customStyle.mb20]}>{CompPromoShowImage2Label}</Text>
                                                    {(item.Image2Path!=null && item.Image2Path!='') && <Image style={customStyle.addVis_listI_Image} source={{uri:item.Image2Path}} />}
                                                </>
                                                }
                                                {CompPromoGramImage &&
                                                <>
                                                    <Text style={[customStyle.addVis_listI_Label2,customStyle.mb20]}>{CompPromoGramImageLabel}</Text>
                                                    {(item.Image3Path!=null && item.Image3Path!='') && <Image style={customStyle.addVis_listI_Image} source={{uri:item.Image3Path}} />}
                                                </>
                                                }
                                                
                                            </View>
                                            
                                            <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={()=>{showRemoveConfirm(item,index)}}>
                                               <FontAwesome name='trash' size={20} color={'red'} />
                                            </TouchableOpacity>
                                        </View>
                                        {/* <View style={customStyle.addVis_listR}>
                                                <View style={[customStyle.addVis_listPcon,customStyle.addVis_listPcon1]}>
                                                    <Text style={customStyle.addVis_listRlbl}>Promotion Type :</Text>
                                                    <Text style={customStyle.addVis_listI_Val2}>{item.PromoType}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listPcon,customStyle.addVis_listPcon2]}>
                                                    <Text style={customStyle.addVis_listRlbl}>Product :</Text>
                                                    <Text style={customStyle.addVis_listI_Val2}>{item.ProductName}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listPcon,customStyle.addVis_listPcon1]}>
                                                    <Text style={customStyle.addVis_listRlbl}>MRP :</Text>
                                                    <Text style={customStyle.addVis_listI_Val2}>{item.MRP}</Text>
                                                </View>
                                                <View style={[customStyle.addVis_listPcon,customStyle.addVis_listPcon2]}>
                                                    <Text style={customStyle.addVis_listRlbl}>Selling Price :</Text>
                                                    <Text style={customStyle.addVis_listI_Val2}>{item.SPrice}</Text>
                                                </View>
                                        </View> */}
                                       
                                    </View>
                                );
                            })
                        }
                    </View>
                </View>
                </ScrollView>
                }
            </View>
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <View style={{zIndex: 10}}>
          <CustomHeader {...props}showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>
        </View>
        {_OpenCaptureImage_Modal()}  
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setshowRemoveConfirm_M(false)},Remove_AddVis,'Do you really want to remove this promotion?')}
        {ConfirmSaveAlert(props,showRAllC_M,()=>{setShowRAllC_M(false)},onConfirmRemoveAll,'Do you really want to remove all promotion data?')}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 && 
            <View style={customStyle.addVis_Wrapper}>
                {_render_addVisFormTop()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        
      </Container>   
    ); 
}
  
  

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