import React, { PureComponent } from "react"
import SearchHeader from "./searchHead"
import VList from "src/common/VList"
import { getParam } from "src/utils"
import { aiSearchInstance } from "src/utils/http"
import "./search-result.scss"
import Recommendation from "./recommendation"
import throttle from "lodash/throttle"

const ForwardRefSearchHead = React.forwardRef((props, ref) => {
  return <SearchHeader {...props} forwardedRef={ref} />
})

const Bottom = ({ item }) => {
  return (
    <div className="bottom">
      <span className="price">¥{item.price1}</span>
      <span className="stale-price">¥{item.price0}</span>
    </div>
  )
}

class SearchResult extends PureComponent {
  prevScrollY = 0
  searchHead = React.createRef()
  swipeUp = "up"
  swipeDown = "down"

  state = {
    courseList: [],
    value: decodeURIComponent(getParam("word")) || "",
    searchHistory: JSON.parse(localStorage.getItem("searchHistory")) || [],
    fixedHeader: false,
    searchHeadStyle: { top: 0 },
    swipeDirection: this.swipeUp,
    isHide: false,
    basicTop: 0,
    resultCount: 0,
  }

  componentDidMount() {
    this.getCourses(getParam("word"))
    document.addEventListener("scroll", this.handleScroll)
  }

  componentWillUnmount() {
    document.removeEventListener("scroll", this.handleScroll)
  }

  getCourses = (word) => {
    aiSearchInstance
      .post(
        `${API["ai-search"]}/aisearch/v1/fusion`,
        {
          search_params: {
            query: word,
            es_fragment_size: 200,
            es_number_of_fragments: 3,
            es_size: 40,
            es_slop: 1,
            milvus_limit: 40,
            timeout: 5,
          },
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((res) => {
        const data = res.data
        console.log("data: ", data)
        const { response, status_code } = data

        if (status_code === 200) {
          this.setState({
            courseList: response,
            resultCount: response.length,
          })
        }
      })
  }

  handleClick = (id) => {
    this.props.history.push(`/detail?id=${id}`)
  }

  handleSearch = () => {
    this.state.value && this.getCourses(this.state.value)
  }

  handleChange = (value) => {
    this.setState({ value })
  }

  toCourseDetail = ({ course_id, v_course_id }) => {
    const { history } = this.props
    history.push(
      course_id === 0
        ? `/play/video?id=${v_course_id}`
        : `/detail?id=${course_id}`
    )
  }

  handleScroll = throttle(() => {
    let y = window.scrollY < 0 ? 0 : window.scrollY,
      h = this.searchHead.current.offsetHeight
    if (y > this.prevScrollY) {
      this.setState({
        searchHeadStyle: {
          top: `${-h}px`,
        },
      })
    }
    if (y < this.prevScrollY) {
      this.setState({
        searchHeadStyle: {
          top: 0,
        },
      })
    }
    // if (y < this.prevScrollY) {
    //     if (this.state.swipeDirection === this.swipeDown) {
    //         y <= headY && this.state.searchHeadStyle.position !== 'fixed' &&
    //         this.setState({
    //             searchHeadStyle: {
    //                 top: `0`,
    //                 position: 'fixed'
    //             }
    //         })
    //     } else {
    //         this.setState({
    //             swipeDirection: this.swipeDown
    //         }, () => {
    //             if (this.state.swipeDirection === this.swipeDown) {
    //                 let h = y > document.querySelector('body').offsetHeight? document.querySelector('body').offsetHeight: y;
    //                 let h1 = this.searchHead.current.offsetHeight
    //                     this.setState({
    //                         searchHeadStyle: {
    //                             // top: `${h > headY ? h - h1 : h}px`
    //                             top: `${y}px`
    //                         }
    //                     })

    //             }
    //         })
    //     }
    // } else {
    //     this.state.swipeDirection !== this.swipeUp &&
    //     this.setState({
    //         swipeDirection: this.swipeUp,
    //         searchHeadStyle: {
    //             position: 'absolute',
    //             top: `${y}px`
    //         }
    //     })
    // }
    this.prevScrollY = y
  }, 0)

  render() {
    const { courseList, isHide, resultCount } = this.state

    return (
      <div className={"search-result"}>
        <ForwardRefSearchHead
          handleSearch={this.handleSearch}
          value={this.state.value}
          handleChange={this.handleChange}
          searchHistory={this.state.searchHistory}
          style={this.state.searchHeadStyle}
          ref={this.searchHead}
          isHide={isHide}
        />
        {resultCount > 0 && (
          <div className="result-count">共{resultCount}个结果</div>
        )}
        {courseList && courseList.length > 0 ? (
          <ul>
            {courseList.map((item, index) => {
              const Info = (
                <div className="info">
                  <p
                    className="title text-overflow-2"
                    dangerouslySetInnerHTML={{
                      __html:
                        item.highlight?.["course_title.pinyin"]?.length > 0
                          ? item.highlight["course_title.pinyin"][0]
                          : item.course_title,
                    }}
                  ></p>
                  {/* <p
                    className="des text-overflow-1"
                    dangerouslySetInnerHTML={{
                      __html:
                        item.highlight?.["course_stage.pinyin"]?.length > 0
                          ? item.highlight["course_stage.pinyin"][0]
                          : "",
                    }}
                  ></p> */}
                  <p
                    className="des text-overflow-1"
                    dangerouslySetInnerHTML={{
                      __html:
                        item.highlight?.["course_lesson.pinyin"]?.length > 0
                          ? item.highlight["course_lesson.pinyin"][0]
                          : "",
                    }}
                  ></p>
                  <div className="course_tags text-overflow-1">
                    {item.course_tags.map((tag, index) => (
                      <span key={index}>{tag}</span>
                    ))}
                  </div>
                  {/* <Bottom item={item} /> */}
                </div>
              )
              const status =
                item["bargain_num"] || item["groupon_num"] ? (
                  <div className="status">
                    {item["bargain_num"] === 0
                      ? `砍价减${item["groupon_num"]}元`
                      : `拼团减${item["bargain_num"]}元`}
                  </div>
                ) : null
              return (
                <VList
                  img={item.image_name}
                  toDetail={this.toCourseDetail}
                  key={index}
                  info={Info}
                  id={item["course_id"]}
                  course={item}
                  status={status}
                  needCourseInfo
                />
              )
            })}
          </ul>
        ) : (
          <div className="empty">
            <img src={require("./image/ss_empty.png")} alt="" />
            抱歉，没有搜到相关内容！
          </div>
        )}
        <Recommendation />
      </div>
    )
  }
}

export default SearchResult
