import React, { Component } from 'react';
import { message, Icon, Spin } from 'antd';
import QRCode from 'qrcode.react';
import fetch from 'dva/fetch';
import FormdataWrapper from '../utils/object-to-formdata-custom';
import { isJSON } from '@/webPublic/one_stop_public/2022beidianke/isJSON';

let ws = null;

/**
 * props{
 *    url: 二维码url
 *    show: 是否显示二维码Modal
 *    wxSocketGateWay: webscoket 链接地址
 *    mockServer: 接口地址前缀 用于获取sessionid;
 *  }
 * */
export default class LoginWithQrCode extends Component {
	constructor(props) {
		super(props);
		const { wxSocketGateWay, mockServer } = this.props;
		this.wxSocketGateWay = wxSocketGateWay;
		this.mockServer = mockServer;
		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 (!this.wxSocketGateWay) {
			return console.warn('没有配置socket接口地址,无法使用消息中心接口');
		}

		ws = new WebSocket(`${this.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(`${this.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>
		);
	}
}
