<template>
  <div style="background-color: #f0f2f5">
    <BasicTable @register="registerTable" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { realTimeDataColumns } from '../../config/detail.config';
  import { useWebSocket } from '@vueuse/core';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { getAuthCache } from '/@/utils/auth';
  import { useMessage } from '/@/hooks/web/useMessage';
  import type { socketDataType } from '../../types';
  import { useGlobSetting } from '/@/hooks/setting';
  export default defineComponent({
    name: 'RealTimeData',
    components: {
      BasicTable,
    },
    props: {
      deviceDetail: {
        type: Object,
        required: true,
      },
    },
    setup(props) {
      const token: string = getAuthCache(JWT_TOKEN_KEY);
      const { socketUrl } = useGlobSetting();
      const state = reactive({
        server: `${socketUrl}${token}`,
        sendValue: JSON.stringify({
          attrSubCmds: [],
          tsSubCmds: [
            {
              entityType: 'DEVICE',
              entityId: props.deviceDetail.tbDeviceId,
              scope: 'LATEST_TELEMETRY',
              cmdId: 1,
            },
          ],
          historyCmds: [],
          entityDataCmds: [],
          entityDataUnsubscribeCmds: [],
          alarmDataCmds: [],
          alarmDataUnsubscribeCmds: [],
          entityCountCmds: [],
          entityCountUnsubscribeCmds: [],
        }),
        recordList: Array<socketDataType>(),
      });
      const { createMessage } = useMessage();
      const [registerTable, { getForm, setTableData }] = useTable({
        columns: realTimeDataColumns,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        dataSource: state.recordList,
        useSearchForm: true,
        formConfig: {
          labelWidth: 100,
          schemas: [
            {
              field: 'key',
              label: '键/值',
              component: 'Input',
              colProps: { span: 6 },
              componentProps: {
                placeholder: '请输入 键/值',
                maxLength: 255,
              },
            },
          ],
          // 自定义前端查询
          submitFunc() {
            const { getFieldsValue } = getForm();
            const { key } = getFieldsValue();
            if (!key) {
              setTableData(state.recordList);
              return;
            }
            let newRecordList = [];
            let len = state.recordList.length;
            for (let i = 0; i < len; i++) {
              if (
                state.recordList[i].key.indexOf(key) >= 0 ||
                state.recordList[i].value.indexOf(key) >= 0
              ) {
                newRecordList.push(state.recordList[i]);
              }
            }
            setTableData(newRecordList);
          },
          resetFunc() {
            setTableData(state.recordList);
          },
        },
      });

      const { send, close } = useWebSocket(state.server, {
        onConnected() {
          send(state.sendValue);
          console.log('建立连接了');
        },
        onMessage(_, e) {
          const { data } = JSON.parse(e.data);
          console.log('来新消息了', '---data---', data);
          const newArray: socketDataType[] = [];
          for (const key in data) {
            const [time, value] = data[key].flat(1);
            let obj = {
              key,
              time,
              value,
            };
            if (state.recordList.length === 0) {
              state.recordList.unshift(obj);
            } else {
              newArray.push(obj);
            }
          }
          newArray.forEach((item) => {
            let flag = false;
            state.recordList.forEach((item1) => {
              if (item1.key === item.key) {
                item1.value = item.value;
                item1.time = item.time;
                flag = true;
              }
            });
            if (!flag) {
              state.recordList.unshift(item);
            }
          });
        },
        onDisconnected() {
          console.log('断开连接了');
          close();
        },
        onError() {
          createMessage.error('webSocket连接超时,请联系管理员');
        },
      });
      return {
        registerTable,
      };
    },
  });
</script>
