import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request/es'
import { useHistory } from 'react-router-dom'

import { Input, message, Modal } from 'antd'
import { SearchOutlined } from '@ant-design/icons'

import { useLogin2p } from 'Login2p/Login2pContext'
import { MaterialService } from '../../Material/Material.service'
import styles from '../css/Search.module.scss'

interface IHeadSearchProps {
  defaultKeyword?: string
  placeholder?: string
  className?: string
  onSearch: (value: string) => void // 搜索
}

/**
 * 顶部的搜索框
 */
const HeadSearch: React.FC<IHeadSearchProps> = props => {
  const { defaultKeyword, placeholder = '请输入内容', className, onSearch } = props
  const [keyWord, setKeyWord] = useState<string | undefined>(defaultKeyword) // 搜索内容
  const [searchShowFlag, setSearchShowFlag] = useState(false) // 搜索下拉框标识
  const [searchKeywordData, setSearchKewordData] = useState<
    { label: string; list: { KeyWord: string }[]; id: string }[]
  >([]) // 搜索历史、热词、关键词
  const login2p = useLogin2p()
  const history = useHistory()
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false) //未登录弹框

  useEffect(() => {
    document.addEventListener('click', () => setSearchShowFlag(false))
    return () => {
      document.removeEventListener('click', () => setSearchShowFlag(false))
    }
  }, [])
  useEffect(() => {
    setKeyWord(defaultKeyword)
  }, [defaultKeyword])

  // 拉取搜索展开数据
  const { run: getSearchList } = useRequest(MaterialService.getSearchKeyWordList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      const newSearchData = []
      if (res?.ListHistory?.length) newSearchData.push({ label: '搜索历史', list: res?.ListHistory, id: '1' })
      if (res?.ListHot?.length) newSearchData.push({ label: '热搜关键词', list: res?.ListHot, id: '2' })
      // if (res?.ListRecommend?.length) newSearchData.push({ label: '推荐关键词', list: res?.ListRecommend, id: '3' })
      setSearchKewordData(newSearchData)
    }
  })

  const handleSeachOnFocus = () => {
    getSearchList()
    setSearchShowFlag(true)
  }
  const handleChangeSeachWord = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyWord(e.target.value)
  }
  const handleOnSearch = () => {
    if (!login2p.jwt) return setIsModalVisible(true)
    if (!keyWord) return message.error('请输入搜索内容')
    onSearch(keyWord || '')
    setSearchShowFlag(false)
  }
  const handleSelectKeyWord = (keyWord: string) => {
    if (!login2p.jwt) return setIsModalVisible(true)
    setKeyWord(keyWord)
    onSearch(keyWord || '')
    setSearchShowFlag(false)
  }
  const handleStopPropagation = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.nativeEvent.stopImmediatePropagation()
  }
  return (
    <>
      <div className={`${styles['head-search-wrapper']} ${className}`} onClick={handleStopPropagation}>
        <SearchOutlined className={styles.searchicon} onClick={handleOnSearch} />
        <Input
          className="input-wrapper"
          placeholder={placeholder}
          size="large"
          variant="borderless"
          onFocus={handleSeachOnFocus}
          value={keyWord}
          onChange={handleChangeSeachWord}
          onPressEnter={handleOnSearch}
        />
        {searchShowFlag && searchKeywordData.length > 0 && (
          <div className="other-wrapper">
            {searchKeywordData?.map(item => (
              <div className="line-wrapper" key={item.id}>
                <div className="line-name">{item.label}</div>
                <div className="line-item-content">
                  {item?.list?.map((cItem, cIndex) => (
                    <span className="line-item" key={cIndex} onClick={handleSelectKeyWord.bind(this, cItem.KeyWord)}>
                      {cItem.KeyWord}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <Modal
        width="350px"
        okText="去登录"
        open={isModalVisible}
        maskClosable={false}
        closable={false}
        onOk={() => {
          history.push(`/login2p?next=${encodeURIComponent(window.location.pathname + window.location.search)}`)
        }}
        onCancel={() => {
          setIsModalVisible(false)
        }}
      >
        <div>请登录后再使用搜索功能</div>
      </Modal>
    </>
  )
}

export default HeadSearch
