/*
 * Create:      柿子
 * CreateDate:  2024/03/07
 * Describe：   单点登录
 * */
import React, { Component } from 'react';
import { Spin, Modal } from 'antd';
import { Keup, Util } from 'tools';
import store from 'store';
import fetchJsonp from 'fetch-jsonp';

class VerifyLogin extends Component {
	constructor(props) {
		super(props);
		this.state = {
			paramsData: {},
			loading: true,
		};
		this.modalSpin = null;
	};

	componentDidMount() {
		this.modalSpin = Modal.info({
			title: '正在校验登录，请稍后...',
			content: <Spin size="large" />,
			okText: "确认",
			onOk() { },
		});
		// 是否是pc端
		if (this.handleIsPC()) {
			typeof (CefSharp) != 'undefined' ? this.handleCefSharp() : this.getLocalIpConfig();
		} else {
			// 移动端专用获取不到MAC地址的 先固定一个MAC地址
			const fixedMAC = { 'hostName': '移动端专用', 'ipv4': '172.18.17.9', 'ipv6': '172.18.17.9', 'mac': '9C-5C-8E-C1-5C-D1' }
			React.$setSessionData('ipConfig', fixedMAC)
			this.getLoginParams(fixedMAC);
		}
	};

	// 判断是否是PC端
	handleIsPC = () => {
		var userAgentInfo = navigator.userAgent;
		var Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
		var flag = true;
		for (var v = 0; v < Agents.length; v++) {
			if (userAgentInfo.indexOf(Agents[v]) > 0) {
				flag = false;
				break;
			}
		}
		return flag;
	};

	handleCefSharp = () => { // 新元素定制浏览器 获取本机IP信息
		let dllParams = "{'inputDir':'GetIP/GetIP.dll','clsName':'GetIP.GetIPConfig','funcName':'IPConfig'}";
		if (CefSharp) {   // 新元素定制浏览器
			CefSharp.BindObjectAsync("xysCefToJavaScripts");
			setTimeout(() => {
				xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
					if (returnVale && JSON.parse(returnVale).result) {
						let fixedMAC = JSON.parse(returnVale)?.result || {};
						React.$setSessionData('ipConfig', fixedMAC)
						this.getLoginParams(fixedMAC);
					} else {
						this.getLocalIpConfig(); // 获取本机IP信息
					}
				})
			}, 100);
		} else {
			const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
			if (frame) {
				frame.DynamicLoadingDLL(dllParams)
					.then(
						data => {
							if (data && JSON.parse(data).result) {
								let fixedMAC = JSON.parse(data)?.result || {};
								React.$setSessionData('ipConfig', fixedMAC);
								this.getLoginParams(fixedMAC);
							} else {
								this.getLocalIpConfig(); // 获取本机IP信息
							}
						},
						err => {
							console.log('error', err);
						}
					)
			} else {
				// 常规浏览器
				this.getLocalIpConfig(); // 获取本机IP信息
			}
		}
	};

	/**获取本机IP信息 */
	getLocalIpConfig = () => {
		let _this = this;
		let data = 'input={"inputDir":"GetIP/GetIP.dll","clsName":"GetIP.GetIPConfig","funcName":"IPConfig"}'
		fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
			jsonpCallback: 'JsonCallback',
		})
			.then(function (response) {
				return response.json()
			}).then(function (json) {
				if (json && JSON.parse(json)) {
					let fixedMAC = JSON.parse(json)?.result || {};
					React.$setSessionData('ipConfig', fixedMAC)
					_this.getLoginParams(fixedMAC);
				}
			}).catch(function (ex) {
				let fixedMAC = { hostName: '', ipv4: '192.168.0.100', ipv6: '192.168.0.100', mac: 'fe80::48a:d9c7:ac9' }
				React.$setSessionData('ipConfig', fixedMAC)
				_this.getLoginParams(fixedMAC);
			})
	};

	// 获取登录参数
	getLoginParams = (ipConfig) => {
		let path = window.location && window.location.href ? window.location.href.split('#')[1] : '';
		let paramsStr = path && path.indexOf('?') > -1 ? path.split('?')[1] : '';
		this.setState({ paramsData: Util.getObjByUrlStr(paramsStr, '=') }, () => {
			this.handleLogin(ipConfig);
		});
	};

	// 登录
	handleLogin = async (ipConfig) => {
		try {
			const { paramsData } = this.state;
			let data = {
				isTips: 'N',
				params: [{
					...paramsData,
					ip: ipConfig?.ipv4 || '',
					mac: ipConfig?.mac || ''
				}],
				session: [{
					"ipv4": ipConfig?.ipv4 || '',
					"ipv6": ipConfig?.ipv6 || '',
					"mac": ipConfig?.mac || '',
				}]
			}
			let res = await React.$asyncPost(this, 'MYHIP00001', data);
			this.loginHref(res);
			this.modalSpin && this.modalSpin.destroy(); // 登录操作结束，关闭loading
		} catch (error) {
			console.log(error);
			this.modalSpin && this.modalSpin.destroy(); // 登录操作结束，关闭loading
			Keup.ModalMessage(3, this, '单点登录异常：' + error?.errorMessage || '', '跳转到登录页', '/login', "现在就去", 'error')
		}
	};

	// 登录方法
	loginHref = (res) => {
		let userData = Object.assign({}, res.result[0])
		let { languageCode } = this.state
		userData.language = languageCode
		userData.messageTime = 1 // 提示显示的时间
		window.sessionStorage.setItem('loginIsSession', 'Y');
		window.sessionStorage.setItem('userData', JSON.stringify(userData));
		store.dispatch({
			type: 'userData',
			value: { loginIs: 'Y' }
		})
		if (userData && 'userYBCode' in userData && userData.userYBCode) {
			this.handleRealNameAuthentication(userData); // 实名认证
		} else {
			this.handleGoBack(userData);
		}
	};

	// 实名认证
	handleRealNameAuthentication = async (record) => {
		try {
			let data = {
				params: [{
					...record
				}]
			}
			let res = await React.$asyncPost(this, '05110027', data);
			let dllParams = res?.result || {};
			if (dllParams?.dllFlag === 'Y') { // 是否调用dll
				let dllRes = await React.$dllPost(dllParams?.funcName || 'AgentFun', dllParams, dllParams?.dllPath || 'INSUNew/PTMedInsuInterface.dll', dllParams?.className || 'PTMedInsuInterface.InsuBusiness');
				console.log('dllRes', dllRes)
			}
			this.handleGoBack(record);
		} catch (error) {
			console.log(error);
			this.handleGoBack(record);
		}
	};

	handleGoBack = (userData) => {
		if (userData.path != '') {
			this.props.history.push({ pathname: userData.path, state: { params: userData?.paras || '' } });
		} else {
			this.props.history.push('/001');
		}
	};

	render() {
		return (
			<div></div>
		)
	}
};

export default VerifyLogin;