import React, { useState, useEffect, memo } 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, TouchableHighlight, Platform, PermissionsAndroid, FlatList, Alert } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, AddStore, checkRange, UploadData2, UploadData, UpdateStoreStatus, getKPIS, marktext1, marktext2, UploadFormData, getDownloadJson1, validateNumber, ValidateEmail, restore_ImageWithMetaData } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, AppVersion, common_ImagePath, ImageFolderPath, CoverageImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, EvilIcons, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import MapIcon from '../assets/performics/map_icon.svg';
import CustomModal from '../components/CustomModal';
import { _checkLocationPermission } from '../components/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import * as RNFS from 'react-native-fs';

import CustomCamera from '../components/Camera';
import HeaderTabs from '../components/HeaderTabs';
import GradientButton from '../components/gradientButton';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import { getBeatDownloadTask, getNewStoresDownloadTask, getPostData, insert_TaskDownloadedData, PJP_colList } from '../components/downloadTasks';
import DownloadDataModal from '../components/downloadDataModal';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

//notifications
import pushNotification from '../pushNotification';

function AddStoreScreen(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 [loaderTitle, setLoaderTitle] = useState(ST.Creatingstore + "...");
  const [processing, setProcessing] = useState(false);
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [rerenderdata, setrerenderdata] = useState(0);
  const [GSTFlag, setGSTFlag] = useState(false);

  const [StoreData, setStoreData] = useState({});

  const [cityList, setCityList] = useState([]);
  const [storeTypeList, setStoreTypeList] = useState([]);
  const [ChainList, setChainList] = useState([]);
  const [StoreCategory, setStoreCategory] = useState([]);
  const [StoreClassList, setStoreClassList] = useState([]);
  const [DistributorList, setDistributorList] = useState([]);
  const [ChannelList, setChannelList] = useState([]);

  const [AllFormData, setAllFormData] = useState({});
  const [showCamera, setShowCamera] = useState(false);
  const [showImg, setShowImg] = useState(false);
  const [ImgURI, setImgURI] = useState("");
  const [StoreImage, setStoreImage] = useState('');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  const [DownloadTasks, setDownloadTasks] = useState([]);
  const [TaskResponse, setTaskResponse] = useState([]);
  const [IsDownloadStart, setIsDownloadStart] = useState(false);
  const [downloadingText, setDownloadingText] = useState('');
  const [dowloadedCount, setDowloadedCount] = useState(-1);
  const [totalCount, setTotalCount] = useState(0);

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

  var TaxType = [
    { TaxType: "GST", TaxTypeId: "GST" },
    { TaxType: "Non GST", TaxTypeId: "NON GST" }]

  let d1 = new Date();
  let today = moment(d1).format('MM/DD/YYYY');

  useEffect(() => {
    getData();
    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

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

  useEffect(() => {
    console.log('dowloadedCount change:', dowloadedCount);
    if (dowloadedCount <= totalCount && IsDownloadStart == true) {
      executeTasks();
    }
    else {
      setIsDownloadStart(false);
      notify(ST.DataDownloaded, 'SHORT');
    }
  }, [dowloadedCount]);

  useEffect(() => {
    if (IsDownloadStart && TaskResponse != null) {
      console.log('increment dowloadedCount changed');
      let count = dowloadedCount + 1;
      setDowloadedCount(count);
    }
  }, [TaskResponse]);

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


  function onBeforeRemove(e) {
    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); } }
      ]
    );
  }


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

    let allData = StoreData;
    allData[key] = val;
    setStoreData(allData);
    setHasUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }



  // download functionality start
  async function startDownload() {
    console.log('startDownload');
    setIsDownloadStart(true);
    setDowloadedCount(0);
  }

  async function beforeExecuteTasks() {
    console.log('beforeExecuteTasks:');
    let DownloadTasks1 = await getNewStoresDownloadTask();
    console.log('All BeatDownloadTask', DownloadTasks1.length);
    setDownloadTasks(DownloadTasks1);
    setTotalCount((DownloadTasks1.length - 1));
    startDownload();
  }

  async function executeTasks() {
    console.log('executeTasks');

    // var DownloadTasks=getDownloadDataTask();
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    var currentIndex = dowloadedCount;

    console.log('currentIndex:', currentIndex);
    if (currentIndex >= 0) {
      let dk_data = DownloadTasks[currentIndex];
      console.log('dk_data', dk_data);
      let key = dk_data.DownloadKey || '';
      setDownloadingText(key);

      var data = await getPostData(DownloadTasks, currentIndex);

      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, data);
      await getDownloadJson1(url, data)
        .then(async (res) => {
          let isAdded = await updateTaskRes(res, currentIndex, 1);
          if (isAdded == true) {
            if (currentIndex == DownloadTasks.length - 1) {
              console.log('last found all downloaded');
              onDownloadComplete();
            }
            else {
              console.log('all downloaded but last not found ');
            }

          }
          else {
            console.log('Cannot download all Data');
          }

        })
        .catch(err => {
          console.log('onPage Team error', err);
        });
    }

  }

  async function onDownloadComplete() {
    let count = dowloadedCount + 1;
    setIsDownloadStart(false);
    setDowloadedCount(count);
    notify(ST.DataDownloaded, 'SHORT');
    props.navigation.goBack();
  }

  async function onTaskError() {
    notify(ST.Cannotdownloaddata);
    setIsDownloadStart(false);
  }

  async function onNoData(data = [], shouldStop = false, tbname = '') {

    if (tbname != '') {
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(`delete from ${tbname} where 1=1`, [], function (txn1, txnres) {
          console.log('deleted all data for ' + tbname);
        }, function (Etxn, err) {
          console.log('err:', err);
        });
      });
    }

    if (shouldStop == true) {
      let msg = ST.Nodatafoundfor + tbname + '';
      if (tbname == 'JourneyPlan_RouteWise') {
        msg = ST.Youhavenojourneyplanfortoday;
      }
      notify(msg);
      setIsDownloadStart(false);
    }
    else {
      setTaskResponse(data);
    }
  }

  async function updateTaskRes(res, index, count) {
    // var DownloadTasks=getDownloadDataTask();   

    const todate = new Date();
    const today = moment(todate).format("MM/DD/YYYY");
    let d2 = today;
    let dk_data = DownloadTasks[index];
    let key = dk_data.DownloadKey || '';
    let IsMandatory = dk_data.IsMandatory == 'true' || dk_data.IsMandatory == 1 ? true : false;

    return new Promise(async (resolve, reject) => {
      switch (key) {

        case 'Mapping_JourneyPlan': {
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_JourneyPlan', PJP_colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Adhoc_JourneyPlan': {
          let i_res = await insert_TaskDownloadedData(res, 'Adhoc_JourneyPlan', PJP_colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_ProductAssortmentStorewise': {
          let colList = ['StoreId', 'ProductId', 'MSL', 'MBQ'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_ProductAssortmentStorewise', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreWindow': {
          let colList = ['StoreId', 'WindowDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StoreWindow', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_WindowQuestion': {
          let colList = ['WindowDefinitionId', 'WindowQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_WindowQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_StorePOSM': {
          let colList = ['StoreId', 'POSMDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StorePOSM', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_POSMQuestion': {
          let colList = ['POSMDefinitionId', 'POSMQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_POSMQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_StoreShelfTalker': {
          let colList = ['StoreId', 'StDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StoreShelfTalker', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_ShelfTalkerQuestion': {
          let colList = ['StDefinitionId', 'StQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_ShelfTalkerQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_StoreVisibility': {
          let colList = ['StoreId', 'VisibilityDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StoreVisibility', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }

        case 'Mapping_VisibilityQuestion': {
          let colList = ['VisibilityDefinitionId', 'VisibilityQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_VisibilityQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_StorePromotion': {
          let colList = ['StoreId', 'PromoDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StorePromotion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_PromotionQuestion': {
          let colList = ['PromoDefinitionId', 'PromoQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_PromotionQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreShareOfShelf': {
          let colList = ['StoreId', 'SOSDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StoreShareOfShelf', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_DisplayChecklist': {
          let colList = ['DisplayId', 'ChecklistId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_DisplayChecklist', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_Survey': {
          let colList = ['StoreId', 'SurveyId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_Survey', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreCategory': {
          let colList = ['StoreId', 'CategoryDefinitionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_StoreCategory', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }
        case 'Mapping_CategoryQuestion': {
          let colList = ['CategoryDefinitionId', 'CategoryQuestionId'];
          let i_res = await insert_TaskDownloadedData(res, 'Mapping_CategoryQuestion', colList, props);
          console.log('i_res:', i_res);
          let data_arr = i_res['data_arr'];
          setTaskResponse(data_arr);
          let r = i_res['r'];
          console.log('r:', r);
          resolve(r);
          break;
        }



      }
    }).catch((err) => {
      console.log('error in downloading', err);
      return false;
    });

  }


  // download functionality end




  async function getData(storeData1, menu1) {
    try {
      await db.transaction(async function (txn) {

        let q1 = `Select * From Master_City`;
        let q2 = `Select * From Master_StoreType`;
        let q3 = `Select * From Master_Chain`;
        let q4 = `Select * From Master_StoreCategory`;
        let q5 = `Select * From Master_StoreClass`;
        let q6 = `Select * From Master_Distributor`;
        let q7 = `Select * From Master_Channel`;

        await txn.executeSql(q1, [], 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) {
                setCityList(arr);

              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        await txn.executeSql(q2, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              arr.push(data);
              if (i == txnres2.rows.length - 1) {
                setStoreTypeList(arr);
                console.log("StoreTypeList:", arr)
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        await txn.executeSql(q3, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              arr.push(data);
              if (i == txnres2.rows.length - 1) {
                setChainList(arr);
                console.log("ChainList:", arr)

              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        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) {
                setStoreCategory(arr);
                console.log("setStoreCategory:", arr)

              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        await txn.executeSql(q5, [], 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) {
                setStoreClassList(arr);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        await txn.executeSql(q6, [], 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) {
                setDistributorList(arr);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
        await txn.executeSql(q7, [], 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) {
                setChannelList(arr);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
      });
    } catch (err) {
      console.log(err);
    }
  }



  async function validateForm() {
    let isValid = true;
    let { Name, Address, Location, PinCode, ContactPerson, ContactNumber, mobileNumber, Email, TaxType, GSTNo, GSTImage, CityId, ChannelId, DistributorId, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = StoreData;
    console.log('ChainId:', ChainId);
    if (Name == '' || Name == null) {
      isValid = false;
      notify(ST.PleaseenterStoreName, 'SHORT');
    }
    else if (Address == '' || Address == null) {
      isValid = false;
      notify(ST.PleaseenterAddress + ' ', 'SHORT');
    }
    else if (Location == '' || Location == null) {
      isValid = false;
      notify('Please enter Location ', 'SHORT');
    }
    else if (PinCode == '' || PinCode == null) {
      isValid = false;
      notify('Please enter Pincode ', 'SHORT');
    }
    else if (PinCode.length != 6) {
      isValid = false;
      notify('Please enter valid Pincode', 'SHORT');
    }
    // else if((ContactPerson=='' || ContactPerson==null )){
    //     isValid=false;
    //     notify('Please enter Contact Person ','SHORT');
    // }
    else if ((ContactNumber != null && ContactNumber != '') && ContactNumber.length != 10) {
      isValid = false;
      notify('Please enter valid Contact Number', 'SHORT');
    }
    else if ((mobileNumber != null && mobileNumber != '') && mobileNumber.length != 10) {
      isValid = false;
      notify('Please enter valid Mobile Number', 'SHORT');
    }
    else if ((Email != '' && Email != null) && !ValidateEmail(Email)) {
      isValid = false;
      notify('Please enter valid Email', 'SHORT');
    }
    else if ((TaxType == '' || TaxType == null)) {
      isValid = false;
      notify('Please select TaxType', 'SHORT');
    } else if (TaxType == 'GST' && (GSTNo == '' || GSTNo == null)) {
      isValid = false;
      notify('Please enter GST No', 'SHORT');
    }
    else if (TaxType == 'GST' && (GSTImage == '' || GSTImage == null)) {
      isValid = false;
      notify('Please Take GST Image', 'SHORT');
    } else if (CityId == '' || CityId == null) {
      isValid = false;
      notify('Please select CityId', 'SHORT');
    } else if (StoreTypeId == '' || StoreTypeId == null) {
      isValid = false;
      notify('Please select StoreTypeId', 'SHORT');
    } else if (ChainId == '' || ChainId == null) {
      isValid = false;
      notify('Please select ChainId', 'SHORT');
    } else if (ChannelId == '' || ChannelId == null) {
      isValid = false;
      notify('Please select ChannelId', 'SHORT');
    } else if (StoreCategoryId == '' || StoreCategoryId == null) {
      isValid = false;
      notify('Please select StoreCategoryId', 'SHORT');
    } else if (StoreClassId == '' || StoreClassId == null) {
      isValid = false;
      notify('Please select StoreClassId', 'SHORT');
    } else if (DistributorId == '' || DistributorId == null) {
      isValid = false;
      notify('Please select DistributorId', 'SHORT');
    }

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


  const submit = async () => {
    let valid = await validateForm();


    if (valid) {
      const url = props.baseurl + getMethodName(METHODS.CREATESTORE);
      let PostData = {
        "UserId": props.UserId,
        "VisitDate": today,
        "StoreName": StoreData.Name || '',
        "Address": StoreData.Address || '',
        "Location": StoreData.Location || '',
        "Pincode": StoreData.PinCode || '',
        "ContactPerson": StoreData.ContactPerson || '',
        "Mobile": StoreData.mobileNumber || '',
        "Phone": StoreData.ContactNumber || '',
        "Email": StoreData.Email || '',
        "TaxType": StoreData.TaxType || '',
        "GSTNo": StoreData.GSTNo || '',
        "GSTImage": StoreData.GSTImage || '',
        "CityId": StoreData.CityId || '',
        "ChannelId": StoreData.ChannelId || '',
        "DistributorId": StoreData.DistributorId || '',
        "ChainId": StoreData.ChainId || '',
        "StoreTypeId": StoreData.StoreTypeId || '',
        "StoreClassId": StoreData.StoreClassId || '',
        "StoreCategoryId": StoreData.StoreCategoryId || '',
      }
      setProcessing(true)
      let fpath = Platform.OS == 'ios' ? ImgURI.replace('file://', '') : ImgURI;
      // var data1 = new FormData();          
      // data1.append('file', {
      //   uri: fpath ,
      //   type: 'image/jpg',
      //   name: StoreImage,
      // });

      // data1.append('Foldername',"GSTImages");
      // data1.append('Path', today);

      const url1 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);

      console.log('url:', url, PostData);
      await UploadData2(url, PostData)
        .then(async (res) => {
          console.log('res:', res);
          if (parseInt(res) > 0) {
            setHasUnsavedChanges(false);
            // Upload Image 
            // if(StoreData.TaxType=='GST' &&  (StoreData.GSTImage!='' && StoreData.GSTImage!=null)){
            // await UploadFormData(url1,data1)
            // .then(async(res1)=>{         
            //   console.log('res1 image upload:',res1);   
            //   let resStatus = res1.includes("Success");
            //   if(resStatus){
            //       setProcessing(false);
            //       beforeExecuteTasks();
            //   }
            //   else{
            //     setProcessing(false);
            //     beforeExecuteTasks();
            //     notify('Cannot upload GST image!');
            //   }


            //   // props.navigation.goBack()     
            // })
            // .catch((err)=>{
            //   console.log(err);
            //   setProcessing(false);
            //   beforeExecuteTasks();
            //   notify('Cannot upload GST image!');
            // });

            // }
            // else{
            //   setProcessing(false);
            //   beforeExecuteTasks();
            // }

            setProcessing(false);
            beforeExecuteTasks();
          }
          else {
            setProcessing(false);
          }
        })
        .catch((err) => {
          console.log(err); setProcessing(false);
        });

    }
  }



  function onselectionChange(option, keyLbl, keyVal, otherData) {
    let allData = StoreData;
    allData[keyLbl] = option.label;
    allData[keyVal] = option.value;

    if (keyLbl == "TaxType" && option.label == 'GST') {
      setGSTFlag(true)
    } else {
      setGSTFlag(false)
    }

    console.log('allData:', allData);
    setStoreData(allData);
    setHasUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  async function openCamera() {
    console.log('openCamera');
    setShowCamera(true);
  }

  async function getImage(imgdata) {
    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();
      ////change by jeevanp
      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);
      ////change by jeevanp
      let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
      let calculate_tym_date_over_img = picture_clicked_time;
      let filename = (props.UserId || '') + '_AddStore-' + 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.Name + ' | User Id:' + props.UserId + ' | Image Type: AddStore' + ' | Date:' + calculate_tym_date_over_img;
      console.log(mark_text1 + "\n" + mark_text2, "mark_text2");

      // renamefile
      let imagePath = `${CoverageImagePath}${filename}`;
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          setImgURI(uri)
          setSelectedImg(uri)
          setShowImg(true)
          setStoreImage(filename)
          setStoreData({ ...StoreData, GSTImage: filename })
          setHasUnsavedChanges(true);
          setrerenderdata(!rerenderdata);

          // 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(ST.Errorimagefilewritefailed + '!!!');
          console.log(err.message, err.code);
        });

    }
  }

  async function OpenImgModal(imgPath) {
    setSelectedImg(imgPath)
    setShowModal(true);
    if ((imgPath != '' && imgPath != null)) {
      setShowImageSaveOp(false);
    }
    else {
      setShowImageSaveOp(true);
    }

  }

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

  function _OpenCaptureImage_Modal(img) {

    const isImageCap = (img != '' || img != null) ? true : false;


    return (
      <CustomModal
        style={customStyle.PromoImgModal}
        title={"Add Store Image"}
        message={""}
        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() }}>
              <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>
    )
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>

      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={'Add Store'} />
      {(IsDownloadStart && dowloadedCount <= totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText} />}
      {_OpenCaptureImage_Modal()}
      <CustomCamera cameraType={'back'} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />
      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper,]}>
          <View style={[customStyle.storelist_parentwrap]}>
            <HeaderTabs {...props} isAddStoreScreen={true} />

            <ScrollView
              style={customStyle.AddStore_ContentOuter}
              contentContainerStyle={customStyle.AddStore_ContentInner}
            >
              {rerenderdata == rerenderdata &&
                <View style={[customStyle.storel_Con,]}>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Name"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                        placeholderTextColor={PageTheme.$placeholder_color}
                        // keyboardType={'number-pad'}
                        value={(StoreData.Name || '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'Name', 'text') }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Address"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        // keyboardType={'number-pad'}
                        value={(StoreData.Address || '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'Address', 'text') }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Location"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        // keyboardType={'number-pad'}
                        value={(StoreData.Location || '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'Location', 'text') }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Pin Code"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        keyboardType={'number-pad'}
                        maxLength={6}
                        value={(StoreData.PinCode != null ? StoreData.PinCode + '' : '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'PinCode', 'numeric'); }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Tax Type"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, TaxType, 'TaxType', 'TaxTypeId', 'TaxType', 'TaxTypeId', onselectionChange, { value: StoreData.TaxType })}
                    </View>
                  </View>
                  {GSTFlag &&
                    <>
                      <View style={customStyle.AddStockM_row} >
                        <Text style={customStyle.AddStockM_label}>{"GST No"}</Text>
                        <View style={customStyle.AddStockM_col} >
                          <TextInput
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color}
                            // keyboardType={'number-pad'}
                            value={(StoreData.GSTNo || '')}
                            onChangeText={(val) => { onStoreDataChange(val, 'GSTNo', 'text'); }}
                          />
                        </View>
                      </View>
                      {
                        <View style={customStyle.osCat_actions}>
                        
                          {!showImg ?
                            <TouchableOpacity onPress={() => { openCamera() }}>
                              <CameraImg5 width={50} height={50} />
                            </TouchableOpacity> : showImg ?
                              <TouchableOpacity onPress={() => { OpenImgModal(ImgURI) }}>
                                <CameraImg3 width={50} height={50} />
                              </TouchableOpacity> : null
                          }
                        </View>
                      }
                    </>
                  }
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Contact Person"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        // keyboardType={'number-pad'}
                        value={(StoreData.ContactPerson || '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'ContactPerson', 'text'); }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Contact Number"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        keyboardType={'number-pad'}
                        maxLength={10}
                        value={(StoreData.ContactNumber != null ? StoreData.ContactNumber + '' : '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'ContactNumber', 'numeric'); }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Mobile Number"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        keyboardType={'number-pad'}
                        maxLength={10}
                        value={(StoreData.mobileNumber != null ? StoreData.mobileNumber + '' : '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'mobileNumber', 'numeric'); }}
                      />
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Email"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      <TextInput
                        style={[customStyle.AddStockM_InputStyle]}
                        placeholder=""
                        autoComplete='off'
                        placeholderTextColor={PageTheme.$placeholder_color}
                        // keyboardType={'number-pad'}
                        value={(StoreData.Email || '')}
                        onChangeText={(val) => { onStoreDataChange(val, 'Email', 'text'); }}
                      />
                    </View>
                  </View>

                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"City"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, cityList, 'CityName', 'CityId', 'CityName', 'CityId', onselectionChange, { value: StoreData.CityName })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Store Type"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, storeTypeList, 'StoreType', 'StoreTypeId', 'StoreType', 'StoreTypeId', onselectionChange, { value: StoreData.StoreType })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Chain Name"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, ChainList, 'ChainName', 'ChainId', 'ChainName', 'ChainId', onselectionChange, { value: StoreData.ChainName })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Channel Name"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, ChannelList, 'ChannelName', 'ChannelId', 'ChannelName', 'ChannelId', onselectionChange, { value: StoreData.ChannelName })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Store Category"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, StoreCategory, 'StoreCategory', 'StoreCategoryId', 'StoreCategory', 'StoreCategoryId', onselectionChange, { value: StoreData.StoreCategory })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Store Class"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, StoreClassList, 'StoreClass', 'StoreClassId', 'StoreClass', 'StoreClassId', onselectionChange, { value: StoreData.StoreClass })}
                    </View>
                  </View>
                  <View style={customStyle.AddStockM_row} >
                    <Text style={customStyle.AddStockM_label}>{"Distributor Name"}</Text>
                    <View style={customStyle.AddStockM_col} >
                      {CustomPicker(props, DistributorList, 'DistributorName', 'DistributorId', 'DistributorName', 'DistributorId', onselectionChange, { value: StoreData.DistributorName })}
                    </View>
                  </View>

                </View>
              }
            </ScrollView>
          </View>
          <View style={[customStyle.AddStore_SubmitBtn]}>
            <GradientButton {...props} title={"Submit"} onPress={() => { submit() }} />
          </View>
        </View>
      </LinearGradient>
    </Container>
  );
}



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