Passed
Push — master ( 4f3f28...c5d2bd )
by Guangyu
04:38 queued 11s
created

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

Complexity

Total Complexity 10
Complexity/F 0

Size

Lines of Code 300
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

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