// import { mqttConnect, mqttSub } from '@/pages/mqtt-connet';

// const parseTopic = (topic: string): DeviceMessage => {
//   const result: DeviceMessage = {};
//   const arr = topic.split('/');
//   if (arr.length > 4) {
//     result.DeviceCode = arr[3];
//     result.SubDeviceId = arr[4];
//   }
//   return result;
// };
export default {
  namespace: 'MQTTMessage',
  state: {
    message: undefined,
    connected: false,
  },
  subscriptions: {
    setupHistory({ dispatch, history }: any) {
      history.listen((location: any) => {
        if (location.pathname === '/DataBoard') {
          console.log(dispatch);
          // const client = mqttConnect();
          // client.on('connect', () => {
          //   dispatch({ type: 'connected', payload: true });
          //   mqttSub(client, {
          //     topic: ['/device_message/1ps9djpswi0cds7cofynkso300eql4iu/#'],
          //     qos: 0,
          //   });
          // });
          // client.on('error', () => {
          //   client.end();
          // });
          //
          // client.on('message', (topic, message: Buffer) => {
          //   // console.log('收到的消息', topic, message.toString());
          //   const data = JSON.parse(message.toString());
          //   const msg = parseTopic(topic);
          //   msg.Data = data;
          //   dispatch({ type: 'message', payload: msg });
          // });
        }
      });
    },
  },
  reducers: {
    connected(state: any, { payload }: any) {
      return { ...state, connected: payload };
    },
    message(state: any, { payload }: any) {
      return { ...state, message: payload };
    },
  },
};

export type DeviceMessage = {
  DeviceCode?: string;
  SubDeviceId?: string;
  Data?: any;
};
