import React, { useEffect, useState } from 'react';
import { Input, Row, Col, Tabs, Pagination , Icon } 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';
import emp from '../../forge/Images/emp.png';

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

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

  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 [ orderBy , setOrderBy ] = useState("scoreDesc");

  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(()=>{
    if(mygetHelmetapi){
      const {name} = mygetHelmetapi;
      document.title = name;
    }
  }, [mygetHelmetapi])

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

  useEffect(()=>{
    setPage(1);
  },[orderBy])

  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,
        orderBy
      }
    }).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);
    if(type !== "1"){
      setOrderBy(undefined);
    }else{
      setOrderBy("scoreDesc");
    }
  }

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

  const svg = ()=>(
    <svg t="1679452192759" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="27711" width="14" height="16">
      <path d="M709.060096 692.0192H315.024896c-11.8784 0-18.432 12.4928-11.1616 20.992l197.12 228.4544a15.0528 15.0528 0 0 0 22.1184 0l197.12-228.4544c7.2704-8.4992 0.7168-20.992-11.1616-20.992z" fill="#bfbfbf" p-id="27712" data-spm-anchor-id="a313x.7781069.0.i11" class="selected"></path><path d="M709.060096 331.9808H315.024896c-11.8784 0-18.432-12.4928-11.1616-20.992L500.983296 82.5344a15.0528 15.0528 0 0 1 22.1184 0l197.12 228.4544c7.2704 8.4992 0.7168 20.992-11.1616 20.992z" fill="#bfbfbf" p-id="27713" data-spm-anchor-id="a313x.7781069.0.i7" class="selected"></path>
    </svg>
  )

  const descSvg = ()=>(
    <svg t="1679451960146" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="27475" width="14" height="16">
      <path d="M709.060096 331.9808H315.024896c-11.8784 0-18.432-12.4928-11.1616-20.992L500.983296 82.5344a15.0528 15.0528 0 0 1 22.1184 0l197.12 228.4544c7.2704 8.4992 0.7168 20.992-11.1616 20.992z" fill="#999999" p-id="27476"></path><path d="M709.060096 692.0192H315.024896c-11.8784 0-18.432 12.4928-11.1616 20.992l197.12 228.4544a15.0528 15.0528 0 0 0 22.1184 0l197.12-228.4544c7.2704-8.4992 0.7168-20.992-11.1616-20.992z" fill="#466aff" p-id="27477" data-spm-anchor-id="a313x.7781069.0.i0" class="selected"></path>
    </svg>
  )

  const ascSvg = ()=>(
    <svg t="1679452192759" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="27711" width="14" height="16">
      <path d="M709.060096 692.0192H315.024896c-11.8784 0-18.432 12.4928-11.1616 20.992l197.12 228.4544a15.0528 15.0528 0 0 0 22.1184 0l197.12-228.4544c7.2704-8.4992 0.7168-20.992-11.1616-20.992z" fill="#999999" p-id="27712"></path><path d="M709.060096 331.9808H315.024896c-11.8784 0-18.432-12.4928-11.1616-20.992L500.983296 82.5344a15.0528 15.0528 0 0 1 22.1184 0l197.12 228.4544c7.2704 8.4992 0.7168 20.992-11.1616 20.992z" fill="#466aff" p-id="27713" data-spm-anchor-id="a313x.7781069.0.i7" class="selected"></path>
    </svg>
  )

  function iconSwitch(array){
    if(array === "desc"){
      return <Icon component={descSvg} />
    }else if(array === "asc"){
      return <Icon component={ascSvg} />
    }else{
      return <Icon component={svg} />
    }
  }



  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">
            <ul className="search-condition">
              <li style={{paddingRight:"22px"}} className={orderBy === "scoreDesc" ? "active":""} onClick={()=>setOrderBy("scoreDesc")}>匹配度</li>
              <li className={orderBy === "watchDesc" || orderBy === "watchAsc" ?"active":""} onClick={()=>setOrderBy(orderBy === "watchDesc" ? "watchAsc" :"watchDesc")}>
                关注数{iconSwitch(orderBy === "watchDesc" ? "desc" : orderBy === "watchAsc" ? "asc" :"")}
              </li>
              <li className={orderBy === "forkDesc" || orderBy === "forkAsc" ?"active":""} onClick={()=>setOrderBy(orderBy === "forkDesc" ? "forkAsc" :"forkDesc")}>
                Fork数{iconSwitch(orderBy === "forkDesc" ? "desc" : orderBy === "forkAsc" ? "asc" :"")}
              </li>
              <li className={orderBy === "starDesc" || orderBy === "starAsc" ?"active":""} onClick={()=>setOrderBy(orderBy === "starDesc" ? "starAsc" :"starDesc")}>
                点赞数{iconSwitch(orderBy === "starDesc" ? "desc" : orderBy === "starAsc" ? "asc" :"")}
              </li>
              <li className={orderBy === "updateTimeDesc" || orderBy === "updateTimeAsc" ?"active":""} onClick={()=>setOrderBy(orderBy === "updateTimeDesc" ? "updateTimeAsc" :"updateTimeDesc")}>
                更新时间{iconSwitch(orderBy === "updateTimeDesc" ? "desc" : orderBy === "updateTimeAsc" ? "asc" :"")}
              </li>
              <li className={orderBy === "createTimeDesc" || orderBy === "createTimeAsc" ?"active":""} onClick={()=>setOrderBy(orderBy === "createTimeDesc" ? "createTimeAsc" :"createTimeDesc")}>
                创建时间{iconSwitch(orderBy === "createTimeDesc" ? "desc" : orderBy === "createTimeAsc" ? "asc" :"")}
              </li>
            </ul>
            <p>{`找到${totalType1}条结果`}</p>
            <ItemList
              list={dataList}
            />
          </div>
          {
            dataList.length ?
              <div className="pb20"><Pagination
                showQuickJumper={dataList.length > size}
                onChange={(page) => { setPage(page) }}
                current={page}
                total={total}
                showTotal={total => `共 ${total} 条`}
              /></div>
              : <div className="none_panels"><div><img src={emp} alt="" /></div></div>
          }
        </TabPane>

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

    </div>
  );
}


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