/* eslint-disable */
import React from 'react';
import css from './search.scss'
import Type from '../type/type'
import Tip from '../tip/tip'
import Content from '../content/content'
import {en, zh} from '../../assets/language/language'

export default class Search extends React.Component {
  constructor(props) {
    super(props)
    // this.initTab = this.getTab(props.match.path)
    this.state = {
      inputFocus: false,
      tab: 'all',
      // tab: this.initTab,
      kw: '',
      contentShow: false,
      contentStyle: {},
      currentUserRecord: [],
      globalUserRecord: [],
      kwChanged: false
    }
    this.lang = props.language === 'en' ? en : zh
    this.search = React.createRef()
    this.main = React.createRef()
  }

  getTab = (path = '') => {
    const num = ['chat', 'contact', 'group', 'sub'].indexOf(path.slice(1))
    if (num >= 0) {
      return ['msg', 'tel', 'friend', 'news'][num]
    } else {
      return 'all'
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this.resize, false)
    document.addEventListener('mousedown', this.onOutsideClick, false)
    document.addEventListener('mousedown', this.onMainOutside, false)
  }

  componentWillReceiveProps(next) {
    const {kw} = this.props
    if (kw && kw !== next.kw) {
      this.searchRecord(next.kw)
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize, false)
    document.removeEventListener('mousedown', this.onOutsideClick, false)
    document.removeEventListener('mousedown', this.onMainOutside, false)
  }

  resize = () => {
    const frame = document.getElementById('app') || document.body
    const frameClient = frame.getBoundingClientRect()
    const searchClient = this.search.current.getBoundingClientRect()
    const contentStyle = {
      width: `${frameClient.width - 70}px`,
      height: `${frameClient.height - 40}px`,
      top: '33px',
      left: `${frameClient.left - searchClient.left + 70}px`
    }

    this.setState({
      contentStyle
    })
  }

  //输入框内容变化
  onType = (e) => {
    const value = e.target.value.replace(/(^\s*)|(\s*$)/g, "")
    if (value) {
      this.setState({
        kw: value,
        contentShow: true,
        kwChanged: true,
        inputFocus: true
      })
      //传输入框的值进行关键词匹配
      this.searchRecord(value);
    } else {
      this.setState({
        kw: '',
        contentShow: false,
        inputFocus: false
      })
    }

  }

  onClose = () => {
    this.setState({
      kw: '',
      contentShow: false,
      inputFocus: false,
    })
  }

  //回车搜索保存搜索记录
  keypress = (e) => {
    if (e.which === 13) {
      this.setState({
        inputFocus: false
      })

      //保存用户搜索记录
      const {kw, tab} = this.state;
      if (kw !== "") {
        this.saveUserBehavior(kw, tab);
      }

    }
  }

  onOutsideClick = (e) => {
    if (e.target === document.querySelector('html')) {
      // 鼠标点击后移出屏幕松开
      return
    }

    // 搜索框没有包含 但是顶部和侧栏包含了点击目标 就关闭
    if (!this.search.current.contains(e.target)) {
      // 鼠标点击到了搜索以外范围
      //console.log('鼠标点击到了搜索以外范围')
      this.setState({
        inputFocus: false
      })

      if (document.querySelector('.kf-nav').contains(e.target) || document.querySelector('.kf-user').contains(e.target) || document.querySelector('.kf-logo').contains(e.target)) {
        this.setState({
          kw: '',
          contentShow: false,//点击其他区域不让搜索结果收起
        })
      }

      //保存用户搜索记录
      const {kw, tab} = this.state;
      if (kw !== "") {
        this.saveUserBehavior(kw, tab);
      }
    }

  }

  onMainOutside = (e) => {
    if (e.target === document.querySelector('html')) {
      // 鼠标点击后移出屏幕松开
      return
    }
    if (!this.main.current.contains(e.target)) {
      // 鼠标点击到了搜索以外范围
      this.setState({
        inputFocus: false
      })

      //保存用户搜索记录
      const {kw, tab} = this.state;
      if (kw !== "") {
        this.saveUserBehavior(kw, tab);
      }

    }
  }

  onFocus = () => {
    this.resize(); // 搜索获取焦点后计算模态框尺寸

    const {kw} = this.state;
    //传输入框的值
    this.searchRecord(kw);

    this.setState({
      inputFocus: true
    })
  }

  //记录用户的搜索历史记录
  saveUserBehavior = (kw, cate) => {

    let sesCategory;
    switch (cate) {
      case "all":
        sesCategory = "global_all";
        break;
      case "sys":
        sesCategory = "global_app";
        break;
      case "todo":
        sesCategory = "global_todo_task";
        break;
      case "msg":
        sesCategory = "global_message";
        break;
      case "tel":
        sesCategory = "global_address_book";
        break;
      case "friend":
        sesCategory = "global_moment";
        break;
      case "news":
        sesCategory = "global_cms";
        break;
      case "knowledge":
        sesCategory = "global_itsm_faq";
        break;

    }
    const {httpAgent} = this.props;
    const {kwChanged} = this.state;
    if (kwChanged) {
      // console.log("执行保存")
      httpAgent.post('/ses/user/behavior/save', {keywords: kw, sesCategory: sesCategory}, {kw}).then(res => {
        this.setState({
          kwChanged: false
        })
      })
    }

  }

  searchTab = (tab) => {
    this.setState({
      tab: tab
    })
  }

  searchRecord = (kw) => {
    const {httpAgent} = this.props
    this.lastKeyWord = kw;
    let currentUserSize;
    let globalUserSize;
    if (kw === "") {
      currentUserSize = 6;
      globalUserSize = "";
    } else {
      currentUserSize = 3;
      globalUserSize = 3;
    }
    httpAgent.post('/ses/user/behavior/record', {keywords: kw, currentUserSize, globalUserSize}, {kw}).then(res => {
      // console.log('get007', res)
      if (res && res.result && res.resultCode === '000000' && this.lastKeyWord === res.backParams.kw) {
        const {currentUserRecord, globalUserRecord} = res.result;
        this.setState({
          currentUserRecord: currentUserRecord,
          globalUserRecord: globalUserRecord,
        })
      }
    })
  }

  //在消息里面，全局搜索全部下，发起会话，隐藏content
  hideContent = () => {
    this.setState({
      contentShow: false
    })
  }

  //点击关键词，更改搜索框的值，进行查询
  spanOnClick = (val) => {
    setTimeout(() => {
      this.setState({
        inputFocus: false,
        kw: val,
        contentShow: true,
        kwChanged: true
      }, () => {
        //保存用户搜索记录
        const {tab} = this.state;
        if (val !== "") {
          this.saveUserBehavior(val, tab);
        }

      });
    }, 10)
  }

  // 关闭搜索模态框
  closeSearchModal = () => {
    this.setState({
      kw: '',
      contentShow: false
    })
  }

  render() {
    const {httpAgent, history, karaui, user} = this.props
    const {keypress, onType, onFocus, onClose, resize, searchRecord, spanOnClick, lang, searchTab, closeSearchModal, hideContent, initTab} = this;
    const {contentStyle, contentShow, kw, inputFocus, currentUserRecord, globalUserRecord,tab} = this.state;
    const tipProps = {
      inputFocus,
      kw,
      currentUserRecord,
      globalUserRecord,
      searchRecord,
      spanOnClick,
      lang,
      httpAgent,
      user
    };
    const typeProps = {contentShow, kw, onType, onFocus, onClose, lang, keypress, user};
    const contentProps = {kw, httpAgent, lang, history, searchTab,onClose, karaui, closeSearchModal, user, hideContent, initTab,tab}

    return (<div ref={this.search} className={css["ks-search"]} tabIndex="-1">
      <div ref={this.main} className={css['ks-main']}>
        <Type {...typeProps} />
        <Tip {...tipProps} />
      </div>
      {Object.keys(contentStyle).length > 0 && contentShow ?
        <div className={`${css["ks-content"]} s-bg-page`} style={contentStyle}>
          <Content {...contentProps}/>
        </div> : null}
    </div>)
  }
}
