Passed
Push — master ( 02289f...d6a19b )
by Guangyu
08:58 queued 15s
created

myems-web/src/components/MyEMS/Space/SpaceLoad.js   B

Complexity

Total Complexity 42
Complexity/F 0

Size

Lines of Code 771
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 42
eloc 643
dl 0
loc 771
rs 8.997
c 0
b 0
f 0
mnd 42
bc 42
fnc 0
bpm 0
cpm 0
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-web/src/components/MyEMS/Space/SpaceLoad.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import React, { Fragment, useEffect, useState, useContext } from 'react';
2
import {
3
  Breadcrumb,
4
  BreadcrumbItem,
5
  Row,
6
  Col,
7
  Card,
8
  CardBody,
9
  Button,
10
  ButtonGroup,
11
  Form,
12
  FormGroup,
13
  Input,
14
  Label,
15
  CustomInput,
16
  Spinner
17
} from 'reactstrap';
18
import CountUp from 'react-countup';
19
import moment from 'moment';
20
import loadable from '@loadable/component';
21
import Cascader from 'rc-cascader';
22
import CardSummary from '../common/CardSummary';
23
import MultiTrendChart from '../common/MultiTrendChart';
24
import LineChart from '../common/LineChart';
25
import { getCookieValue, createCookie } from '../../../helpers/utils';
26
import withRedirect from '../../../hoc/withRedirect';
27
import { withTranslation } from 'react-i18next';
28
import { toast } from 'react-toastify';
29
import ButtonIcon from '../../common/ButtonIcon';
30
import { APIBaseURL } from '../../../config';
31
import { periodTypeOptions } from '../common/PeriodTypeOptions';
32
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
33
import DateRangePickerWrapper from '../common/DateRangePickerWrapper';
34
import { endOfDay} from 'date-fns';
35
import AppContext from '../../../context/Context';
36
37
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
38
39
40
const SpaceLoad = ({ setRedirect, setRedirectUrl, t }) => {
41
  let current_moment = moment();
42
  useEffect(() => {
43
    let is_logged_in = getCookieValue('is_logged_in');
44
    let user_name = getCookieValue('user_name');
45
    let user_display_name = getCookieValue('user_display_name');
46
    let user_uuid = getCookieValue('user_uuid');
47
    let token = getCookieValue('token');
48
    if (is_logged_in === null || !is_logged_in) {
49
      setRedirectUrl(`/authentication/basic/login`);
50
      setRedirect(true);
51
    } else {
52
      //update expires time of cookies
53
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
54
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
55
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
56
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
57
      createCookie('token', token, 1000 * 60 * 60 * 8);
58
    }
59
  });
60
  // State
61
  // Query Parameters
62
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
63
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
64
  const [comparisonType, setComparisonType] = useState('month-on-month');
65
  const [periodType, setPeriodType] = useState('daily');
66
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
67
  const [basePeriodDateRange, setBasePeriodDateRange] = useState([current_moment.clone().subtract(1, 'months').startOf('month').toDate(), current_moment.clone().subtract(1, 'months').toDate()]);
68
  const [basePeriodDateRangePickerDisabled, setBasePeriodDateRangePickerDisabled] = useState(true);
69
  const [reportingPeriodDateRange, setReportingPeriodDateRange] = useState([current_moment.clone().startOf('month').toDate(), current_moment.toDate()]);
70
  const dateRangePickerLocale = {
71
    sunday: t('sunday'),
72
    monday: t('monday'),
73
    tuesday: t('tuesday'),
74
    wednesday: t('wednesday'),
75
    thursday: t('thursday'),
76
    friday: t('friday'),
77
    saturday: t('saturday'),
78
    ok: t('ok'),
79
    today: t('today'),
80
    yesterday: t('yesterday'),
81
    hours: t('hours'),
82
    minutes: t('minutes'),
83
    seconds: t('seconds'),
84
    last7Days: t('last7Days'),
85
    formattedMonthPattern: 'yyyy-MM-dd'
86
  };
87
  const dateRangePickerStyle = { display: 'block', zIndex: 10};
88
  const { language } = useContext(AppContext);
89
  
90
  // buttons
91
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
92
  const [spinnerHidden, setSpinnerHidden] = useState(true);
93
  const [exportButtonHidden, setExportButtonHidden] = useState(true);
94
95
  //Results
96
  const [cardSummaryList, setCardSummaryList] = useState([]);
97
98
  const [spaceBaseAndReportingNames, setSpaceBaseAndReportingNames] = useState({"a0":""});
99
  const [spaceBaseAndReportingUnits, setSpaceBaseAndReportingUnits] = useState({"a0":"()"});
100
101
  const [spaceBaseLabels, setSpaceBaseLabels] = useState({"a0": []});
102
  const [spaceBaseData, setSpaceBaseData] = useState({"a0": []});
103
  const [spaceBaseSubtotals, setSpaceBaseSubtotals] = useState({"a0": (0).toFixed(2)});
104
105
  const [spaceReportingLabels, setSpaceReportingLabels] = useState({"a0": []});
106
  const [spaceReportingData, setSpaceReportingData] = useState({"a0": []});
107
  const [spaceReportingSubtotals, setSpaceReportingSubtotals] = useState({"a0": (0).toFixed(2)});
108
109
  const [spaceReportingRates, setSpaceReportingRates] = useState({"a0": []});
110
  const [spaceReportingOptions, setSpaceReportingOptions] = useState([]);
111
  
112
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
113
  const [parameterLineChartData, setParameterLineChartData] = useState({});
114
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
115
  
116
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
117
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
118
  const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
119
  
120
  useEffect(() => {
121
    let isResponseOK = false;
122
    fetch(APIBaseURL + '/spaces/tree', {
123
      method: 'GET',
124
      headers: {
125
        "Content-type": "application/json",
126
        "User-UUID": getCookieValue('user_uuid'),
127
        "Token": getCookieValue('token')
128
      },
129
      body: null,
130
131
    }).then(response => {
132
      console.log(response);
133
      if (response.ok) {
134
        isResponseOK = true;
135
        // enable submit button
136
        setSubmitButtonDisabled(false);
137
      }
138
      return response.json();
139
    }).then(json => {
140
      console.log(json);
141
      if (isResponseOK) {
142
        // rename keys 
143
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
144
        setCascaderOptions(json);
145
        setSelectedSpaceName([json[0]].map(o => o.label));
146
        setSelectedSpaceID([json[0]].map(o => o.value));
147
      } else {
148
        toast.error(t(json.description));
149
      }
150
    }).catch(err => {
151
      console.log(err);
152
    });
153
154
  }, []);
155
156
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
157
  
158
  let onSpaceCascaderChange = (value, selectedOptions) => {
159
    console.log(value, selectedOptions);
160
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
161
    setSelectedSpaceID(value[value.length - 1]);
162
  }
163
164
  let onComparisonTypeChange = ({ target }) => {
165
    console.log(target.value);
166
    setComparisonType(target.value);
167
    if (target.value === 'year-over-year') {
168
      setBasePeriodDateRangePickerDisabled(true);
169
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'years').toDate(),
170
        moment(reportingPeriodDateRange[1]).subtract(1, 'years').toDate()]);
171
    } else if (target.value === 'month-on-month') {
172
      setBasePeriodDateRangePickerDisabled(true);
173
      setBasePeriodDateRange([moment(reportingPeriodDateRange[0]).subtract(1, 'months').toDate(),
174
        moment(reportingPeriodDateRange[1]).subtract(1, 'months').toDate()]);
175
    } else if (target.value === 'free-comparison') {
176
      setBasePeriodDateRangePickerDisabled(false);
177
    } else if (target.value === 'none-comparison') {
178
      setBasePeriodDateRange([null, null]);
179
      setBasePeriodDateRangePickerDisabled(true);
180
    }
181
  };
182
183
  // Callback fired when value changed
184
  let onBasePeriodChange = (DateRange) => {
185
    if(DateRange == null) {
186
      setBasePeriodDateRange([null, null]);
187
    } else {
188
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
189
        // if the user did not change time value, set the default time to the end of day
190
        DateRange[1] = endOfDay(DateRange[1]);
191
      }
192
      setBasePeriodDateRange([DateRange[0], DateRange[1]]);
193
    }
194
  };
195
196
  // Callback fired when value changed
197
  let onReportingPeriodChange = (DateRange) => {
198
    if(DateRange == null) {
199
      setReportingPeriodDateRange([null, null]);
200
    } else {
201
      if (moment(DateRange[1]).format('HH:mm:ss') == '00:00:00') {
202
        // if the user did not change time value, set the default time to the end of day
203
        DateRange[1] = endOfDay(DateRange[1]);
204
      }
205
      setReportingPeriodDateRange([DateRange[0], DateRange[1]]);
206
      if (comparisonType === 'year-over-year') {
207
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'years').toDate(), moment(DateRange[1]).clone().subtract(1, 'years').toDate()]);
208
      } else if (comparisonType === 'month-on-month') {
209
        setBasePeriodDateRange([moment(DateRange[0]).clone().subtract(1, 'months').toDate(), moment(DateRange[1]).clone().subtract(1, 'months').toDate()]);
210
      }
211
    }
212
  };
213
214
  // Callback fired when value clean
215
  let onBasePeriodClean = event => {
216
    setBasePeriodDateRange([null, null]);
217
  };
218
219
  // Callback fired when value clean
220
  let onReportingPeriodClean = event => {
221
    setReportingPeriodDateRange([null, null]);
222
  };
223
224
  const isBasePeriodTimestampExists = (base_period_data) => {
225
    const timestamps = base_period_data['timestamps'];
226
227
    if (timestamps.length === 0) {
228
      return false;
229
    }
230
231
    for (let i = 0; i < timestamps.length; i++) {
232
      if (timestamps[i].length > 0) {
233
        return true;
234
      }
235
    }
236
    return false
237
  }
238
239
  // Handler
240
  const handleSubmit = e => {
241
    e.preventDefault();
242
    console.log('handleSubmit');
243
    console.log(selectedSpaceID);
244
    console.log(comparisonType);
245
    console.log(periodType);
246
    console.log(basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : null)
247
    console.log(basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : null)
248
    console.log(moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss'))
249
    console.log(moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss'));
250
    
251
    // disable submit button
252
    setSubmitButtonDisabled(true);
253
    // show spinner
254
    setSpinnerHidden(false);
255
    // hide export button
256
    setExportButtonHidden(true)
257
258
    // Reinitialize tables
259
    setDetailedDataTableData([]);
260
261
    let isResponseOK = false;
262
    fetch(APIBaseURL + '/reports/spaceload?' +
263
      'spaceid=' + selectedSpaceID +
264
      '&periodtype=' + periodType +
265
      '&baseperiodstartdatetime=' + (basePeriodDateRange[0] != null ? moment(basePeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') : '') +
266
      '&baseperiodenddatetime=' + (basePeriodDateRange[1] != null ? moment(basePeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') : '') +
267
      '&reportingperiodstartdatetime=' + moment(reportingPeriodDateRange[0]).format('YYYY-MM-DDTHH:mm:ss') +
268
      '&reportingperiodenddatetime=' + moment(reportingPeriodDateRange[1]).format('YYYY-MM-DDTHH:mm:ss') + 
269
      '&language=' + language, {
270
      method: 'GET',
271
      headers: {
272
        "Content-type": "application/json",
273
        "User-UUID": getCookieValue('user_uuid'),
274
        "Token": getCookieValue('token')
275
      },
276
      body: null,
277
278
    }).then(response => {
279
      if (response.ok) {
280
        isResponseOK = true;
281
      }
282
      return response.json();
283
    }).then(json => {
284
      if (isResponseOK) {
285
        console.log(json)
286
        
287
        let cardSummaryArray = []
288
        json['reporting_period']['names'].forEach((currentValue, index) => {
289
          let cardSummaryItem = {}
290
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
291
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
292
          cardSummaryItem['average'] = json['reporting_period']['averages'][index];
293
          cardSummaryItem['average_increment_rate'] = parseFloat(json['reporting_period']['averages_increment_rate'][index] * 100).toFixed(2) + "%";
294
          cardSummaryItem['average_per_unit_area'] = json['reporting_period']['averages_per_unit_area'][index];
295
          cardSummaryItem['maximum'] = json['reporting_period']['maximums'][index];
296
          cardSummaryItem['maximum_increment_rate'] = parseFloat(json['reporting_period']['maximums_increment_rate'][index] * 100).toFixed(2) + "%";
297
          cardSummaryItem['maximum_per_unit_area'] = json['reporting_period']['maximums_per_unit_area'][index];
298
          cardSummaryItem['factor'] = json['reporting_period']['factors'][index];
299
          cardSummaryItem['factor_increment_rate'] = parseFloat(json['reporting_period']['factors_increment_rate'][index] * 100).toFixed(2) + "%";
300
          cardSummaryArray.push(cardSummaryItem);
301
        });
302
        setCardSummaryList(cardSummaryArray);
303
304
        let base_timestamps = {}
305
        json['base_period']['timestamps'].forEach((currentValue, index) => {
306
          base_timestamps['a' + index] = currentValue;
307
        });
308
        setSpaceBaseLabels(base_timestamps)
309
310
        let base_values = {}
311
        json['base_period']['sub_maximums'].forEach((currentValue, index) => {
312
          base_values['a' + index] = currentValue;
313
        });
314
        setSpaceBaseData(base_values)
315
316
        /*
317
        * Tip:
318
        *     base_names === reporting_names
319
        *     base_units === reporting_units
320
        * */
321
322
        let base_and_reporting_names = {}
323
        json['reporting_period']['names'].forEach((currentValue, index) => {
324
          base_and_reporting_names['a' + index] = currentValue;
325
        });
326
        setSpaceBaseAndReportingNames(base_and_reporting_names)
327
328
        let base_and_reporting_units = {}
329
        json['reporting_period']['units'].forEach((currentValue, index) => {
330
          base_and_reporting_units['a' + index] = "("+currentValue+"/H)";
331
        });
332
        setSpaceBaseAndReportingUnits(base_and_reporting_units)
333
334
        // let base_subtotals = {}
335
        // json['base_period']['subtotals'].forEach((currentValue, index) => {
336
        //   base_subtotals['a' + index] = currentValue.toFixed(2);
337
        // });
338
        // setSpaceBaseSubtotals(base_subtotals)
339
340
        let reporting_timestamps = {}
341
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
342
          reporting_timestamps['a' + index] = currentValue;
343
        });
344
        setSpaceReportingLabels(reporting_timestamps);
345
346
        let reporting_values = {}
347
        json['reporting_period']['sub_maximums'].forEach((currentValue, index) => {
348
          reporting_values['a' + index] = currentValue;
349
        });
350
        setSpaceReportingData(reporting_values);
351
352
        // let reporting_subtotals = {}
353
        // json['reporting_period']['subtotals'].forEach((currentValue, index) => {
354
        //   reporting_subtotals['a' + index] = currentValue.toFixed(2);
355
        // });
356
        // setSpaceReportingSubtotals(reporting_subtotals);
357
358
        let rates = {}
359
        json['reporting_period']['rates_of_sub_maximums'].forEach((currentValue, index) => {
360
          let currentRate = Array();
361
          currentValue.forEach((rate) => {
362
            currentRate.push(rate ? parseFloat(rate * 100).toFixed(2) : '0.00');
363
          });
364
          rates['a' + index] = currentRate;
365
        });
366
        setSpaceReportingRates(rates)
367
368
        let options = Array();
369
        json['reporting_period']['names'].forEach((currentValue, index) => {
370
          let unit = json['reporting_period']['units'][index];
371
          options.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + '/H)'});
372
        });
373
        setSpaceReportingOptions(options);
374
      
375
        let timestamps = {}
376
        json['parameters']['timestamps'].forEach((currentValue, index) => {
377
          timestamps['a' + index] = currentValue;
378
        });
379
        setParameterLineChartLabels(timestamps);
380
381
        let values = {}
382
        json['parameters']['values'].forEach((currentValue, index) => {
383
          values['a' + index] = currentValue;
384
        });
385
        setParameterLineChartData(values);
386
      
387
        let names = Array();
388
        json['parameters']['names'].forEach((currentValue, index) => {
389
          
390
          names.push({ 'value': 'a' + index, 'label': currentValue });
391
        });
392
        setParameterLineChartOptions(names);
393
394
        if(!isBasePeriodTimestampExists(json['base_period'])) {
395
          let detailed_value_list = [];
396
          if (json['reporting_period']['timestamps'].length > 0) {
397
            json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
398
              let detailed_value = {};
399
              detailed_value['id'] = timestampIndex;
400
              detailed_value['startdatetime'] = currentTimestamp;
401
              json['reporting_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
402
                if (json['reporting_period']['sub_averages'][energyCategoryIndex][timestampIndex] != null) {
403
                  detailed_value['a' + 2 * energyCategoryIndex] = json['reporting_period']['sub_averages'][energyCategoryIndex][timestampIndex];
404
                } else {
405
                  detailed_value['a' + 2 * energyCategoryIndex] = null;
406
                };
407
408
                if (json['reporting_period']['sub_maximums'][energyCategoryIndex][timestampIndex] != null) {
409
                  detailed_value['a' + (2 * energyCategoryIndex + 1)] = json['reporting_period']['sub_maximums'][energyCategoryIndex][timestampIndex];
410
                } else {
411
                  detailed_value['a' + (2 * energyCategoryIndex + 1)] = null;
412
                };
413
              });
414
              detailed_value_list.push(detailed_value);
415
            });
416
          }
417
          ;
418
419
          setTimeout(() => {
420
            setDetailedDataTableData(detailed_value_list);
421
          }, 0)
422
423
          let detailed_column_list = [];
424
          detailed_column_list.push({
425
            dataField: 'startdatetime',
426
            text: t('Datetime'),
427
            sort: true
428
          })
429
          json['reporting_period']['names'].forEach((currentValue, index) => {
430
            let unit = json['reporting_period']['units'][index];
431
            detailed_column_list.push({
432
              dataField: 'a' + 2 * index,
433
              text: currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
434
              sort: true,
435
              formatter: function (decimalValue) {
436
                if (typeof decimalValue === 'number') {
437
                  return decimalValue.toFixed(2);
438
                } else {
439
                  return null;
440
                }
441
              }
442
            });
443
            detailed_column_list.push({
444
              dataField: 'a' + (2 * index + 1),
445
              text: currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
446
              sort: true,
447
              formatter: function (decimalValue) {
448
                if (typeof decimalValue === 'number') {
449
                  return decimalValue.toFixed(2);
450
                } else {
451
                  return null;
452
                }
453
              }
454
            });
455
          });
456
          setDetailedDataTableColumns(detailed_column_list);
457
        } else {
458
          /*
459
          * Tip:
460
          *     json['base_period']['names'] ===  json['reporting_period']['names']
461
          *     json['base_period']['units'] ===  json['reporting_period']['units']
462
          * */
463
          let detailed_column_list = [];
464
          detailed_column_list.push({
465
            dataField: 'basePeriodDatetime',
466
            text: t('Base Period') + ' - ' + t('Datetime'),
467
            sort: true
468
          })
469
470
          json['base_period']['names'].forEach((currentValue, index) => {
471
            let unit = json['base_period']['units'][index];
472
            detailed_column_list.push({
473
              dataField: 'a' + 2 * index,
474
              text: t('Base Period') + ' - ' + currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
475
              sort: true,
476
              formatter: function (decimalValue) {
477
                if (typeof decimalValue === 'number') {
478
                  return decimalValue.toFixed(2);
479
                } else {
480
                  return null;
481
                }
482
              }
483
            });
484
            detailed_column_list.push({
485
              dataField: 'a' + (2 * index + 1),
486
              text: t('Base Period') + ' - ' + currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
487
              sort: true,
488
              formatter: function (decimalValue) {
489
                if (typeof decimalValue === 'number') {
490
                  return decimalValue.toFixed(2);
491
                } else {
492
                  return null;
493
                }
494
              }
495
            });
496
          });
497
498
          detailed_column_list.push({
499
            dataField: 'reportingPeriodDatetime',
500
            text: t('Reporting Period') + ' - ' + t('Datetime'),
501
            sort: true
502
          })
503
504
          json['reporting_period']['names'].forEach((currentValue, index) => {
505
            let unit = json['reporting_period']['units'][index];
506
            detailed_column_list.push({
507
              dataField: 'b' + 2 * index,
508
              text: t('Reporting Period') + ' - ' + currentValue + ' ' + t('Average Load') + ' (' + unit + '/H)',
509
              sort: true,
510
              formatter: function (decimalValue) {
511
                if (typeof decimalValue === 'number') {
512
                  return decimalValue.toFixed(2);
513
                } else {
514
                  return null;
515
                }
516
              }
517
            });
518
            detailed_column_list.push({
519
              dataField: 'b' + (2 * index + 1),
520
              text: t('Reporting Period') + ' - ' + currentValue + ' ' + t('Maximum Load') + ' (' + unit + '/H)',
521
              sort: true,
522
              formatter: function (decimalValue) {
523
                if (typeof decimalValue === 'number') {
524
                  return decimalValue.toFixed(2);
525
                } else {
526
                  return null;
527
                }
528
              }
529
            });
530
          });
531
          setDetailedDataTableColumns(detailed_column_list);
532
533
          let detailed_value_list = [];
534
          if (json['base_period']['timestamps'].length > 0 || json['reporting_period']['timestamps'].length > 0) {
535
            const max_timestamps_length = json['base_period']['timestamps'][0].length >= json['reporting_period']['timestamps'][0].length?
536
                json['base_period']['timestamps'][0].length : json['reporting_period']['timestamps'][0].length;
537
            for (let index = 0; index < max_timestamps_length; index++) {
538
              let detailed_value = {};
539
              detailed_value['id'] = index;
540
              detailed_value['basePeriodDatetime'] = index < json['base_period']['timestamps'][0].length? json['base_period']['timestamps'][0][index] : null;
541
              json['base_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
542
                detailed_value['a' + energyCategoryIndex*2] = index < json['base_period']['sub_averages'][energyCategoryIndex].length? json['base_period']['sub_averages'][energyCategoryIndex][index] : null;
543
              });
544
              json['base_period']['sub_maximums'].forEach((currentValue, energyCategoryIndex) => {
545
                detailed_value['a' + (energyCategoryIndex*2+1)] = index < json['base_period']['sub_maximums'][energyCategoryIndex].length? json['base_period']['sub_maximums'][energyCategoryIndex][index] : null;
546
              });
547
              detailed_value['reportingPeriodDatetime'] = index < json['reporting_period']['timestamps'][0].length? json['reporting_period']['timestamps'][0][index] : null;
548
              json['reporting_period']['sub_averages'].forEach((currentValue, energyCategoryIndex) => {
549
                detailed_value['b' + energyCategoryIndex*2] = index < json['reporting_period']['sub_averages'][energyCategoryIndex].length? json['reporting_period']['sub_averages'][energyCategoryIndex][index] : null;
550
              });
551
              json['reporting_period']['sub_maximums'].forEach((currentValue, energyCategoryIndex) => {
552
                detailed_value['b' + (energyCategoryIndex*2+1)] = index < json['reporting_period']['sub_maximums'][energyCategoryIndex].length? json['reporting_period']['sub_maximums'][energyCategoryIndex][index] : null;
553
              });
554
              detailed_value_list.push(detailed_value);
555
            }
556
            setTimeout( () => {
557
              setDetailedDataTableData(detailed_value_list);
558
            }, 0)
559
          }
560
        }
561
        
562
        setExcelBytesBase64(json['excel_bytes_base64']);
563
      
564
        // enable submit button
565
        setSubmitButtonDisabled(false);
566
        // hide spinner
567
        setSpinnerHidden(true);
568
        // show export button
569
        setExportButtonHidden(false)
570
        
571
      
572
      } else {
573
        toast.error(t(json.description))
574
      }
575
    }).catch(err => {
576
      console.log(err);
577
    });
578
  };
579
580
  const handleExport = e => {
581
    e.preventDefault();
582
    const mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
583
    const fileName = 'spaceload.xlsx'
584
    var fileUrl = "data:" + mimeType + ";base64," + excelBytesBase64;
585
    fetch(fileUrl)
586
        .then(response => response.blob())
587
        .then(blob => {
588
            var link = window.document.createElement("a");
589
            link.href = window.URL.createObjectURL(blob, { type: mimeType });
590
            link.download = fileName;
591
            document.body.appendChild(link);
592
            link.click();
593
            document.body.removeChild(link);
594
        });
595
  };
596
  
597
  return (
598
    <Fragment>
599
      <div>
600
        <Breadcrumb>
601
          <BreadcrumbItem>{t('Space Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Load')}</BreadcrumbItem>
602
        </Breadcrumb>
603
      </div>
604
      <Card className="bg-light mb-3">
605
        <CardBody className="p-3">
606
          <Form onSubmit={handleSubmit}>
607
            <Row form>
608
              <Col xs={6} sm={3}>
609
                <FormGroup className="form-group">
610
                  <Label className={labelClasses} for="space">
611
                    {t('Space')}
612
                  </Label>
613
                  <br />
614
                  <Cascader options={cascaderOptions}
615
                    onChange={onSpaceCascaderChange}
616
                    changeOnSelect
617
                    expandTrigger="hover">
618
                    <Input value={selectedSpaceName || ''} readOnly />
619
                  </Cascader>
620
                </FormGroup>
621
              </Col>
622
              <Col xs="auto">
623
                <FormGroup>
624
                  <Label className={labelClasses} for="comparisonType">
625
                    {t('Comparison Types')}
626
                  </Label>
627
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
628
                    defaultValue="month-on-month"
629
                    onChange={onComparisonTypeChange}
630
                  >
631
                    {comparisonTypeOptions.map((comparisonType, index) => (
632
                      <option value={comparisonType.value} key={comparisonType.value} >
633
                        {t(comparisonType.label)}
634
                      </option>
635
                    ))}
636
                  </CustomInput>
637
                </FormGroup>
638
              </Col>
639
              <Col xs="auto">
640
                <FormGroup>
641
                  <Label className={labelClasses} for="periodType">
642
                    {t('Period Types')}
643
                  </Label>
644
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
645
                  >
646
                    {periodTypeOptions.map((periodType, index) => (
647
                      <option value={periodType.value} key={periodType.value} >
648
                        {t(periodType.label)}
649
                      </option>
650
                    ))}
651
                  </CustomInput>
652
                </FormGroup>
653
              </Col>
654
              <Col xs={6} sm={3}>
655
                <FormGroup className="form-group">
656
                  <Label className={labelClasses} for="basePeriodDateRangePicker">{t('Base Period')}{t('(Optional)')}</Label>
657
                  <DateRangePickerWrapper 
658
                    id='basePeriodDateRangePicker'
659
                    disabled={basePeriodDateRangePickerDisabled}
660
                    format="yyyy-MM-dd HH:mm:ss"
661
                    value={basePeriodDateRange}
662
                    onChange={onBasePeriodChange}
663
                    size="md"
664
                    style={dateRangePickerStyle}
665
                    onClean={onBasePeriodClean}
666
                    locale={dateRangePickerLocale}
667
                    placeholder={t("Select Date Range")}
668
                   />
669
                </FormGroup>
670
              </Col>
671
              <Col xs={6} sm={3}>
672
                <FormGroup className="form-group">
673
                  <Label className={labelClasses} for="reportingPeriodDateRangePicker">{t('Reporting Period')}</Label>
674
                  <br/>
675
                  <DateRangePickerWrapper
676
                    id='reportingPeriodDateRangePicker'
677
                    format="yyyy-MM-dd HH:mm:ss"
678
                    value={reportingPeriodDateRange}
679
                    onChange={onReportingPeriodChange}
680
                    size="md"
681
                    style={dateRangePickerStyle}
682
                    onClean={onReportingPeriodClean}
683
                    locale={dateRangePickerLocale}
684
                    placeholder={t("Select Date Range")}
685
                  />
686
                </FormGroup>
687
              </Col>
688
              <Col xs="auto">
689
                <FormGroup>
690
                  <br></br>
691
                  <ButtonGroup id="submit">
692
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
693
                  </ButtonGroup>
694
                </FormGroup>
695
              </Col>
696
              <Col xs="auto">
697
                <FormGroup>
698
                  <br></br>
699
                  <Spinner color="primary" hidden={spinnerHidden}  />
700
                </FormGroup>
701
              </Col>
702
              <Col xs="auto">
703
                  <br></br>
704
                  <ButtonIcon icon="external-link-alt" transform="shrink-3 down-2" color="falcon-default" 
705
                  hidden={exportButtonHidden}
706
                  onClick={handleExport} >
707
                    {t('Export')}
708
                  </ButtonIcon>
709
              </Col>
710
            </Row>
711
          </Form>
712
        </CardBody>
713
      </Card>
714
      {cardSummaryList.map(cardSummaryItem => (
715
        <div className="card-deck" key={cardSummaryItem['name']}>
716
          <CardSummary key={cardSummaryItem['name'] + 'average'}
717
            rate={cardSummaryItem['average_increment_rate']}
718
            title={t('Reporting Period CATEGORY Average Load UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + '/H)' })}
719
            color="success" 
720
            footnote={t('Per Unit Area')} 
721
            footvalue={cardSummaryItem['average_per_unit_area']}
722
            footunit={"(" + cardSummaryItem['unit'] + "/H/M²)"} >
723
            {cardSummaryItem['average'] && <CountUp end={cardSummaryItem['average']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
724
          </CardSummary>
725
          <CardSummary key={cardSummaryItem['name'] + 'maximum'}
726
            rate={cardSummaryItem['maximum_increment_rate']}
727
            title={t('Reporting Period CATEGORY Maximum Load UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + '/H)' })}
728
            color="success" 
729
            footnote={t('Per Unit Area')} 
730
            footvalue={cardSummaryItem['maximum_per_unit_area']}
731
            footunit={"(" + cardSummaryItem['unit'] + "/H/M²)"} >
732
            {cardSummaryItem['maximum'] && <CountUp end={cardSummaryItem['maximum']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
733
          </CardSummary>
734
          <CardSummary key={cardSummaryItem['name'] + 'factor'}
735
            rate={cardSummaryItem['factor_increment_rate']}
736
            title={t('Reporting Period CATEGORY Load Factor', { 'CATEGORY': cardSummaryItem['name'] })}
737
            color="success" 
738
            footnote={t('Ratio of Average Load to Maximum Load')} >
739
            {cardSummaryItem['factor'] && <CountUp end={cardSummaryItem['factor']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
740
          </CardSummary>
741
        </div>
742
      ))}
743
744
      <MultiTrendChart reportingTitle = {{"name": "Reporting Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": spaceBaseAndReportingNames, "UNIT": spaceBaseAndReportingUnits}}
745
        baseTitle = {{"name": "Base Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": spaceBaseAndReportingNames, "UNIT": spaceBaseAndReportingUnits}}
746
        reportingTooltipTitle = {{"name": "Reporting Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": spaceBaseAndReportingNames, "UNIT": spaceBaseAndReportingUnits}}
747
        baseTooltipTitle = {{"name": "Base Period CATEGORY Maximum Load UNIT", "substitute": ["CATEGORY", "UNIT"], "CATEGORY": spaceBaseAndReportingNames, "UNIT": spaceBaseAndReportingUnits}}
748
        reportingLabels={spaceReportingLabels}
749
        reportingData={spaceReportingData}
750
        baseLabels={spaceBaseLabels}
751
        baseData={spaceBaseData}
752
        rates={spaceReportingRates}
753
        options={spaceReportingOptions}>
754
      </MultiTrendChart>
755
756
      <LineChart reportingTitle={t('Related Parameters')}
757
        baseTitle=''
758
        labels={parameterLineChartLabels}
759
        data={parameterLineChartData}
760
        options={parameterLineChartOptions}>
761
      </LineChart>
762
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
763
      </DetailedDataTable>
764
      <br />
765
      
766
    </Fragment>
767
  );
768
};
769
770
export default withTranslation()(withRedirect(SpaceLoad));
771