import React from 'react';
import Header from '../../forge/Head/Header';
import NewHeader from './NewHeader';
import NewFooter from './NewFooter';
import { downloadFile } from 'educoder';
import { getCurrentExpert } from 'src/military/expert/api';
import axios from 'axios';
import { Spin } 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, headFoot) {
	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,
				completeProfile:false,
				showCP:false,
				showNotice:true,
				gopage: undefined,
				Footerdown: 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 = () => {
			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
					})
					if(response.data && response.data.login){
						if(response.data.need_edit_info){
							this.setState({
								giteaVisible:true,
								email:response.data.email
							})
						}
					}
					if(response.data && response.data.login){
						if(response.data.need_edit_info){
							this.setState({
								giteaVisible:true,
								email:response.data.email
							})
						}
					}
					// if (this.props.match.path === "/" && response.data.login) {
					// 	this.props.history.push(`/users/${response.data.login}`);
					// }

					// 考虑到以后部分系统不会用到专家评审系统，所以这里没有使用Promise.All
					getCurrentExpert().then(res => {
						if(res){
							let isExpert = false;
							let expertId = '';
							let expertDraft = false;
							if (res && res.data && res.data.length) {
								for (const item of res.data) {
									if (item.status === 1) {
										isExpert = true;
										expertId = item.id;
									} else {
										expertDraft = true;
									}
								}
							}
							const newUser = { ...this.state.current_user, isExpert, expertId, expertDraft };
							this.setState({
								user: newUser,
								current_user: newUser
							});
						}
					}).catch((error) => {
						console.log(error)
					});
				}
			}).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
			})
		}

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

		render() {
			let { isRender , current_user , giteaVisible , email , completeProfile , showCP , showNotice , publicNav , mygetHelmetapi ,Footerdown} = 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} onOk={this.onOk}/>
					<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> */}
					<NewHeader {...this.state} {...this.props} {...common}></NewHeader>
					<Spin spinning={this.state.globalLoading} delay={0} className="globalSpin"
						size="large" tip={this._gLoadingTip || "加载中..."}
					>
						<div className="newContainer newContainers">
							{!publicNav && <div style={{height:"70px"}}></div> }
							{
								current_user &&
								<WrappedComponent initCommonState={(user) => this.initCommonState(user)}
									{...this.props} {...this.state} {...common} >
								</WrappedComponent>
							}
						</div>
					</Spin>
					{
						headFoot && headFoot.noFooter ? "" :
							<NewFooter
								{...this.state} {...this.props}
								Footerdown={Footerdown}
							/>
					}
				</div>
			);
		}
	}
}
