import React from 'react';
import Header from '../../forge/Head/Header'
import NewFooter from '../../forge/Head/Footer';
import axios from 'axios';
import { Spin } from 'antd';
import './TPMIndex.css';
import LoginDialog from '../login/LoginDialog';
import EducoderAccount from '../../forge/Component/EducoderAccount';

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,

				isRender: false,
				globalLoading: false,
				dataquerys: {},
				isloginCancel: undefined,
				mygetHelmetapi: null,
				giteaVisible:false,
				email:undefined
			}
		}

		// 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 = "没有找到该页面";
			}

			///请求定制化的信息
			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}`);
					}
					if(response.data && response.data.login){
						if(response.data.need_edit_info){
							this.setState({
								giteaVisible:true,
								email:response.data.email
							})
						}
					}
				}
			}).catch((error) => {
				console.log(error)
			})
		};
		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 != ''
		}

		onOk =(values)=>{
			let url = `/users/sync_user_info.json`;
			const { current_user } = this.state;
			axios.post(url,{
				login:current_user && current_user.login,
				...values
			}).then(result=>{
				if(result && result.data && result.data.status === 0){
					this.setState({
						giteaVisible:false,
						email:undefined
					})
					window.location.reload();
				}
			}).catch(error=>{})
		}


		render() {
			let { isRender , current_user , giteaVisible , email } = this.state;
			const common = {
				showLoginDialog: this.showLoginDialog,
				checkIfLogin: this.checkIfLogin,
			};
			return (
				<div className="indexHOC">
					<EducoderAccount visible={giteaVisible} email={email} onOk={this.onOk}/>
					{isRender === true ? <LoginDialog
						Modifyloginvalue={() => this.hideLoginDialog()}
						{...this.props}
						{...this.state}
					/> : ""}
					<Header {...this.state} {...this.props}></Header>
					<Spin spinning={this.state.globalLoading} delay={0} className="globalSpin"
						size="large" tip={this._gLoadingTip || "加载中..."}
					>
						<div className="newContainer newContainers">
							<div style={{height:"70px"}}></div>
							{
								current_user &&
								<WrappedComponent initCommonState={(user) => this.initCommonState(user)}
									{...this.props} {...this.state} {...common} >
								</WrappedComponent>
							}
						</div>
					</Spin>
					<NewFooter {...this.state} {...this.props} />
				</div>
			);
		}
	}
}
