import React, { useEffect, useState } from 'react';
import { Input, Row, Col, Tabs, Pagination } from 'antd';
import axios from 'axios';
import { TPMIndexHOC } from '../tpm/TPMIndexHOC';
import { SnackbarHOC } from 'educoder';
import ItemList from './ItemList';
import Nodata from '../../forge/Nodata';
import './index.scss';

const { Search } = Input;
const { TabPane } = Tabs;

const GlobalSearch = ({ location, showNotification, history }) => {

  const size = 10;
  let defaultValue = decodeURI(location.search.split("=")[1] || "");

  const [term, setTerm] = useState(defaultValue);
  const [searchValue, setSearchValue] = useState(defaultValue);

  const [type, setType] = useState(1);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [dataList, setDataList] = useState([]);

  const [forcesearch, setForcesearch] = useState(false);

  const [totalType1, setTotalType1] = useState(0);
  const [totalType2, setTotalType2] = useState(0);
  const [totalType3, setTotalType3] = useState(0);
  const [totalType4, setTotalType4] = useState(0);
  const [totalType5, setTotalType5] = useState(0);

  const [ref, setRef] = useState(undefined);
  const [focus, setFocus] = useState(0);


  useEffect(() => {
    searchDataList();
  }, [type, page, term, forcesearch]);

  useEffect(() => {
    if (ref) {
      ref && ref.input.input.focus();
    }
  }, [focus])


  function searchFun(val) {
    setTerm(val);
    setPage(1);
    setForcesearch(!forcesearch);
  }

  function searchDataList() {
    let chromesettingArray = JSON.parse(localStorage.getItem('chromesetting'));
    let https = chromesettingArray.common.search || 'https://statistics.trustie.net';
    const url = https + '/search';
    if (!term) {
      // showNotification('请输入关键字');
      setFocus(focus + 1);
      return;
    }
    axios.defaults.withCredentials = true;
    axios.get(url, {
      params: {
        page,
        size,
        term,
        type,
      }
    }).then(res => {
      if (res && res.status === 200 && res.data && res.data.code === '1') {
        const data = res.data.data;
        setDataList(data.rows);
        setTotal(data.total);
        for (const item of data.searchItemTypes) {
          if (item.type == 1) {
            setTotalType1(item.count);
          } else if (item.type == 2) {
            setTotalType2(item.count);
          } else if (item.type == 3) {
            setTotalType3(item.count);
          } else if (item.type == 4) {
            setTotalType4(item.count);
          } else if (item.type == 5) {
            setTotalType5(item.count);
          }
        }
      } else if (res && res.data) {
        showNotification(res.data.data.message);
        setDataList([]);
        setTotal(0);
      } else {
        showNotification('查询失败！');
        setDataList([]);
        setTotal(0);
      }
    }).catch(err => {
      showNotification('查询失败！返回错误');
      setDataList([]);
      setTotal(0);
    })
  }


  function changeTab(type) {
    setType(type);
    setPage(1);
  }

  useEffect(() => {
    history.listen(historyLocation => {
      setSearchValue(historyLocation.search.split("=")[1] || "");
      setTerm(historyLocation.search.split("=")[1] || "");
    })
  }, [history]);



  return (
    <div className="suit-main clearfix">
      <div className="search-head">

        <Row className="search-box">
          <Col xs={20} sm={16} lg={13} >
            <Search
              placeholder="请输入搜索关键字"
              enterButton="搜索"
              size="large"
              onSearch={searchFun}
              className={{ 'global-search': true, "required-search": !searchValue }}
              value={searchValue}
              onChange={(e) => { setSearchValue(e.target.value) }}
              ref={(el) => setRef(el)}
            />
            {!searchValue && <span className="ant-form-explain">请输入搜索关键字</span>}
          </Col>
        </Row>
      </div>


      <Tabs defaultActiveKey="1" onChange={changeTab}>
        <TabPane tab={`项目（${totalType1}）`} key={1}>
          <div className="search-content">
            <p>{`找到${totalType1}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              />
              : <Nodata _html="暂无数据" className="no-data-box" />
          }
        </TabPane>

        <TabPane tab={`帖子（${totalType2}）`} key="2">
          <div className="search-content">
            <p>{`找到${totalType2}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              /> : <Nodata _html="暂无数据" />
          }
        </TabPane>

        {/* <TabPane tab={`众包任务（${totalType3}）`} key={3}>
          <div className="search-content">
            <p>{`找到${totalType3}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              /> : <Nodata _html="暂无数据" />
          }
        </TabPane>

        <TabPane tab={`资源（${totalType4}）`} key="4">
          <div className="search-content">
            <p>{`找到${totalType4}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              /> : <Nodata _html="暂无数据" />
          }
        </TabPane> */}

        <TabPane tab={`易修（${totalType5}）`} key="5">
          <div className="search-content">
            <p>{`找到${totalType5}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              /> : <Nodata _html="暂无数据" />
          }
        </TabPane>
      </Tabs>

    </div>
  );
}


export default SnackbarHOC()(TPMIndexHOC(GlobalSearch));
