text: import React, { Fragment, useEffect, useState } from 'react';
  import {
    Breadcrumb,
    BreadcrumbItem,
    Row,
    Col,
    Card,
    CardBody,
    Button,
    ButtonGroup,
    Form,
    FormGroup,
    Input,
    Label,
    CustomInput,
    Spinner,
  } from 'reactstrap';
  import Datetime from 'react-datetime';
  import moment from 'moment';
  import loadable from '@loadable/component';
  import Cascader from 'rc-cascader';
  import { getCookieValue, createCookie } from '../../../helpers/utils';
  import withRedirect from '../../../hoc/withRedirect';
  import { withTranslation } from 'react-i18next';
  import { toast } from 'react-toastify';
  import ButtonIcon from '../../common/ButtonIcon';
  import { APIBaseURL } from '../../../config';
  
  
  const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
  
  
  const CombinedEquipmentBatch = ({ setRedirect, setRedirectUrl, t }) => {
    let current_moment = moment();
    useEffect(() => {
      let is_logged_in = getCookieValue('is_logged_in');
      let user_name = getCookieValue('user_name');
      let user_display_name = getCookieValue('user_display_name');
      let user_uuid = getCookieValue('user_uuid');
      let token = getCookieValue('token');
      if (is_logged_in === null || !is_logged_in) {
        setRedirectUrl(`/authentication/basic/login`);
        setRedirect(true);
      } else {
        //update expires time of cookies
        createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
        createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
        createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
        createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
        createCookie('token', token, 1000 * 60 * 60 * 8);
      }
    });
    // State
    // Query Parameters
    const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
    const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
    const [combinedEquipmentList, setCombinedEquipmentList] = useState([]);
    const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(current_moment.clone().startOf('month'));
    const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
    const [cascaderOptions, setCascaderOptions] = useState(undefined);
        
    // buttons
    const [submitButtonDisabled, setSubmitButtonDisabled] = useState(false);
    const [spinnerHidden, setSpinnerHidden] = useState(true);
    const [exportButtonHidden, setExportButtonHidden] = useState(true);
  
    //Results
    const [detailedDataTableColumns, setDetailedDataTableColumns] = useState(
      [{dataField: 'name', text: t('Name'), sort: true}, {dataField: 'space', text: t('Space'), sort: true}]);
    const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
    
    useEffect(() => {
      let isResponseOK = false;
      fetch(APIBaseURL + '/spaces/tree', {
        method: 'GET',
        headers: {
          "Content-type": "application/json",
          "User-UUID": getCookieValue('user_uuid'),
          "Token": getCookieValue('token')
        },
        body: null,
  
      }).then(response => {
        console.log(response);
        if (response.ok) {
          isResponseOK = true;
        }
        return response.json();
      }).then(json => {
        console.log(json);
        if (isResponseOK) {
          // rename keys 
          json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
          setCascaderOptions(json);
          // set the default selected space
          setSelectedSpaceName([json[0]].map(o => o.label));
          setSelectedSpaceID([json[0]].map(o => o.value));
  
          setSubmitButtonDisabled(false);
          setSpinnerHidden(true);
        } else {
          toast.error(json.description);
        }
      }).catch(err => {
        console.log(err);
      });
  
    }, []);
  
    const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
  
    let onSpaceCascaderChange = (value, selectedOptions) => {
      setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
      setSelectedSpaceID(value[value.length - 1]);
      setCombinedEquipmentList([]);
      setExportButtonHidden(true);
      setSubmitButtonDisabled(false);
    }
    let onReportingPeriodBeginsDatetimeChange = (newDateTime) => {
      setReportingPeriodBeginsDatetime(newDateTime);
    }
  
    let onReportingPeriodEndsDatetimeChange = (newDateTime) => {
      setReportingPeriodEndsDatetime(newDateTime);
    }
  
    var getValidReportingPeriodBeginsDatetimes = function (currentDate) {
      return currentDate.isBefore(moment(reportingPeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
    }
  
    var getValidReportingPeriodEndsDatetimes = function (currentDate) {
      return currentDate.isAfter(moment(reportingPeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
    }
  
    // Handler
    const handleSubmit = e => {
      e.preventDefault();
      console.log('handleSubmit');
      console.log(selectedSpaceID);
      console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
      console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
  
      // disable submit button
      setSubmitButtonDisabled(true);
      // show spinner
      setSpinnerHidden(false);
      // hide export buttion
      setExportButtonHidden(true)
   
      // Reinitialize tables
      setCombinedEquipmentList([]);
      
      let isResponseOK = false;
      fetch(APIBaseURL + '/reports/combinedequipmentbatch?' +
        'spaceid=' + selectedSpaceID +
        '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
        '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
        method: 'GET',
        headers: {
          "Content-type": "application/json",
          "User-UUID": getCookieValue('user_uuid'),
          "Token": getCookieValue('token')
        },
        body: null,
  
      }).then(response => {
        if (response.ok) {
          isResponseOK = true;
        };
        return response.json();
      }).then(json => {
        if (isResponseOK) {
          console.log(json)
          let combined_equipments = [];
          if (json['combined_equipments'].length > 0) {
            json['combined_equipments'].forEach((currentCombinedEquipment, index) => {
              let detailed_value = {};
              detailed_value['id'] = currentCombinedEquipment['id'];
              detailed_value['name'] = currentCombinedEquipment['combined_equipment_name'];
              detailed_value['space'] = currentCombinedEquipment['space_name'];
              detailed_value['costcenter'] = currentCombinedEquipment['cost_center_name'];
              currentCombinedEquipment['values'].forEach((currentValue, energyCategoryIndex) => {
                detailed_value['a' + energyCategoryIndex] = currentValue.toFixed(2);
              });
              combined_equipments.push(detailed_value);
            });
          };
  
          setCombinedEquipmentList(combined_equipments);
  
          let detailed_column_list = [];
          detailed_column_list.push({
            dataField: 'name',
            text: t('Name'),
            sort: true
          });
          detailed_column_list.push({
            dataField: 'space',
            text: t('Space'),
            sort: true
          });
          json['energycategories'].forEach((currentValue, index) => {
            detailed_column_list.push({
              dataField: 'a' + index,
              text: currentValue['name'] + ' (' + currentValue['unit_of_measure'] + ')',
              sort: true
            })
          });
          setDetailedDataTableColumns(detailed_column_list);
  
          setExcelBytesBase64(json['excel_bytes_base64']);
  
          // enable submit button
          setSubmitButtonDisabled(false);
          // hide spinner
          setSpinnerHidden(true);
          // show export buttion
          setExportButtonHidden(false);
            
        } else {
          toast.error(json.description)
        }
      }).catch(err => {
        console.log(err);
      });
    };
  
    const handleExport = e => {
      e.preventDefault();
      const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const fileName = 'combinedequipmentbatch.xlsx'
      var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
      fetch(fileUrl)
          .then(response => response.blob())
          .then(blob => {
              var link = window.document.createElement("a");
              link.href = window.URL.createObjectURL(blob, { type: mimeType });
              link.download = fileName;
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
          });
    };
    
  
  
    return (
      <Fragment>
        <div>
          <Breadcrumb>
            <BreadcrumbItem>{t('Combined Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Batch Analysis')}</BreadcrumbItem>
          </Breadcrumb>
        </div>
        <Card className="bg-light mb-3">
          <CardBody className="p-3">
            <Form onSubmit={handleSubmit}>
              <Row form>
                <Col xs={6} sm={3}>
                  <FormGroup className="form-group">
                    <Label className={labelClasses} for="space">
                      {t('Space')}
                    </Label>
                    <br />
                    <Cascader options={cascaderOptions}
                      onChange={onSpaceCascaderChange}
                      changeOnSelect
                      expandTrigger="hover">
                      <Input value={selectedSpaceName || ''} readOnly />
                    </Cascader>
                  </FormGroup>
                </Col>
                
                <Col xs={6} sm={3}>
                  <FormGroup className="form-group">
                    <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
                      {t('Reporting Period Begins')}
                    </Label>
                    <Datetime id='reportingPeriodBeginsDatetime'
                      value={reportingPeriodBeginsDatetime}
                      onChange={onReportingPeriodBeginsDatetimeChange}
                      isValidDate={getValidReportingPeriodBeginsDatetimes}
                      closeOnSelect={true} />
                  </FormGroup>
                </Col>
                <Col xs={6} sm={3}>
                  <FormGroup className="form-group">
                    <Label className={labelClasses} for="reportingPeriodEndsDatetime">
                      {t('Reporting Period Ends')}
                    </Label>
                    <Datetime id='reportingPeriodEndsDatetime'
                      value={reportingPeriodEndsDatetime}
                      onChange={onReportingPeriodEndsDatetimeChange}
                      isValidDate={getValidReportingPeriodEndsDatetimes}
                      closeOnSelect={true} />
                  </FormGroup>
                </Col>
                <Col xs="auto">
                  <FormGroup>
                    <br></br>
                    <ButtonGroup id="submit">
                      <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
                    </ButtonGroup>
                  </FormGroup>
                </Col>
                <Col xs="auto">
                  <FormGroup>
                    <br></br>
                    <Spinner color="primary" hidden={spinnerHidden}  />
                  </FormGroup>
                </Col>
                <Col xs="auto">
                    <br></br>
                    <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
                    hidden={exportButtonHidden}
                    onClick={handleExport} >
                      {t('Export')}
                    </ButtonIcon>
                </Col>
              </Row>
            </Form>
          </CardBody>
        </Card>
        <DetailedDataTable data={combinedEquipmentList} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
        </DetailedDataTable>
  
      </Fragment>
    );
  };
  
  export default withTranslation()(withRedirect(CombinedEquipmentBatch));
  