


import React,{PureComponent} from "react";
import { Link } from "react-router-dom";
import InputMask from "react-input-mask";
import DatePicker from "react-datepicker";
import TimePicker from 'react-time-picker';
import "react-datepicker/dist/react-datepicker.css";
import ReactQuill from "react-quill";

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

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";
import cookie from "react-cookies";

// import { googleTranslate } from "./utils/googleTranslate";

import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox
} 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.state = { file: ''};
      //this.googleTranslateElementInit = this.googleTranslateElementInit.bind(this);
      // this.state = {file: '',imagePreviewUrl: ''};
     
      this.state = {
        shareholdersImage: [{ name: "", sequence: "1" }],
        user_id:'0',
        total:'1',
        units:'',
        org:'',
        emp:'',
        googleTranslateElementInit:'',
        startDate: new Date(),
        time: '10:00',
        timezones:'',
        selectedFile: null,
        moreDocs: [{ name: ""}],
        units:'',
        files: '',
        docs:'',
        docs1:'',
        fd:'',
        timezones:'',
        formData:{
          employee_id: '',
          attendance_date: '',
          clock_in: '',
          clock_out: '',
          timezone:'',
          languageCodes: [],
          language: cookie.load("language") ? cookie.load("language") : "en",
          question: cookie.load("question")
            ? cookie.load("question")
            : "What language do you prefer to read with?"
        },
        submitted: false,
        timeOut: 5000,
        showCloseButton: true,
        progressBar: true,
        position: "top-right",
        submitted1: false,
       
       
       
      }
     
      this.options = {
        timeOut: parseInt(this.state.timeOut),
        showCloseButton: this.state.showCloseButton,
        progressBar: this.state.progressBar,
        position: this.state.position
      };
    
    }

    _handleImageChange(e) {
        e.preventDefault();
        let reader = new FileReader();
        let file = e.target.files[0];
        reader.onloadend = () => {
          this.setState({
            file: file,
            imagePreviewUrl: reader.result
          });
        }
        reader.readAsDataURL(file)
      }



      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('/');
      }
      googleTranslateElementInit () {
        /* eslint-disable no-new */
        new window.google.translate.TranslateElement({pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element')
      }
    componentDidMount(){   
     
      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']){  
            this.state.user_id = answer_array['3'];
            fetch(myConstClass.BASE_URL+'organization/getAdmoreInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{this.setState({formData: response})}).catch(err => console.log(err));
        }
        fetch(myConstClass.BASE_URL+'organization/getAdminDocs/'+answer_array['3'])
        .then(response => response.json())
        .then(response =>{
        this.setState({docs: response})
      }).catch(err => console.log(err))
       
        fetch(myConstClass.BASE_URL + 'organization/get_all_organizations/'+admin_id)
        .then(response => response.json())
        .then(response => { this.setState({ organization: response }); }).catch(err => console.log(err)); 
           

      
          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);

      //   googleTranslate.getSupportedLanguages("en", function(err, languageCodes) {
      //     getLanguageCodes(languageCodes); // use a callback function to setState
      //   });
    
      //   const getLanguageCodes = languageCodes => {
      //     this.setState({ languageCodes });
      //   };
       }
     

//new change start for addmore 
        
      handleAddmoreDocs = () => {
        
        this.setState({
          moreDocs: this.state.moreDocs.concat([{ name: "" }])
        });
      }
      handleRemoveShareholderImage = idx => () => {
        this.setState({
          shareholdersImage: this.state.shareholdersImage.filter((s, sidx) => idx !== sidx)
        });
      };
      handleRemovemoreDocsEdit = i => () => { 

        fetch(myConstClass.BASE_URL+'organization/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)
        });
      };
       
      handleRemovemoreDocs = idx => () => {
        fetch(myConstClass.BASE_URL+'organization/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({
          moreDocs: this.state.moreDocs.filter((s, sidx) => idx !== sidx)
        });
      };
      handleShareholderNameChangeImage = idx => evt => {
        const newShareholders = this.state.shareholdersImage.map((shareholder, sidx) => {
          if (idx !== sidx) return shareholder;
          return { ...shareholder, name: evt.target.value };
        });
    
        this.setState({ shareholdersImage: newShareholders });
      }; 
           
      handleStatusChangeImage = idx => evt => {
        const newShareholders = this.state.shareholdersImage.map((shareholder, sidx) => {
          if (idx !== sidx) return shareholder;
          return { ...shareholder, name: evt.target.value };
        });
    
        this.setState({ shareholdersImage: newShareholders });
      }; 
       
     
      handleChangeSequenceno = idx => evt => {
        const newShareholders = this.state.shareholdersImage.map((shareholder, sidx) => {
          if (idx !== sidx) return shareholder;
          return { ...shareholder, name: evt.target.value };
        });
    
        this.setState({ shareholdersImage: newShareholders });
      }; 
      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+'organization/add_more_docs/'+this.state.user_id, {
            method: 'POST',
             body:data })
            .then(response => response.json())
            .then(response =>{this.setState({fd: response})}).catch(err => console.log(err)) 
       })  
      };


 

      // <-----------------------------end------------------------->
      handleAddShareholderImage = () => {
        this.setState({
          shareholdersImage: this.state.shareholdersImage.concat([{ name: "" }])
        });
        var total = $('#total').val();
        var totalNew = parseInt(total)+1;
        // alert(totalNew);
        // $('#total').val(totalNew);
        this.state.total = totalNew;
      }

      //  googleTranslateElementInit() {
      //   const google = window.google;
      //   new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
      // }
      handleValidSubmit = () => {
        var admin_id= localStorage.getItem('uname'); 

        this.setState({ submitted: true }, () => {  
            setTimeout(() => this.setState({ submitted: false }), 5000);
            const data = new FormData()
            console.log(this.state.file);
            console.log(this.state.moreDocs);
            data.append('file', this.state.file);
            data.append('file', this.state.moreDocs); 
            data.append('formdata',JSON.stringify($('#pform').serializeArray()));     
            fetch(myConstClass.BASE_URL+`organization/add_more/`+this.state.user_id, {
                    method: 'POST',
                    body: data,
                    // contentType: "application/json; charset=utf-8",
                  }).then(response =>  response.json()).then((response) => {
                    if(response == true){
                      (this.state.user_id =='0' ) ?
                      toastr.success(
                        'Success',
                        "Promotion Added Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Promotion Updated Successfully..!",
                        this.options
                      );
    
                      this.props.history.push('/morepromotions/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not Add Promotion ..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }

      render () { 
        // const { formData,units,submitted} = this.state;
        const { formData,units,submitted,timezones,docs} = this.state;
        const { languageCodes, language, question } = this.state;
         const { organization} = this.state;
        // let {imagePreviewUrl} = this.state;
        // let $imagePreview = null;
        // let file_link;
        // let img;
        // if(this.state.user_id !=='0'){
        // //  file_link = `https://alpha.workzoneplus.com/backend/uploads/banners/`+formData.image;
        //  file_link = `https://beta.workzoneplus.com/backend/uploads/banners/`+formData.image;
        // // file_link = `http://localhost/workzone/backend/uploads/banners/`+formData.image;
        //  img =  <img src={file_link}  style={{width: '50px',height:'50px'}}/>;
        // } else {
        //  file_link = ''; 
        //  img = '';
        // }
      
        // if (imagePreviewUrl) {
        //     $imagePreview = (<img src={imagePreviewUrl} style={{width: '50px',height:'50px'}}/>);   
        //     img = '';
        //   } else {
        //     $imagePreview = (<div className="previewText"></div>);   
        //   }

          
            
            let documents;
           if(this.state.user_id !=='0'){
            documents = "Documents Uploaded :";
           } else {
            documents = "";
           }
          

        return(
        
        <Container fluid> 
          <Header>
          {/* <div style={{fontSize:'20px',float:'right'}}  id="google_translate_element"></div> */}
            <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/morepromotions/listing">MorePromotions List</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}>
                {/* With AvGroup AvInput and AvFeedback to build your own */}
                <Row>
                <Col lg={6}>
                <AvGroup>
                  {/* <AvInput name="employee_id" id="example" required value={formData ? formData.employee_id:''}/>
                  <AvFeedback>Enter Employee ID!</AvFeedback> */}
                 <AvField
                  type="select"
                  name="organization_id"
                  label="Select Organization"
                  value={formData ? formData.organization_id:''}
                >
                  {organization ?  organization.map((cell, i) => {
                  return(<option value={cell.id}>{cell.title}</option>)
                  }) : ''}       
                </AvField>
                </AvGroup>
                </Col>
                </Row>
                {this.state.shareholdersImage.map((shareholder, idx) => (
                
           <div className="shareholder">
              {/* {docs ?  docs.map((cell, i) => {  */}
            
                <Row>
                  
                <Col lg={6}>  
                <AvGroup>
               
            {/* <input style={{width:'50%'}}
              type="text" id={`image_url${idx + 1}`} name={`image_url${idx + 1}`}
              placeholder={`URL`}
              value={shareholder.name}
              onChange={this.handleShareholderNameChangeImage(idx)}
            /> */}
                  <Label for="example">Sequence No</Label>
                  <Input style={{width:'100%'}} id={`sequence_no${idx + 1}`}  name={`sequence_no${idx + 1}`}
              type="number" 
              placeholder={`Enter your Sequence No`}
              required value={formData ? formData.sequence_no:''}
           onChange={this.handleChangeSequenceno}
              > </Input>
                </AvGroup>
                </Col> 
               
          
           <Col lg={6}>  
           <AvGroup>
                  <Label for="example">Redirect URL</Label>
                  <Input 
              type="text" id={`redirect_url${idx + 1}`} name={`redirect_url${idx + 1}`}
              placeholder={`URL`}
              required value={formData ? formData.redirect_url:''}
          onChange={this.handleShareholderNameChangeImage(idx)}
            > </Input>
                </AvGroup>
           </Col> 
           </Row><Row>
           <Col lg={6}>  
           <AvGroup>
                <Label for="example">Status</Label>
              <Input
                        // type="select"
                        // id="exampleCustomSelect"
                        // name="status"
                        // className="mb-3" */}
                        //  style={{width:'100%'}}
                        type="select" id={`status${idx + 1}`}  name={`status${idx + 1}`}
                         
                        value={shareholder.status}
                         onChange={this.handleStatusChangeImage(idx)}
                        
                   >
                      <option value="1">Active</option>
                        <option value="2">In-Active</option>
                    </Input>
                </AvGroup>
            </Col>
           
            {/* <Row>
            <Col lg={6}>
           
            
            <Label for="example">Select Image</Label>    
            <Input type="file"
             name="image"
             id= 'file'
             onChange={(e)=>this._handleImageChange(e)} /><br/> <br/>   
             {img}<br/> <br/>
              <div className="imgPreview">
                 {$imagePreview}              
               </div>
            </Col><br/><br/><br/><br/>
           </Row><br/> */}


           
                
                  
             <Col lg={6}> 
                    <Label for="example">Select File</Label>  <br/> 
                     {this.state.moreDocs.map((hrdoc, idx) => (
                       <div className="hrdoc">
                        <input  id={`file_${idx}`}  type="file" name ={`file_${idx}`}   onChange={this.handleDocumentChange(idx) } />
                        {/* <i onClick={this.handleRemovemoreDocs(idx)} class=" fa-trash" style={{color:'red',fontSize:'20px',cursor:'pointer'}}>X</i> */}
                       <br/> <br/></div>
                    ))}</Col>
                     {/* <Col lg={6}>  
                <AvGroup>
                  <AvInput type="hidden" name="emp_id" id="example" value='1'/>
              
                </AvGroup>
                </Col>  */}
               
                 {/* }) : '' } */}
                    </Row>
                   
                    <i onClick={this.handleRemoveShareholderImage(idx)} class="fa-trash"  style={{color:'red',fontSize:'20px',float:'right',cursor:'pointer'}}>X</i>
             
                    </div>
                     ))}
                    
                    <button style={{marginTop:'15px'}}
                      type="button"

                      onClick={this.handleAddShareholderImage}
                      className=" btn btn-secondary"
                      style={{color:'#ffffff',border: '1px solid #ffffff',float:'right'}}
                    >
                      Add More
                    </button><br/>
                  
            
               <br/>
               <Row>
                    {documents}
                 <Col lg={6}><br/>
                  {docs ?  docs.map((cell, i) => {
                  return(   <div><a href= { `https://beta.workzoneplus.com/backend/uploads/more_doc/`+cell.more_id+'/'+cell.document} >{cell.document}           </a>
                         {/* <i onClick={this.handleRemovemoreDocsEdit(i)} class=" fa-trash" style={{color:'red',fontSize:'20px',cursor:'pointer'}}>   X</i> */}
                         <hr/></div>)
                   }) : '' }
                     
                  </Col>
                    </Row>
                {/* <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">Sequence</Label>
                  <AvInput name="sequence" value={formData ? formData.sequence:''} id="example" validate={{
                  required: {value: true},
                  pattern: {value: '^[0-9]+$'},
                  
                }} />
                  <AvFeedback>Enter Number</AvFeedback>
                </AvGroup>
                </Col>
                </Row> */}
             <FormGroup row>
                  <Col md="6">
                      {/* <Label htmlFor="text-input">Image</Label> */}
                    </Col>
                  <Col xs="12" md="9">           
{this.state.shareholdersImage.map((shareholder, idx) => (
           <div className="shareholder">
            {/* <input style={{width:'50%'}}
              type="text" id={`image_url${idx + 1}`} name={`image_url${idx + 1}`}
              placeholder={`URL`}
              value={shareholder.name}
              onChange={this.handleShareholderNameChangeImage(idx)}
            /> */}

      
          
            {/* <i onClick={this.handleRemoveShareholderImage(idx)} class="fa-trash" style={{color:'red',fontSize:'20px',cursor:'pointer'}}>X</i> */}
          </div>
        ))}
</Col>
        {/* <button style={{marginTop:'15px'}}
          type="button"
          onClick={this.handleAddShareholderImage}
          className="btn btn-primary btn-sm"
          style={{color:'#ffffff',border: '1px solid #ffffff',float:'right'}}
        >
          Add More
        </button> */}
                       
                 
                  
                  </FormGroup>  
     
                <FormGroup>
                <input  style={{margin:'5px'}} id="total" name="total"
              type="hidden"
           
              value={this.state.total}
             
            />
                <Link to="/morepromotions/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;


