import React, { useState, useEffect, useCallback, useRef } from 'react'; import { FormattedMessage, history, useModel } from 'umi'; import styles from './index.less'; import cx from 'classnames'; import QRCode from 'qrcodejs2'; import { qrCodeInfo } from '@/services/sagacare_service/member'; import { ReloadOutlined } from '@ant-design/icons'; export default () => { const loginLogo = require('@/assets/images/loginLogo.svg'); const qrcodeRef = useRef(); const wsRef = useRef(); const [expireTime, setExpireTime] = useState(); //过期时间 const [qrCodeId, setQrCodeId] = useState(); //生成二维码id const getqrCodeInfo = () => { qrCodeInfo() .then((res) => { var expireTime = res?.data?.expireTime; var qrCodeId = res?.data?.qrCodeId; setExpireTime(expireTime); setQrCodeId(qrCodeId); }) .catch((err) => {}); }; useEffect(() => { getqrCodeInfo(); }, []); useEffect(() => { if (!qrCodeId) return; if (qrcodeRef.current) { qrcodeRef.current.makeCode(qrCodeId); } else { qrcodeRef.current = new QRCode('qrcodeRef', { text: qrCodeId, width: 160, height: 160, colorDark: '#000000', colorLight: '#ffffff', }); } wsRef.current = new WebSocket( `wss://duoduoenv.sagacloud.cn/duoduo-service/websocket/webSocket/${qrCodeId}`, ); // 获取连接状态 console.log('ws连接状态:' + wsRef.current.readyState); //监听是否连接成功 wsRef.current.onopen = function () { console.log('ws连接状态:onopen' + wsRef.current.readyState); //连接成功则发送一个数据 // wsRef.current.send('test1'); }; // 接听服务器发回的信息并处理展示 wsRef.current.onmessage = function (data) { console.log('接收到来自服务器的消息:', data.data); if (data?.data?.indexOf('token') > -1) { var info = JSON.parse(data.data); console.log('登录成功:', info); var tokenUser = info.tokenUser; var token = info.token; localStorage.setItem('user', JSON.stringify(tokenUser)); localStorage.setItem('token', token); // projectObj = { projectId: tokenUser.projectId }; // user = tokenUser; history.push('/home'); } //完成通信后关闭WebSocket连接 // wsRef.current.close(); }; // 监听连接关闭事件 wsRef.current.onclose = function (e) { // 监听整个过程中websocket的状态 console.log('ws连接状态:onclose' + wsRef.current.readyState); console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean); }; // 监听并处理error事件 wsRef.current.onerror = function (error) { console.log('ws连接状态:error', error); }; }, [qrCodeId]); const reloadQrcode = () => { getqrCodeInfo(); }; return (
{expireTime < new Date().getTime() && (
)}
请使用小程序扫码登录
); };