import React,{PureComponent} from "react";
import { Link } from "react-router-dom";

import {
  CustomInput,
  Breadcrumb,
  BreadcrumbItem,Row,Col,
  Card,
  CardBody,
  Container,
  Button,
  Label,
  FormGroup} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";

import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import { toastr } from "react-redux-toastr";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback} from "availity-reactstrap-validation";


class Validation extends PureComponent {
    constructor(props) {
      super(props);
      this.routeChange = this.routeChange.bind(this);
      this.onChangeHandler = this.onChangeHandler.bind(this);
      this.facematchChange=this.facematchChange.bind(this);
    this.livenessEnable=this.livenessEnable.bind(this);
    this.handleCheckonly=this.handleCheckonly.bind(this);
   this.handleCheckChangeqrcode=this.handleCheckChangeqrcode.bind(this);
    this.handleCheckChangehrbiomatrics=this.handleCheckChangehrbiomatrics.bind(this);
      //this.googleTranslateElementInit = this.googleTranslateElementInit.bind(this);
      this.state = { file: ''};
      // this.state = {file: '',imagePreviewUrl: ''};
      this.state = {
        is_biomatrics:false,
      facematch_percentage:'50',
      liveness_percentage:'20',
      facematchpercentage:false,
        user_id:'0',
        selectedFile: null,
        hrDocs: [{ name: ""}],
        units:'',
        files: '',
        docs:'',
        docs1:'',
        fd:'',
        timezones:'',
        formData:{
          title: '',
          quantity: '',
          weight: '',
          unit: '',
          sequence:'',
        },
        submitted1: false,
        submitted: false,
        timeOut: 5000,
        showCloseButton: true,
        progressBar: true,
        position: "top-right"
      }
     
      this.options = {
        timeOut: parseInt(this.state.timeOut),
        showCloseButton: this.state.showCloseButton,
        progressBar: this.state.progressBar,
        position: this.state.position
      }; 
    
    }

    handleCheckChangeqrcode=()=>
    {
      this.setState({
        organizationqr_scan: !this.state.organizationqr_scan
      })
    }
  
    handleCheckChangehrbiomatrics=()=>
    {
      //alert(this.state.facematch_enable);
      if(this.state.is_biomatrics==false)
      {
      
        this.setState({
          facematchenableblock: true
        });
        
        if(this.state.facematchvalue==true)
        {
         this.setState({
          facematchpercentage: true
        });
        }
  
  
        if(this.state.livenessvalue==true)
        {
         this.setState({
          livenesspercentage: true
        });
        }
       
        // this.setState({
        //   facematchpercentage: false
        // });
        
        // this.setState({
        //   livenesspercentage: false
        // });
  
      }
      else{
        this.setState({
          facematchenableblock: false
        });
        
        this.setState({
          livenessenable: false
        });
          this.setState({
          facematchpercentage: false
        });
        
        this.setState({
          livenesspercentage: false
        });
      }
      this.setState({
        is_biomatrics: !this.state.is_biomatrics
      })
    }
    facematchChange(e) {
     // alert(e.currentTarget.checked);
      if (e.currentTarget.checked == true) {
        this.setState({
          facematchvalue:  true
        });
        this.setState({facematchpercentage:true});
      }
      else{
        this.setState({
          facematchvalue:  false
        });
        this.setState({facematchpercentage:false});
      }
    }

    livenessEnable(e)
    {
      if (e.currentTarget.checked == true) {
        this.setState({
          livenessvalue:  true
        });
        this.setState({livenesspercentage:true});
          
      }
      else
      {
        this.setState({
          livenessvalue:  false
        });
        this.setState({livenesspercentage:false});
      }
    }

    onChangeHandler=event=>{
      // this.setState({
      //  selectedFile: event.target.files,
      // })
       let file = event.target.files[0];
       this.setState({
        file: file,
      });
      // this.setState({files: this.state.files.concat(Array.from(event.target.files))}
      
      }
  

    routeChange() {
      this.props.history.push('/');
    }
    componentDidMount(){

    //   window.googleTranslateElementInit = this.googleTranslateElementInit
    //     const google = window.google;
    // const script = document.createElement("script");
    // script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);   

      var admin_id= localStorage.getItem('uname'); 
      if(admin_id == null){
        this.routeChange();
      } 
        const answer_array = this.props.location.pathname.split('/');
        //alert(answer_array['3']);
    
       if(answer_array['3'] &&  answer_array['3'].includes("hr")){ 
        this.state.req_id = answer_array['3'];
            var req = answer_array['3'];
            var request_id = req.substr(2, 4);
            fetch(myConstClass.BASE_URL+'user/getRequestInfo/'+request_id)
            .then(response => response.json())
            .then(response =>{
            this.setState({formData: response})
          }).catch(err => console.log(err))
       } else if(answer_array['3']){ 
            this.state.user_id = answer_array['3'];
            fetch(myConstClass.BASE_URL+'user/getAdminInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{

              
              if(response.only_checkin=='1')
              {
                this.setState({
                  only_checkin:  true
                     });
              }
              else{
                this.setState({
                  only_checkin:  false
                     });
              }
              if(response.organizationqr_scan=='1')
              {
                this.setState({
                  organizationqr_scan:  true
                     });
              }
              else{
                this.setState({
                  organizationqr_scan:  false
                     });
              }
    
              if(response.is_biomatrics=='1')
              {
                this.setState({
                  facematchenableblock:  true
                     });
                     this.setState({
                      is_biomatrics:  true
                         });
    
    
                         if(response.liveness_enable=='1')
                         {
                           this.setState({
                       livenessenable:  true
                     });
                     this.setState({
                       livenessvalue:  true
                     });
                     this.setState({
                       livenesspercentage:  true
                     });
                         }
                         else{
                           this.setState({
                             livenessenable:  false
                           });
                           this.setState({
                             livenesspercentage:  false
                           });
                           this.setState({
                             livenessvalue:  false
                           });
                         }
           
           
                         if(response.facematch_enable=='1')
                         {
                           this.setState({
                       facematch_enable:true
                     });
                     this.setState({
                       facematchvalue:true
                     });
                     this.setState({
                      facematchpercentage:true
                     });
                         }
                         else{
                           this.setState({
                             facematch_enable:false
                           });
                           this.setState({
                             facematchvalue:false
                           });
                           this.setState({
                            facematchpercentage:false
                           });
                         }
    
              }
              else{
    
                this.setState({
                  is_biomatrics:false
                     });
    
                this.setState({
                  facematchenableblock:false
                });

                this.setState({
                  facematchpercentage:false
                });
              
                this.setState({
                  livenesspercentage:false
                });
              }


             






            this.setState({formData: response})
          }).catch(err => console.log(err))
      
          fetch(myConstClass.BASE_URL+'user/getAdminDocs/'+answer_array['3'])
          .then(response => response.json())
          .then(response =>{
          this.setState({docs: response})
        }).catch(err => console.log(err))

          
        }
        fetch(myConstClass.BASE_URL+'user/get_all_timezones/')
        .then(response => response.json())
        .then(response =>{this.setState({timezones: response})}).catch(err => console.log(err))    
      }

      // googleTranslateElementInit () {
      //   /* eslint-disable no-new */
      //   const google = window.google;
      //     new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element_1');
      //   new window.google.translate.TranslateElement({pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element_1')
      // }

      // this.setState({hrDocs: this.state.hrDocs.concat(Array.from(evt.target.files))}
      handleDocumentChange = idx => evt => {
        // const newHrDocs = this.state.hrDocs.map((hrdoc, sidx) => {
        //   if (idx !== sidx) return hrdoc;
        //   return { ...hrdoc, name: evt.target.files };
        // });

        // this.setState({ hrDocs: newHrDocs });
        let file = evt.target.files[0];
        this.setState({
         file: file,
       });
       this.setState({ submitted1: true }, () => {  
       setTimeout(() => this.setState({ submitted: false }), 5000);
       const data = new FormData() 
       data.append('file', this.state.file);
            fetch(myConstClass.BASE_URL+'user/add_admin_docs/'+this.state.user_id, {
            method: 'POST',
             body:data })
            .then(response => response.json())
            .then(response =>{this.setState({fd: response})}).catch(err => console.log(err)) 
       })  
      };


      handleRemoveHrDocs = idx => () => {
        fetch(myConstClass.BASE_URL+'user/remove_admin_docs/'+this.state.user_id+'/'+idx)
        .then(response => response.json())
        .then(response =>{this.setState({fd: response})}).catch(err => console.log(err))   

        this.setState({
          hrDocs: this.state.hrDocs.filter((s, sidx) => idx !== sidx)
        });
      };
      
      
      handleAddHrDocs = () => {
        
        this.setState({
          hrDocs: this.state.hrDocs.concat([{ name: "" }])
        });
      }

      handleRemoveHrDocsEdit = i => () => { 

        fetch(myConstClass.BASE_URL+'user/remove_admin_docs/'+this.state.user_id+'/'+i)
          .then(response => response.json())
          .then(response =>{this.setState({fd: response})}).catch(err => console.log(err))   

        this.setState({
          docs: this.state.docs.filter((s, si) => i !== si)
        });
      };
      handleCheckonly=()=>
      {
    
        this.setState({
          only_checkin: !this.state.only_checkin
        })
     
      }


      handleValidSubmit = () => {
 
        this.setState({ submitted: true }, () => {
         
            setTimeout(() => this.setState({ submitted: false }), 5000);
            const data = new FormData()
            // for(var x = 0; x<this.state.files.length; x++) {
            // data.append('file', this.state.files[x])
            // }
            // alert( JSON.stringify(this.state.shareholdersImage));
            //  for(var x = 0; x<this.state.shareholdersImage.length; x++) {
            // var arr =  JSON.stringify(this.state.shareholdersImage[x]);
            // }

            data.append('signup_id', this.state.req_id);
            data.append('file', this.state.file);
            data.append('file', this.state.hrDocs);
            data.append('formdata',JSON.stringify($('#pform').serializeArray()));  
            fetch(myConstClass.BASE_URL+`user/add_admin/`+this.state.user_id, {
                    method: 'POST',
                    // body: JSON.stringify($('#pform').serializeArray()),
                    body:data,
                  }).then(response =>  response.json()).then((response) => {
                    if(response == true){
                      
                      (this.state.user_id =='0' ) ?
                      toastr.success(
                        'Success',
                        "Hr Admin Added Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Hr Admin Updated Successfully..!",
                        this.options
                      );
    
                      this.props.history.push('/hradmin/listing');
                    } else if(response == 2){
                      toastr.error(
                        'Error',
                        "Email Already Exists..!",
                        this.options
                      )
                    } else if(response == 5){
                      toastr.error(
                        'Error',
                        "HR Code Already Exists..!",
                        this.options
                      )
                    } else {
                      toastr.error(
                        'Error',
                        "HR Admin not Added..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }


      render () { 
        const { formData,units,submitted,timezones,docs} = this.state;
        let documents;
        let personal_documents;
       if(this.state.user_id !=='0'){
        documents = "Documents Uploaded :";
       } else {
        documents = "";
       }
      
       if(this.state.req_id != null){
        personal_documents = <div>Uploaded Document: <a href= { `https://beta.workzoneplus.com/backend/uploads/`+formData.personal_doc} >{formData.personal_doc}</a>
        <hr/></div>;
       } else {
        personal_documents = "";
       }
       
        //  documents = 
        
        return(
        <Container fluid>
          <Header><div  id="google_translate_element_1"></div><br/>
            <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>
      
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/hradmin/listing">HR Admin</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</BreadcrumbItem>
            </Breadcrumb>
          </Header>
      
          <Card>
            {/* <CardHeader>
              <CardTitle tag="h5">Availity Validation</CardTitle>
              <h6 className="card-subtitle text-muted">
                Form validation by availity-reactstrap-validation
              </h6>
            </CardHeader> */}
            <CardBody>
              <AvForm id="pform" onValidSubmit={this.handleValidSubmit}  encType="multipart/form-data">
               
                {/* With AvGroup AvInput and AvFeedback to build your own */}
                <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">First Name</Label>
                  <AvInput name="first_name" id="example" required value={formData ? formData.first_name || formData.name:'' }/>
                  <AvFeedback>Enter First Name!</AvFeedback>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <AvGroup>
                  <Label for="example">Last Name</Label>
                  <AvInput name="last_name" id="example" required value={formData ? formData.last_name:''}/>
                  <AvFeedback>Enter Last Name!</AvFeedback>
                </AvGroup>
                </Col>
                </Row>
                <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">Email</Label>
                  <AvInput name="email" type="email" id="example"   readonly ={(this.state.user_id !='0' ) ? 'readonly' : false } required value={formData ? formData.email:''}/>
                  <AvFeedback>Enter Email</AvFeedback>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <AvGroup>
                  <Label for="example">Password</Label>
                  <AvInput name="password"  id="example" required value={formData ? formData.password:''}/>
                  <AvFeedback>Enter Password</AvFeedback>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <AvGroup>
                  <Label for="example">Mobile No</Label>
                  <AvInput name="mobile_no"  id="example"  required value={formData ? formData.mobile_no:''}/>
                  <AvFeedback>Enter Mobile No</AvFeedback>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <AvGroup>
                  <Label for="example">Position</Label>
                  <AvInput name="position"  id="example" required value={formData ? formData.position:''}/>
                  <AvFeedback>Enter Position</AvFeedback>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <AvGroup>
                 <AvField
                  type="select"
                  name="gender"
                  label="Select Gender"
                  value={formData ? formData.gender:''}
                >
                      <option value="1">Male</option>
                      <option value="2">Female</option>
                      <option value="3">Other</option>
                </AvField>
                </AvGroup>
                </Col>
                <Col lg={6}>
                {/* <AvGroup>
                <Label for="example">Status</Label>
                <Input
                        type="select"
                        id="exampleCustomSelect"
                        name="status"
                        className="mb-3"
                    >
                        <option value="1">Active</option>
                        <option value="2">In-Active</option>
                    </Input>
                </AvGroup> */}
                <AvGroup>
                <AvField
                    type="select"
                    name="status"
                    label="Select Status"
                    value={formData ? formData.status:''}
                  >
                     <option value="1">Active</option>
                        <option value="2">In-Active</option>
              </AvField>
              </AvGroup>
                </Col>
                {/* <Col lg={6}>
                 <AvField
                  type="select"
                  name="unit"
                  label="Unit"
                  value={formData ? formData.unit:''}
                >
                  {units ?  units.map((cell, i) => {
                  return(<option value={cell.id}>{cell.name}({cell.symbol})</option>)
                  }) : ''}       
                </AvField>
                </Col> */}
                </Row>
                <Row>
                <Col lg={6}>
                 <AvField
                  type="select"
                  name="timezone"
                  label="Select Timezone"
                  value={formData ? formData.timezone:''}
                >
                  {timezones ?  timezones.map((cell, i) => {
                  return(<option value={cell.TimeZone}>{cell.TimeZone+'(UTC '+cell.UTC_offset+')'}</option>)
                  }) : ''}       
                </AvField>
                </Col> 
                <Col lg={6}>
                  <AvGroup>
                   <Label for="example">ID Code</Label>
                   <AvInput name="hr_code" id="example" required value={formData ? formData.hr_code:''}/>
                   <AvFeedback>Enter ID Code!</AvFeedback>
                  </AvGroup>
                 </Col>
                </Row>
        
                  <Row>
                  <Col lg={6}>
                <AvGroup>
                 <AvField
                  type="select"
                  name="manage_promotions"
                  label="Allow Manage Promotions"
                  value={formData ? formData.manage_promotions:''}
                >     <option value="0">No</option>
                      <option value="1">Yes</option>
                      
                </AvField>
                </AvGroup>
                </Col>

                <Col lg={6}>
                <AvGroup>
                 <AvField
                  type="select"
                  name="is_archived"
                  label="Allow Archived"
                  value={formData ? formData.is_archived:''}
                >     <option value="0">No</option>
                      <option value="1">Yes</option>
                      
                </AvField>
                </AvGroup>
                </Col>
               </Row>
               {/* <Row>
               <Col lg={6}>
                <AvGroup>
                 <AvField
                  type="select"
                  name="is_biomatrics"
                  label="Allow Biomatrics"
                  value={formData ? formData.is_biomatrics:''}
                >     <option value="0">No</option>
                      <option value="1">Yes</option>
                      
                </AvField>
                </AvGroup>
                </Col>
               </Row> */}
             

               <Row>



<Col lg={6}>
        <Label for="example">Hr Biomatrics</Label>
     <CustomInput
    type="checkbox"
    name = "is_biomatrics"
    id="exampleCustomCheckbox"
    label="Hr Biomatrics"

    className="mb-2"
    checked={ this.state.is_biomatrics} 
    onChange={ this.handleCheckChangehrbiomatrics }
/>
   </Col> 











              <Col lg={6}>
        <Label for="example">Scan Organization Qr Code</Label><br/>
     <CustomInput
    type="checkbox"
    name = "organizationqr_scan"
    id="exampleCustomCheckbox1"
    label="Scan Organization Qr Code"

    className="mb-2"
    checked={ this.state.organizationqr_scan} 
    onChange={ this.handleCheckChangeqrcode }
/>
   </Col> 

</Row>

<br/>

              <Row>

<Col lg={6} style={{ display: this.state.facematchenableblock ? "block" : "none" }}>


<CustomInput
style={{ color: 'black', border: '1px solid #ffffff', float: 'right !important', margin: 'auto', fontSize: "15px" }}
checked={this.state.facematchvalue}
type="switch"
id="exampleCustomSwitch"
name="facematch_enable"
label="Facematch"
onChange={this.facematchChange}
/>

</Col>




<Col lg={6}  style={{ display: this.state.facematchpercentage ? "block" : "none" }}>
  <AvGroup>
    <Label for="example">  Percentage<span style={{color:'red',fontSize:'15px'}}> (0-100%)</span></Label>

    <AvInput name="facematch_percentage" id="example" required value={formData.facematch_percentage ? formData.facematch_percentage : '50'} />
    <AvFeedback>Enter Percentage</AvFeedback>

  </AvGroup>
</Col>
</Row>

<br/>
<Row>

<Col lg={6} style={{ display: this.state.facematchenableblock ? "block" : "none" }}>


<CustomInput
style={{ color: 'black', border: '1px solid #ffffff', float: 'right !important', margin: 'auto', fontSize: "15px" }}
checked={this.state.livenessvalue}
type="switch"
id="exampleCustomSwitch1"
name="liveness_enable"
label="Liveness"
onChange={this.livenessEnable}
/>

</Col>




<Col lg={6}  style={{ display: this.state.livenesspercentage ? "block" : "none" }}>
  <AvGroup>
    <Label for="example">Percentage<span style={{color:'red',fontSize:'15px'}}> (0-100%)</span></Label>

    <AvInput name="liveness_percentage" id="example" required value={formData.liveness_percentage ? formData.liveness_percentage : '20'} />
    <AvFeedback>Enter Percentage</AvFeedback>

  </AvGroup>
</Col>
</Row>
<br/>

<Row>

<Col lg={6}>
        <Label for="example"></Label><br/>
     <CustomInput
    type="checkbox"
    name = "only_checkin"
    id="exampleCustomCheckbox2"
    label="Checkin with gps only"
    className="mb-2"
    checked={this.state.only_checkin} 
    onChange={this.handleCheckonly}
/>
   </Col> 

</Row>

<Row>
                <Col lg={3}><br/>
                  {documents}
                
                  {personal_documents}
                  {docs ?  docs.map((cell, i) => {

                  return(   <div><a href= { `https://beta.workzoneplus.com/backend/uploads/docs/hr_admin/`+cell.hr_admin_id+'/'+cell.document} >{cell.document}           </a>
                         <i onClick={this.handleRemoveHrDocsEdit(i)} class=" fa-trash" style={{color:'red',fontSize:'20px',cursor:'pointer'}}>   X</i><hr/></div>)
                   }) : '' }
                  </Col>
                  </Row>
                  
                  <Row>
                  <Col xs="12" md="9">
                    <Label for="example">Select File</Label>  <br/> 
                     {this.state.hrDocs.map((hrdoc, idx) => (
                       <div className="hrdoc">
                        <input  id={`file_${idx}`}  type="file" name ={`file_${idx}`}  onChange={this.handleDocumentChange(idx)}/>
                        <i onClick={this.handleRemoveHrDocs(idx)} class=" fa-trash" style={{color:'red',fontSize:'20px',cursor:'pointer'}}>X</i>
                       <br/> <br/></div>
                    ))}

<small>('png','jpg','jpeg','pdf','docs','JPG')</small>

<br/>

                    <button style={{marginTop:'15px'}}
                      type="button"
                      onClick={this.handleAddHrDocs}
                      className="btn btn-primary btn-sm"
                    >
                      Add More
                    </button><br/>
                  </Col>
               </Row><br/>















                <FormGroup>
                <Link to="/hradmin/listing" style={{margin:"0rem 1.50rem 1.50rem 0rem",border: "#6f42c1 1px solid",color: "#6f42c1",padding: "0.10rem 0.90rem 0.30rem 0.90rem",textDecoration: 'none',borderRadius:'0.2rem'}}>Cancel</Link>
                {(this.state.user_id !='0' ) ? <Button disabled={submitted}>{
                              (submitted && 'Your form is submitted!')
                              || (!submitted && 'Update')
                          }</Button> : <Button disabled={submitted}>{
                              (submitted && 'Your form is submitted!')
                              || (!submitted && 'Add')
                          }</Button> }
                  
                   </FormGroup>
              </AvForm>
            </CardBody>
          </Card>
        </Container>
      )
      }




}

export default Validation;

