Bladeren bron

feat(device): running status end

Lind 4 jaren geleden
bovenliggende
commit
a8da923a85

+ 26 - 10
src/pages/device/Instance/Detail/MetadataLog/Event/index.tsx

@@ -1,6 +1,6 @@
+import type { ProColumns } from '@jetlinks/pro-table';
 import ProTable from '@jetlinks/pro-table';
 import { service } from '@/pages/device/Instance';
-import encodeQuery from '@/utils/encodeQuery';
 import { Drawer } from 'antd';
 import { useParams } from 'umi';
 import type { EventMetadata } from '@/pages/device/Product/typings';
@@ -16,25 +16,41 @@ const EventLog = (props: Props) => {
   const params = useParams<{ id: string }>();
   const { data, visible, close } = props;
 
+  const createColumn = (): ProColumns[] =>
+    data.valueType?.type === 'object'
+      ? data.valueType.properties.map(
+          (i: any) =>
+            ({
+              key: i.id,
+              title: i.name,
+              dataIndex: i.id,
+              renderText: (text) => (typeof text === 'object' ? JSON.stringify(text) : text),
+            } as ProColumns),
+        )
+      : [
+          {
+            title: '数据',
+            dataIndex: `value`,
+            ellipsis: true,
+            render: (text) => JSON.stringify(text),
+          },
+        ];
+
   return (
     <Drawer title={data.name} visible={visible} onClose={() => close()} width="45vw">
       <ProTable
         size="small"
+        rowKey="id"
         toolBarRender={false}
         request={async (param) =>
-          service.getPropertyData(
-            params.id,
-            encodeQuery({
-              ...param,
-              terms: { property: data.id },
-              sorts: { timestamp: 'desc' },
-            }),
-          )
+          service.getEventCount(params.id, data.id!, {
+            ...param,
+          })
         }
         pagination={{
           pageSize: 15,
         }}
-        columns={columns}
+        columns={[...columns, ...createColumn()]}
       />
     </Drawer>
   );

+ 8 - 1
src/pages/device/Instance/Detail/PropertyLog/index.tsx

@@ -34,7 +34,14 @@ const PropertyLog = (props: Props) => {
         pagination={{
           pageSize: 15,
         }}
-        columns={columns}
+        columns={[
+          ...columns,
+          {
+            dataIndex: 'formatValue',
+            title: '数据',
+            copyable: true,
+          },
+        ]}
       />
     </Drawer>
   );

+ 0 - 5
src/pages/device/Instance/Detail/MetadataLog/columns.ts

@@ -14,10 +14,5 @@ const columns: ProColumns<MetadataLogData>[] = [
     width: 200,
     renderText: (text: string) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
   },
-  {
-    dataIndex: 'formatValue',
-    title: '数据',
-    copyable: true,
-  },
 ];
 export default columns;

+ 22 - 12
src/pages/device/Instance/Detail/Running/Event.tsx

@@ -1,5 +1,5 @@
 import { SyncOutlined, UnorderedListOutlined } from '@ant-design/icons';
-import { Badge, Divider, message, Tooltip } from 'antd';
+import { Badge, Divider, Tooltip } from 'antd';
 import ProCard from '@ant-design/pro-card';
 import type { EventMetadata, ObserverMetadata } from '@/pages/device/Product/typings';
 import { useEffect, useRef, useState } from 'react';
@@ -22,21 +22,30 @@ const Event = (props: Props) => {
 
   const [count, setCount] = useState<number>(0);
   const cacheCount = useRef<number>(count);
-  useEffect(() => {
+
+  const [loading, setLoading] = useState<boolean>(false);
+  const initCount = () => {
+    setLoading(true);
     if (data.id) {
-      service.getEventCount(params.id, data.id).then((resp) => {
-        if (resp.status === 200) {
-          setCount(resp.result?.total);
-          cacheCount.current = resp.result?.total;
-        }
-      });
+      service
+        .getEventCount(params.id, data.id, {
+          format: true,
+          pageSize: 1,
+        })
+        .then((resp) => {
+          if (resp.status === 200) {
+            setCount(resp.result?.total);
+            cacheCount.current = resp.result?.total;
+          }
+        })
+        .finally(() => setLoading(false));
     }
-
+  };
+  useEffect(() => {
+    initCount();
     data.subscribe((payload: unknown) => {
-      console.log('订阅到消息', payload);
       if (payload) {
         cacheCount.current = cacheCount.current + 1;
-        console.log(cacheCount.current, 'currnt');
         setCount(cacheCount.current);
       }
     });
@@ -48,7 +57,7 @@ const Event = (props: Props) => {
       title={`${data.name}: ${count}`}
       extra={
         <>
-          <SyncOutlined onClick={() => message.success('刷新')} />
+          <SyncOutlined onClick={initCount} />
           <Divider type="vertical" />
           <Tooltip placement="top" title="详情">
             <UnorderedListOutlined
@@ -59,6 +68,7 @@ const Event = (props: Props) => {
           </Tooltip>
         </>
       }
+      loading={loading}
       layout="center"
       bordered
       headerBordered

+ 1 - 1
src/pages/device/Instance/Detail/Running/Property.tsx

@@ -6,7 +6,7 @@ import { Line } from '@ant-design/charts';
 import { useCallback, useEffect, useRef, useState } from 'react';
 import { service } from '@/pages/device/Instance';
 import { useParams } from 'umi';
-import PropertyLog from '@/pages/device/Instance/Detail/PropertyLog';
+import PropertyLog from '@/pages/device/Instance/Detail/MetadataLog/Property';
 
 interface Props {
   data: Partial<PropertyMetadata> & ObserverMetadata;

+ 29 - 18
src/pages/device/Instance/Detail/Running/index.tsx

@@ -1,5 +1,5 @@
 import { InstanceModel, service } from '@/pages/device/Instance';
-import { Badge, Card, Col, Row } from 'antd';
+import { Card, Col, Row } from 'antd';
 import type {
   DeviceMetadata,
   EventMetadata,
@@ -12,6 +12,8 @@ import Property from '@/pages/device/Instance/Detail/Running/Property';
 import Event from '@/pages/device/Instance/Detail/Running/Event';
 import useSendWebsocketMessage from '@/hooks/websocket/useSendWebsocketMessage';
 import { map } from 'rxjs/operators';
+import moment from 'moment';
+import { deviceStatus } from '@/pages/device/Instance/Detail';
 
 const ColResponsiveProps = {
   xs: 24,
@@ -43,12 +45,9 @@ const Running = () => {
   };
   metadata.events = metadata.events.map(addObserver);
   metadata.properties = metadata.properties.map(addObserver);
-  const [propertiesList, setPropertiesList] = useState<string[]>([]);
-
-  useEffect(() => {
-    const list = metadata.properties.map((item: any) => item.id);
-    setPropertiesList(list);
-  }, []);
+  const [propertiesList, setPropertiesList] = useState<string[]>(
+    metadata.properties.map((item: any) => item.id),
+  );
 
   /**
    * 订阅属性数据
@@ -123,6 +122,21 @@ const Running = () => {
     getDashboard();
   }, []);
 
+  const [renderCount, setRenderCount] = useState<number>(15);
+  window.onscroll = () => {
+    const a = document.documentElement.scrollTop;
+    const c = document.documentElement.scrollHeight;
+    const b = document.body.clientHeight;
+    if (a + b >= c - 50) {
+      const list: any = [];
+      metadata.properties.slice(renderCount, renderCount + 15).map((item) => {
+        list.push(item.id);
+      });
+      setPropertiesList([...list]);
+      setRenderCount(renderCount + 15);
+    }
+  };
+
   const renderCard = useCallback(() => {
     return [
       ...metadata.properties.map((item) => (
@@ -135,8 +149,8 @@ const Running = () => {
           <Event data={item as Partial<EventMetadata> & ObserverMetadata} />
         </Col>
       )),
-    ];
-  }, [device]);
+    ].splice(0, renderCount);
+  }, [device, renderCount]);
 
   return (
     <Row gutter={24}>
@@ -149,21 +163,18 @@ const Running = () => {
         >
           <div style={{ height: 60 }}>
             <Row gutter={[16, 16]}>
+              <Col span={24}>{deviceStatus.get(InstanceModel.detail.state?.value)}</Col>
               <Col span={24}>
-                <Badge status="success" text={<span style={{ fontSize: 25 }}>在线</span>} />
-              </Col>
-              <Col span={24}>
-                {intl.formatMessage({
-                  id: 'pages.device.instanceDetail.running.onlineTime',
-                  defaultMessage: '在线时间',
-                })}
-                : 2021-8-20 12:20:33
+                {device.state?.value === 'online' ? (
+                  <span>上线时间:{moment(device?.onlineTime).format('YYYY-MM-DD HH:mm:ss')}</span>
+                ) : (
+                  <span>离线时间:{moment(device?.offlineTime).format('YYYY-MM-DD HH:mm:ss')}</span>
+                )}
               </Col>
             </Row>
           </div>
         </Card>
       </Col>
-
       {renderCard()}
     </Row>
   );

+ 13 - 2
src/pages/device/Instance/Detail/index.tsx

@@ -1,7 +1,7 @@
 import { PageContainer } from '@ant-design/pro-layout';
 import { InstanceModel, service } from '@/pages/device/Instance';
 import { history, useParams } from 'umi';
-import { Button } from 'antd';
+import { Badge, Button, Divider } from 'antd';
 import { useEffect, useState } from 'react';
 import { statusMap } from '@/pages/device/Product';
 import { observer } from '@formily/react';
@@ -14,6 +14,10 @@ import Functions from '@/pages/device/Instance/Detail/Functions';
 import Running from '@/pages/device/Instance/Detail/Running';
 import { useIntl } from '@@/plugin-locale/localeExports';
 
+export const deviceStatus = new Map();
+deviceStatus.set('online', <Badge status="success" text={'在线'} />);
+deviceStatus.set('offline', <Badge status="error" text={'离线'} />);
+deviceStatus.set('notActive', <Badge status="processing" text={'未启用'} />);
 const InstanceDetail = observer(() => {
   const intl = useIntl();
   const [tab, setTab] = useState<string>('detail');
@@ -36,7 +40,7 @@ const InstanceDetail = observer(() => {
       key: 'detail',
       tab: intl.formatMessage({
         id: 'pages.device.instanceDetail.detail',
-        defaultMessage: '实例信息',
+        defaultMessage: '配置信息',
       }),
       component: <Config />,
     },
@@ -104,6 +108,13 @@ const InstanceDetail = observer(() => {
       onTabChange={setTab}
       tabList={list}
       content={<Info />}
+      title={
+        <>
+          {InstanceModel.detail.name}
+          <Divider type="vertical" />
+          {deviceStatus.get(InstanceModel.detail.state?.value)}
+        </>
+      }
       extra={[
         statusMap[0],
         <Button key="2">

+ 5 - 4
src/pages/device/Instance/service.ts

@@ -56,10 +56,11 @@ class Service extends BaseService<DeviceInstance> {
       params,
     });
 
-  public getEventCount = (deviceId: string, eventId: string) =>
-    request(
-      `/${SystemConst.API_BASE}/device/instance/${deviceId}/event/${eventId}?format=true&pageSize=1`,
-    );
+  public getEventCount = (deviceId: string, eventId: string, params: Record<string, unknown>) =>
+    request(`/${SystemConst.API_BASE}/device/instance/${deviceId}/event/${eventId}`, {
+      method: 'GET',
+      params,
+    });
 }
 
 export default Service;

+ 1 - 0
src/pages/device/Instance/typings.d.ts

@@ -35,6 +35,7 @@ export type DeviceInstance = {
   address: string;
   registerTime: number;
   onlineTime: string | number;
+  offlineTime: string | number;
   tags: any;
 };