import React, { Component } from 'react';
import AccountProfile from "../../modules/user/AccountProfile";
import { getImageUrl } from 'educoder'
import axios from 'axios';
import { Modal, Input, message, notification , Dropdown , Menu } from 'antd';

import LoginDialog from '../../modules/login/LoginDialog';
import GotoQQgroup from '../../modal/GotoQQgroup'

import '../../modules/tpm/TPMIndex.css';
import logo from '../../modules/tpm/images/logo.png';

import './header.scss';
const $ = window.$
// TODO 这部分脚本从公共脚本中直接调用
const { Search } = Input;
let old_url;

window._header_componentHandler = null;
// 非trustie链接则新开页跳转
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,
      checked_notice: false,
      RadioGroupvalue: undefined,
      submitapplications: false,
      isRender: false,
      showSearchOpentype: false,
      showTrial: false,
      setevaluatinghides: false,
      occupation: 0,
      mydisplay: false,
      headtypesonClickbool: false,
      headtypess: "/",
      settings: null,
      goshowqqgtounp: false,
      visiblemyss: false,
      openSearch:false,
    }
  }
  componentDidMount() {
    // this.getAppdata();
    this.geturlsdata();
    window._header_componentHandler = this;

    //下拉框的显示隐藏
    var hoverTimeout;
    var hoveredPanel;
    $(".edu-menu-panel").hover(function () {
      if (hoverTimeout) { // 一次只显示一个panel
        if (hoveredPanel && hoveredPanel !== this) {
          $(hoveredPanel).find(".edu-menu-list").hide()
        }
        clearTimeout(hoverTimeout);
        hoverTimeout = null;
      }
      hoveredPanel = this;
      $(this).find(".edu-menu-list").show();
    }, function () {
      var that = this;
      // 延迟hide
      hoverTimeout = setTimeout(function () {
        $(that).find(".edu-menu-list").hide();
      }, 800)

    });
    //获取游览器地址
    try {
      window.sessionStorage.setItem("yslgeturls", JSON.stringify(window.location.href))
    } catch (e) {}
  }

  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
    })
    if (newProps.Headertop !== undefined) {
      old_url = newProps.Headertop.old_url
    }
  }
  getCookie = (key) => {
    var arr, reg = RegExp('(^| )' + key + '=([^;]+)(;|$)');
    if (arr === document.cookie.match(reg))
      return decodeURIComponent(arr[2]);
    else
      return null;
  }

  delCookie = (name) => {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = this.getCookie(name);
    if (cval != null) {
      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
  }
  onLogout = () => {
    const url = `/accounts/logout.json`
    this.delCookie("autologin_trustie")
    axios.get(url, {
    }).then((response) => {
      if (response.data.status === 1) {
        this.setState({
          user: undefined
        })
        window.location.href = "/login"
        message.success('退出成功');
      }
    });
  }

  tojoinclass = () => {
    let { user } = this.state;
    if (user === undefined) {
      this.setState({
        isRender: true
      })
      return
    }
    if (user && user.login === "") {
      this.setState({
        isRender: true
      })
      return;
    }
    if (user && user.profile_completed === false) {
      this.setState({
        AccountProfiletype: true
      })
      return;
    }
    this.setState({
      Addcoursestypes: true,
    })
  }

  tojoinitem = () => {
    if (this.props.user && this.props.user.email === undefined || this.props.user && this.props.user.email === null || this.props.user && this.props.user.email === "") {
      this.openNotification("请先绑定邮箱，谢谢");
      return
    }
    let { user } = this.state;
    if (user === undefined) {
      this.setState({
        isRender: true
      })
      return
    }
    if (user && user.login === "") {
      this.setState({
        isRender: true
      })
      return;
    }

    if (user && user.profile_completed === false) {
      this.setState({
        AccountProfiletype: true
      })
      return;
    }

    this.setState({
      tojoinitemtype: true
    })
  }


  submitstatevalue = (sum, value, data) => {
    this.setState({
      Addcoursestypes: false,
      tojoinitemtype: false,
      tojoinclasstitle: undefined,
      rolearr: ["", ""],
      Checkboxteacherchecked: false,
      Checkboxstudentchecked: false,
      Checkboxteachingchecked: false,
      Checkboxteachertype: false,
      Checkboxteachingtype: false,
      code_notice: false,
      checked_notice: false,
      submitapplicationssum: sum,
      submitapplications: true,
      submitapplicationsvalue: value,
      submitapplicationsvaluedata: data,
      RadioGroupvalue: undefined
    })
  }

  onChangeRadioGroup = (e) => {
    this.setState({
      RadioGroupvalue: e.target.value,
    });
  }

  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;
      }
    }
  }

  hidesubmitapplications = () => {
    this.setState({
      Addcoursestypes: false,
      tojoinitemtype: false,
      tojoinclasstitle: undefined,
      rolearr: ["", ""],
      Checkboxteacherchecked: false,
      Checkboxstudentchecked: false,
      Checkboxteachingchecked: false,
      Checkboxteachertype: false,
      Checkboxteachingtype: false,
      code_notice: false,
      checked_notice: false,
      submitapplications: false,
      RadioGroupvalue: undefined
    })
  }
  educoderlogin = () => {
    //登录账号
    this.setState({
      isRender: true
    })
  }
  educoderloginysl = () => {
    //退出账号
    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) => {
    console.log("调用了");
    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,
    })
  }

  getAppdata = () => {
    try {
      var chromesettingArray = JSON.parse(localStorage.getItem('chromesetting'));
      var chromesettingresponseArray = JSON.parse(localStorage.getItem('chromesettingresponse'));
      this.setState({
        settings: chromesettingArray
      });
      if (chromesettingArray.tab_logo_url) {
        this.gettablogourldata(chromesettingresponseArray);
      } else {
        this.gettablogourlnull();
      }
    } catch (e) {
      this.geturlsdata();
    }
  };

  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));
        try {
          if (response.data.setting.tab_logo_url) {
            this.gettablogourldata(response);
          } else {
            this.gettablogourlnull();
          }
        } catch (e) {
          this.gettablogourlnull();
        }
      } else {
        this.gettablogourlnull();
      }
    }).catch((error) => {
      this.gettablogourlnull();
    });
  }

  matchpaths = (url) => {
    const { match } = this.props;
    if(url){
      if (match.path.indexOf(url) > -1) {
        return true
      }else {
        return false
      }
    }
  }


  // 处理弹框
  setgoshowqqgtounp = (bool) => {
    this.setState({
      goshowqqgtounp: bool
    })
  }

  addMenu=(list)=>{
    return(
      list && list.length >0 && 
      <div className="dropdownFlex">
        <Menu> 
          {
            list.map((item,key)=>{
              return(
                (item.name !=="加入课堂" && item.name !=="加入开发项目") && <Menu.Item><a href={item.url}>{item.name}</a></Menu.Item>
              )
            })
          }
        </Menu>
      </div>
    )
  }

  render() {
    const { match} = this.props;
    let current_user = this.props.user;
    let { Addcoursestypes,
      tojoinitemtype,
      tojoinclasstitle,
      code_notice,
      checked_notice,
      AccountProfiletype,
      submitapplications,
      submitapplicationsvalue,
      user,
      isRender,
      showSearchOpentype,
      headtypesonClickbool,
      headtypess,
      settings,
      goshowqqgtounp,
      openSearch,
    } = this.state;
    /*用户名称  用户头像url*/
    let activeIndex = false;
    let activeForums = false;
    let activeShixuns = false;
    let activePaths = false;
    let coursestype = false;
    let activePackages = false;
    let activeMoopCases = false;
    let activeCompetitions = false;

    if (match.path === '/forums') {
      activeForums = true;
    } else if (match.path.startsWith('/shixuns')) {
      activeShixuns = true;
    } else if (match.path.startsWith('/paths')) {
      activePaths = true;
    } else if (match.path.startsWith('/courses')) {
      coursestype = true;
    } else if (match.path.startsWith('/crowdsourcing')) {
      activePackages = true;
    } else if (match.path.startsWith('/moop_cases')) {
      activeMoopCases = true;
    } else if (match.path.startsWith('/competitions')) {
      activeCompetitions = true;
    } else {
      activeIndex = true;
    }

    let headtypes = '/';
    if (settings) {
      if (settings.navbar) {
        if (settings.navbar.length > 0) {
          if (match.path === '/') {
            if (headtypesonClickbool === false) {
              headtypes = undefined;
            } else {
              headtypes = headtypess;
            }
          } else {
            for (var i = 0; i < settings.navbar.length; i++) {
              if (match.path === settings.navbar[i].link) {
                headtypes = settings.navbar[i].link;
                break;
              }
            }
          }
        }
      }
    }
    let shixuntype = false;
    let pathstype = false;
    let coursestypes = false;
    if (this.props && this.props.mygetHelmetapi != null) {
      let shixun = "/shixuns";
      let paths = "/paths";
      let courses = "/courses";
      this.props.mygetHelmetapi.navbar.map((item, key) => {
        var reg = RegExp(item.link);
        if (shixun.match(reg)) {
          if (item.hidden === true) {
            shixuntype = true
          }
        }
        if (paths.match(reg)) {
          if (item.hidden === true) {
            pathstype = true
          }
        }
        if (courses.match(reg)) {
          if (item.hidden === true) {
            coursestypes = true
          }
        }
      })
    }

    let search_url = settings && settings.common && settings.common.search;
    let notice_url = settings && settings.common && settings.common.notice;
    return (
      <div className="newHeaders" id="nHeader">
        <div className="headerContent">
          {isRender === true ?
            <LoginDialog
              {...this.props}
              {...this.state}
              Modifyloginvalue={() => this.Modifyloginvalue()}
            /> : ""}

          {AccountProfiletype === true ?
            <AccountProfile
              hideAccountProfile={() => this.hideAccountProfile()}
              {...this.props}
              {...this.state}
            /> : ""}
          {
            goshowqqgtounp === true ?
            <GotoQQgroup {...this.state} {...this.props} setgoshowqqgtounp={(bool) => this.setgoshowqqgtounp(bool)}></GotoQQgroup>
            :""
          }
          {
            settings && settings.nav_logo_url ?
            <a href={settings && settings.new_course.default_url} className={"fl mr30"} style={{minWidth:"45px"}}>
              <img alt="可控开源社区" className="logoimg" style={{ heigth: "40px" }} src={getImageUrl(`/${settings.nav_logo_url}`)}></img>
            </a>
            :
            ""
          }
          <div className="head-nav pr" id={"head-navpre1"}>
            {
              settings && settings.navbar && settings.navbar.length > 0 ?
              <ul id="header-nav">
                {
                  settings.navbar && settings.navbar.map((item, key) => {
                    var new_link = item.link;
                    var user_login = this.props.user && this.props.user.login;
                    var is_hidden = item.hidden
                    if (new_link && (new_link.indexOf("courses") > -1 || new_link.indexOf("contests") > -1)) {
                      if (user_login) {
                        if (new_link.indexOf("courses") > -1) {
                          new_link = new_link.replace(/courses/g, "users/" + user_login + "/courses")
                        } else if (new_link.indexOf("contests") > -1) {
                          new_link = new_link.replace(/contests/g, "users/" + user_login + "/contests")
                        }
                      } else {
                        is_hidden = true
                      }
                    }
                    if (user_login && (new_link && new_link.indexOf("homes") > -1)) {
                      new_link = new_link.replace(/homes/g, "users/" + user_login + "/user_activities")
                    }
                    
                    var waiLian = (new_link && str.filter(item=>new_link.indexOf(item)>-1) );
                    var wl = waiLian && waiLian.length>0;
                    return (
                      <li key={key} onClick={() => this.headtypesonClick(item.link, true)} className={`${this.matchpaths(item.link) === true ? 'pr active' : 'pr'}`} style={!is_hidden ? { display: 'flex' } : { display: 'none' }}>
                        <a href={new_link} target={wl ? "_self":"_blank"}>{item.name}</a>
                      </li>
                    )
                  })
                }
              </ul>
            : ""
            }
          </div>
          <div className="head-right">
            {search_url ? this.SearchInput(openSearch,search_url):""}
            {
              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 ml30"></i>
              </Dropdown>:""
            }
            
            {this.props.user && this.props.user.login && notice_url ?
              <div className="ml30 edu-menu-panel">
                {user && user.login &&
                  <a href={`${notice_url}`} style={{ position: 'relative' }}>
                    <i className="iconfont icon-xiaoxilingdang color-white"></i>
                    <span className="newslight" style={{ display: this.props.Headertop === undefined ? "none" : this.props.Headertop.new_message === true ? "block" : "none" }}>
                    </span>
                  </a>
                }
              </div>:""
            }
            <Modal
              keyboard={false}
              title="提示"
              visible={submitapplications}
              closable={false}
              footer={null}
            >
              <div className="task_popup_con ml30">
                <div className="mr15">
                  <ul>
                    <div className="task-popup-content">
                      <p className="task-popup-text-center font-16">
                        {submitapplicationsvalue}
                      </p>
                    </div>
                    <li className="clearfix mt10 edu-txt-center">
                      <a className="task-btn mr10"
                        onClick={this.hidesubmitapplications}>取消</a>
                      <a
                        className="task-btn task-btn-orange ml20"
                        onClick={this.submitsubmitapplications}>确定</a>
                    </li>
                  </ul>
                </div>
              </div>
            </Modal>
          </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>
            :
            <div className="ml30 edu-menu-panel" style={{ height: "70px", lineHeight: "70px" }}>
              <a href={`/users/${this.props.current_user === undefined ? "" : this.props.current_user.login}/courses`}>
                <img alt="头像" className="radius" height="34" id="nh_user_logo" name="avatar_image" src={getImageUrl(`/${user.image_url}`)} width="34">
                </img>
              </a>
              <ul className="edu-menu-list" style={{ top: '60px', textAlign: 'center' }}>
                <li className="bor-bottom-greyE" style={{cursor:"default",background:"#fff"}}>{this.props.current_user.username}</li>
                {
                  settings && settings.personal && settings.personal.length > 0 && settings.personal.map((item,key)=>{
                    return(
                      <li key={key}><a href={item.url} target="_blank">{item.name}</a></li>
                    )
                  })
                }
                <li className="bor-top-greyE">
                  <a onClick={() => this.educoderloginysl()}>退出</a>
                </li>
              </ul>
            </div>
          }
        </div>
      </div>
    );
  }
}

export default NewHeader;
