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 './bulk_import.scss';

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 BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
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";

// const file_link = `${process.env.PUBLIC_URL}/CsvFile/sample-csv-bulk_employee.csv`;
const file_link = `${process.env.PUBLIC_URL}/CsvFile/sample/sample_employee_csv.csv`;

const tableColumns = [
  {
    dataField: "employee_id",
    text: "Emp ID",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "first_name",
    text: "First Name",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "last_name",
    text: "Last Name",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "email",
    text: "Email ",
    sort: true,
    headerStyle: { width:"20%" } 
  },
  {
    dataField: "mobile_no",
    text: "Mobile No",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "gender",
    text: "Gender",
    sort: true,
    headerStyle: { width:"12%" }  
  },
  {
    dataField: "date_of_birth",
    text: "Date Of Birth",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "status",
    text: "Status",
    headerStyle: { width:"15%" }
  },
];

class Import extends PureComponent {
    constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
      this.change = this.change.bind(this);
      this.hrChange = this.hrChange.bind(this);
      this.state = {
        selectedFile: null,
        posts:'',
        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
      };
    }

    onChangeHandler=event=>{
      console.log(event.target.files[0]);
      this.setState({
        selectedFile: event.target.files[0],
        loaded: 0,
      })
  }


  change(event){
      this.oid = event.target.value;
  }
  hrChange(event){
    this.hid = event.target.value;
    fetch(myConstClass.BASE_URL+'user/get_all_organizations_by_hr/'+this.hid)
    .then(response => response.json())
    .then(response =>{this.setState({org: response})}).catch(err => console.log(err))
}
onSaveClickHandler = () => {
  const data = new FormData() 
  data.append('file', this.state.selectedFile);
  data.append('session_id', localStorage.getItem('session_id'));
  fetch(myConstClass.BASE_URL+`/user/save_import_data/`+this.oid+'/'+this.hid, {
    method: 'POST',
    body: data,
  }).then(response =>  response.json()).then((response) => {
    if(response == true){
      toastr.success(
        'Success',
        "Employee Added Successfully..!",
        this.options
      )
      this.props.history.push('/employee/listing');
    }else if(response == 3){
      toastr.error(
        'Error',
        "Please Select HR admin..!",
        this.options
      )
    } else if(response == 4){
      toastr.error(
        'Error',
        "Please Select Organization..!",
        this.options
      )
    } else {
       toastr.error(
        'Error',
        "Bulk Import Failed..!",
        this.options
      )
    }
  })
.catch();


}

  onClickHandler = () => {
    const data = new FormData() 
    data.append('file', this.state.selectedFile);
    data.append('session_id', localStorage.getItem('session_id'));
    fetch(myConstClass.BASE_URL+`/user/import/`+this.oid+'/'+this.hid, {
      method: 'POST',
      body: data,
    })
    .then(response => response.json())
    .then(response =>{this.setState({posts: response})
  }).catch(err => console.log(err))
  
  }

    routeChange() {
      this.props.history.push('/');
    }
    handleSubmit = () => {
      alert(JSON.stringify($('#pform').serializeArray()));
    }
    componentDidMount(){   
      var admin_id= localStorage.getItem('uname'); 
      if(admin_id == null){
        this.routeChange();
       }
       fetch(myConstClass.BASE_URL+'user/get_all_hradmins/'+admin_id)
       .then(response => response.json())
       .then(response =>{this.setState({he_admin: response})}).catch(err => console.log(err))

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




      render () { 
        const { posts} = this.state;
        const { fileData} = this.state;
        const { org,he_admin} = this.state; 
        // if(this.state.user_id !=='0' ){
        //     var __html = formData.temp_data; 
        // }

      
        return(
        <Container fluid>
          <Header>
            <HeaderTitle>Import</HeaderTitle>
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/employee/listing">Employee List</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>Import Employees</BreadcrumbItem>
            </Breadcrumb>
          </Header>    
          <Card>
            <CardBody>
              
             <AvForm id="pform" onSubmit={this.handleSubmit}>
                  <Row>
                  <Col lg={6}>
                  <Label for="example">Download Sample CSV file</Label>
                  <br/> <a href={file_link}>
                      <Button color="primary" type="button" className="">Download Sample File</Button>
                 </a>
                 </Col>
                 </Row><br/><hr/>
                  <Row>
                  <Col lg={6}>
                  <Label for="example">Select File</Label>   <br/> 
                    <input type="file" name="file" onChange={this.onChangeHandler}/>  
                  </Col>
                </Row><br/>
                <Col md={6}>
                <Row>
                  <button type="button"  style={{width: '40%',height:'10%'}} className="btn btn-primary btn-block col-md-4" onClick={this.onClickHandler}>Upload</button>
                  </Row>
                  </Col>
                <br/>
                { this.state.posts ?
                <div>
                  <Row>
            <div class="col-md-4">
            <AvGroup>
            <AvField
           type="select"
           name="hr_admin_id"
           label="Select HR Admin"
           onChange={this.hrChange}
           value={this.state.hr_admin_id}
         >
           <option value={0}>All HR Admins</option>
           {he_admin ?  he_admin.map((cell, i) => {
           return(<option value={cell.id}>{cell.first_name+' '+cell.last_name}</option>)
           }) : ''}       
         </AvField> 
         </AvGroup></div>
         <div class="col-md-4">
          <AvGroup>
          <AvField
           type="select"
           name="organization_id"
           label="Select Organization"
           onChange={this.change}
           value={this.state.organization_id}
         >
           <option value={0}>All Organization</option>
           {org ?  org.map((cell, i) => {
           return(<option value={cell.id}>{cell.title}</option>)
           }) : ''}       
         </AvField> 
         </AvGroup>
            </div>
    </Row>
           <ToolkitProvider
            keyField="name"
            data={this.state.posts}
            columns={tableColumns}
            exportCSV
          >
            {props => (
              <div>
                <BootstrapTable
                    {...props.baseProps}
                    bootstrap4
                    bordered={false}
                    pagination={paginationFactory({
                      // sizePerPage: 25,
                      sizePerPage: 10,
                      sizePerPageList: [5, 10, 25, 50]
                    })}
                  />
              </div>
            )}
            </ToolkitProvider>
            <Col md={6}>
                <button type="button" className="btn btn-primary btn-block col-md-4" onClick={this.onSaveClickHandler}>Save</button>         
            </Col>
            </div> :''}
              </AvForm>
           </CardBody>
          </Card>
       </Container>
      )
      }

    }
 export default Import;


