import React, { Component } from 'react';
import AccountProfile from "../../modules/user/AccountProfile";
import { getImageUrl , openNewWindow } from 'educoder';
import axios from 'axios';
import cookie from 'react-cookies';
import { notification , Dropdown ,Popover, Menu,Badge, Input, Divider } from 'antd';
import { Link } from 'react-router-dom';

import LoginDialog from '../../modules/login/LoginDialog';
import HeadSearch from '../Component/HeadSearch';

import AddProjectModal from './AddProjectModal';
import '../../modules/tpm/TPMIndex.css';
import CheckProfile from '../Component/ProfileModal/Profile';

import './header.scss';
import Engineer from './Engineer';
const $ = window.$
// TODO 这部分脚本从公共脚本中直接调用
const { Search } = Input;
window._header_componentHandler = null;
// 非trustie链接则新开页跳转
const isPath= window.location.hostname ==='code.educoder.net' || window.location.hostname==='testforgeplus.educoder.net';
const str = ['www.trustie.net','forgeplus.trustie.net','forum.trustie.net','testforgeplus.trustie.net']
class NewHeader extends Component {
  constructor(props) {
    super(props)
    this.state = {
      Addcoursestypes: false,
      tojoinitemtype: false,
      tojoinclasstitle: undefined,
      rolearr: ["", ""],
      Checkboxteacherchecked: false,
      Checkboxstudentchecked: false,
      Checkboxteachingchecked: false,
      Checkboxteachertype: false,
      Checkboxteachingtype: false,
      code_notice: false,
      RadioGroupvalue: undefined,
      submitapplications: false,
      isRender: false,
      showTrial: false,
      setevaluatinghides: false,
      occupation: 0,
      mydisplay: false,
      // headtypesonClickbool: false,
      // headtypess: "/",
      settings: null,
      visiblemyss: false,
      openSearch:false,
      visible:false,  //浮动消息框展示控制
      QQVisible:false,
      educoderBanner:undefined
    }
  }
  componentDidMount() {
    this.geturlsdata();
    window._header_componentHandler = this;
    this.getEducoderSetting();
    try {
      window.sessionStorage.setItem("yslgeturls", JSON.stringify(window.location.href))
    } catch (e) {}
  }

  getEducoderSetting=()=>{
    const url = `https://data.educoder.net/api/setting.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        this.setState({
          educoderBanner:result.data.setting && result.data.setting.navbar
        })
      }
    }).catch(error=>{})
  }

  SearchInput = (open,item)=>{
    if(open){
      return(
        <div
          onBlur={() => {
            setTimeout(() => {
              this.setState({
                openSearch:false
              })
            }, 300)
          }}
        >
          <Search placeholder="实践课程/教学课堂/实践项目/交流问答"
            className={`search-input mr20`}
            onSearch={(value)=>this.onGlobalSearch(value,item)}
            autoFocus={true}
          />
        </div>
      )
    }else{
      return <i className="iconfont icon-sousuo font-18 color-white ml30" onClick={() => {
        this.setState({openSearch:true})
      }} />
    }
  }

  onGlobalSearch=(value,item)=>{
    window.location.href=`${item}?value=` + value;
  }

  openNotification = (messge) => {
    notification.open({
      message: "提示",
      description:
        messge,
    });
  };

  componentWillReceiveProps(newProps, oldProps) {
    this.setState({
      user: newProps.user
    })
  }

  submitsubmitapplications = () => {
    let {
      submitapplicationssum,
      submitapplicationsvaluedata
    } = this.state;
    this.setState({
      submitapplications: false,
      RadioGroupvalue: undefined
    })
    if (submitapplicationssum === 0) {
      if (submitapplicationsvaluedata !== undefined) {
        window.location.href = "/courses/" + submitapplicationsvaluedata;
      }
    } else if (submitapplicationssum === 1) {
      if (submitapplicationsvaluedata !== undefined) {
        window.location.href = "/projects/" + submitapplicationsvaluedata;
      }
    }
  }

  educoderlogin = () => {
    //登录账号
    this.setState({
      isRender: true
    })
  }
  educoderloginysl = () => {
    //退出账号时清除登录页面的下次自动登录（用户再次打开登录页面时下次自动登录框不勾选）
    cookie.remove("autologin");
    //退出账号
    var url = `/accounts/logout.json`;
    axios.get((url)).then((result) => {
      if (result !== undefined) {
        window.location.href = "/";
      }
    }).catch((error) => {
      console.log(error);
    })
  }

  hideAddcoursestypes = () => {
    this.setState({
      Addcoursestypes: false
    })
  };
  HideAddcoursestypess = (i) => {
    this.setState({
      Addcoursestypes: false,
      mydisplay: true,
      occupation: i,
    })
  };
  ModalCancelsy = () => {
    this.setState({
      mydisplay: false,
    })
  };


  hidetojoinclass = () => {
    this.setState({
      tojoinclasstype: false,
      tojoinitemtype: false,
      tojoinclasstitle: undefined,
      rolearr: ["", ""],
      Checkboxteacherchecked: false,
      Checkboxstudentchecked: false,
      Checkboxteachingchecked: false,
      Checkboxteachertype: false,
      Checkboxteachingtype: false,
      code_notice: false,
      checked_notice: false,
      RadioGroupvalue: undefined
    })
  }

  // 关闭
  cancelModulationModels = () => {
    this.setState({ isRenders: false })
  }

  setevaluatinghides = () => {
    this.setState({
      setevaluatinghides: true
    })
  }
  //修改登录方法
  Modifyloginvalue = () => {
    this.setState({
      isRender: false,
    })
  }

  hideAccountProfile = () => {
    this.setState({
      AccountProfiletype: false
    })
  };
  // headtypesonClick = (url, bool) => {
  //   this.setState({
  //     headtypess: url,
  //     headtypesonClickbool: bool,
  //   })
  // }
  //获取数据为空的时候
  gettablogourlnull = () => {
    this.setState({
      settings: undefined
    });
    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);
  }

  handleVisibleChanges = (boll) => {
    this.setState({
      visiblemyss: boll,
    })
  }

  geturlsdata = () => {
    let url = "/setting.json";
    axios.get(url).then((response) => {
      if (response && response.data) {
        this.setState({ settings: response.data.setting });
        localStorage.setItem('chromesetting', JSON.stringify(response.data.setting));
        localStorage.setItem('chromesettingresponse', JSON.stringify(response));
      } else {
        this.gettablogourlnull();
      }
    }).catch((error) => {
      this.gettablogourlnull();
    });
  }

  matchpaths = (url) => {
    const { match } = this.props;
    const isDev = window.location.port == 3007;
    const isdev2= isDev ?'https://testforgeplus.trustie.net':`https://${window.location.hostname}`;
    let str = "";
    if(url.indexOf("http")>-1){
      str = isdev2+match.url;
    }else{
      str = match.path;
    }
    if (url && (str === url || (str === url+'/'))) {
      return true;
    }else {
      return false;
    }
  }
  
  checkProfile=(url)=>{
    const { showCompeleteDialog , completeProfile } = this.props;
    if(!completeProfile){
      showCompeleteDialog && showCompeleteDialog();
    }else{
      window.location.href(url);
    }
  }

  addMenu=(list)=>{
    return(
      list && list.length >0 && 
      <div className="dropdownFlex">
        <Menu> 
          {
            list.map((item,key)=>{
              return(
                (item.name !=="加入课堂" && item.name !=="加入开发项目" && item.name !=="新建开发项目") && 
                <Menu.Item key={item.name+key}>
                  <CheckProfile {...this.props} sureFunc={()=>{window.location.href=item.url}}>{item.name}</CheckProfile>
                </Menu.Item>
              )
            })
          }
        </Menu>
        <Menu>
          {
            list.map((item,key)=>{
              return(
                (item.name ==="新建开发项目") && 
                <Menu.Item key={item.name+key}>
                  <CheckProfile {...this.props} sureFunc={()=>{window.location.href=item.url}}>{item.name}</CheckProfile>
                </Menu.Item>
              )
            })
          }
          <Menu.Item>
            <AddProjectModal {...this.props} showNotification={this.props.showNotification}/>
          </Menu.Item>
        </Menu>
      </div>
    )
  }

  renderMenu=(personal)=>{
    const { current_user } = this.props;
    return(
      <Menu className="currentMenu">
        <Menu.Item>
          <span className="currentName" title={current_user && current_user.username}>{current_user && current_user.username}</span>
        </Menu.Item>
          {
            personal && personal.length > 0 && personal.map((item,key)=>{
              return(
                <li key={key}><a href={item.url} target="_blank">{item.name}</a></li>
              )
            })
          }
          {/* <li><Link to={`/settings/profile`}>设置</Link></li> */}
        <Menu.Item><a onClick={() => this.educoderloginysl()}>退出</a></Menu.Item>
      </Menu>
    )
  }

  handleVisibleChange = visible => {
    this.setState({ visible });
  };

  turntoEngineer=(url)=>{
    const { current_user } = this.props;
    if(current_user && current_user.login){
      if(url){
        window.location.href=url;
      }else{
        this.setState({
          QQVisible:true
        })
      }
    }else{
      this.educoderlogin();
    }
  }

  setQQVisible=()=>{
    this.setState({
      QQVisible:false
    })
  }

  menus=(item)=>{
    return(
      <div className="downMenus">
        {
          item.map((i,k)=>{
            return(
              !i.hidden && <li onClick={()=>{window.location.href=this.checkLink(i.link)}}>
                {k!==0 &&<Divider />}
                <aside className="font-16 color-ooo">{i.name}</aside>
                <div className="font-14" style={{color:"rgb(159, 167, 179)",whiteSpace:'nowrap'}}>{i.content}</div>
              </li>
            )
          })
        }
      </div>
    )
  }

  checkLink=(link)=>{
    if(link.indexOf("http")>-1){
      return link;
    }else{
      return `https://www.educoder.net${link}`;
    }
  }

  render() {
    let current_user = this.props.user;
    let {
      QQVisible,
      AccountProfiletype,
      user,
      isRender,
      settings,
      visible,
      educoderBanner
    } = this.state;
    let search_url = settings && settings.common && settings.common.search;
    return (
      <div className={`newHeaders`} id="nHeader">
        <Engineer QQVisible={QQVisible} setQQVisible={this.setQQVisible}/>
        <div className="headerContent">
          {isRender === true ?
            <LoginDialog
              {...this.props}
              {...this.state}
              Modifyloginvalue={() => this.Modifyloginvalue()}
            /> : ""}

          {AccountProfiletype === true ?
            <AccountProfile
              hideAccountProfile={() => this.hideAccountProfile()}
              {...this.props}
              {...this.state}
            /> : ""}
            {/* <div style={{width:"78px"}}>
              {
                publicNav &&
                <a href={'https://www.ccf.org.cn/'} className={"fl"}>
                  <img src={MainLogo} alt="ccf" width="63px"/>
                </a>
              }
            </div> */}
            {/* {
              settings && settings.nav_logo_url ?
              <a href={settings && settings.new_course.default_url} className={"fl mr50"}>
                <img alt="可控开源社区" className="logoimg" src={getImageUrl(`/${settings.nav_logo_url}`)}></img>
              </a>
              :
              ""
            } */}
          <div className="head-nav pr" id={"head-navpre1"}>
            {
              educoderBanner && educoderBanner.length > 0 ?
              <ul id="header-nav">
                {
                  educoderBanner.map((item, key) => {
                    var new_link = item.link;
                    var is_hidden = item.hidden;
                    return (
                      <li key={key} onClick={() => this.headtypesonClick(item.link, true)} className={`${((isPath && item.name === "大学开源") || this.matchpaths(item.link) === true) ? 'pr active' : 'pr'}`} style={!is_hidden ? { display: 'block' } : { display: 'none' }}>
                        {
                          item.subitem && item.subitem.length>0 ?
                          <Dropdown overlay={this.menus(item.subitem)}>
                            <div className="namediv">
                              <a href={this.checkLink(new_link)} ><div dangerouslySetInnerHTML={{ __html: item.name }}></div> </a>
                              <i className="iconfont icon-xiala1"></i>
                            </div>
                          </Dropdown>
                          :
                          <a href={this.checkLink(new_link)} ><div dangerouslySetInnerHTML={{ __html: item.name }}></div></a>
                        }
                      </li>
                    )
                  })
                }
                {/* {
                  settings && settings.engineer_url !== undefined ?
                  <li>
                    <a onClick={()=>this.turntoEngineer(settings.engineer_url)}>工程认证</a>
                  </li>
                  :""
                } */}
              </ul>
            : ""
            }
          </div>
          <div className="head-right">
            { search_url && <HeadSearch {...this.props} searchUrl={settings && settings.common && settings.common.search}/>}
            {
              current_user && (current_user.main_site || current_user.login) && (settings && settings.add && settings.add.length>0)?
              <Dropdown overlay={this.addMenu(settings && settings.add)} placement="bottomRight">
                <i className="iconfont icon-tianjiafangda color-white font-18 mr15 ml15" style={{marginBottom:"3px"}}/>
              </Dropdown>:""
            }
            
            { (settings && settings.common && settings.common.notice) && (current_user && current_user.login)?
              <a href={settings.common.notice} className="message-icon">
                {current_user &&
                  <i className="iconfont icon-xiaoxilingdang color-white ml15 mr15"></i>
                }
              </a>
              : ""
            }
          </div>
          {!user || (user && !user.login)  ?
            <span className="font-15 ml30">
              <a onClick={() => this.educoderlogin()} className="mr5 color-white">登录</a>
              {
                settings && settings.common && settings.common.register &&
                <span><em className="vertical-line"></em><a className="ml5 color-white" href={`${settings.common.register}`} target="_blank">注册</a></span>
              }
            </span>
            :
            <Dropdown placement={`bottomRight`} overlay={this.renderMenu(settings && settings.personal)}>
              <div className="ml15" style={{display:"flex"}}>
                <a href={`/${this.props.current_user  && this.props.current_user.login}`}>
                  <img alt="头像" src={getImageUrl(`/${user.image_url}`)} className="currentImg"></img>
                </a>
                <i className="iconfont icon-xiala1 font-14 ml3 mt5 mr3" style={{color:"#979797"}}></i>
              </div>
            </Dropdown>
          }
        </div>
      </div>
    );
  }
}

export default NewHeader;
