import Taro, { useDidShow, useShareAppMessage } from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './search.module.scss'
import Goods from './components/goods'
import Search from '@/components/search'
import { alert, goLink } from '@/common/common'
import { AddSearchHistoryApi, GetHotSearchApi, GetSearchHistoryApi } from '@/api/search'
import { SCENE, SEARCH_EMPTY_IMAGE } from '@/common/constant'
import useLogin from '@/use/useLogin'
import Empty from '@/components/empty'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import InfiniteScroll from '@/components/infiniteScroll'
import { GetProductListApi, mallsearchHistorydelete } from '@/api/material'

interface searchDataParam { search_key: '' }
export default () => {
  useLogin()

  const [searchData, setSearchData] = useState<{
    hotField: searchDataParam[]
    historyField: searchDataParam[]
    showIndex: number
    code_or_name: string
    page: number
    size: number
  }>({
    hotField: [],
    historyField: [],
    showIndex: 1, // 1代表输入框没内容搜索 2是有
    code_or_name: '',
    page: 1,
    size: 10,
  })

  // 获取热门搜索数据
  const { fetchData: hotFetchData } = GetHotSearchApi()
  const getHotSearch = async() => {
    const { data } = await hotFetchData({ page: 1, size: 10 })
    setSearchData(val => ({ ...val, hotField: data.list }))
  }

  // 获取历史搜索数据
  const { fetchData: HistoryFetchData } = GetSearchHistoryApi()
  const getSearchHistory = async() => {
    const { data } = await HistoryFetchData({ page: 1, size: 10 })
    setSearchData(val => ({ ...val, historyField: data.list }))
  }

  useDidShow(() => {
    getHotSearch()
    getSearchHistory()
  })

  // 添加搜索关键字
  const addSearchField = useRef({ key: '', screen: SCENE.SearchScene })
  const { fetchData: addFetchData } = AddSearchHistoryApi()
  const addSearchHistory = async() => {
    await addFetchData(addSearchField.current)
    // goLink('/pages/searchList/searchList', {key: addSearchField.current.key})
  }

  // 默认输入框词
  const [defaultValue, setdefaultValue] = useState('')

  // 搜索事件, status = true 添加搜索， status = false 直接跳转
  const searchEvent = (e, status = true) => {
    addSearchField.current.key = e
    setdefaultValue(e)
    // if (e == '') {
    //   alert.error('请输入关键词')
    //   return false
    // }
    // addSearchField.current.key = e
    // status && addSearchHistory()
    // Taro.navigateTo({
    //   url: `/pages/searchList/searchList?key=${addSearchField.current.key}`,
    // })

    addSearchHistory()
    setSearchData(val => ({ ...val, showIndex: 2, page: 1, size: 10, code_or_name: e }))
    // getProductList()
  }

  const changeSearch = useCallback(debounce((e) => {
    if (e.trim().length == 0 && e != '') {
      alert.error('请输入关键词')
    }
    if (e.trim().length != 0) {
      addSearchField.current.key = e
      addSearchHistory()
      getSearchHistory()
      setSearchData(val => ({ ...val, showIndex: 2, page: 1, size: 10, code_or_name: e }))
      // getProductList()
    }
    if (e == '') {
      getSearchHistory()
      setSearchData(val => ({ ...val, showIndex: 1 }))
    }
  }, 300), [])

  // 返回
  const handCancel = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }

  // 获取面料列表
  const [materialList, setMaterialList] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
  const { fetchData: materialFetchData, state: materialState } = GetProductListApi()
  const getProductList = async() => {
    const { data } = await materialFetchData(getFilterData(searchData))
    setMaterialList({ list: data.list, total: data.total })
    Taro.stopPullDownRefresh()
  }

  // 上拉加载数据
  const pageNum = useRef({ size: searchData.size, page: searchData.page })
  const getScrolltolower = () => {
    if (materialList.list.length < materialList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchData({ ...searchData, size })
    }
  }

  // 监听筛选条件变化
  useEffect(() => {
    if (searchData.code_or_name !== '') {
      getProductList()
    }
  }, [searchData.code_or_name])

  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: materialList.list, total: materialList.total, status: materialState.loading })
  }, [materialList, materialState])

  // 删除历史搜索
  const { fetchData: deleteFetch } = mallsearchHistorydelete()
  const handDelete = async() => {
    const res = await deleteFetch()
    Taro.showLoading({
      title: '请稍等...',
    })
    if (res) {
      alert.success('删除成功')
      getSearchHistory()
      setSearchData(val => ({ ...val, showIndex: 1 }))
      Taro.hideLoading()
    }
    else {
      alert.error('删除失败')
      Taro.hideLoading()
    }
  }

  return (
    <View className={styles.main}>
      <View className={styles.search}>
        <View className={styles.searchBox}>
          <Search
            changeOnSearch={changeSearch}
            placeholder="请输入面料关键词"
            defaultValue={defaultValue}
          />
        </View>
        <View className={styles.cancelFont} onClick={() => handCancel()}>取消</View>
      </View>
      {
        searchData.showIndex === 1 && <>
          {
            searchData?.historyField.length === 0
            && <View className={styles.topFlex}>
              <View className={styles.historyFont}>历史搜索</View>
              <View className={styles.up_search} onClick={() => goLink('/pages/searchList/hightSearchList')}>
                {'高级搜索 >'}
              </View>
            </View>
          }
          {searchData?.hotField.length > 0 && (
            <View className={styles.hot}>
              <View className={styles.hot_header}>
                <View className={styles.hot_header_title}>热门面料</View>
              </View>
              <View className={styles.list}>
                {searchData.hotField.map((item, index) => {
                  return (
                    <View className={styles.item} onClick={() => searchEvent(item.search_key, false)} key={index}>
                      {item.search_key}
                    </View>
                  )
                })}
              </View>
            </View>
          )}
          {searchData?.historyField.length > 0 && (
            <View className={styles.history}>
              <View className={styles.history_header}>
                <View className={styles.history_header_title}>历史搜索</View>
                {
                  searchData?.historyField.length > 0 && <View className={classnames('iconfont icon-shanchu', styles.miconfont)} onClick={() => handDelete()}></View>
                }

              </View>
              <View className={styles.list}>
                {searchData?.historyField?.map((item, index) => (
                  <View className={styles.item} onClick={() => searchEvent(item.search_key, false)} key={index}>
                    {item.search_key}
                  </View>
                ))}
              </View>
              <View className={styles.up_search} onClick={() => goLink('/pages/searchList/hightSearchList')}>
                {'高级搜索 >'}
              </View>
            </View>
          )}
          {
            searchData?.historyField.length === 0 && <Empty picUrl={SEARCH_EMPTY_IMAGE} text="无搜索历史"></Empty>
          }
        </>
      }
      {
        searchData.showIndex === 2 && <View className={styles.reslutBox}>
          <View className={styles.reslutTitle}>搜索结果</View>
          <View className={styles.scrollBox}>
            <InfiniteScroll selfonScrollToLower={getScrolltolower} statusMore={statusMore}>
              {
                materialList?.list.map((item) => {
                  return (
                    <Goods clickItem={() => goLink(`/pages/details/index?id=${item.id}`)} key={item} data={item}></Goods>
                  )
                })
              }
            </InfiniteScroll>
          </View>
        </View>
      }
    </View>
  )
}
