import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from "../../constant.js";
import $ from "jquery";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import filterFactory from "react-bootstrap-table2-filter";
import cellEditFactory from "react-bootstrap-table2-editor";
import dateFormat from "dateformat";
// import { PDFDownloadLink } from '@react-pdf/renderer';
import Select from "react-select";
import "./bulk_import.scss";
import moment from "moment";
//import dateFormat from 'dateformat';
import TimePicker from "react-time-picker";
import "react-datepicker/dist/react-datepicker.css";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Label,
  Card,
  CardBody,
  Container,
  CustomInput,
  Button,
  Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
} from "reactstrap";

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

import BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider, { Search } from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import "react-confirm-alert/src/react-confirm-alert.css"; // Import css
import {
  AvInput,
  AvForm,
  AvField,
  AvGroup,
  AvFeedback,
} from "availity-reactstrap-validation";
import CardHeader from "reactstrap/lib/CardHeader";
import { T, Config, TF } from "react-translator-component";
//import { color } from "html2canvas/dist/types/css/types/color.js";
Config.default = localStorage.getItem("lang");
const { SearchBar } = Search;
const rowStyle = (cell, row) => {
  //alert(JSON.stringify(row));
  var cellarray = Object.keys(cell);
  // alert(cellarray);
  //alert(array[3]);
  if (cellarray[3].includes("_date")) {
    return {
      backgroundColor: "red",
    };
  } else {
  }
};

const tableColumns = [
  {
    dataField: "employee_id",
    text: TF("{0}", T("Employee")),
    sort: true,
    headersctyle: { width: "15%" },
    editable: false,
  },
  {
    dataField: "date",
    text: TF("{0}", T("Date")),
    sort: true,
    headersctyle: { width: "15%" },
    ref: "name1",
    editable: false,
  },
  // {
  //   dataField: "shift_name",
  //   text:TF("{0}", T("Shift")),
  //   sort: true,
  //   headersctyle: { width:"15%" },
  //   // filter: textFilter()
  // },
  {
    dataField: "shift_time",
    text: TF("{0}", T("Time")),
    sort: true,
    editable: false,
    //headersctyle: { width:"15%" },
    // editCellStyle: {
    //   backgroundColor: '#20B2AA'
    // }

    // filter: textFilter()
  },
  // {
  //   dataField: "pay_code",
  //   text: TF("{0}", T("Pay Code")),
  //   sort: true,
  //   headersctyle: { width: "15%" },
  //   editable: false,
  //   // filter: textFilter()
  // },
  {
    dataField: "action",
    text: TF("{0}", T("Action")),
    headersctyle: { width: "10%" },
    csvExport: false,
    editable: false,
  },
];

const tableColumnsEmp = [
  {
    dataField: "employee_id",
    text: TF("{0}", T("Employee")),
    sort: true,
    headersctyle: { width: "15%" },
    editable: false,
  },
  {
    dataField: "date",
    text: TF("{0}", T("Date")),
    sort: true,
    headersctyle: { width: "15%" },
    ref: "name1",
    editable: false,
  },
  // {
  //   dataField: "shift_name",
  //   text:TF("{0}", T("Shift")),
  //   sort: true,
  //   headersctyle: { width:"15%" },
  //   // filter: textFilter()
  // },
  {
    dataField: "shift_time",
    text: TF("{0}", T("Time")),
    sort: true,
    editable: false,
    //headersctyle: { width:"15%" },
    // editCellStyle: {
    //   backgroundColor: '#20B2AA'
    // }

    // filter: textFilter()
  },
  {
    dataField: "pay_code",
    text: TF("{0}", T("Pay Code")),
    sort: true,
    headersctyle: { width: "15%" },
    editable: false,
    // filter: textFilter()
  },
];

// console.log('-----------------'+JSON.stringify(tableColumns[0])+'-----------------');

const MyExportCSV = (props) => {
  //alert(JSON.stringify(props));
  const handleClick = () => {
    props.onExport();
  };
  return (
    <div>
      <button className="btn btn-secondary mt-2" onClick={handleClick}>
        {TF("{0}", T("Export"))}
      </button>
    </div>
  );
};

class Shift_schedular extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      filtered: [],
    };

    this.routeChange = this.routeChange.bind(this);
    this.radioChange = this.radioChange.bind(this);
    this.dep_change = this.dep_change.bind(this);
    this.state = {
      status: null,
      designation: null,
      department: null,
      organization_id: null,
      view: 0,
      loading: false,
    };
    this.did = 0;
    this.eid = 0;
    this.state = {
      open_mod1: false,
      submitted: false,
      user_id: 0,
      formDataCSVc: [],
      formDataCSVcc: [],
      shiftreportdata: [],
      formData: [],
      headersc: [],
      dates: [],
      headerscc: [],
      formData: [],
      from_date: Date.now(),
      to_date: Date.now(),
      shifts: "",
      countries: "",
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
      departments: [],
    };
    // this.change = this.change.bind(this);
    this.flag = 0;
    this.orgId = 0;
    this.dep_id = 0;
    this.did = 0;
    this.eid = 0;
    this.paycode_id = 0;
  }

  change = (event) => {
    this.paycode_id = event.target.value;
    var admin_id = localStorage.getItem("uname");
    var fdate = dateFormat(this.state.from_date, "yyyy-mm-dd");
    var tdate = dateFormat(this.state.to_date, "yyyy-mm-dd");
    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftScheduleReport/" +
        admin_id +
        "/" +
        fdate +
        "/" +
        "0" +
        "/" +
        tdate +
        "/" +
        this.dep_id +
        "/" +
        this.eid +
        "/" +
        this.paycode_id
    )
      // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
      .then((response) => response.json())
      .then((response) => this.setState({ shiftreportdata: response }))
      .catch((err) => console.log(err));
    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftSchedule/" +
        admin_id +
        "/" +
        fdate +
        "/0/" +
        tdate +
        "/" +
        this.org_id +
        "/" +
        this.dep_id +
        "/" +
        this.did +
        "/" +
        this.eid +
        "/" +
        this.paycode_id
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.action = (
            <div>
              <Icon.Edit3
                style={{ margin: "0px 15px 0px 0px", cursor: "Pointer" }}
                onClick={() => this.edit(id)}
              />
            </div>
          );
          // console.log(element);
          element.id = i;
          i++;
        });
        this.setState({ formData: response });
      })
      .catch((err) => console.log(err));

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftScheduleCSVheaderArray/" +
        admin_id +
        "/" +
        fdate +
        "/" +
        "0" +
        "/" +
        tdate
    )
      // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
      .then((response) => response.json())
      .then((response) => this.setState({ headerscc: response }))
      .catch((err) => console.log(err));

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftScheduleCSVArray/" +
        admin_id +
        "/" +
        fdate +
        "/" +
        "0" +
        "/" +
        tdate +
        "/" +
        this.dep_id +
        "/" +
        this.eid +
        "/" +
        this.paycode_id
    )
      // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
      .then((response) => response.json())
      .then((response) => this.setState({ formDataCSVcc: response }))
      .catch((err) => console.log(err));

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftScheduleCSV/" +
        admin_id +
        "/" +
        fdate +
        "/" +
        "0" +
        "/" +
        tdate +
        "/" +
        this.dep_id +
        "/" +
        this.eid
    )
      // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
      .then((response) => response.json())
      .then((response) => this.setState({ formDataCSVc: response }))
      .catch((err) => console.log(err));
  };
  routeChange() {
    this.props.history.push("/");
  }

  // radioChange(e) {

  //   var admin_id = localStorage.getItem('uname');
  //   var fdate = dateFormat(this.state.from_date, 'yyyy-mm-dd');
  //   var tdate = dateFormat(this.state.to_date, 'yyyy-mm-dd');

  //   if (e.currentTarget.checked == true) {

  //     fetch(myConstClass.BASE_URL + 'shifts/getShiftScheduleReport/' + admin_id + '/' + fdate + '/' + '0' + '/' + tdate + '/' + this.dep_id + '/' + this.eid + '/' + this.paycode_id)
  //       // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
  //       .then(response => response.json())
  //       .then(response => this.setState({ shiftreportdata: response })).catch(err => console.log(err))
  //     console.log('+++++++++');
  //     console.log(this.state.shiftreportdata);
  //     console.log('+++++++++');

  //     this.setState({ view: '1' });
  //     $("#stable").removeClass("table");
  //     $("#stable").addClass("tablenew");
  //     var start = new Date(fdate);
  //     var end = new Date(tdate);

  //     var diff = new Date(end - start);

  //     // get days
  //     var days = diff / 1000 / 60 / 60 / 24;

  //     //alert(days);
  //     if (days < 4) {
  //       //  alert(days);
  //       $("#stable").addClass("table1");
  //       $("#stable").removeClass("tablenew");
  //     }
  //     else {
  //       $("#stable").removeClass("table1");
  //       $("#stable").addClass("tablenew");
  //     }

  //   }
  //   else {
  //     this.setState({ view: '0' });
  //     $("#stable").addClass("table");
  //     $("#stable").removeClass("tablenew");
  //   }
  //   // let a=e.currentTarget.name;
  //   //  alert(e.currentTarget.value);

  //   // alert(e.currentTarget.checked);

  //   if (this.dep_id == null || this.dep_id == '') {
  //     this.dep_id = 0;
  //   } else {
  //     this.dep_id = this.dep_id;
  //   }

  //   if (e.currentTarget.checked == true) {

  //     // fetch(myConstClass.BASE_URL+'shifts/getShiftScheduleCSVArray/'+admin_id+'/'+fdate+'/'+'0'+'/'+tdate+'/'+this.dep_id+'/'+ this.eid+'/'+this.paycode_id)
  //     // // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
  //     //   .then(response => response.json())
  //     //   .then(response =>

  //     //     this.setState({formDataCSVcc: response})

  //     //     ).catch(err => console.log(err))
  //     //const dates = [];

  //     // const dates = [];
  //     fetch(myConstClass.BASE_URL + 'shifts/getShiftScheduleCSVheaderArray/' + admin_id + '/' + fdate + '/' + '0' + '/' + tdate)
  //       // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
  //       .then(response => response.json())
  //       .then(response => {
  //         let i = 1;
  //         response.forEach(elementnew => {

  //         });

  //         this.setState({ headerscc: response })

  //       }).catch(err => console.log(err))
  //     //  const date = new Date(startDate.getTime());

  //     // while (fdate <= tdate) {
  //     //   dates.push(new Date(fdate));
  //     //   fdate.setDate(fdate.getDate() + 1);
  //     // }

  //     fetch(myConstClass.BASE_URL + 'shifts/getShiftScheduleCSVArray/' + admin_id + '/' + fdate + '/' + '0' + '/' + tdate + '/' + this.dep_id + '/' + this.eid + '/' + this.paycode_id)
  //       // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
  //       .then(response1 => response1.json())
  //       .then(response1 => {
  //         response1.forEach(element => {
  //           console.log('------');
  //           console.log(element);
  //           console.log('------');

  //           //alert(dates.length);
  //           //element.name=<div style={{color:"green"}}>{element.name}</div>;
  //           let v;
  //           let di;
  //           let msg;
  //           //alert(dates.length);
  //           const propertyNames = Object.keys(element);
  //           //alert(propertyNames[3]);
  //           //  console.log('--+----');
  //           //   console.log(dates);
  //           //   console.log('---+---');
  //           var data = [];
  //           var sale_vat_objects = [];
  //           for (v = 0; v <= this.state.dates.length - 1; v++) {
  //             //   di=String(dates[v]);

  //             // alert(dates[v]);
  //             //  if(di!='undefined')
  //             //  {
  //             //msg = dates[v];
  //             // console.log('--+----');
  //             // console.log(element);
  //             // console.log('---+---');
  //             //let cout=element.msg;
  //             //alert(v);alert(dates[v]);
  //             sale_vat_objects.push({
  //               msg: this.state.dates[v]
  //             });
  //             //  if(dates[v]==propertyNames[3])
  //             //  {
  //             //   // alert(dates[v]);
  //             //   //jsonData['msg']=dates[v];
  //             //   //data=dates[v];
  //             //   //alert(dates[v]);alert(propertyNames[3]);
  //             //   //element.dates[v]=<div style={{color:"green"}}>{element.dates[v]}</div>;
  //             //  }

  //             // var s="Mar282023";
  //             //alert(cout);
  //             //element.msg=<div style={{color:"green"}}>{cout}</div>;
  //             //  }

  //           }
  //           console.log('--+-++---');
  //           console.log(sale_vat_objects);
  //           console.log('---++++---');

  //           sale_vat_objects.forEach(date => {
  //             if (date.msg == propertyNames[3]) {
  //               let a = element.date.msg;
  //               //console.log(date.msg); console.log(propertyNames[3]);
  //               a = <div style={{ color: "green" }}>{element.date.msg}</div>;
  //             }
  //             //alert(element.msg);

  //           });
  //           // for (let x in sale_vat_objects) {
  //           //   console.log(x + ": "+ sale_vat_objects[x])
  //           // }

  //           //

  //           //element.Mar282023=<div style={{color:"green"}}>{element.Mar282023}</div>;
  //           // const myJSON = JSON.stringify(element);
  //           // alert(myJSON);
  //           // if(element.name)
  //           // {
  //           //   //alert('name');
  //           //  //alert(element.dataField);
  //           //  // element.name=<div>{element.name}</div>;
  //           // }
  //           // else
  //           // {
  //           //   //alert('hii');
  //           //   //alert(elementnew.dataField); alert(element.dataField);
  //           //   var listDate = [];
  //           //   var startDate = fdate;
  //           //   var endDate = tdate;
  //           //   var dateMove = new Date(startDate);
  //           //   var strDate = startDate;

  //           //  // while (strDate < endDate){
  //           //     var strDate = dateMove.toISOString().slice(0,10);
  //           //     listDate.push(strDate);
  //           //     dateMove.setDate(dateMove.getDate()+1);
  //           // //  };
  //           //   //console.log(listDate);

  //           //  // element.dataField=<div style={{color:"green"}}>{element.dataField}</div>;
  //           // }

  //         });
  //         this.setState({ formDataCSVcc: response1 })

  //       }).catch(err => console.log(err))

  //   }

  //   else {

  //     fetch(myConstClass.BASE_URL + 'shifts/getShiftSchedule/' + admin_id + '/' + fdate + '/' + '0' + '/' + tdate + '/' + this.org_id + '/' + this.dep_id + '/' + this.did + '/' + this.eid + '/' + this.paycode_id)
  //       .then(response => response.json())
  //       .then(response => {
  //         let i = 1;
  //         response.forEach(element => {
  //           let id = element.id;
  //           element.action = <div><Icon.Edit3 style={{ margin: '0px 15px 0px 0px', cursor: 'Pointer' }} onClick={() => this.edit(id)} /></div>;
  //           // console.log(element);
  //           element.id = i;
  //           i++;
  //         });
  //         this.setState({ formData: response })
  //       }).catch(err => console.log(err))

  //   }

  // }

  radioChange(e) {
    var admin_id = localStorage.getItem("uname");
    var fdate = dateFormat(this.state.from_date, "yyyy-mm-dd");
    var tdate = dateFormat(this.state.to_date, "yyyy-mm-dd");

    if (e.currentTarget.checked == true) {
      this.setState({ view: "1" });
      $("#stable").removeClass("table");
      $("#stable").addClass("tablenew");
      var start = new Date(fdate);
      var end = new Date(tdate);

      var diff = new Date(end - start);

      // get days
      var days = diff / 1000 / 60 / 60 / 24;

      //alert(days);
      if (days < 4) {
        //  alert(days);
        $("#stable").addClass("table1");
        $("#stable").removeClass("tablenew");
      } else {
        $("#stable").removeClass("table1");
        $("#stable").addClass("tablenew");
      }
    } else {
      this.setState({ view: "0" });
      $("#stable").addClass("table");
      $("#stable").removeClass("tablenew");
    }
    // let a=e.currentTarget.name;
    //  alert(e.currentTarget.value);

    // alert(e.currentTarget.checked);

    if (this.dep_id == null || this.dep_id == "") {
      this.dep_id = 0;
    } else {
      this.dep_id = this.dep_id;
    }

    if (e.currentTarget.checked == true) {
      fetch(
        myConstClass.BASE_URL +
          "shifts/getShiftScheduleCSVheaderArray/" +
          admin_id +
          "/" +
          fdate +
          "/" +
          "0" +
          "/" +
          tdate
      )
        // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
        .then((response) => response.json())
        .then((response) => {
          this.setState({ headerscc: response });

          fetch(
            myConstClass.BASE_URL +
              "shifts/getShiftScheduleCSVArray/" +
              admin_id +
              "/" +
              fdate +
              "/" +
              this.orgId +
              "/" +
              tdate +
              "/" +
              this.dep_id +
              "/" +
              this.eid +
              "/" +
              this.paycode_id
          )
            // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
            .then((response1) => response1.json())
            .then((response1) => {
              response1.forEach((element) => {
                console.log("------");
                console.log(element);
                console.log("------");

                //alert(dates.length);
                //element.name=<div style={{color:"green"}}>{element.name}</div>;
                let v;
                //alert(dates.length);
                const propertyNames = Object.keys(element);
                //alert(propertyNames[3]);
                //  console.log('--+----');
                //   console.log(dates);
                //   console.log('---+---');
                var sale_vat_objects = [];
                for (v = 0; v <= this.state.dates.length - 1; v++) {
                  //   di=String(dates[v]);

                  // alert(dates[v]);
                  //  if(di!='undefined')
                  //  {
                  //msg = dates[v];
                  // console.log('--+----');
                  // console.log(element);
                  // console.log('---+---');
                  //let cout=element.msg;
                  //alert(v);alert(dates[v]);
                  sale_vat_objects.push({
                    msg: this.state.dates[v],
                  });
                  //  if(dates[v]==propertyNames[3])
                  //  {
                  //   // alert(dates[v]);
                  //   //jsonData['msg']=dates[v];
                  //   //data=dates[v];
                  //   //alert(dates[v]);alert(propertyNames[3]);
                  //   //element.dates[v]=<div style={{color:"green"}}>{element.dates[v]}</div>;
                  //  }

                  // var s="Mar282023";
                  //alert(cout);
                  //element.msg=<div style={{color:"green"}}>{cout}</div>;
                  //  }
                }
                console.log("--+-++---");
                console.log(sale_vat_objects);
                console.log("---++++---");

                sale_vat_objects.forEach((date) => {
                  if (date.msg == propertyNames[3]) {
                    let a = element.date.msg;
                    //console.log(date.msg); console.log(propertyNames[3]);
                    a = (
                      <div style={{ color: "green" }}>{element.date.msg}</div>
                    );
                  }
                  //alert(element.msg);
                });
                // for (let x in sale_vat_objects) {
                //   console.log(x + ": "+ sale_vat_objects[x])
                // }

                //

                //element.Mar282023=<div style={{color:"green"}}>{element.Mar282023}</div>;
                // const myJSON = JSON.stringify(element);
                // alert(myJSON);
                // if(element.name)
                // {
                //   //alert('name');
                //  //alert(element.dataField);
                //  // element.name=<div>{element.name}</div>;
                // }
                // else
                // {
                //   //alert('hii');
                //   //alert(elementnew.dataField); alert(element.dataField);
                //   var listDate = [];
                //   var startDate = fdate;
                //   var endDate = tdate;
                //   var dateMove = new Date(startDate);
                //   var strDate = startDate;

                //  // while (strDate < endDate){
                //     var strDate = dateMove.toISOString().slice(0,10);
                //     listDate.push(strDate);
                //     dateMove.setDate(dateMove.getDate()+1);
                // //  };
                //   //console.log(listDate);

                //  // element.dataField=<div style={{color:"green"}}>{element.dataField}</div>;
                // }
              });
              this.setState({ formDataCSVcc: response1 });
            })
            .catch((err) => console.log(err));
        })
        .catch((err) => console.log(err));
    } else {
      fetch(
        myConstClass.BASE_URL +
          "shifts/getShiftSchedule/" +
          admin_id +
          "/" +
          fdate +
          "/" +
          "0" +
          "/" +
          tdate +
          "/" +
          this.org_id +
          "/" +
          this.dep_id +
          "/" +
          this.did +
          "/" +
          this.eid +
          "/" +
          this.paycode_id
      )
        .then((response) => response.json())
        .then((response) => {
          let i = 1;
          response.forEach((element) => {
            let id = element.id;
            element.action = (
              <div>
                <Icon.Edit3
                  style={{ margin: "0px 15px 0px 0px", cursor: "Pointer" }}
                  onClick={() => this.edit(id)}
                />
              </div>
            );
            // console.log(element);
            element.id = i;
            i++;
          });
          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }
  }
  onInTimeChange = (in_time) => {
    this.setState({ in_time });
    $(".in_time")
      .children(".react-time-picker__wrapper")
      .css("border-color", "hsl(0,0%,80%)");
    $("#in_time").hide();
  };
  // onInTimeChange = clock_in => this.setState({ clock_in })
  onOutTimeChange = (out_time) => {
    this.setState({ out_time });
    $(".out_time")
      .children(".react-time-picker__wrapper")
      .css("border-color", "hsl(0,0%,80%)");
    $("#out_time").hide();
  };

  componentDidMount() {
    var fdate = dateFormat(this.state.from_date, "yyyy-mm-dd");
    var tdate = dateFormat(this.state.to_date, "yyyy-mm-dd");
    document.querySelector(".react-bootstrap-table").style.minHeight = "243px";
    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }

    fetch(
      myConstClass.BASE_URL + "organization/get_all_organizations/" + admin_id
    )
      .then((response) => response.json())
      .then((response) => {
        this.setState({ org: response });
        response.forEach((element) => {
          this.setState({ organization_id: element.id });
        });
      })
      .catch((err) => console.log(err));

    fetch(
      myConstClass.BASE_URL + "user/get_all_Employees/" + admin_id + "/" + 0
    )
      .then((response) => response.json())
      .then((response) => {
        this.setState({ emp: response });
      })
      .catch((err) => console.log(err));
  }

  edit(e, date) {
    // alert(e);
    var empleave_add = localStorage.getItem("empschduler_add");
    var empleave_edit = localStorage.getItem("empschduler_edit");
    var login_type = localStorage.getItem("login_type");
    var edit_msg = localStorage.getItem("edit_msg");
    var add_msg = localStorage.getItem("add_msg");

    //alert(empleave_add);  alert(login_type); alert(e);

    if (login_type == "sub_admin") {
      if (e == "0") {
        if (empleave_add == "false") {
          // alert('hii')
          toastr.error(TF("{0}", T("Error")), add_msg);
          return;
        }
      }

      if (e != "0") {
        if (empleave_edit == "false") {
          toastr.error(TF("{0}", T("Error")), edit_msg);
          return;
        }
      }
    }
    this.props.history.push({
      pathname: "/" + "shift_schedular/add",
      state: {
        _id: e,
        _id1: 0,
      },
    });
  }

  handleFromDateChange = (from_date) => {
    this.setState({ from_date });
  };

  change_emp = (event) => {
    this.eid = event.target.value;
  };

  dep_change = (selectedDep) => {
    this.setState({ selectedDep });
    // this.dep_id = event.target.value;

    if (selectedDep == null || selectedDep == undefined) {
      this.dep_id = 0;
    } else {
      let x = Object.values(selectedDep);
      // this.dep_id = event.target.value;
      this.dep_id = x[0];
    }
  };

  handleToDateChange = (to_date) => {
    // this.setState({ formDataCSVcc: [] });

    // to_date.setDate(this.state.from_date.getDate() + 7);
    this.setState({ to_date });
    var admin_id = localStorage.getItem("uname");
    var tdate = dateFormat(this.state.to_date, "yyyy-mm-dd");
    var fdate = dateFormat(this.state.from_date, "yyyy-mm-dd");
    var login_type = localStorage.getItem("login_type");
    var login_id = localStorage.getItem("login_id");

    if (login_type == "emp") {
      fetch(
        myConstClass.BASE_URL +
          "shifts/getShiftSchedule/" +
          admin_id +
          "/" +
          fdate +
          "/" +
          login_id +
          "/" +
          tdate +
          "/" +
          0 +
          "/" +
          0 +
          "/" +
          0 +
          "/" +
          this.eid +
          "/" +
          this.paycode_id
      )
        .then((response) => response.json())
        .then((response) => {
          let i = 1;
          response.forEach((element) => {
            //   element.action = <div><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} /><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;
            // console.log(element);
            element.id = i;
            i++;
          });
          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }
  };

  changeOrganization = (event) => {
    var admin_id = localStorage.getItem("uname");
    this.setState({ formData: [] });
    if (event == null || event == undefined) {
      this.orgId = 0;
    } else {
      //let x = Object.values(selectedDep);
      // this.dep_id = event.target.value;
      this.orgId = event.target.value;
    }
    fetch(
      myConstClass.BASE_URL +
        "organization/getDepartmentByOrg/" +
        admin_id +
        "/" +
        this.orgId
    )
      .then((response) => response.json())
      .then((response) => {
        this.setState({ departments: response });
      })
      .catch((err) => console.log(err));
  };

  shiftReport = () => {
    this.orgId = this.state.organization_id;
    var admin_id = localStorage.getItem("uname");
    var tdate = dateFormat(this.state.to_date, "yyyy-mm-dd");
    var fdate = dateFormat(this.state.from_date, "yyyy-mm-dd");
    // fetch(
    //   myConstClass.BASE_URL +
    //     "shifts/getShiftScheduleCSVheaderArray/" +
    //     admin_id +
    //     "/" +
    //     fdate +
    //     "/" +
    //     "0" +
    //     "/" +
    //     tdate
    // )
    //   // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
    //   .then((response) => response.json())
    //   .then((response) => this.setState({ headerscc: response }))
    //   .catch((err) => console.log(err));

    // fetch(
    //   myConstClass.BASE_URL +
    //     "shifts/getShiftScheduleReport/" +
    //     admin_id +
    //     "/" +
    //     fdate +
    //     "/" +
    //     "0" +
    //     "/" +
    //     tdate +
    //     "/" +
    //     this.dep_id +
    //     "/" +
    //     this.eid +
    //     "/" +
    //     this.paycode_id
    // )
    //   // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
    //   .then((response) => response.json())
    //   .then((response) => this.setState({ shiftreportdata: response }))
    //   .catch((err) => console.log(err));

    // fetch(
    //   myConstClass.BASE_URL +
    //     "shifts/getShiftScheduleCSVArray/" +
    //     admin_id +
    //     "/" +
    //     fdate +
    //     "/" +
    //     "0" +
    //     "/" +
    //     tdate +
    //     "/" +
    //     this.dep_id +
    //     "/" +
    //     this.eid +
    //     "/" +
    //     this.paycode_id
    // )
    //   // fetch(myConstClass.BASE_URL+`/shifts/getShiftsCSV/`+admin_id)
    //   .then((response) => response.json())
    //   .then((response) => this.setState({ formDataCSVcc: response }))
    //   .catch((err) => console.log(err));

    var login_type = localStorage.getItem("login_type");
    var login_id = localStorage.getItem("login_id");

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftSchedule/" +
        admin_id +
        "/" +
        fdate +
        "/0/" +
        tdate +
        "/" +
        this.orgId +
        "/" +
        this.dep_id +
        "/" +
        this.did +
        "/" +
        this.eid +
        "/" +
        this.paycode_id +
        "/1"
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          let date = element.date;
          element.action = (
            <div>
              <Icon.Edit3
                style={
                  element.is_close == "0"
                    ? { margin: "0px 15px 0px 0px", cursor: "Pointer" }
                    : {
                        margin: "0px 15px 0px 0px",
                        cursor: "Pointer",
                        color: "red",
                        pointerEvents: "none",
                        cursor: "default",
                      }
                }
                onClick={() => this.edit(id, date)}
              />
            </div>
          );
          element.paycode = (
            <div style={{ color: element.pay_code_color }}>
              {element.pay_code}
            </div>
          );

          // console.log(element);
          element.id = i;
          i++;
        });
        this.setState({ formData: response });
      })
      .catch((err) => console.log(err));
  };

  editany(id, coloumn_name, value) {
    var admin_id = localStorage.getItem("uname");

    fetch(myConstClass.BASE_URL + "shifts/getPayCodes/" + admin_id)
      .then((response) => response.json())
      .then((response) => {
        this.setState({ pay_codes: response });
      })
      .catch((err) => console.log(err));

    let text = coloumn_name;
    const myArray = text.split("(");
    //alert(myArray);

    var empleave_add = localStorage.getItem("empschduler_add");
    var empleave_edit = localStorage.getItem("empschduler_edit");
    var login_type = localStorage.getItem("login_type");
    var edit_msg = localStorage.getItem("edit_msg");
    var add_msg = localStorage.getItem("add_msg");

    //alert(empleave_add);  alert(login_type); alert(e);

    if (login_type == "sub_admin") {
      if (id == "0") {
        if (empleave_add == "false") {
          // alert('hii')
          toastr.error(TF("{0}", T("Error")), add_msg);
          return;
        }
      }

      if (id != "0") {
        if (empleave_edit == "false") {
          toastr.error(TF("{0}", T("Error")), edit_msg);
          return;
        }
      }
    }
    this.props.history.push({
      pathname: "/" + "shift_schedular/add",
      state: {
        _id: id,
        _id1: myArray[0],
      },
    });

    // fetch(myConstClass.BASE_URL + 'shifts/getShiftScdeuleInfoAdjust/' + id + '/' + myArray[0])
    //   .then(response => response.json())
    //   .then(response => {

    //     //this.setState({employee_shift:[{ value:response.employee_id, label:response.emp_name }]});
    //     if (this.state.user_id != '0') {
    //       this.setState({ employee_shift: [{ value: response.shift_id, label: response.emp_shift }] });
    //       this.setState({ pay_code: [{ value: response.pay_code, label: response.paycode_name }] });

    //     }

    //     this.setState({ formDataM: response })

    //   }).catch(err => console.log(err))

    // this.setState({ 'visibleallowance': true });
    // alert(id); alert(coloumn_name);
    // alert('hii');
    // this.setState({ formDataCSVAtt: [] })
    // const data = new FormData();
    // data.append('id', id);
    // data.append('coloumn_name', coloumn_name);
    // data.append('value', value);
    // // data.append('formdata',JSON.stringify($('#taskform1').serializeArray()));
    // fetch(myConstClass.BASE_URL + `\payroll/update_att/`, {
    //     method: 'POST',
    //     body: data,
    //     // contentType: "application/json; charset=utf-8",
    // })
    //     .then(response => response.json()).then((response) => {
    //         fetch(myConstClass.BASE_URL + `/payroll/getPayrollTableTempData/` + this.props.location.state._id + '/' + this.state.organization_id + '/' + this.eMasterAttId)
    //             .then(response => response.json())
    //             .then(response => {
    //                 this.setState({ formDataCSVAtt: response })
    //             }).catch(err => console.log(err))

    //     })
    //     .catch();
  }
  toggledocTemplate = () => {
    this.setState({ visibleallowance: false });
  };
  render() {
    var admin_id = localStorage.getItem("uname");
    var login_type = localStorage.getItem("login_type");
    const { shifts, departments, emp, pay_codes, org, formDataM } = this.state;

    let depOp = departments
      ? departments.map((cell) => {
          return { value: cell.did, label: cell.name };
        })
      : [];
    let import_btn;
    if (admin_id == 0) {
      import_btn = (
        <div>
          <Col lg={6}>
            {/*<Link to={'/'+myConstClass.TENANT_PAGE_PATH+"shift_schedular/importschedular"}> <Button color="primary" type="button" className="import_btn">Import +</Button></Link>*/}
          </Col>
        </div>
      );
    } else if (admin_id != 0 && login_type != "emp") {
      import_btn = (
        <div class="col-md-6">
          {/* <Link to={'/'+myConstClass.TENANT_PAGE_PATH+"shift_schedular/importschedular"}> <Button color="primary" type="button" className="import_btn">Import +</Button></Link>*/}
        </div>
      );
    }
    //for export csv

    //  const tableHeaderColumns = this.state.headerscc.map((column) => (
    //   <TableHeaderColumn
    //     dataField={column.dataField}
    //    //  dataFormat={column.dataField}
    //   // dataSort={column.dataField}
    //   >
    //     {column.text}
    //   </TableHeaderColumn>
    // ))

    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
            {" "}
            {T("Shift")} {T("Scheduler")}
          </HeaderTitle>

          {admin_id != "0" && login_type != "emp" ? (
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to={"/" + "dashboard"}>{T("Dashboard")}</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>
                {T("Shift")} {T("Scheduler")}
              </BreadcrumbItem>

              <button
                class="mr-1 mb-1 btn btn-outline-secondary"
                onClick={() => this.edit(this.state.user_id)}
                style={{
                  color: "#ffffff",
                  border: "1px solid #ffffff",
                  float: "right !important",
                  margin: "auto",
                }}
              >
                <Icon.PlusCircle />
                &nbsp;&nbsp;{T("ADD")}
              </button>
            </Breadcrumb>
          ) : (
            ""
          )}
        </Header>
        <Card>
          <Row></Row>

          <CardHeader></CardHeader>

          <ToolkitProvider
            keyField="name"
            // data={this.state.formData}
            columns={
              this.state.view == "1" ? this.state.headerscc : tableColumns
            }
            data={
              this.state.view == "1"
                ? this.state.formDataCSVcc
                : this.state.formData
            }
            //  columns={tableHeaderColumns}
            exportCSV={{
              fileName:
                TF("{0} {1} {2}_", T("Work"), T("Schedule"), T("List")) +
                moment() +
                ".csv",
              exportAll: true,
              style: { color: "red" },
            }}
          >
            {(props) => (
              <div>
                <AvForm id="sform">
                  <Row className="shifts">
                    <div class="col-md-4">
                      <Label for="example">
                        {T("Select")} {T("From")} {T("Date")}
                      </Label>{" "}
                      <br />
                      <DatePicker
                        name="from_date"
                        selected={this.state.from_date}
                        onChange={this.handleFromDateChange}
                        minDate={moment().toDate()}
                        dateFormat="dd-MM-yyyy"
                        className="is-untouched is-pristine av-valid form-control"
                        value={this.state.from_date}
                      />
                    </div>
                    <div class="col-md-4">
                      <AvGroup>
                        <AvField
                          style={{ height: "38px" }}
                          type="select"
                          name="employee_id"
                          label={TF("{0} {1}", T("Select"), T("Organization"))}
                          onChange={this.changeOrganization}
                          //onChange={this.changeOrganization}
                          value={this.state.organization_id}
                        >
                          {/* <option value={0}>
                            {TF("{0} {1}", T("Select"), T("Organization"))}{" "}
                          </option> */}
                          {org
                            ? org.map((cell) => {
                                return (
                                  <option value={cell.id}>{cell.title}</option>
                                );
                              })
                            : ""}
                        </AvField>
                      </AvGroup>
                    </div>
                    <div class="col-md-4">
                      <AvField
                        style={{ height: "38px" }}
                        type="select"
                        name="employee_id"
                        label={TF("{0} {1}", T("Select"), T("Employee"))}
                        onChange={this.change_emp}
                        value={this.state.employee_id}
                      >
                        <option value={0}>
                          {T("Select")} {T("Employee")}
                        </option>
                        {emp
                          ? emp.map((cell) => {
                              return (
                                <option value={cell.id}>
                                  {cell.first_name} {cell.last_name}
                                </option>
                              );
                            })
                          : ""}
                      </AvField>
                    </div>
                  </Row>
                  <Row className="shifts">
                    <div class="col-md-4">
                      <Button onClick={this.shiftReport}>
                        {TF("{0} {1}", T("Shift"), T("Report"))}{" "}
                      </Button>
                    </div>
                    <div class="col-md-4"></div>
                  </Row>
                </AvForm>
                <CardBody>
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                    <Row>
                      {login_type != "emp" ? (
                        <div class="col-md-4">
                          <MyExportCSV {...props.csvProps} />
                        </div>
                      ) : (
                        <div class="col-md-4"> </div>
                      )}
                      <div class="col-md-4"> </div>
                      <div class="col-md-4" style={{ textAlign: "right" }}>
                        <Label for="example"> </Label>
                        <SearchBar
                          {...props.searchProps}
                          placeholder={T("Search")}
                        />
                      </div>{" "}
                      <br />
                    </Row>
                  </AvForm>
                  <br />

                  <div class="table_wrapper">
                    {/* <BootstrapTable
                        id="stable"
                        className="myFormat"
                        {...props.baseProps}
                        bootstrap4
                        bordered={false}
                        filter={filterFactory()}
                        filterPosition="top"
                        rowStyle={rowStyle}
                        //editCellStyle={editCellStyle} 
                        //editCellStyle: (cell, row, rowIndex, colIndex) => {
                        // it is suppose to return an object
                        // }
                        // onFilteredChange={filtered => {this.setState({ filtered });}}
                        pagination={paginationFactory({
                          // sizePerPage: 25,
                          sizePerPage: 10,
                          sizePerPageList: [5, 10, 25, 50]
                        })}
                      /> */}
                    {this.state.view == "1" ? (
                      <BootstrapTable
                        {...props.baseProps}
                        bootstrap4
                        bordered={false}
                        filter={filterFactory()}
                        filterPosition="top"
                        cellEdit={cellEditFactory({
                          mode: "click",
                          blurToSave: true,
                          // style: {
                          footerStyle: { backgroundColor: "green" },

                          editCellStyle: () => {
                            // it is suppose to return an object
                            //  color:"red"
                            // backgroundColor: "green"
                            return { color: "green" };
                          },

                          // },

                          afterSaveCell: (oldValue, newValue, row, column) => {
                            // alert(row);
                            this.editany(
                              row.employee_id,
                              column.text,
                              newValue
                            );
                          },
                        })}
                        // onFilteredChange={filtered => {this.setState({ filtered });}}
                        pagination={paginationFactory({
                          // sizePerPage: 25,
                          sizePerPage: 10,
                          sizePerPageList: [5, 10, 25, 50],
                        })}
                      />
                    ) : (
                      <BootstrapTable
                        {...props.baseProps}
                        bootstrap4
                        bordered={false}
                        filter={filterFactory()}
                        filterPosition="top"
                        cellEdit={cellEditFactory({
                          mode: "click",
                          blurToSave: true,
                          editCellStyle: () => {
                            // it is suppose to return an object
                            //  color:"red"
                            // backgroundColor: "green"
                            return { color: "green" };
                          },

                          afterSaveCell: (oldValue, newValue, row, column) => {
                            this.editany(
                              row.employee_id,
                              column.text,
                              newValue
                            );
                          },
                        })}
                        // onFilteredChange={filtered => {this.setState({ filtered });}}
                        pagination={paginationFactory({
                          // sizePerPage: 25,
                          sizePerPage: 10,
                          sizePerPageList: [5, 10, 25, 50],
                        })}
                      />
                    )}
                  </div>
                </CardBody>
              </div>
            )}
          </ToolkitProvider>
        </Card>

        {/* <ExportCSVTable /> */}
      </Container>
    );
  }
}

export default Shift_schedular;
