Passed
Push — master ( c49fa8...c04ae7 )
by Guangyu
05:06 queued 11s
created

src/components/MyEMS/Monitoring/TenantEquipments.js   A

Complexity

Total Complexity 10
Complexity/F 0

Size

Lines of Code 323
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 279
mnd 10
bc 10
fnc 0
dl 0
loc 323
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { Fragment, useState, useEffect } from 'react';
2
import {
3
  Breadcrumb,
4
  BreadcrumbItem,
5
  Button,
6
  ButtonGroup,
7
  Card,
8
  CardBody,
9
  Col,
10
  CustomInput,
11
  Row,
12
  Form,
13
  FormGroup,
14
  Input,
15
  Label,
16
  Spinner,
17
} from 'reactstrap';
18
import Loader from '../../common/Loader';
19
import useFakeFetch from '../../../hooks/useFakeFetch';
20
import { isIterableArray } from '../../../helpers/utils';
21
import Flex from '../../common/Flex';
22
import Cascader from 'rc-cascader';
23
import classNames from 'classnames';
24
import EquipmentList from './EquipmentList';
25
import EquipmentFooter from './EquipmentFooter';
26
import usePagination from '../../../hooks/usePagination';
27
import equipments from './equipments';
28
import { getCookieValue, createCookie } from '../../../helpers/utils';
29
import withRedirect from '../../../hoc/withRedirect';
30
import { withTranslation } from 'react-i18next';
31
import { toast } from 'react-toastify';
32
import { APIBaseURL } from '../../../config';
33
34
35
const TenantEquipments = ({ setRedirect, setRedirectUrl, t }) => {
36
  useEffect(() => {
37
    let is_logged_in = getCookieValue('is_logged_in');
38
    let user_name = getCookieValue('user_name');
39
    let user_display_name = getCookieValue('user_display_name');
40
    let user_uuid = getCookieValue('user_uuid');
41
    let token = getCookieValue('token');
42
    if (is_logged_in === null || !is_logged_in) {
43
      setRedirectUrl(`/authentication/basic/login`);
44
      setRedirect(true);
45
    } else {
46
      //update expires time of cookies
47
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
48
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
49
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
50
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
51
      createCookie('token', token, 1000 * 60 * 60 * 8);
52
    }
53
  });
54
  // State
55
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
56
  const [selectedSpaceID, setSelectedSpaceID] = useState(undefined);
57
  const [tenantList, setTenantList] = useState([]);
58
  const [selectedTenant, setSelectedTenant] = useState(undefined);
59
  const [equipmentIds, setEquipmentIds] = useState([]);
60
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
61
  
62
  // button
63
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
64
  const [spinnerHidden, setSpinnerHidden] = useState(true);
65
66
  useEffect(() => {
67
    let isResponseOK = false;
68
    fetch(APIBaseURL + '/spaces/tree', {
69
      method: 'GET',
70
      headers: {
71
        "Content-type": "application/json",
72
        "User-UUID": getCookieValue('user_uuid'),
73
        "Token": getCookieValue('token')
74
      },
75
      body: null,
76
77
    }).then(response => {
78
      console.log(response);
79
      if (response.ok) {
80
        isResponseOK = true;
81
      }
82
      return response.json();
83
    }).then(json => {
84
      console.log(json);
85
      if (isResponseOK) {
86
        // rename keys 
87
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
88
        setCascaderOptions(json);
89
        setSelectedSpaceName([json[0]].map(o => o.label));
90
        setSelectedSpaceID([json[0]].map(o => o.value));
91
        // get Tenants by root Space ID
92
        let isResponseOK = false;
93
        fetch(APIBaseURL + '/spaces/' + [json[0]].map(o => o.value) + '/tenants', {
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
          if (response.ok) {
104
            isResponseOK = true;
105
          }
106
          return response.json();
107
        }).then(json => {
108
          if (isResponseOK) {
109
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
110
            console.log(json);
111
            setTenantList(json[0]);
112
            if (json[0].length > 0) {
113
              setSelectedTenant(json[0][0].value);
114
              // enable submit button
115
              setSubmitButtonDisabled(false);
116
            } else {
117
              setSelectedTenant(undefined);
118
              // disable submit button
119
              setSubmitButtonDisabled(true);
120
            }
121
          } else {
122
            toast.error(json.description)
123
          }
124
        }).catch(err => {
125
          console.log(err);
126
        });
127
        // end of get Tenants by root Space ID
128
      } else {
129
        toast.error(json.description);
130
      }
131
    }).catch(err => {
132
      console.log(err);
133
    });
134
135
  }, []);
136
137
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
138
139
  const sliderSettings = {
140
    infinite: true,
141
    speed: 500,
142
    slidesToShow: 1,
143
    slidesToScroll: 1
144
  };
145
146
  let onSpaceCascaderChange = (value, selectedOptions) => {
147
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
148
    setSelectedSpaceID(value[value.length - 1]);
149
150
    let isResponseOK = false;
151
    fetch(APIBaseURL + '/spaces/' + value[value.length - 1] + '/tenants', {
152
      method: 'GET',
153
      headers: {
154
        "Content-type": "application/json",
155
        "User-UUID": getCookieValue('user_uuid'),
156
        "Token": getCookieValue('token')
157
      },
158
      body: null,
159
160
    }).then(response => {
161
      if (response.ok) {
162
        isResponseOK = true;
163
      }
164
      return response.json();
165
    }).then(json => {
166
      if (isResponseOK) {
167
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
168
        console.log(json)
169
        setTenantList(json[0]);
170
        if (json[0].length > 0) {
171
          setSelectedTenant(json[0][0].value);
172
          // enable submit button
173
          setSubmitButtonDisabled(false);
174
        } else {
175
          setSelectedTenant(undefined);
176
          // disable submit button
177
          setSubmitButtonDisabled(true);
178
        }
179
      } else {
180
        toast.error(json.description)
181
      }
182
    }).catch(err => {
183
      console.log(err);
184
    });
185
  }
186
  // Hook
187
  const { loading } = useFakeFetch(equipments);
188
  const { data: paginationData, meta: paginationMeta, handler: paginationHandler } = usePagination(equipmentIds, 4);
189
  const { total, itemsPerPage, from, to } = paginationMeta;
190
  const { perPage } = paginationHandler;
191
192
  const isList = true;
193
  const isGrid = false;
194
195
  useEffect(() => {
196
    setEquipmentIds(equipments.map(equipment => equipment.id));
197
  }, []);
198
199
  // Handler
200
  const handleSubmit = e => {
201
    e.preventDefault();
202
    console.log('handleSubmit');
203
    console.log(selectedSpaceID);
204
    console.log(selectedTenant);
205
    // // disable submit button
206
    // setSubmitButtonDisabled(true);
207
    // // show spinner
208
    // setSpinnerHidden(false);
209
        
210
    // // enable submit button
211
    // setSubmitButtonDisabled(false);
212
    // // hide spinner
213
    // setSpinnerHidden(true);
214
  };
215
216
  return (
217
    <Fragment>
218
      <div>
219
        <Breadcrumb>
220
          <BreadcrumbItem>{t('Monitoring')}</BreadcrumbItem><BreadcrumbItem active>{t('Tenant Equipments')}</BreadcrumbItem>
221
        </Breadcrumb>
222
      </div>
223
      <Card className="bg-light mb-3">
224
        <CardBody className="p-3">
225
          <Form onSubmit={handleSubmit}>
226
            <Row form>
227
              <Col xs="auto">
228
                <FormGroup className="form-group">
229
                  <Label className={labelClasses} for="space">
230
                    {t('Space')}
231
                  </Label>
232
                  <br />
233
                  <Cascader options={cascaderOptions}
234
                    onChange={onSpaceCascaderChange}
235
                    changeOnSelect
236
                    expandTrigger="hover">
237
                    <Input value={selectedSpaceName || ''} readOnly />
238
                  </Cascader>
239
                </FormGroup>
240
              </Col>
241
              <Col xs="auto">
242
                <FormGroup>
243
                  <Label className={labelClasses} for="tenantSelect">
244
                    {t('Tenant')}
245
                  </Label>
246
                  <CustomInput type="select" id="tenantSelect" name="tenantSelect" onChange={({ target }) => setSelectedTenant(target.value)}
247
                  >
248
                    {tenantList.map((tenant, index) => (
249
                      <option value={tenant.value} key={tenant.value}>
250
                        {tenant.label}
251
                      </option>
252
                    ))}
253
                  </CustomInput>
254
                </FormGroup>
255
              </Col>
256
              <Col xs="auto">
257
                <FormGroup>
258
                  <br></br>
259
                  <ButtonGroup id="submit">
260
                    <Button color="success" disabled={submitButtonDisabled} >{t('Submit')}</Button>
261
                  </ButtonGroup>
262
                </FormGroup>
263
              </Col>
264
              <Col xs="auto">
265
                <FormGroup>
266
                  <br></br>
267
                  <Spinner color="primary" hidden={spinnerHidden}  />
268
                </FormGroup>
269
              </Col>
270
            </Row>
271
          </Form>
272
        </CardBody>
273
      </Card>
274
275
276
      <Card>
277
        <CardBody className={classNames({ 'p-0  overflow-hidden': isList, 'pb-0': isGrid })}>
278
          {loading ? (
279
            <Loader />
280
          ) : (
281
              <Row noGutters={isList}>
282
                {isIterableArray(equipments) &&
283
                  equipments
284
                    .filter(equipment => paginationData.includes(equipment.id))
285
                    .map((equipment, index) => <EquipmentList {...equipment} sliderSettings={sliderSettings} key={equipment.id} index={index} />)}
286
              </Row>
287
            )}
288
        </CardBody>
289
        <EquipmentFooter meta={paginationMeta} handler={paginationHandler} />
290
      </Card>
291
      <Card className="mb-3">
292
        <CardBody>
293
          <Row className="justify-content-between align-items-center">
294
            <Col sm="auto" className="mb-2 mb-sm-0" tag={Flex} align="center">
295
              <h6 className="mb-0 text-nowrap ml-2">
296
                {t('Show Up to')}
297
              </h6>
298
              <CustomInput
299
                id="itemsPerPage"
300
                type="select"
301
                bsSize="sm"
302
                value={itemsPerPage}
303
                onChange={({ target }) => perPage(Number(target.value))}
304
              >
305
                <option value={2}>2</option>
306
                <option value={4}>4</option>
307
                <option value={6}>6</option>
308
                <option value={total}>{t('All')}</option>
309
              </CustomInput>
310
              <h6 className="mb-0 text-nowrap ml-2">
311
                {t('FROM - TO of TOTAL Equipments', { 'FROM': from, 'TO': to, 'TOTAL': total })}
312
              </h6>
313
            </Col>
314
315
          </Row>
316
        </CardBody>
317
      </Card>
318
    </Fragment>
319
  );
320
};
321
322
export default withTranslation()(withRedirect(TenantEquipments));
323