提交 534d1bb1 authored 作者: 钟是志's avatar 钟是志

将登录组件抽到 webpublic 里面

上级 6577aab6
import React, { Component } from 'react';
import { message, Icon, Spin } from 'antd';
import QRCode from 'qrcode.react';
import config from '@/config/config';
import fetch from 'dva/fetch';
import FormdataWrapper from '../utils/object-to-formdata-custom';
import { isJSON } from '../utils/utils';
let ws = null;
export default class LoginWithQrCode extends Component {
constructor(props) {
super(props);
this.state = {
connectTimes: 0,
sessionId: '',
connectStatus: false,
showRefresh: false,
};
this.initWs();
}
initWs = () => {
ws = null;
};
componentWillUnmount(){
this.initWs(); // 组件不加载的时候 注销websocket
}
startConnect = () => {
let that = this;
const { sessionId } = that.state;
const { connectTimes, connectStatus } = this.state;
if (connectStatus) {
return true;
}
if (connectTimes > 3) {
console.log('连接次数超过3次不能再次连接websokcet中心');
message.warning('服务器错误,无法使用扫码登录');
return false;
}
if (!config.wxSocketGateWay) {
return console.warn('没有配置socket接口地址,无法使用消息中心接口');
}
ws = new WebSocket(`${config.wxSocketGateWay}/${sessionId}`);
ws.onopen = (evt) => {
that.setState({
connectStatus: true,
});
console.log('open WebSocket success');
};
ws.onclose = () => {
// 链接断开后 显示刷新二维码
// that.getAppId();
that.setState({
showRefresh: true,
})
};
ws.onmessage = (evt) => {
if (typeof evt.data === String) {
console.log('Received data string');
console.log(evt.data);
}
if (evt.data && isJSON(evt.data)) {
let info = JSON.parse(evt.data);
if (info.status) {
message.success('扫码登录成功,正在跳转', 3);
window.location.href = info.redirectUrl;
}
}
};
if (ws.readyState === WebSocket.CLOSED) {
this.setState({
connectTimes: connectTimes + 1,
}, () => {
ws = null;
this.startConnect();
});
}
ws.onerror = (event) => {
if (event) {
console.log('websocket报错,无法重新发起扫码登录');
}
};
};
getAppId = () => {
const options = {
body: FormdataWrapper({}),
credentials: 'omit',
mode: 'cors',
method: 'POST',
headers: {
Accept: 'application/json',
},
};
fetch(`${config.mockServer}/wx/` + 'wxAuthApi/getScanSessionId', options)
.then(response => {
if (response.status !== 200) {
return response.text();
}
return response.json();
})
.then(response => {
if (response && response.sessionId) {
this.setState({
sessionId: response.sessionId,
}, () => {
});
} else {
console.log('未获取到sessionId.无法使用扫码登录');
}
});
};
componentDidMount() {
this.getAppId();
}
refreshQrCode = () => {
this.getAppId();
this.setState({
connectTimes: 0,
showRefresh: false,
connectStatus: false,
})
};
render() {
const { sessionId, connectStatus,showRefresh, loading } = this.state;
const { url, show } = this.props;
if (this.props.show && !connectStatus) {
this.startConnect();
}
return (
<div>
<div style={{
textAlign: 'center',
margin: '0 auto',
}}>
{
this.props.show && !connectStatus ? <Spin size="large" style={{
height: '200px',
paddingTop: '100px',}}/>:
<QRCode
bgColor="white"
fgColor='black'
value={url + '/' + sessionId}
size={200}
/>
}
{
showRefresh ?
<div style={{
fontSize: '16px',
marginTop: '10px',
borderTop: '1px solid #eee',
}}>
<Icon type="info-circle" style={{color: '#E36968'}}/>
<span style={{
fontWeight: 'blod',
}}
>二维码已过期</span>
<p>
您可以<span
style={{
color: '#BC2831',
cursor: 'pointer',
}}
onClick={this.refreshQrCode}
>
点击刷新二维码
</span>
重新扫描验证
</p>
</div> : null
}
</div>
</div>
);
}
}
import React from 'react';
import LoginWithQrCode from './LoginWithQrCode';
export default function LoginByQrCode({ url, LoginType }) {
return (
<div>
<div style={{ backgroundColor: 'white', width: 288, padding: 10, margin: 'auto' }}>
<LoginWithQrCode url={url} show={LoginType === 1}/>
</div>
<div style={{ marginTop: 20, color: 'white' }}>
请使用
<span style={{ color: 'red' }}>微信扫一扫</span>
扫码登录
</div>
</div>
);
}
function isObject (value) {
return value === Object(value)
}
function isArray (value) {
return Array.isArray(value)
}
function isFile (value) {
return value instanceof File
}
function makeArrayKey (key) {
return key
}
function objectToFormData (obj, fd, pre) {
fd = fd || new FormData()
Object.keys(obj).forEach(function (prop) {
var key = pre ? (pre + '[' + prop + ']') : prop
if (isObject(obj[prop]) && !isArray(obj[prop]) && !isFile(obj[prop])) {
objectToFormData(obj[prop], fd, key)
} else if (isArray(obj[prop])) {
obj[prop].forEach(function (value) {
var arrayKey = makeArrayKey(key)
if (isObject(value) && !isFile(value)) {
objectToFormData(value, fd, arrayKey)
} else {
fd.append(arrayKey, value)
}
})
} else {
if(obj[prop]!=null) fd.append(key, obj[prop])
}
})
return fd
}
export default objectToFormData
import React from 'react';
import moment from 'moment';
import { Icon, message, notification } from 'antd';
let messageTime = new Date().getTime() - 3000;
/**
* 校验 开始时间必须在结束时间之前的函数
* */
export function checkDate(endTime = '2019-01-01', startTime = '2018-12-31') {
return moment(endTime).isAfter(moment(startTime));
}
/**
* 去除字符串中的所有html 标签
* */
export function matchReg(str) {
let reg = /<\/?.+?\/?>/g;
return str.replace(reg, '').replace(/&nbsp;/g, ' ');
}
export function htmlFormat(str) {
if(typeof str !== 'string'){
return '';
}
const newTxt = str.replace(/\s+([^<>]+)(?=<)/g, function(match) {
return match.replace(/\s/g, '&nbsp;');
});
return newTxt;
}
export function countSpecialField(filedSpanBig, nameSpanBig) {
let style = {};
if (document.body.clientWidth > 1400) {
if (filedSpanBig === 5) { // 当设置一行排列5个字段时 自定义宽度为20%
style = { width: '20%' };
}
if (filedSpanBig === 1 && nameSpanBig === 2) { // 当一行显示一个字段 然后名字又特别长时 使用这个width
style = { width: '6%' };
}
}
return style;
};
/**
* 深拷贝函数
* */
export function deepCopy(obj, parent = null) {
if (React.isValidElement(obj)) {
return React.cloneElement(obj);
}
if (['boolean', 'string', 'number'].indexOf(typeof obj) > -1 || !obj) {
return obj;
}
let result;
if (obj.constructor === Array) {
result = [];
} else {
result = {};
}
let keys = Object.keys(obj),
key = null,
temp = null,
_parent = parent;
// 该字段有父级则需要追溯该字段的父级
while (_parent) {
// 如果该字段引用了它的父级则为循环引用
if (_parent.originalParent === obj) {
// 循环引用直接返回同级的新对象
return _parent.currentParent;
}
_parent = _parent.parent;
}
for (let i = 0; i < keys.length; i++) {
key = keys[i];
temp = obj[key];
// 如果字段的值也是一个对象
if (temp && typeof temp === 'object') {
// 递归执行深拷贝 将同级的待拷贝对象与新对象传递给 parent 方便追溯循环引用
result[key] = deepCopy(temp, {
originalParent: obj,
currentParent: result,
parent: parent,
});
} else {
result[key] = temp;
}
}
return result;
}
/**
* 获取表单元素中每个元素的值,
* @param type
* @param e
* @param other
* @returns {*|boolean}
*/
export function getFormElemValue(type, e, other) {
let value = e;
switch (type) {
case 'input':
value = e.target.value;
break;
case 'checkbox':
value = e.target.checked;
break;
case 'textarea':
value = e.target.value;
break;
case 'buttonUpload':
value = e.url;
break;
case 'upload':
value = Array.isArray(e) ? e.join(',') : '';
break;
default:
break;
}
return value;
}
/**
* 生成随机字符串
* */
export function randomStr() {
return Math.random().toString(36).substr(2);
}
export function isJSON(str) {
if (typeof str == 'string') {
try {
JSON.parse(str);
if (typeof JSON.parse(str) === 'number') {
return false;
}
return true;
} catch (e) {
return false;
}
}
}
export function checkMustHaveValue(configFileds, data){
for (let item of configFileds) {
if (!data[item.key] && data[item.key] !== false && data[item.key] !== 0) {
return false;
}
}
return true;
}
export function mustHaveValue(configFields, data) {
for (let item of configFields) {
if (!item.required) continue;
if (Array.isArray(data[item.key]) && data[item.key].length < 1) {
message.warning(`${item.name}是必填项请填写`);
return false;
}
if (!data[item.key] && data[item.key] !== false && data[item.key] !== 0) {
message.warning(`${item.name}是必填项请填写`);
return false;
}
}
return true;
}
/**
* 判断数组中是否有重复元素
* 通过数组排序,比较临近元素
* */
export function isRepeat(ary) {
if (ary.length <= 1) {
return false;
}
let nary = ary.sort();
for (let i = 0; i < ary.length - 1; i++) {
if (nary[i] === nary[i + 1]) {
return nary[i];
// alert("数组重复内容:" + nary[i]);
}
}
return false;
}
export function displayRender(label) {
if (label) {
return label[label.length - 1];
} else {
return '';
}
}
export function isEmptyValue(value) {
return typeof value === 'undefined' || value === null || value === '';
}
// 全局的通知消息组件
export function controlNotification(props) {
const nowTime = new Date().getTime();
if (nowTime - messageTime < 3000) {
return;
}
messageTime = nowTime;
notification.info({
...props,
icon:
<Icon type="info-circle"
style={{ color: '#fa8c16' }}
/>,
});
return true;
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论