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

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,
				email:undefined,
				completeProfile:false,
				showCP:false,
				showNotice:true,
				gopage: undefined,
				giteaVisible:false
			}
		}

		// 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();
			window.scrollTo(0,0);
		}


		//获取数据为空的时候
		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();
						// }
					}
				}
			}).catch((error) => {
				// this.gettablogourlnull();
			});
		}
		
		fetchUsers = () => {
			if (this.props.match.path === "/") {
				this.setState({
					publicNav:true
				})
			}else{
				this.setState({
					publicNav:false
				})
			}
			let url = `/users/get_user_info.json`;
			axios.get(url).then((response) => {
				if (response && response.data) {
					this.initCommonState(response.data)
					this.setState({
						tpmLoading: false,
						completeProfile:response.data.profile_completed
					})
					console.log("11：",response.data);
					if(response.data && response.data.login){
						if(!response.data.has_gitea_user){
							this.setState({
								giteaVisible:true,
								email:response.data.email
							})
						}else{
							this.setState({
								giteaVisible:false
							})
						}
						// 如果处于登录状态，且刚刚打开，那么跳到个人主页
						// if(this.props.match.path === "/" && this.props.history.length===2){
						// 	this.props.history.push(`/${response.data.login}`)
						// }
					}else{
						this.setState({
							giteaVisible:false
						})
					}
				}
			}).catch((error) => {
				console.log(error)
			})
		};
		hideLoginDialog = () => {
			this.setState({
				isRender: false,
				isloginCancel: undefined
			})
		}

		showLoginDialog = (gopage) => {
			this.setState({
				isRender: true,
				isloginCancel: "iscancel",
				gopage: gopage,
			})
		}
		//验证登录是否成功方法
		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=>{})
		}
		hideSystemNotice=()=>{
			this.setState({
				showNotice:false
			})
			this.getAppdatausr();
		}

		showCompeleteDialog=()=>{
			this.setState({
				showCP:true
			})
		}

		render() {
			let { isRender , current_user , giteaVisible , email , completeProfile , showCP , showNotice , publicNav , mygetHelmetapi } = this.state;
			const common = {
				showLoginDialog: this.showLoginDialog,
				checkIfLogin: this.checkIfLogin,
				resetUserInfo:this.fetchUsers,
				showCompeleteDialog:this.showCompeleteDialog
			};
			return (
				<div className="indexHOC">
					<SystemNotice 
						showNotice={showNotice}
						system_notification={mygetHelmetapi && mygetHelmetapi.system_notification} 
						history={this.props.history} 
						login={current_user && current_user.login}
						hideSystemNotice={this.hideSystemNotice}
					/>
					<EducoderAccount 
						visible={giteaVisible} 
						email={email} 
						isCancel={false}
						onOk={this.onOk} 
						onCancel={()=>{
							message.info('未填邮箱及密码,可能影响协同开发部分功能的使用');this.setState({giteaVisible:false})
						}}
						showNotification={this.props.showNotification}
						current_user={current_user}
					/>
					<ProfileModal 
						visible={!completeProfile && showCP} 
						onCancel={()=>{this.setState({showCP:false})}}
						history={this.props.history}
					/>
					{isRender === true ? <LoginDialog
						Modifyloginvalue={() => this.hideLoginDialog()}
						{...this.props}
						{...this.state}
					/> : ""}
					<Header {...this.state} {...this.props} {...common} publicNav={publicNav}></Header>
					<Spin spinning={this.state.globalLoading} delay={0} className="globalSpin"
						size="large" tip={this._gLoadingTip || "加载中..."}
					>
						<div className="newContainer newContainers">
							<div style={{height:"72px"}}></div>
							<div style={{minHeight:"60vh"}}>
								{
									current_user &&
									<WrappedComponent initCommonState={(user) => this.initCommonState(user)}
										{...this.props} {...this.state} {...common} >
									</WrappedComponent>
								}
							</div>
						</div>
					</Spin>
					<NewFooter {...this.state} {...this.props} />
				</div>
			);
		}
	}
}
