import React,{PureComponent} from "react";
import { Link } from "react-router-dom";
import "react-datepicker/dist/react-datepicker.css";
import {
  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.googleTranslateElementInit = this.googleTranslateElementInit.bind(this);
      // state = {
      //   startDate: new Date()
      // };
      this.state = {
        user_id:'0',
        units:'',
        org:'',
        emp:'',
        startDate: new Date(),
        time: '10:00',
        timezones:'',
        groups:'',
        employee_group:[],
        formData_groups:'',
        formData:{
          employee_id: '',
          attendance_date: '',
          clock_in: '',
          clock_out: '',
          timezone:'',
        },
        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
      };
    
    }


    handleTextChange = (announcement) => {  
      this.setState({ announcement });
      };

    handleGroupChange =  (group) => {
      this.setState({ employee_group: group });
    }

    routeChange() {
      this.props.history.push('/');
    }
    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+'announcements/getAnnouncementsInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{this.setState({formData: response})}).catch(err => console.log(err));

            fetch(myConstClass.BASE_URL+'announcements/getAnnouncementsFileInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{this.setState({fileData: response})}).catch(err => console.log(err));
          

            fetch(myConstClass.BASE_URL+'announcements/getEmployeeGroupsInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{
              response.map((cell) => {
                this.setState({employee_group:[{ value:cell.id, label:cell.title}]}) ;
                // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
                })
              // response.forEach(element => { alert(element.id+' '+element.title);
              //   let id=element.id;
              //   let name=element.title;
              //   this.setState({employee_group:[{ value:id, label:name}]});   
              //  // console.log(element);
              //  element.id = i;
              //  i++;
              // });
              this.setState({formData_groups: response})}).catch(err => console.log(err));
        }
        
        var admin_id= localStorage.getItem('uname'); 
        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));      
     
        fetch(myConstClass.BASE_URL+'user/get_all_emp_groups/'+admin_id)
        .then(response => response.json())
        .then(response =>{this.setState({groups: response}) }).catch(err => console.log(err))
        
      }


    
  

      handleValidSubmit = () => {
        var admin_id= localStorage.getItem('uname'); 

        this.setState({ submitted: true }, () => {  
            setTimeout(() => this.setState({ submitted: false }), 5000);
             const data = new FormData() 
            // data.append('announcemnt',html);
            data.append('formdata',JSON.stringify($('#pform').serializeArray()));
            fetch(myConstClass.BASE_URL+`announcements/add_announcements/`+admin_id+'/'+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',
                        "Announcement Added Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Announcement Updated Successfully..!",
                        this.options
                      );
    
                      this.props.history.push('/announcements/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not Add Announcement ..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }

      render () { 
        const { formData,submitted,groups} = this.state;
        const { organization} = this.state;
        if(this.state.user_id !=='0' ){
        }
        let groupOp;
        groupOp =   groups ?  groups.map((cell) => {
          return { value: cell.id, label: cell.title };
          // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
          }) : '';
          // if(this.state.user_id !=='0' ){
          //   employee_group1 =  formData_groups ?  formData_groups.map((cell, i) => {
          //     return { value: cell.id, label: cell.title };
          //     // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
          //     }) :'' ;
          //  } else {
          //   employee_group1 = employee_group;
          //  }   
      
        return(
        <Container fluid>
          <Header>
            {/* <div  id="google_translate_element_an"></div><br/> */}
            <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/announcements/listing">Announcement List</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</BreadcrumbItem>
            </Breadcrumb>
          </Header>    
          <Card>
            <CardBody>
              <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                <Row>
                <Col lg={6}>
                <AvGroup>
                 <AvField
                  type="select"
                  name="organization_id"
                  label="Select Organization"
                  value={formData ? formData.organization_id:''}
                >
                  {organization ?  organization.map((cell) => {
                  return(<option value={cell.id}>{cell.title}</option>)
                  }) : ''}       
                </AvField>
                </AvGroup>
                </Col>
                <Col lg={6}>  
                <AvGroup>
                  <Label for="example">Title</Label> <span style={{ color: "red", fontSize: "15px" }}> *</span>{" "}
                  <AvInput name="title" id="example" required value={formData ? formData.title:''}/>
                  <AvFeedback>Enter Title !</AvFeedback>
                </AvGroup>
                </Col> 
             </Row>
           <Row>
          
           <Col lg={6}>  
              <AvGroup>
                <Label for="example">Description</Label> <span style={{ color: "red", fontSize: "15px" }}> *</span>{" "}
                <AvInput type="textarea" name="announcement" id="example" required value={formData ? formData.temp_data:''}/>
              <AvFeedback>Enter Description..!</AvFeedback>
              </AvGroup>
             </Col>
             <Col lg={6}>
                <AvGroup>
                <Label for="example">Select Status</Label>
                <AvField
                  type="select"
                  value={formData ? formData.status : '1'}
                  name="status"
                  className="mb-3"
                  
                >
                  {/* <option disabled={true} value="">Select Status</option> */}
                  <option  value="1">Active</option>
                  <option  value="2">In-Active</option>
                 
                </AvField>
              </AvGroup>
             </Col>
           </Row>
            <FormGroup>
            <Link to="/announcements/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;


