import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import InputMask from "react-input-mask";
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 * 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.handleCheckChange = this.handleCheckChange.bind(this);
     // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    this.state = { policy_file: "", book_file: "" };
    // this.state = {company_file: '',book_file: ''};
    this.state = {
      hr_code: "",
      qr_code: "",
      qr_code_last: "",
      selectedPolicyFile: null,
      selectedBookFile: null,
      user_id: "0",
      units: "",
      org: "",
      timezones: "",
      formData: {
        title: "",
        city: "",
        state: "",
        country: "",
        owner: "",
        status: "",
      },
      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,
    };
  }

  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");
    //alert(admin_id);
    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 + "user/getHrAdminInfo/" + 0 + "/" + admin_id)
        .then((response) => response.json())
        .then((response) => {
          this.setState({
            hr_code: response.hr_code,
          });
          if (this.state.user_id == 0) {
            this.setState({
              is_dynamic: false,
            });
            var staticQrcoode = response.hr_code + "-";

            this.setState({
              qr_code: response.hr_code + "-",
            });
          }
          this.setState({ hradmin: response });
        })
        .catch((err) => console.log(err));

      fetch(
        myConstClass.BASE_URL +
          "organization/getOrganizationInfo/" +
          answer_array["3"]
      )
        .then((response) => response.json())
        .then((response) => {
          if (response.is_dynamic == 1) {
            this.setState({
              is_dynamic: true,
            });
          } else {
            this.setState({
              is_dynamic: false,
            });
          }
          var a = response.qr_code;
          var test = a.split("-");
          //alert(qr_code);alert(test);
          this.setState({
            qr_code: test[0] + "-",
          });
          this.setState({
            qr_code_last: test[1],
          });

          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }
  }

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

  onPolicyChangeHandler(e) {
    e.preventDefault();
    let reader = new FileReader();
    let policy_file = e.target.files[0];
    reader.onloadend = () => {
      this.setState({
        policy_file: policy_file,
        // imagePreviewUrl: reader.result
      });
    };
    reader.readAsDataURL(policy_file);
  }
  onBookChangeHandler(e) {
    e.preventDefault();
    let reader = new FileReader();
    let book_file = e.target.files[0];
    reader.onloadend = () => {
      this.setState({
        book_file: book_file,
        // imagePreviewUrl: reader.result
      });
    };
    reader.readAsDataURL(book_file);
  }
  onChartChangeHandler(e) {
    e.preventDefault();
    let reader = new FileReader();
    let organization_chart = e.target.files[0];
    reader.onloadend = () => {
      this.setState({
        organization_chart: organization_chart,
        // imagePreviewUrl: reader.result
      });
    };
    reader.readAsDataURL(organization_chart);
  }
  // onBookChangeHandler=event=>{
  //   console.log(event.target.files[0]);
  //   this.setState({
  //   selectedFile: event.target.files[0],
  //   loaded: 0,
  //   })
  //   }

  handleCheckChange() {
    //alert(this.state.hr_code);
    var d = new Date();
    var strDate =
      d.getFullYear() + "_" + (d.getMonth() + 1) + "_" + d.getDate();
    // alert(this.state.is_dynamic);
    //var qr=$("#qr_code").val();
    var dynamicQrcoode = this.state.hr_code + "_" + strDate + "-";
    var staticQrcoode = this.state.hr_code + "-";
    if (this.state.is_dynamic == false) {
      this.setState({
        qr_code: dynamicQrcoode,
      });
    } else {
      this.setState({
        qr_code: staticQrcoode,
      });
    }
    this.setState({
      is_dynamic: !this.state.is_dynamic,
    });
  }
  // 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"
  //   );
  // }

  handleValidSubmit = () => {
    var admin_id = localStorage.getItem("uname");
    this.setState({ submitted: true }, () => {
      setTimeout(() => this.setState({ submitted: false }), 5000);
      const data = new FormData();
      data.append("company_policy_file", this.state.policy_file);
      data.append("emp_book_file", this.state.book_file);
      data.append("organization_chart", this.state.organization_chart);
      data.append("formdata", JSON.stringify($("#pform").serializeArray()));
      fetch(
        myConstClass.BASE_URL +
          `organization/add_organization/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          // body: JSON.stringify($('#pform').serializeArray()),
          body: data,
        }
      )
        .then((response) => response.json())
        .then((response) => {
          if (response == 3) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Organization Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Organization Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/settingsorganization/listing");
          } else if (response == 2) {
            toastr.error(
              "More than 1 organization cannot be added ..!",
              this.options
            );
          } else if (response == 5) {
            toastr.error("Organization Code already exists ..!", this.options);
          } else if (response == 7) {
            toastr.error("Only PDF files are acceptable ..!", this.options);
          } else {
            toastr.error("Error", "Can not Add Organization ..!", this.options);
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, units, submitted } = this.state;
    const { org, timezones } = this.state;
    var admin_id = localStorage.getItem("uname");
    //alert(admin_id);
    //alert(this.state.user_id);
    let status;
    let o_file;
    let o_file_title;
    let organization_chart_link;
    let book_file_link;
    let policy_file_link;
    let c_file;
    let c_file_title;
    let b_file;
    let b_file_title;
    if (this.state.user_id !== 0 && admin_id == 0) {
      //alert(admin_id);
      if (formData.status == 0) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
             <option value="1">In-Active</option>
             <option value="2">Active</option>
            {/* <option value="0">Pending</option> */}
          </AvField>
        );
      } else if (formData.status == 1) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
            <option value="0">Pending</option>
            <option value="2">Active</option>
           
            {/* <option value="2">Active</option> */}

          </AvField>
        );
      } else if (formData.status == 2) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
            <option value="0">Pending</option>
            <option value="1">In-Active</option>
            {/* <option value="2">Active</option> */}
          </AvField>
        );
      }
    } else {
      status = (
        <AvField
          type="select"
          name="status"
          label="Select Status"
          value={formData ? formData.status : ""}
        >
          <option value="0">Pending</option>
          <option value="1">Approved /In-Active</option>
          <option value="2">Active</option>
        </AvField>
      );
    }
    // if(this.state.user_id =='0' && admin_id != 0 ){
    //   status='';
    // }

    if (this.state.user_id != 0 && admin_id != 0) {
      // policy_file_link = `http://localhost/workzonepro/uploads/organizations/`+formData.	company_policy_file;
      // book_file_link = `http://localhost/workzonepro/uploads/organizations/`+formData.	emp_book_file;
      policy_file_link =
        `https://beta.workzoneplus.com/backend/uploads/organizations/` +
        formData.id +
        "/" +
        formData.company_policy_file;
      book_file_link =
        `https://beta.workzoneplus.com/backend/uploads/organizations/` +
        formData.id +
        "/" +
        formData.emp_book_file;
      organization_chart_link =
        `https://beta.workzoneplus.com/backend/uploads/organizations/` +
        formData.id +
        "/" +
        formData.organization_chart;

      if (formData.company_policy_file) {
        c_file_title = "Company Policy : ";
        c_file = (
          <a href={policy_file_link} target="_blank">
            Company Policy
          </a>
        );
      } else {
        c_file_title = "";
        c_file = "";
      }
      if (formData.emp_book_file) {
        b_file_title = "Employee HandBook : ";
        b_file = (
          <a href={book_file_link} target="_blank">
            Employee HandBook
          </a>
        );
      } else {
        b_file_title = "";
        b_file = "";
      }

      if (formData.organization_chart) {
        o_file_title = "Organization Chart: ";
        o_file = (
          <a href={organization_chart_link} target="_blank">
            Organization Chart
          </a>
        );
      } else {
        o_file_title = "";
        o_file = "";
      }

      if (formData.status == 0) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
            <option value="0">Pending</option>
          </AvField>
        );
      } else if (formData.status == 1) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
            <option value="1">Approved /In-Active</option>
            <option value="2">Active</option>
          </AvField>
        );
      } else if (formData.status == 2) {
        status = (
          <AvField
            type="select"
            name="status"
            label="Select Status"
            value={formData ? formData.status : ""}
          >
            <option value="1">Approved /In-Active</option>
            <option value="2">Active</option>
          </AvField>
        );
      }
    } 
    
    // else {
    //   status = (
    //     <AvField
    //       type="select"
    //       name="status"
    //       label="Select Status"
    //       value={formData ? formData.status : ""}
    //     >
    //       <option value="0">Pending</option>
    //       <option value="1">Approved /In-Active</option>
    //       <option value="2">Active</option>
    //     </AvField>
    //   );
    // }

    let new_status;
    new_status = "";

    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="/settingsorganization/listing">Organization 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>
                    <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>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Code</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="org_code"
                      id="example"
                      required
                      value={formData ? formData.org_code : ""}
                    />
                    <AvFeedback>Enter Code!</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  {/* <AvGroup>
                  <Label for="example">Address Line 1</Label>
                  <AvInput type="textarea" name="addressline1" id="example" required value={formData ? formData.addressline1:''}/>
                  <AvFeedback>Enter Address Line 1!</AvFeedback>
                </AvGroup> */}
                  <AvGroup>
                    <Label for="example">Address Line 1</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="addressline1"
                      id="example"
                      required
                      value={formData ? formData.addressline1 : ""}
                    />
                    <AvFeedback>Enter Address Line 1 !</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  {/* <AvGroup>
                  <Label for="example">Address Line 2</Label>
                  <AvInput type="textarea" name="addressline2" id="example" required value={formData ? formData.addressline2:''}/>
                  <AvFeedback>Enter Address Line 2!</AvFeedback>
                </AvGroup> */}
                  {/* <AvGroup> */}
                    <Label for="example">Address Line 2</Label>{" "}
                   
                    <AvInput
                      name="addressline2"
                      id="example"
                      value={formData ? formData.addressline2 : ""}
                    />
                    {/* <AvFeedback>Enter Address Line 2 !</AvFeedback> */}
                  {/* </AvGroup> */}
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">City</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="city"
                      id="example"
                      required
                      value={formData ? formData.city : ""}
                    />
                    <AvFeedback>Enter City!</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">State / Province</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="state"
                      id="example"
                      required
                      value={formData ? formData.state : ""}
                    />
                    <AvFeedback>Enter State!</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Country</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="country"
                      id="example"
                      required
                      value={formData ? formData.country : ""}
                    />
                    <AvFeedback>Enter Country!</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Attendance Radius (in Meters)</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="attendance_radius"
                      id="example"
                      required
                      value={formData ? formData.attendance_radius : ""}
                    />
                    <AvFeedback>Enter Attendance Radius!</AvFeedback>
                  </AvGroup>
                </Col>
                {/* {(admin_id !='0' ) ?  */}
                <Col lg={6}>
                  <AvGroup>
                    {/* {(this.state.user_id == 0  && admin_id != 0 ) ? new_status : status } */}
                    {status}
                  </AvGroup>
                </Col>
              </Row>
              <Row>
                <Col lg={12}>
                  {/* <AvGroup> */}
                  <Label for="example">Company Policy</Label> <br />
                  <input
                    type="file"
                    id="file1"
                    accept="image/pdf"
                    name="company_policy_file"
                    onChange={(e) => this.onPolicyChangeHandler(e)}
                  />
                  <br />
                  <small>('pdf')</small>
                  {/* </AvGroup> */}
                </Col>
              </Row>
              {c_file_title} {c_file}
              <br />
              <br />
              <Row>
                <Col lg={12}>
                  {/* <AvGroup> */}
                  <Label for="example">Employee HandBook</Label> <br />
                  <input
                    type="file"
                    id="file2"
                    name="emp_book_file"
                    accept="image/pdf"
                    onChange={(e) => this.onBookChangeHandler(e)}
                  />
                  <br />
                  <small>('pdf')</small>
                  {/* </AvGroup> */}
                </Col>
              </Row>
              {b_file_title}
              {b_file} <br />
              <br />
              <Row>
                <Col lg={6}>
                  {/* <AvGroup> */}
                  <Label for="example">Organization Chart</Label> <br />
                  <input
                    type="file"
                    id="file1"
                    name="organization_chart"
                    accept="image/pdf"
                    onChange={(e) => this.onChartChangeHandler(e)}
                  />
                  <br />
                  <small>('pdf')</small>
                  {/* </AvGroup>  */}
                  {o_file_title} {o_file}
                </Col>
              </Row>
              <br />
              <Row>
                <Col lg={6}>
                  <Label for="example">Dynamic</Label>
                  <CustomInput
                    type="checkbox"
                    name="is_dyanamic"
                    id="exampleCustomCheckbox"
                    label="Dyanamic"
                    disabled={admin_id == "0" ? true : false}
                    className="mb-2"
                    checked={this.state.is_dynamic}
                    onChange={this.handleCheckChange}
                  />
                </Col>
                <Col lg={3}>
                <Label for="example">Qr Code</Label>  <span style={{ color: "red", fontSize: "15px" }}> *</span>
                  <AvInput
                    name="qr_code_1"
                    id="qr_code"
                    value={this.state.qr_code}
                    readOnly
                  />
                </Col>
                <Col lg={3}>
                
                  <AvGroup>
                    <AvInput
                      name="qr_code"
                      id="qr_code"
                      readOnly={admin_id == "0" ? true : false}
                      required
                      style={{ marginTop: "30px" }}
                      value={this.state.qr_code_last}
                      pattern="[a-zA-Z]+"
                    />
                    <AvFeedback>Enter Qrcode</AvFeedback>
                  </AvGroup>
                </Col>
              </Row>
              <FormGroup>
                <Link
                  to="/settingsorganization/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;
