Passed
Push — master ( 0b01ae...6aca38 )
by Guangyu
08:43 queued 11s
created

src/components/MyEMS/Equipment/EquipmentEnergyCategory.js   A

Complexity

Total Complexity 25
Complexity/F 0

Size

Lines of Code 665
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 25
eloc 588
mnd 25
bc 25
fnc 0
dl 0
loc 665
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { Fragment, useEffect, useState } 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
} from 'reactstrap';
17
import CountUp from 'react-countup';
18
import Datetime from 'react-datetime';
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 LineChart from '../common/LineChart';
24
import SharePie from '../common/SharePie';
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 { APIBaseURL } from '../../../config';
30
import { periodTypeOptions } from '../common/PeriodTypeOptions';
31
import { comparisonTypeOptions } from '../common/ComparisonTypeOptions';
32
33
34
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
35
36
const EquipmentEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
37
  let current_moment = moment();
38
  useEffect(() => {
39
    let is_logged_in = getCookieValue('is_logged_in');
40
    let user_name = getCookieValue('user_name');
41
    let user_display_name = getCookieValue('user_display_name');
42
    let user_uuid = getCookieValue('user_uuid');
43
    let token = getCookieValue('token');
44
    if (is_logged_in === null || !is_logged_in) {
45
      setRedirectUrl(`/authentication/basic/login`);
46
      setRedirect(true);
47
    } else {
48
      //update expires time of cookies
49
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
50
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
51
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
52
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
53
      createCookie('token', token, 1000 * 60 * 60 * 8);
54
    }
55
  });
56
  // State
57
  // Query Parameters
58
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
59
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
60
  const [equipmentList, setEquipmentList] = useState([]);
61
  const [selectedEquipment, setSelectedEquipment] = useState(undefined);
62
  const [comparisonType, setComparisonType] = useState('month-on-month');
63
  const [periodType, setPeriodType] = useState('daily');
64
  const [basePeriodBeginsDatetime, setBasePeriodBeginsDatetime] = useState(current_moment.clone().subtract(1, 'months').startOf('month'));
65
  const [basePeriodEndsDatetime, setBasePeriodEndsDatetime] = useState(current_moment.clone().subtract(1, 'months'));
66
  const [basePeriodBeginsDatetimeDisabled, setBasePeriodBeginsDatetimeDisabled] = useState(true);
67
  const [basePeriodEndsDatetimeDisabled, setBasePeriodEndsDatetimeDisabled] = useState(true);
68
  const [reportingPeriodBeginsDatetime, setReportingPeriodBeginsDatetime] = useState(current_moment.clone().startOf('month'));
69
  const [reportingPeriodEndsDatetime, setReportingPeriodEndsDatetime] = useState(current_moment);
70
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
71
  const [isDisabled, setIsDisabled] = useState(true);
72
  //Results
73
  const [timeOfUseShareData, setTimeOfUseShareData] = useState([]);
74
  const [TCEShareData, setTCEShareData] = useState([]);
75
  const [TCO2EShareData, setTCO2EShareData] = useState([]);
76
77
  const [cardSummaryList, setCardSummaryList] = useState([]);
78
  const [totalInTCE, setTotalInTCE] = useState({});
79
  const [totalInTCO2E, setTotalInTCO2E] = useState({});
80
  const [equipmentLineChartLabels, setEquipmentLineChartLabels] = useState([]);
81
  const [equipmentLineChartData, setEquipmentLineChartData] = useState({});
82
  const [equipmentLineChartOptions, setEquipmentLineChartOptions] = useState([]);
83
84
  const [parameterLineChartLabels, setParameterLineChartLabels] = useState([]);
85
  const [parameterLineChartData, setParameterLineChartData] = useState({});
86
  const [parameterLineChartOptions, setParameterLineChartOptions] = useState([]);
87
88
  const [detailedDataTableData, setDetailedDataTableData] = useState([]);
89
  const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
90
91
  useEffect(() => {
92
    let isResponseOK = false;
93
    fetch(APIBaseURL + '/spaces/tree', {
94
      method: 'GET',
95
      headers: {
96
        "Content-type": "application/json",
97
        "User-UUID": getCookieValue('user_uuid'),
98
        "Token": getCookieValue('token')
99
      },
100
      body: null,
101
102
    }).then(response => {
103
      console.log(response);
104
      if (response.ok) {
105
        isResponseOK = true;
106
      }
107
      return response.json();
108
    }).then(json => {
109
      console.log(json);
110
      if (isResponseOK) {
111
        // rename keys 
112
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
113
        setCascaderOptions(json);
114
        setSelectedSpaceName([json[0]].map(o => o.label));
115
        setSelectedSpaceID([json[0]].map(o => o.value));
116
        // get Equipments by root Space ID
117
        let isResponseOK = false;
118
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/equipments', {
119
          method: 'GET',
120
          headers: {
121
            "Content-type": "application/json",
122
            "User-UUID": getCookieValue('user_uuid'),
123
            "Token": getCookieValue('token')
124
          },
125
          body: null,
126
127
        }).then(response => {
128
          if (response.ok) {
129
            isResponseOK = true;
130
          }
131
          return response.json();
132
        }).then(json => {
133
          if (isResponseOK) {
134
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
135
            console.log(json);
136
            setEquipmentList(json[0]);
137
            if (json[0].length > 0) {
138
              setSelectedEquipment(json[0][0].value);
139
              setIsDisabled(false);
140
            } else {
141
              setSelectedEquipment(undefined);
142
              setIsDisabled(true);
143
            }
144
          } else {
145
            toast.error(json.description)
146
          }
147
        }).catch(err => {
148
          console.log(err);
149
        });
150
        // end of get Equipments by root Space ID
151
      } else {
152
        toast.error(json.description);
153
      }
154
    }).catch(err => {
155
      console.log(err);
156
    });
157
158
  }, []);
159
  
160
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
161
162
  
163
164
  let onSpaceCascaderChange = (value, selectedOptions) => {
165
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
166
    setSelectedSpaceID(value[value.length - 1]);
167
168
    let isResponseOK = false;
169
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/equipments', {
170
      method: 'GET',
171
      headers: {
172
        "Content-type": "application/json",
173
        "User-UUID": getCookieValue('user_uuid'),
174
        "Token": getCookieValue('token')
175
      },
176
      body: null,
177
178
    }).then(response => {
179
      if (response.ok) {
180
        isResponseOK = true;
181
      }
182
      return response.json();
183
    }).then(json => {
184
      if (isResponseOK) {
185
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
186
        console.log(json)
187
        setEquipmentList(json[0]);
188
        if (json[0].length > 0) {
189
          setSelectedEquipment(json[0][0].value);
190
          setIsDisabled(false);
191
        } else {
192
          setSelectedEquipment(undefined);
193
          setIsDisabled(true);
194
        }
195
      } else {
196
        toast.error(json.description)
197
      }
198
    }).catch(err => {
199
      console.log(err);
200
    });
201
  }
202
203
204
  let onComparisonTypeChange = ({ target }) => {
205
    console.log(target.value);
206
    setComparisonType(target.value);
207
    if (target.value === 'year-over-year') {
208
      setBasePeriodBeginsDatetimeDisabled(true);
209
      setBasePeriodEndsDatetimeDisabled(true);
210
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'years'));
211
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'years'));
212
    } else if (target.value === 'month-on-month') {
213
      setBasePeriodBeginsDatetimeDisabled(true);
214
      setBasePeriodEndsDatetimeDisabled(true);
215
      setBasePeriodBeginsDatetime(moment(reportingPeriodBeginsDatetime).subtract(1, 'months'));
216
      setBasePeriodEndsDatetime(moment(reportingPeriodEndsDatetime).subtract(1, 'months'));
217
    } else if (target.value === 'free-comparison') {
218
      setBasePeriodBeginsDatetimeDisabled(false);
219
      setBasePeriodEndsDatetimeDisabled(false);
220
    } else if (target.value === 'none-comparison') {
221
      setBasePeriodBeginsDatetime(undefined);
222
      setBasePeriodEndsDatetime(undefined);
223
      setBasePeriodBeginsDatetimeDisabled(true);
224
      setBasePeriodEndsDatetimeDisabled(true);
225
    }
226
  }
227
228
  let onBasePeriodBeginsDatetimeChange = (newDateTime) => {
229
    setBasePeriodBeginsDatetime(newDateTime);
230
  }
231
232
  let onBasePeriodEndsDatetimeChange = (newDateTime) => {
233
    setBasePeriodEndsDatetime(newDateTime);
234
  }
235
236
  let onReportingPeriodBeginsDatetimeChange = (newDateTime) => {
237
    setReportingPeriodBeginsDatetime(newDateTime);
238
    if (comparisonType === 'year-over-year') {
239
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'years'));
240
    } else if (comparisonType === 'month-on-month') {
241
      setBasePeriodBeginsDatetime(newDateTime.clone().subtract(1, 'months'));
242
    }
243
  }
244
245
  let onReportingPeriodEndsDatetimeChange = (newDateTime) => {
246
    setReportingPeriodEndsDatetime(newDateTime);
247
    if (comparisonType === 'year-over-year') {
248
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'years'));
249
    } else if (comparisonType === 'month-on-month') {
250
      setBasePeriodEndsDatetime(newDateTime.clone().subtract(1, 'months'));
251
    }
252
  }
253
254
  var getValidBasePeriodBeginsDatetimes = function (currentDate) {
255
    return currentDate.isBefore(moment(basePeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
256
  }
257
258
  var getValidBasePeriodEndsDatetimes = function (currentDate) {
259
    return currentDate.isAfter(moment(basePeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
260
  }
261
262
  var getValidReportingPeriodBeginsDatetimes = function (currentDate) {
263
    return currentDate.isBefore(moment(reportingPeriodEndsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
264
  }
265
266
  var getValidReportingPeriodEndsDatetimes = function (currentDate) {
267
    return currentDate.isAfter(moment(reportingPeriodBeginsDatetime, 'MM/DD/YYYY, hh:mm:ss a'));
268
  }
269
270
  // Handler
271
  const handleSubmit = e => {
272
    e.preventDefault();
273
    console.log('handleSubmit');
274
    console.log(selectedSpaceID);
275
    console.log(selectedEquipment);
276
    console.log(comparisonType);
277
    console.log(periodType);
278
    console.log(basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
279
    console.log(basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : undefined);
280
    console.log(reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
281
    console.log(reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'));
282
283
    // Reinitialize tables
284
    setDetailedDataTableData([]);
285
    
286
    let isResponseOK = false;
287
    fetch(APIBaseURL + '/reports/equipmentenergycategory?' +
288
      'equipmentid=' + selectedEquipment +
289
      '&periodtype=' + periodType +
290
      '&baseperiodstartdatetime=' + (basePeriodBeginsDatetime != null ? basePeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
291
      '&baseperiodenddatetime=' + (basePeriodEndsDatetime != null ? basePeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss') : '') +
292
      '&reportingperiodstartdatetime=' + reportingPeriodBeginsDatetime.format('YYYY-MM-DDTHH:mm:ss') +
293
      '&reportingperiodenddatetime=' + reportingPeriodEndsDatetime.format('YYYY-MM-DDTHH:mm:ss'), {
294
      method: 'GET',
295
      headers: {
296
        "Content-type": "application/json",
297
        "User-UUID": getCookieValue('user_uuid'),
298
        "Token": getCookieValue('token')
299
      },
300
      body: null,
301
302
    }).then(response => {
303
      if (response.ok) {
304
        isResponseOK = true;
305
      }
306
      return response.json();
307
    }).then(json => {
308
      if (isResponseOK) {
309
        console.log(json)
310
        let cardSummaryArray = []
311
        json['reporting_period']['names'].forEach((currentValue, index) => {
312
          let cardSummaryItem = {}
313
          cardSummaryItem['name'] = json['reporting_period']['names'][index];
314
          cardSummaryItem['unit'] = json['reporting_period']['units'][index];
315
          cardSummaryItem['subtotal'] = json['reporting_period']['subtotals'][index];
316
          cardSummaryItem['increment_rate'] = parseFloat(json['reporting_period']['increment_rates'][index] * 100).toFixed(2) + "%";
317
          cardSummaryArray.push(cardSummaryItem);
318
        });
319
        setCardSummaryList(cardSummaryArray);
320
        
321
        let timeOfUseArray = [];
322
        json['reporting_period']['energy_category_ids'].forEach((currentValue, index) => {
323
          if(currentValue == 1) {
324
            // energy_category_id 1 electricity
325
            let timeOfUseItem = {}
326
            timeOfUseItem['id'] = 1;
327
            timeOfUseItem['name'] =  t('Top-Peak');
328
            timeOfUseItem['value'] = json['reporting_period']['toppeaks'][index];
329
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
330
            timeOfUseArray.push(timeOfUseItem);
331
            
332
            timeOfUseItem = {}
333
            timeOfUseItem['id'] = 2;
334
            timeOfUseItem['name'] =  t('On-Peak');
335
            timeOfUseItem['value'] = json['reporting_period']['onpeaks'][index];
336
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
337
            timeOfUseArray.push(timeOfUseItem);
338
339
            timeOfUseItem = {}
340
            timeOfUseItem['id'] = 3;
341
            timeOfUseItem['name'] =  t('Mid-Peak');
342
            timeOfUseItem['value'] = json['reporting_period']['midpeaks'][index];
343
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
344
            timeOfUseArray.push(timeOfUseItem);
345
346
            timeOfUseItem = {}
347
            timeOfUseItem['id'] = 4;
348
            timeOfUseItem['name'] =  t('Off-Peak');
349
            timeOfUseItem['value'] = json['reporting_period']['offpeaks'][index];
350
            timeOfUseItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
351
            timeOfUseArray.push(timeOfUseItem);
352
          }
353
        });
354
        setTimeOfUseShareData(timeOfUseArray);
355
356
        
357
        let totalInTCE = {}; 
358
        totalInTCE['value'] = json['reporting_period']['total_in_kgce'] / 1000; // convert from kg to t
359
        totalInTCE['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgce'] * 100).toFixed(2) + "%";
360
        setTotalInTCE(totalInTCE);
361
362
        let totalInTCO2E = {}; 
363
        totalInTCO2E['value'] = json['reporting_period']['total_in_kgco2e'] / 1000; // convert from kg to t
364
        totalInTCO2E['increment_rate'] = parseFloat(json['reporting_period']['increment_rate_in_kgco2e'] * 100).toFixed(2) + "%";
365
        setTotalInTCO2E(totalInTCO2E);
366
367
        let TCEDataArray = [];
368
        json['reporting_period']['names'].forEach((currentValue, index) => {
369
          let TCEDataItem = {}
370
          TCEDataItem['id'] = index;
371
          TCEDataItem['name'] = currentValue;
372
          TCEDataItem['value'] = json['reporting_period']['subtotals_in_kgce'][index] / 1000; // convert from kg to t
373
          TCEDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
374
          TCEDataArray.push(TCEDataItem);
375
        });
376
        setTCEShareData(TCEDataArray);
377
378
        let TCO2EDataArray = [];
379
        json['reporting_period']['names'].forEach((currentValue, index) => {
380
          let TCO2EDataItem = {}
381
          TCO2EDataItem['id'] = index;
382
          TCO2EDataItem['name'] = currentValue;
383
          TCO2EDataItem['value'] = json['reporting_period']['subtotals_in_kgco2e'][index] / 1000; // convert from kg to t
384
          TCO2EDataItem['color'] = "#"+((1<<24)*Math.random()|0).toString(16);
385
          TCO2EDataArray.push(TCO2EDataItem);
386
        });
387
        setTCO2EShareData(TCO2EDataArray);
388
389
        let timestamps = {}
390
        json['reporting_period']['timestamps'].forEach((currentValue, index) => {
391
          timestamps['a' + index] = currentValue;
392
        });
393
        setEquipmentLineChartLabels(timestamps);
394
        
395
        let values = {}
396
        json['reporting_period']['values'].forEach((currentValue, index) => {
397
          values['a' + index] = currentValue;
398
        });
399
        setEquipmentLineChartData(values);
400
        
401
        let names = Array();
402
        json['reporting_period']['names'].forEach((currentValue, index) => {
403
          let unit = json['reporting_period']['units'][index];
404
          names.push({ 'value': 'a' + index, 'label': currentValue + ' (' + unit + ')'});
405
        });
406
        setEquipmentLineChartOptions(names);
407
       
408
        timestamps = {}
409
        json['parameters']['timestamps'].forEach((currentValue, index) => {
410
          timestamps['a' + index] = currentValue;
411
        });
412
        setParameterLineChartLabels(timestamps);
413
414
        values = {}
415
        json['parameters']['values'].forEach((currentValue, index) => {
416
          values['a' + index] = currentValue;
417
        });
418
        setParameterLineChartData(values);
419
      
420
        names = Array();
421
        json['parameters']['names'].forEach((currentValue, index) => {
422
          if (currentValue.startsWith('TARIFF-')) {
423
            currentValue = t('Tariff') + currentValue.replace('TARIFF-', '-');
424
          }
425
          
426
          names.push({ 'value': 'a' + index, 'label': currentValue });
427
        });
428
        setParameterLineChartOptions(names);
429
        
430
        let detailed_value_list = [];
431
        json['reporting_period']['timestamps'][0].forEach((currentTimestamp, timestampIndex) => {
432
          let detailed_value = {};
433
          detailed_value['id'] = timestampIndex;
434
          detailed_value['startdatetime'] = currentTimestamp;
435
          json['reporting_period']['values'].forEach((currentValue, energyCategoryIndex) => {
436
            detailed_value['a' + energyCategoryIndex] = json['reporting_period']['values'][energyCategoryIndex][timestampIndex].toFixed(2);
437
          });
438
          detailed_value_list.push(detailed_value);
439
        });
440
441
        let detailed_value = {};
442
        detailed_value['id'] = detailed_value_list.length;
443
        detailed_value['startdatetime'] = t('Subtotal');
444
        json['reporting_period']['subtotals'].forEach((currentValue, index) => {
445
            detailed_value['a' + index] = currentValue.toFixed(2);
446
          });
447
        detailed_value_list.push(detailed_value);
448
        setDetailedDataTableData(detailed_value_list);
449
        
450
        let detailed_column_list = [];
451
        detailed_column_list.push({
452
          dataField: 'startdatetime',
453
          text: t('Datetime'),
454
          sort: true
455
        })
456
        json['reporting_period']['names'].forEach((currentValue, index) => {
457
          let unit = json['reporting_period']['units'][index];
458
          detailed_column_list.push({
459
            dataField: 'a' + index,
460
            text: currentValue + ' (' + unit + ')',
461
            sort: true
462
          })
463
        });
464
        setDetailedDataTableColumns(detailed_column_list);
465
        } else {
466
          toast.error(json.description)
467
        }
468
      }).catch(err => {
469
        console.log(err);
470
      });
471
  };
472
473
474
  return (
475
    <Fragment>
476
      <div>
477
        <Breadcrumb>
478
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Energy Category Data')}</BreadcrumbItem>
479
        </Breadcrumb>
480
      </div>
481
      <Card className="bg-light mb-3">
482
        <CardBody className="p-3">
483
          <Form onSubmit={handleSubmit}>
484
            <Row form>
485
              <Col xs="auto">
486
                <FormGroup className="form-group">
487
                  <Label className={labelClasses} for="space">
488
                    {t('Space')}
489
                  </Label>
490
                  <br />
491
                  <Cascader options={cascaderOptions}
492
                    onChange={onSpaceCascaderChange}
493
                    changeOnSelect
494
                    expandTrigger="hover">
495
                    <Input value={selectedSpaceName || ''} readOnly />
496
                  </Cascader>
497
                </FormGroup>
498
              </Col>
499
              <Col xs="auto">
500
                <FormGroup>
501
                  <Label className={labelClasses} for="equipmentSelect">
502
                    {t('Equipment')}
503
                  </Label>
504
                  <CustomInput type="select" id="equipmentSelect" name="equipmentSelect" onChange={({ target }) => setSelectedEquipment(target.value)}
505
                  >
506
                    {equipmentList.map((equipment, index) => (
507
                      <option value={equipment.value} key={equipment.value}>
508
                        {equipment.label}
509
                      </option>
510
                    ))}
511
                  </CustomInput>
512
                </FormGroup>
513
              </Col>
514
              <Col xs="auto">
515
                <FormGroup>
516
                  <Label className={labelClasses} for="comparisonType">
517
                    {t('Comparison Types')}
518
                  </Label>
519
                  <CustomInput type="select" id="comparisonType" name="comparisonType"
520
                    defaultValue="month-on-month"
521
                    onChange={onComparisonTypeChange}
522
                  >
523
                    {comparisonTypeOptions.map((comparisonType, index) => (
524
                      <option value={comparisonType.value} key={comparisonType.value} >
525
                        {t(comparisonType.label)}
526
                      </option>
527
                    ))}
528
                  </CustomInput>
529
                </FormGroup>
530
              </Col>
531
              <Col xs="auto">
532
                <FormGroup>
533
                  <Label className={labelClasses} for="periodType">
534
                    {t('Period Types')}
535
                  </Label>
536
                  <CustomInput type="select" id="periodType" name="periodType" defaultValue="daily" onChange={({ target }) => setPeriodType(target.value)}
537
                  >
538
                    {periodTypeOptions.map((periodType, index) => (
539
                      <option value={periodType.value} key={periodType.value} >
540
                        {t(periodType.label)}
541
                      </option>
542
                    ))}
543
                  </CustomInput>
544
                </FormGroup>
545
              </Col>
546
              <Col xs="auto">
547
                <FormGroup className="form-group">
548
                  <Label className={labelClasses} for="basePeriodBeginsDatetime">
549
                    {t('Base Period Begins')}{t('(Optional)')}
550
                  </Label>
551
                  <Datetime id='basePeriodBeginsDatetime'
552
                    value={basePeriodBeginsDatetime}
553
                    inputProps={{ disabled: basePeriodBeginsDatetimeDisabled }}
554
                    onChange={onBasePeriodBeginsDatetimeChange}
555
                    isValidDate={getValidBasePeriodBeginsDatetimes}
556
                    closeOnSelect={true} />
557
                </FormGroup>
558
              </Col>
559
              <Col xs="auto">
560
                <FormGroup className="form-group">
561
                  <Label className={labelClasses} for="basePeriodEndsDatetime">
562
                    {t('Base Period Ends')}{t('(Optional)')}
563
                  </Label>
564
                  <Datetime id='basePeriodEndsDatetime'
565
                    value={basePeriodEndsDatetime}
566
                    inputProps={{ disabled: basePeriodEndsDatetimeDisabled }}
567
                    onChange={onBasePeriodEndsDatetimeChange}
568
                    isValidDate={getValidBasePeriodEndsDatetimes}
569
                    closeOnSelect={true} />
570
                </FormGroup>
571
              </Col>
572
              <Col xs="auto">
573
                <FormGroup className="form-group">
574
                  <Label className={labelClasses} for="reportingPeriodBeginsDatetime">
575
                    {t('Reporting Period Begins')}
576
                  </Label>
577
                  <Datetime id='reportingPeriodBeginsDatetime'
578
                    value={reportingPeriodBeginsDatetime}
579
                    onChange={onReportingPeriodBeginsDatetimeChange}
580
                    isValidDate={getValidReportingPeriodBeginsDatetimes}
581
                    closeOnSelect={true} />
582
                </FormGroup>
583
              </Col>
584
              <Col xs="auto">
585
                <FormGroup className="form-group">
586
                  <Label className={labelClasses} for="reportingPeriodEndsDatetime">
587
                    {t('Reporting Period Ends')}
588
                  </Label>
589
                  <Datetime id='reportingPeriodEndsDatetime'
590
                    value={reportingPeriodEndsDatetime}
591
                    onChange={onReportingPeriodEndsDatetimeChange}
592
                    isValidDate={getValidReportingPeriodEndsDatetimes}
593
                    closeOnSelect={true} />
594
                </FormGroup>
595
              </Col>
596
              <Col xs="auto">
597
                <FormGroup>
598
                  <br></br>
599
                  <ButtonGroup id="submit">
600
                    <Button color="success" disabled={isDisabled} >{t('Submit')}</Button>
601
                  </ButtonGroup>
602
                </FormGroup>
603
              </Col>
604
            </Row>
605
          </Form>
606
        </CardBody>
607
      </Card>
608
      <div className="card-deck">
609
        {cardSummaryList.map(cardSummaryItem => (
610
          <CardSummary key={cardSummaryItem['name']}
611
            rate={cardSummaryItem['increment_rate']}
612
            title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': cardSummaryItem['name'], 'UNIT': '(' + cardSummaryItem['unit'] + ')' })}
613
            color="success" >
614
            {cardSummaryItem['subtotal'] && <CountUp end={cardSummaryItem['subtotal']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
615
          </CardSummary>
616
        ))}
617
       
618
        <CardSummary 
619
          rate={totalInTCE['increment_rate'] || ''} 
620
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Standard Coal'), 'UNIT': '(TCE)' })}
621
          color="warning" >
622
          {totalInTCE['value'] && <CountUp end={totalInTCE['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
623
        </CardSummary>
624
        <CardSummary 
625
          rate={totalInTCO2E['increment_rate'] || ''} 
626
          title={t('Reporting Period Consumption CATEGORY UNIT', { 'CATEGORY': t('Ton of Carbon Dioxide Emissions'), 'UNIT': '(TCO2E)' })}
627
          color="warning" >
628
          {totalInTCO2E['value'] && <CountUp end={totalInTCO2E['value']} duration={2} prefix="" separator="," decimal="." decimals={2} />}
629
        </CardSummary>
630
      </div>
631
632
      <Row noGutters>
633
        <Col className="mb-3 pr-lg-2 mb-3">
634
          <SharePie data={timeOfUseShareData} title={t('Electricity Consumption by Time-Of-Use')} />
635
        </Col>
636
        <Col className="mb-3 pr-lg-2 mb-3">
637
          <SharePie data={TCEShareData} title={t('Ton of Standard Coal by Energy Category')} />
638
        </Col>
639
        <Col className="mb-3 pr-lg-2 mb-3">
640
          <SharePie data={TCO2EShareData} title={t('Carbon Dioxide Emissions by Energy Category')} />
641
        </Col>
642
      </Row>
643
      <LineChart reportingTitle={t('Reporting Period Consumption CATEGORY VALUE UNIT', { 'CATEGORY': null, 'VALUE': null, 'UNIT': null })}
644
        baseTitle=''
645
        labels={equipmentLineChartLabels}
646
        data={equipmentLineChartData}
647
        options={equipmentLineChartOptions}>
648
      </LineChart>
649
650
      <LineChart reportingTitle={t('Related Parameters')}
651
        baseTitle=''
652
        labels={parameterLineChartLabels}
653
        data={parameterLineChartData}
654
        options={parameterLineChartOptions}>
655
      </LineChart>
656
      <br />
657
      <DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
658
      </DetailedDataTable>
659
660
    </Fragment>
661
  );
662
};
663
664
export default withTranslation()(withRedirect(EquipmentEnergyCategory));
665