import React, {Component} from 'react'
import sCss from "./sys.scss"
import SysItem from "./item/item";
import Panel from "../../common/panel/panel";
import SearchPanel from '../../common/searchPanel/searchPanel'
import SearchDate from '../../common/searchDate/searchDate'
import getSearchTime from "../../../utils/getSearchTime";
import Nothing from "../nothing/nothing";
import {Load} from 'karaui'


export default class System extends Component {
  constructor(props) {
    super(props);
    this.state = {
      appList: {
        webAppInfos: []
      },
      load:true
    }
  }

  componentDidMount() {
    const {kw, searchTime} = this.props
    if (kw) {
      this.search(kw,searchTime.start, searchTime.end)
    }
  }


  componentWillReceiveProps(next) {
    const {kw, clearSearchCount} = this.props
    const {searchTime} = next
    if (kw && kw !== next.kw) {
      this.search(next.kw,searchTime.start, searchTime.end)
      clearSearchCount()
    }
  }

  //根据时间查询
  searchByTime = (type, s, e, label) => {
    const {startTime, endTime} = getSearchTime(type, s, e)
    const {kw, changeSearchTime} = this.props;
    this.search(kw, startTime, endTime);
    // console.log('set time',type,s,e,startTime,endTime)
    changeSearchTime({type,label,start:startTime,end:endTime})
  }

  search = (kw, from = '', to = '') => {
    const {httpAgent, language} = this.props
    this.lastKeyWord = kw
    const body = {keywords: kw, from, to, isHighlight: true}
    const header = {language: language === 'en' ? 'en' : 'cn', platform: 'web'}
    httpAgent.post('/webhook/apps.search', body, kw, null, header).then(res => {
      // console.log("系统", res)
      if (res && res.webAppInfos && res.resultCode === '000000' && this.lastKeyWord === res.backParams) {
        this.setState({
          appList: res,
          load:false
        })
      }
    })
  }

  getItem = (result) => {
    const {lang} = this.props
    const li = result.map((v) => {
      return <SysItem key={v.id} data={v} lang={lang}/>
    })
    return <ul className={sCss["sys-content"]}>
      {li}
    </ul>
  }


  render() {
    const {lang, searchTime} = this.props;
    const {load}=this.state;
    const {webAppInfos, kw, millis, resultCode, resultMessage} = this.state.appList;
    const selectDate = <SearchDate chooseTime={this.searchByTime} searchTime={searchTime} lang={lang}/>;

    return (
      !load ? webAppInfos.length > 0 ?
        <SearchPanel num={webAppInfos.length} time={millis} selectDate={selectDate} lang={lang}>
          <Panel title={`${lang.sys}${ webAppInfos.length > 99 ? "99+" : webAppInfos.length}(${lang.item})`} isLast
                 lang={lang}>
            {this.getItem(webAppInfos)}
          </Panel>
        </SearchPanel> : <Nothing lang={lang}/> : <Load/>
    )
  }

}
