import React from 'react';
import NewHeader from './NewHeader'
import NewFooter from './NewFooter'
import { downloadFile } from 'educoder'
import axios from 'axios';
import { Spin } from 'antd';
import './TPMIndex.css';
import LoginDialog from '../login/LoginDialog';
import AccountProfile from '../user/AccountProfile';
import AccountPhoneemail from '../user/AccountPhoneemail';

export function TPMIndexHOC(WrappedComponent) {
	return class II extends React.Component {
		constructor(props) {
			super(props);
			window.$('#root').css('position', 'relative')

			this.state = {
				tpmLoading: true,
				resLoading: true,
				Headertop: undefined,
				Footerdown: undefined,

				isRender: false,
				AccountProfiletype: false,
				AccountPhoneemailtype: false,
				globalLoading: false,
				dataquerys: {},
				isloginCancel: undefined,
				mygetHelmetapi: null,
			}
		}

		// header里面需要有user
		initCommonState(user) {
			// 更新头像后，需要改变参数，不然会被图片缓存影响到  --> 后台已加 ?t=${new Date().getTime()
			const newUser = Object.assign({}, { ...user }, { image_url: `${user.image_url}` });
			this.setState({
				user: newUser,
				current_user: newUser
			})
		}


		keyupListener = (e) => {
			if (e.key === "Escape") {
				this.setState({ globalLoading: false })
			}
		}
		componentWillUnmount() {
			window.removeEventListener('keyup', this.keyupListener)
		}
		componentWillMount() {
			this.fetchUsers();
		}

		componentDidMount() {
			window.addEventListener('keyup', this.keyupListener)

			if (this.props.match.path === "/") {
				// document.title="创新源于实践";
			} else if (this.props.match.path === "/403") {
				document.title = "你没有权限访问";
			} else if (this.props.match.path === "/nopage") {
				document.title = "没有找到该页面";
			} else if (this.props.match.path === "/shixuns") {
				document.title = "实训项目";
			} else if (this.props.match.path === "/paths") {
				document.title = "实践课程";
			} else if (this.props.match.path === "/classrooms") {
				document.title = "教学课堂";
			}

			///请求定制化的信息
			this.getAppdata();
		}


		//获取数据为空的时候
		gettablogourlnull = () => {
			this.setState({
				mygetHelmetapi: undefined
			});
			document.title = "Forge";
			var link = document.createElement('link'),
				oldLink = document.getElementById('dynamic-favicon');
			link.id = 'dynamic-favicon';
			link.rel = 'shortcut icon';
			link.href = "/react/build/./favicon.ico";
			if (oldLink) {
				document.head.removeChild(oldLink);
			}
			document.head.appendChild(link);
		};

		//获取数据的时候
		gettablogourldata = (response) => {
			document.title = response.data.setting.name;
			var link = document.createElement('link'),
				oldLink = document.getElementById('dynamic-favicon');
			link.id = 'dynamic-favicon';
			link.rel = 'shortcut icon';
			link.href = '/' + response.data.setting.tab_logo_url;
			if (oldLink) {
				document.head.removeChild(oldLink);
			}
			document.head.appendChild(link);
		}
		//获取当前定制信息
		getAppdata = () => {
			try {
				var chromesettingArray = JSON.parse(localStorage.getItem('chromesetting'));
				var chromesettingresponseArray = JSON.parse(localStorage.getItem('chromesettingresponse'));
				this.setState({
					mygetHelmetapi: chromesettingArray
				});
				if (chromesettingArray.tab_logo_url) {
					this.gettablogourldata(chromesettingresponseArray);
				} else {
					this.gettablogourlnull();
				}
			} catch (e) {
				console.log("hoc获取游览器配置失败 重新请求开始读取配置");
				this.getAppdatausr();
			}
		};
		getAppdatausr = () => {
			let url = "/setting.json";
			axios.get(url).then((response) => {
				if (response) {
					if (response.data) {
						this.setState({
							mygetHelmetapi: response.data.setting
						});
						localStorage.setItem('chromesetting', JSON.stringify(response.data.setting));
						localStorage.setItem('chromesettingresponse', JSON.stringify(response));
						try {
							if (response.data.setting.tab_logo_url) {
								this.gettablogourldata(response);
							} else {
								this.gettablogourlnull();
							}
						} catch (e) {
							this.gettablogourlnull();
						}
					} else {
						this.gettablogourlnull();
					}
				} else {
					this.gettablogourlnull();
				}
			}).catch((error) => {
				this.gettablogourlnull();
			});
		}
		
		fetchUsers = () => {
			let url = `/users/get_user_info.json`;
			axios.get(url).then((response) => {
				if (response && response.data) {
					this.initCommonState(response.data)
					this.setState({
						tpmLoading: false
					})
					if (this.props.match.path === "/" && response.data.login) {
						this.props.history.push(`/users/${response.data.login}`);
					}
				}
			}).catch((error) => {
				console.log(error)
			})
		};
		//截取url 数据的
		foo = (url) => {
			var json = {};
			var regExp = /[\?\&](\w+)(=?)(\w*)/g;
			var arr;
			do {
				arr = regExp.exec(url);
				if (arr) {
					var key = arr[1];
					var value = arr[3];
					if (!arr[2])
						value = undefined;

					json[key] = value;
				}
			} while (arr);
			return json;
		};

		hideLoginDialog = () => {
			this.setState({
				isRender: false,
				isloginCancel: undefined
			})
		}

		showLoginDialog = () => {
			this.setState({
				isRender: true,
				isloginCancel: "iscancel"
			})
		}
		//验证登录是否成功方法
		checkIfLogin = () => {
			return this.state.current_user && this.state.current_user.login != ''
		}

		hideAccountProfile = () => {
			this.setState({
				AccountProfiletype: false
			})
		}

		showProfileCompleteDialog = () => {
			this.dialogObj = {}
			this.setState({
				AccountProfiletype: true
			})
		}
		showhideAccountPhoneemailDialog = () => {
			this.dialogObj = {}
			this.setState({
				AccountPhoneemailtype: true
			})
		}
		hideAccountPhoneemailtype = () => {
			this.setState({
				AccountPhoneemailtype: false
			})
		}
		//验证是否完善资料
		checkIfProfileCompleted = () => {
			return this.state.current_user && this.state.current_user.profile_completed
		}

		showaccountprofileDialog = () => {
			this.dialogObj = {
				content: '您需要去完成您的个人资料，才能使用此功能',
				okText: '立即完成',
				okHref: '/account/profile'
			}
			this.setState({
				AccountProfiletype: true,
			})
		}
		showProfessionalCertificationDialog = () => {
			this.dialogObj = {
				content: '您需要去完成您的职业认证，才能使用此功能',
				okText: '立即完成',
				okHref: '/account/certification'
			}
			this.setState({
				AccountProfiletype: true,
			})
		}
		checkIfProfessionalCertification = () => {
			return this.state.current_user && this.state.current_user.professional_certification
		}


		ShowOnlinePdf = (url) => {
			return axios({
				method: 'get',
				url: url,
				responseType: 'arraybuffer',
			}).then((result) => {
				var binaryData = [];
				binaryData.push(result.data);
				this.url = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" }));
				window.open(this.url);
			})
		}
		DownloadFileA = (title, url) => {
			let link = document.createElement('a');
			document.body.appendChild(link);
			link.href = url;
			link.download = title;
			//兼容火狐浏览器
			let evt = document.createEvent("MouseEvents");
			evt.initEvent("click", false, false);
			link.dispatchEvent(evt);
			document.body.removeChild(link);
		}

		DownloadOpenPdf = (type, url) => {
			type === true ? window.open(url) : window.location.href = url;
		}
		slowDownload = (url, tip) => {
			this._gLoadingTip = tip || '正在生成文件，请稍后...';
			this.setState({ globalLoading: true })
			const fileUrl = url;
			downloadFile({
				url: fileUrl,
				successCallback: (url) => {
					this.setState({ globalLoading: false })
					console.log('successCallback')
				},
				failCallback: (responseHtml, url) => {
					this.setState({ globalLoading: false })
					console.log('failCallback')
				}
			})
		}
		yslslowCheckresults = (tip) => {
			this._gLoadingTip = tip || '成绩计算中，请稍候...';
			this.setState({ globalLoading: true })
		}
		yslslowCheckresultsNo = () => {
			this.setState({ globalLoading: false })
		}

		showGlobalLoading = (tip) => {
			this._gLoadingTip = tip || '加载中，请稍后...';
			this.setState({ globalLoading: true })
		}
		hideGlobalLoading = () => {
			this.setState({ globalLoading: false })
		}

		MdifHasAnchorJustScorll = () => {
			//mdhash滚动
			let anchor = decodeURI(this.props.location.hash).replace('#', '');
			// 对应id的话, 滚动到相应位置
			if (!!anchor) {
				let anchorElement = document.getElementsByName(anchor);
				if (anchorElement) {
					if (anchorElement.length > 0) {
						anchorElement[anchorElement.length - 1].scrollIntoView();
					}
				}
			}
		}

		//跳转道描点的地方
		scrollToAnchor = (anchorName) => {
			if (anchorName) {
				// 找到锚点
				let anchorElement = document.getElementById(anchorName);
				// 如果对应id的锚点存在，就跳转到锚点
				if (anchorElement) {
					anchorElement.scrollIntoView();
				}
			}
		}

		render() {
			let { Footerdown, isRender, AccountProfiletype, AccountPhoneemailtype, current_user } = this.state;
			const common = {

				showLoginDialog: this.showLoginDialog,
				checkIfLogin: this.checkIfLogin,
				showProfileCompleteDialog: this.showProfileCompleteDialog,
				showhideAccountPhoneemailDialog: this.showhideAccountPhoneemailDialog,
				checkIfProfileCompleted: this.checkIfProfileCompleted,
				showaccountprofileDialog: this.showaccountprofileDialog,
				checkIfProfessionalCertification: this.checkIfProfessionalCertification,
				showProfessionalCertificationDialog: this.showProfessionalCertificationDialog,

				ShowOnlinePdf: (url) => this.ShowOnlinePdf(url),
				DownloadFileA: (title, url) => this.DownloadFileA(title, url),
				DownloadOpenPdf: (type, url) => this.DownloadOpenPdf(type, url),

				slowDownload: this.slowDownload,
				showGlobalLoading: this.showGlobalLoading,
				hideGlobalLoading: this.hideGlobalLoading,
				yslslowCheckresults: this.yslslowCheckresults,
				yslslowCheckresultsNo: this.yslslowCheckresultsNo,
				MdifHasAnchorJustScorll: this.MdifHasAnchorJustScorll,
				scrollToAnchor: this.scrollToAnchor
			};
			return (
				<div className="indexHOC">
					{isRender === true ? <LoginDialog
						Modifyloginvalue={() => this.hideLoginDialog()}
						{...this.props}
						{...this.state}
					/> : ""}
					{/* AccountProfile 也用作职业认证 */}
					{AccountProfiletype === true ? <AccountProfile
						hideAccountProfile={() => this.hideAccountProfile()}
						{...this.props}
						{...this.state}
						{...this.dialogObj}
					/> : ""}
					{/*验证是否注册手机邮箱*/}
					{AccountPhoneemailtype === true ? <AccountPhoneemail
						hideAccountProfile={() => this.hideAccountPhoneemailtype()}
						{...this.props}
						{...this.state}
						{...this.dialogObj}
					/> : ""}
					<NewHeader {...this.state} {...this.props}></NewHeader>
					<Spin spinning={this.state.globalLoading} delay={0} className="globalSpin"
						size="large"
						tip={this._gLoadingTip || "加载中..."}
					>
						<div className="newContainer newContainers">
							{
								current_user &&
								<WrappedComponent initCommonState={(user) => this.initCommonState(user)}
									{...this.props} {...this.state}
									{...common}
								>
								</WrappedComponent>
							}
							
						</div>
					</Spin>
					<NewFooter
						{...this.state} {...this.props}
						Footerdown={Footerdown}
					/>
				</div>
			);
		}
	}
}
