import { View, Text, TextInput,TouchableOpacity, NativeModules, Icon, Image } from 'react-native'
import React,{useState,useEffect} from 'react'
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {connect} from 'react-redux'
import CustomHeader from '../components/customHeader';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import DrawerHeader from '../components/drawerHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import GradientButton from '../components/gradientButton';
import { CustomPicker } from '../components/CustomPicker';
import { ScrollView } from 'react-native-gesture-handler';
import Svg, { SvgUri, SvgXml} from 'react-native-svg';
import add_icon from '../assets/performics/add_image.svg';
import camera_Icon from '../assets/performics/camera_icon.svg';
import camera_IconTick from '../assets/performics/camera_icon.svg';
// import DocumentPicker , { types } from '@react-native-documents/picker';
import { pick } from '@react-native-documents/picker';
import { common_ImagePath, db, resumeurl} from '../constants/constants';
import { ConfirmSaveAlert } from '../components/alert';
import { AppTables } from '../constants/tableConstants';
import {notify} from '../components/notify';
import CustomCamera from '../components/Camera';
import moment from 'moment';
import cameraImg from '../assets/performics/camera_front_image.svg'
import { MaterialCommunityIcons } from '../components/icons';
import {marktext1,marktext2, UploadData, UploadData2, UploadFormData} from '../controller/functions';
import { getMethodName, METHODS } from '../constants/methodNames';
import * as mime from 'mime';
import * as RNFS from 'react-native-fs';
import {testurl} from '../constants/constants';
import {getDownloadJson,DownloadData} from '../controller/functions';
import {get_item} from '../components/localStorage';
import { Props } from 'react-native-image-zoom-viewer/built/image-viewer.type';


   

function HR(props) {

    const route = useRoute();
  
    const [currentItem, setcurrentItem] = useState({});
    
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);

    const [formData, setFormData] = useState({});
    const [rerenderdata, setrerenderdata] = useState(0);
    const [datas,setDatas] = useState([]);
    
    const [expdata,setexpData] = useState([]);
    const [singleFile, setSingleFile] = useState({});
    const [showAlert, setShowAlert] = useState(false);
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    const [showCamera, setShowCamera] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [hrImage, setHrImage] = useState({});

    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [getImageProps,setGetImageProps]= useState({});
    const [resumeData, setresumeData] = useState([]);
    const [dowloadedCount, setDowloadedCount] = useState(-1);
    const [Position,setPosition] = useState([]);
    const [Education,setEducation] = useState([]);

  const [processing, setProcessing] = useState(true);
    // Position = [
    //     {
    //       positionName: 'Merchandiser',
    //       positionID: 1,
    
    //     },
    //     {
    //         positionName: 'Supervisor',
    //         positionID: 2,
      
    //       },
    // ];

    // Education = [
    //     {
    //         educationName: '10th',
    //         educationID: 1,
    
    //     },
    //     {
    //         educationName: '12th',
    //         educationID: 2,
        
    //     },
    //     {
    //         educationName: 'Graduation',
    //         educationID: 3,
    
    //     },
    //     {
    //         educationName: 'Post-Graduation',
    //         educationID: 4,
        
    //     },
    // ];


  useEffect(() => { 
    let params = props.route.params !=null?props.route.params:{};
    let currentitem1 = params.imagedesc!=null?params.imagedesc:{};
    console.log("Currentitem1",currentitem1);
    setcurrentItem(currentitem1)
    downloaddatahr();

    const onremoveSubscription=props.navigation.addListener('beforeRemove', onBeforeRemove);

    
 
    return function cleanup() {
       props.navigation.removeListener('beforeRemove', onBeforeRemove);
       return onremoveSubscription;

    }
    // viewFormData();
  }, [resumeData]);

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


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

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


function onselectionChange(option,keyLbl,keyVal,otherData){
        
    let data=formData;
    data[keyVal]=option.value;
    data[keyLbl]=option.label;
    // setHasUnsavedChanges(true);
    setFormData(data);
    setrerenderdata(!rerenderdata);
    
}

function onTextChange(key, val,type=''){
        
    let data=formData;
    data[key]=val;
    // setHasUnsavedChanges(true);
    setFormData(data);
    setrerenderdata(!rerenderdata);
    
}

function explistData(){
    let arraylistdata = formData.experience;
    console.log('arraylistdata',arraylistdata)
    setexpData(arraylistdata);
}


const selectOneFile = async () => {
    //Opening Document Picker for selection of one file
    console.log('selectOneFile');
    try {
       
      const res = await pick({
        presentationStyle: 'fullScreen',
        type: [
          'public.image',     // images (JPG/PNG)
          'com.adobe.pdf'     // PDFs
        ],
      });

    console.log('res : ' + JSON.stringify(res));
    console.log('URI : ' + res[0].uri);
    console.log('Type : ' + res[0].type);
    console.log('File Name : ' + res[0].name);
    console.log('File Size : ' + res[0].size);

    let filepath=res[0].uri;
    let picture_selected_time=new Date();
    picture_selected_time=moment(picture_selected_time).format('DDMMYYYYHHmmss')
    let filetype=res[0].type;
    let name_ext='';//name_arr[name_arr.length-1];
    if(filetype=='image/png'){
        name_ext='png';
    }
    else if(filetype=='image/jpg' || filetype=='image/jpeg'){
        name_ext='jpg';
    }
    else if(filetype=='application/pdf'){
        name_ext='pdf';
    }

    

    let filename = 'Resumefile_'+ props.UserId + picture_selected_time+'.'+name_ext;
    let nfileP='file://'+`${common_ImagePath}${filename}`;

        
    RNFS.moveFile(filepath,nfileP)
    .then(resn => {
      let obj={filePath: nfileP,fileName:filename,filetype:filetype}
      setSingleFile(obj);
    })
    .catch(err => {
        console.log('ERROR: on file store!');
        console.log(err.message, err.code);
    }); 
    
      
    }catch (err) {
      console.log('Error: ' + JSON.stringify(err));
      // if (DocumentPicker.isCancel(err)) {
      //   //If user canceled the document selection
      //   alert('Canceled from single doc picker');
      // } else {
        
      //   alert('Unknown Error: ' + JSON.stringify(err));
      //   throw err;
      // }
    }
  };

function onSaveCancel(){
    setShowAlert(false);
}

async function onSubmitData(){
  
    let isvalid=await validate();
    
    if(isvalid){
      console.log('isvalidvalue',isvalid);
       setShowAlert(true);
    }
}

async function saveData(){
    console.log()
    setHasUnsavedChanges(false);
    setShowAlert(false);
    setLoaderTitle('Saving Data...');
    setProcessing(true);

    try {   
      
        await db.transaction(async function (txn) {   
          let values='';  
          let status='N';
          let uniqueId='R'+props.UserId+moment().format('DDMMYYYYHHmmss')+(Math.floor(Math.random()*1000)+1);
          values =` ('${uniqueId}','${props.UserId}','${formData.name}','${formData.mobileno}','${formData.locality}','${formData.DesignationName}','${formData.project}','${formData.agency}','${formData.experience}','${formData.Qualification_Name}','${formData.store}','${(singleFile.fileName || '')}','${(singleFile.filetype || '')}','${(hrImage.Image1Name || '')}','${(hrImage.Image2Name || '')}','${d2}','${status}') `;
          let add_data=`INSERT INTO ${AppTables.RESUME_DATA} (UID,EMP_ID,NAME,MOBILE_NO,LOCALITY,POSITION,PROJECT,AGENCY,EXPERIENCE,EDUCATION,STORE,RESUME_FILE,TYPE,IMAGE1,IMAGE2,ADDED_DATE,STATUS) VALUES ${values} `;

          // await txn.executeSql(`Select * From ${AppTables.RESUME_DATA} where EMP_ID='${props.UserId}' and ADDED_DATE='${d2}' `,[],async function (txn2, txnres) {
          //     console.log('old geotag removed'); 
              // console.log('values:',values);
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('av added');
                notify('HR data added successfully','SHORT');
                allUploadData(uniqueId);
                // setProcessing(false);
                // props.navigation.goBack();
              },
              function (txn2, txnerr){ console.log(txnerr);
                // setProcessing(false);
                notify('Cannot add resume data') 
              });
          // });   
          
        });          
    } catch (err) {
        console.log(err);          
    } 
}

async function validate(){
  let isValid=true;
  if (!formData.name) {
    alert('Please enter Name');
    isValid=false;
  }
  else if (!formData.mobileno) {
    alert('Please enter Mobile No.');
    isValid=false;
  }
  else if (!formData.locality) {
    alert('Please enter Locality');
    isValid=false;
  }
  else if (!formData.DesignationName) {
    alert('Please enter Position');
    isValid=false;
  }
  else if (!formData.project) {
    alert('Please enter Project');
    isValid=false;
  }
  else if (!formData.agency) {
    alert('Please enter Agency');
    isValid=false;
  }
  else if (!formData.experience) {
      alert('Please enter Experience');
      isValid=false;
  }
  else if (!formData.Qualification_Name) {
      alert('Please enter Education');
      isValid=false;
  }
  else if (!formData.store) {
      alert('Please enter Store');
      isValid=false;
  }

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


async function getPostData(uniqueId=''){
  return new Promise((resolve,reject)=>{
    db.transaction(async function (txn) {

        let q2=` SELECT * FROM ${AppTables.RESUME_DATA} WHERE UID='${uniqueId}' `;
        let resumeData={},myresumeObj={};
        let Allfiles = [];
        
        await txn.executeSql(q2,[],async function (txn2, txnres2) { 
            if(txnres2.rows.length>0){ 
                for(var i=0;i<txnres2.rows.length;i++){
                    let data =txnres2.rows.item(i);
                    let {NAME,MOBILE_NO,LOCALITY,POSITION,PROJECT,AGENCY,EXPERIENCE,EDUCATION,STORE,RESUME_FILE,TYPE,IMAGE1,IMAGE2,ADDED_DATE}=data;
                    let obj={};
                    obj['Name']=NAME;
                    obj['Mobile_No']=MOBILE_NO;
                    obj['Locality']=LOCALITY;
                    obj['Position']=POSITION;
                    obj['Project']=PROJECT;
                    obj['Agency']=AGENCY;
                    obj['Experience']=EXPERIENCE;
                    obj['Education']=EDUCATION;
                    obj['Store']=STORE;
                    obj['ResumeFile']=RESUME_FILE;
                    obj['Type']=TYPE;
                    obj['IMAGE1']=IMAGE1;
                    obj['IMAGE2']=IMAGE2;
                    obj['Added_Date']=ADDED_DATE;

                    myresumeObj= obj;

                    console.log('IMAGE1:',IMAGE1);
                    console.log('IMAGE2:',IMAGE2);
                    if (RESUME_FILE!=null && RESUME_FILE!='') {
                      let imgPath=common_ImagePath+RESUME_FILE;
                      let file={
                          uri: imgPath,
                          name: RESUME_FILE,
                          filetype:TYPE,
                          folderName:'ResumeFiles',
                      }
                      Allfiles.push(file);
                    }
                    if (IMAGE1!=null && IMAGE1!='') {
                        let imgPath=common_ImagePath+IMAGE1;
                       let file={
                            uri: imgPath,
                            name: IMAGE1,
                            filetype:TYPE,
                            folderName:'ResumeFiles',
                        }
                        Allfiles.push(file);
                    }

                    if (IMAGE2!=null && IMAGE2!='') {
                        let imgPath=common_ImagePath+IMAGE2;
                       let file={
                            uri: imgPath,
                            name: IMAGE2,
                            filetype:TYPE,
                            folderName:'ResumeFiles',
                        }
                        Allfiles.push(file);
                    }

                    
                }
                resumeData['MID']="0";
                resumeData['Keys']='ResumeData';
                resumeData['JsonData']=JSON.stringify(myresumeObj);
                resumeData['UserId']=props.UserId;
                // resumeData['ProjectID']=props.projectCode;
                // resumeData['ProjectName']=props.projectName;



                console.log('postData',resumeData);
                resolve({'PostData':resumeData,'Allfiles':Allfiles});
                
            }
            else{
             resolve({'PostData':resumeData,'Allfiles':[]});
            }
        },function (txn2, txnerr) { console.log(txnerr);resolve({'PostData':resumeData,'Allfiles':[]});},);


     
       
          
      })
      
  

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

}

async function allUploadData(uniqueId=''){
    console.log('getUploadData');
    let allResumData=await getPostData(uniqueId);
    let PostData1=allResumData.PostData || {};
    let Allfiles=allResumData.Allfiles || [];
   
    const url=resumeurl+getMethodName(METHODS.UPLOADJSON_METHOD);
    console.log('url: ',url,PostData1);

  
    await UploadData2(url,PostData1)
    .then(async(res)=>{ 
      console.log('resultupload',res);
      // res={UploadJsonResult:'Success'};
      if(res.UploadJsonResult && res.UploadJsonResult.includes('Success')){
        let isupdated=await UpdateResumeStatus(uniqueId);
        console.log('isStatus Updated:',isupdated);
        // Upload Image 
        let isImageUploaded=await uploadImages(Allfiles);
        console.log('isImageUploaded:',isImageUploaded);
        setProcessing(false);
        if(isImageUploaded){
          notify('All resume data uploaded successfully!');
          props.navigation.goBack();
        }
        else{
          notify('Data uploaded but cannot upload files and images!');
        }
      }
      else{
        setProcessing(false);
        notify('Error while uploading resume data');
      }
      
    })

   

}

async function uploadImages(Allfiles=[]){
  let uploadFileCount=0;
  console.log('Allfile in uploadImages ',Allfiles);
  const url1=('https://hrm.parinaam.in/webservice/Imageupload.asmx/')+getMethodName(METHODS.UPLOADIMAGES_METHOD)
  console.log('url1:',url1);

  let isAllUploaded=false;
  return await new Promise.all(
    Allfiles.map(async(file,index)=>{
      console.log('file:',file.uri);
      let actualfilepath='file://'+file.uri;
      console.log('actualfilepath',actualfilepath)
      let isExists=await RNFS.exists(actualfilepath).then((res)=>{return res;});
      console.log('isExists file',index,isExists,actualfilepath);
      let postData=new FormData();
      postData.append('file', {
          uri: actualfilepath,
          type: file.type,//mime.getType(actualfilepath),
          name: file.name,
      });
      
      postData.append('Foldername',file.folderName);

      console.log("url1",url1)
      
      console.log("postdataimage",postData);
      return await UploadFormData(url1,postData)
      .then(async(res1)=>{         
        console.log('res1:',res1);      
        if(res1.includes('Success')){
          uploadFileCount++;
          RNFS.unlink(actualfilepath);
          return true;
        }else{
          return true;
        }  
      })
      .catch((err)=>{
        console.log(err);
        return false;
      });
    

     
    })
  ).then((val)=>{
    console.log('onall files return :',val);
    if(Allfiles.length==uploadFileCount){
      return true;
    }
    else{
      return false;
    }
  }).catch((err)=>{
    console.log('error',err);
    return false;
  });
  

 
}


  async function UpdateResumeStatus(uniqueId=''){
    
    return new Promise((resolve,reject)=>{
      db.transaction(async function (txn) {  
        
          
        let status='Y';
        // let JcpType=isAdhocScreen==true?'Sup_AdhocJourneyPlan':'Sup_JourneyPlan';
        let q=`Update ${AppTables.RESUME_DATA} set STATUS='${status}' where  UID='${uniqueId}'`;
        await txn.executeSql(q,[],async function (txn2, txnres2) {
          console.log('resume update');  
          resolve(true);

        },function(txn2,txnerr){y
          notify('Error while updating resume status');
          console.log(txnerr);
          resolve(false);
        });
      });     
    }).catch((err)=>{
      console.log(err);
      notify('Error while updating resume status');
      return false;
    });
    
}


// 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.height;
//         let picture_clicked_time=new Date();
//         picture_clicked_time=moment(picture_clicked_time).format('DDMMYYYYHHmmss')
//         let filename='Resume'+(props.UserId || '')+picture_clicked_time+'.jpg';

//         let imagePath='file://'+`${common_ImagePath}${filename}`;

        
//         RNFS.moveFile(imgurl,imagePath)
//         .then(resn => {
//           let data=image;
//           if(type=='1'){
//               data['Image1Path']=imagePath;
//               data['Image1Name']=filename;
//           }
//           else{
//               data['Image2Path']=imagePath;
//               data['Image2Name']=filename;
//           }

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


async function getImage(imgdata){
  let type=getImageProps.type || '';

  if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
      notify(ST.Cameraunavailable);
  }
  else if(typeof imgdata =='object' && imgdata.uri!=null){
    const img=imgdata;
    const imgurl=img.uri, imgWidth=img.width, imgHeight=img.height;
   
    
    let picture_clicked_time=new Date();
    picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
    
    
    const mark_text1=picture_clicked_time;
   
    const mark_text2=' Name:'+formData.name+' | Image Type: Resume'+' | Date:'+picture_clicked_time;

   
    console.log('imgurl marktext1:',mark_text2);
    await marktext1(mark_text1,imgurl)
    .then((res)=>{
        if(res.success){
          
            let uri=res.uri;
            marktext2(mark_text2,uri,imgWidth, imgHeight)
            .then((res)=>{

                if(res.success){
                    let picture_clickedd=new Date();
                    // let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                    let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                    let filename='Resume'+(formData.name || '')+picture_clicked_time+'.jpg';
                    let alldata=hrImage;

                    let imagePath='file://'+`${common_ImagePath}${filename}`;
                    RNFS.moveFile(res.uri,imagePath)
                    .then(resn => {
                      if(type=='1'){
                        alldata['Image1Path']=imagePath;
                        alldata['Image1Name']=filename;
                        setHrImage(alldata);
                        setrerenderdata(!rerenderdata);
                       
                      }
                      else{
                        alldata['Image2Path']=imagePath;
                        alldata['Image2Name']=filename;
                        setHrImage(alldata);
                        setrerenderdata(!rerenderdata);
                     
                      }
                  
                    
                       
                    })
                    .catch(err => {
                        console.log('ERROR: image file write failed!!!');
                        console.log(err.message, err.code);
                    }); 
                             
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
              
            });
          
            
        }
        else{
            if(res.imagenotfound){
                notify(ST.Pleasecaptureaimage);
            }
            else{
                notify(res.error);
            }
        }
    });            
}        
}

async function openCamera(type='1'){  
    setGetImageProps({type:type}); 
    setShowCamera(true);
}

async function downloaddatahr(){
  let token = await get_item('loginToken');
  let loginInfo=await get_item('loginInfo');
  const loginDetails=JSON.parse(loginInfo);
  
  const data={Downloadtype: 'Position_Master',username: loginDetails.UserId,empid: '',token: token,};
  const url=resumeurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
  console.log('res',data)

  //download position data

  await getDownloadJson(url,data)
  .then((res)=>{        
    if(res.Position_Master){
     
      let dataarr=res.Position_Master?res.Position_Master:[];         
      setPosition(dataarr);
      downloaddatahq();
      // call education
       setProcessing(false);
    }
  })
  .catch((err)=>{
    setProcessing(false);
    notify('Not data downloaded..!','SHORT');
    console.log('Position_Master not download data...!',err);
  }); 


}

async function downloaddatahq(){
  
  let loginInfo=await get_item('loginInfo');
  const loginDetails=JSON.parse(loginInfo);
  
  const data={Downloadtype:"Qualification_Master",username:loginDetails.UserId,empid:'',};
  const url=resumeurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);

  //
  await getDownloadJson(url,data)
  .then((res)=>{        
    if(res.Qualification_Master){
      let dataarr=res.Qualification_Master?res.Qualification_Master:[];         
      setEducation(dataarr);
      setProcessing(false);
    }
  })
  .catch((err)=>{
    setProcessing(false);
    console.log('Position_Master not download data...!',err);
  }); 


}
// console.log('imagePath.Image1Path',imagePath.Image1Path)
// console.log('imagePath.Image2Path',imagePath.Image2Path)

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>  
    {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
    <CustomHeader {...props} title={'Add Resume/CV'}/>
      {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
      <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.hr_customstylewrapper,customStyle.ImageTypesPageWrap]}>

    <View style={[ customStyle.mt10]}>
        <TouchableOpacity style = {[customStyle.hr_viewButton]} onPress={()=>{props.navigation.navigate('ViewListData')}}>
        <Text style = {[customStyle.hr_viewButtonText]}>View List</Text>
        </TouchableOpacity>
        
         </View>

         <View style ={[customStyle.hr_LHd,customStyle.mt40]}></View>


  { rerenderdata==rerenderdata &&
    <ScrollView 
     contentContainerStyle={customStyle.hr_scroll} 
     style={customStyle.hr_scrollOuter}
     showsVerticalScrollIndicator={false}
    >
        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Name</Text></View>
                                                            
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
            style={[customStyle.hrInputStyle]}
            placeholder=""
            placeholderTextColor={PageTheme.$placeholder_color} 
            value ={(formData.name!=null?formData.name:'')}
            onChangeText={(val)=>{onTextChange('name',val)}}
            autoComplete='off'
            />
            </View>
        
        </View>


        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Mobile No.</Text></View>
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
            style={[customStyle.hrInputStyle]}
            placeholder=""
            placeholderTextColor={PageTheme.$placeholder_color} 
            value ={(formData.mobileno!=null?formData.mobileno:'')}
            keyboardType = 'number-pad'
            maxLength={10}
            onChangeText={(val)=>{onTextChange('mobileno',val)}}
            autoComplete='off'/>
            </View>
        </View>

        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Locality</Text></View>
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
              style={[customStyle.hrInputStyle]}
              placeholder=""
              placeholderTextColor={PageTheme.$placeholder_color} 
              value ={(formData.locality!=null?formData.locality:'')}
              onChangeText={(val)=>{onTextChange('locality',val)}}
              autoComplete='off'
            />
            </View>
        </View>
        <View style={[customStyle.hr_childlayout]}>
        <View style={customStyle.addVisFormGrp}>
            <Text style={customStyle.hr_prd_flexlabel}>{'Position'}</Text>
            {CustomPicker(props,Position,'DesignationName','DesignationId','DesignationName','DesignationId',onselectionChange,{value:formData.DesignationName,otherData:{}})}
        </View>
        </View>

        <View style={[customStyle.hr_childlayout]}>
          <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Project</Text></View>
          <View style={[customStyle.hr_prd_col100]}>
          <TextInput 
            style={[customStyle.hrInputStyle]}
            placeholder=""
            placeholderTextColor={PageTheme.$placeholder_color} 
            value ={(formData.project!=null?formData.project:'')}
            onChangeText={(val)=>{onTextChange('project',val)}}
            autoComplete='off'
          />
          </View>
        </View>

        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Agency</Text></View>
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
              style={[customStyle.hrInputStyle]}
              placeholder=""
              placeholderTextColor={PageTheme.$placeholder_color} 
              value ={(formData.agency!=null?formData.agency:'')}
              onChangeText={(val)=>{onTextChange('agency',val)}}
              autoComplete='off'
            />
            </View>
        </View>


        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Experience</Text></View>
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
            style={[customStyle.hrInputStyleexp,{}]}
            placeholder=""
            placeholderTextColor={PageTheme.$placeholder_color} 
            multiline={true}
            numberOfLines={5}
            value ={(formData.experience!=null?formData.experience:'')}
            onChangeText={(val)=>{onTextChange('experience',val)}}
            autoComplete='off'
            />
            </View>
        </View>


        <View style={[customStyle.hr_childlayout]}>
        <View style={customStyle.addVisFormGrp}>
            <Text style={customStyle.hr_prd_flexlabel}>{'Highest Qualification'}</Text>
            {CustomPicker(props,Education,'Qualification_Name','Qualification_Id','Qualification_Name','Qualification_Id',onselectionChange,{value:formData.Qualification_Name,otherData:{}})}
            
        </View>
        </View>

        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Store</Text></View>
                                                            
            <View style={[customStyle.hr_prd_col100]}>
            <TextInput 
              style={[customStyle.hrInputStyle]}
              placeholder=""
              placeholderTextColor={PageTheme.$placeholder_color} 
              value ={(formData.store!=null?formData.store:'')}
              onChangeText={(val)=>{onTextChange('store',val)}}
              autoComplete='off'
            />
            </View>
        </View>

        <View style={[customStyle.hr_childlayout]}>
            <View style={{}}><Text style={customStyle.hr_prd_flexlabel}>Upload PDF/Images</Text></View>
            <View style={[customStyle.hr_prd_colexp]}>
             <Text style={[customStyle.hrInputStylepdf]} >{singleFile.fileName!=null ? singleFile.fileName: ''}</Text>
            <TouchableOpacity onPress={selectOneFile} style={{zIndex:9999}}>
              <SvgXml width={45} height={45} xml={add_icon}/>
             </TouchableOpacity>
            </View>

        </View> 
        <View style={[customStyle.addVisCol100]}>
          <View style={customStyle.addVisFormGrp}>
              <Text style={customStyle.addVisLabel}>Photo of CV</Text>
              <View style={customStyle.addVisCameras}>
                  <View style={customStyle.openStkCameraCon}>
                      { (hrImage.Image1Path=='' || hrImage.Image1Path==null) && 
                          <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{{openCamera('1')}}}>
                              <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                          </TouchableOpacity>
                      }
                      {
                        // console.log('imagePath.Image1Path',imagePath.Image2Path)

                        (hrImage.Image1Path!='' && hrImage.Image1Path!=null) && 
                          <View style={customStyle.osCatImageView}>
                            
                              <Image style={customStyle.osCatImage} source={{uri:hrImage.Image1Path}}/>
                              <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{{openCamera('1')}}}>
                                  <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                              </TouchableOpacity>
                          </View>                                    
                      }       
                  </View>

                  <View style={customStyle.addVisCameras}>
                  <View style={customStyle.openStkCameraCon}>
                      { (hrImage.Image2Path=='' || hrImage.Image2Path==null) && 
                          <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{{openCamera('2')}}}>
                              <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                          </TouchableOpacity>
                      }
                      { (hrImage.Image2Path!='' && hrImage.Image2Path!=null) && 
                          <View style={customStyle.osCatImageView}>
                              <Image style={customStyle.osCatImage} source={{uri:hrImage.Image2Path}}/>
                              <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{{openCamera('1')}}}>
                                  <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                              </TouchableOpacity>
                          </View>                                    
                      }       
                  </View>
                  
              </View>
                  
              </View>
          </View>
        </View>
    </ScrollView> }
  

    <View style={[customStyle.hr_SubmitBtn]}>
        <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
        </View>
    </View>
    </LinearGradient>

   

     </Container>
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(HR)