import { Component } from 'react'
import { View, Text } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import Taro from '@tarojs/taro'

import './index.less'
import CustomNavbar from '@src/components/TopNavBar'
import ScrollViewHoc from '@src/components/ScrollView'
import BookHead from '@src/components/PupPetry/BookHead'
import BookboxRowBig from '@src/components/PupPetry/BookBox/BookboxRowBig'
import BookSearch from '@src/components/PupPetry/BookSearch'
import useApi from '@src/Hook/useApi'
import { Store } from '@src/app'


type PageStateProps = {
    store: Store
}
interface Search {
    props: PageStateProps;
}
interface ContentData {
    current: number,
    total: number,
    size: number,
    records: any[]
}
interface State {
    searchData: ContentData;
    searchVal: string,
    hotVal: any[],
    historyVal: any[],
    api: {
        getBookPageList: (data: any) => Promise<any>
    } | null
}


@inject('store')
@observer
class Search extends Component {
    state: State = {
        searchData: {
            current: 0,
            total: 0,
            size: 0,
            records: []
        },   // 搜索结果
        searchVal: "",    // 搜索内容
        hotVal: [],       // 搜索页大家都在搜list
        historyVal: [],   // 搜索历史
        api: null
    }
    onLoad() {
        try {
            let searchValue: any[] = Taro.getStorageSync('search-val')
            if (searchValue) {
                this.setState({
                    historyVal: searchValue,
                })
            }
        } catch (e) { }
    }
    componentDidMount(): void {
        let api = useApi()
        this.setState({ api })
    }
    /** 点击搜索历史 */
    historyHanlde = (text: string) => {
        this.searchHandle(text)
    }

    /** 搜索 */
    searchHandle = (value: string) => {
        this.setState({
            searchVal: value
        })
        this.getSearchData({ bookNameOrAuthorName: value, pageNum: 1, pageSize: 20 })
    }
    // 获取搜索结果
    getSearchData = (params) => {
        return new Promise((resolve, reject) => {
            let { bookNameOrAuthorName } = params
            this.state.api?.getBookPageList(params).then((res: any) => {
                console.log(res)
                try {
                    // 保存搜索记录
                    let searchValue: any[] = this.state.historyVal
                    if (searchValue) {
                        let ind = searchValue.findIndex(item => item === bookNameOrAuthorName)
                        if (ind === -1) {
                            if (searchValue.length >= 10) {
                                searchValue = searchValue.splice(1)
                                searchValue.push(bookNameOrAuthorName)
                            } else {
                                searchValue.push(bookNameOrAuthorName)
                            }
                            Taro.setStorageSync('search-val', searchValue)
                        }
                    } else {
                        Taro.setStorageSync('search-val', [bookNameOrAuthorName])
                    }
                    this.setState({
                        historyVal: Taro.getStorageSync('search-val')
                    })
                } catch (e) {
                }
                this.setState({
                    searchData: res?.data?.data
                })
                resolve(res)
            })
        })
    }
    /** 清除搜索历史 */
    removeHistory = () => {
        try {
            Taro.removeStorageSync('search-val')
            this.setState({
                historyVal: []
            })
        } catch (e) {
            // Do something when catch error
        }
    }
    //下来加载
    load = () => {
        return new Promise((resolve, reject) => {
            let { size, total, records } = this.state.searchData
            let pageSize = size + 20
            if (records?.length >= total) {
                Taro.showToast({
                    title: '没有更多了~~',
                    duration: 2000,
                    icon: 'none'
                })
                reject()
                return
            } else {
                this.getSearchData({ bookNameOrAuthorName: this.state.searchVal, pageNum: 1, pageSize }).then(res => {
                    console.log("Res", res)
                    resolve(true)
                })
            }
        })
    }
    render() {
        return <View className='search'>
            <View>
                <BookSearch onBack={this.searchHandle} val={this.state.searchVal} onClear={() => {
                    this.setState({
                        searchVal: "",
                        searchData: {
                            current: 0,
                            total: 0,
                            size: 0,
                            records: []
                        }
                    })
                }} />
            </View>
            {
                this.state.searchData?.records?.length === 0 ? <View>
                    {/* 推荐小说缺少接口 */}
                    {/* <BookHead title="大家都在搜" fontSize={32}></BookHead> */}
                    {/* <BookHotTabs hotValue={this.state.hotVal} onBack={(id) => { Taro.navigateTo({ url: `/pages/book/bookDetails/index?bookId=${id}` }) }} scroll={false}></BookHotTabs> */}
                    <View className="line"></View>
                    <BookHead title="搜索历史" fontSize={32} imgUrl={require('../../icon/delete.png')} fitOnBack={this.removeHistory} imgWidth={36}></BookHead>
                    {/* 历史记录 */}
                    <View className="history">
                        {
                            this.state.historyVal?.map(item => {
                                return <View className="histore_item" onClick={() => {
                                    this.historyHanlde(item)
                                }}>
                                    <Text>{item}</Text>
                                </View>
                            })
                        }
                    </View>
                </View> :

                    <View>
                        <View className="searchTs">
                            搜索"<Text>{this.state.searchVal}</Text>"结果，共<Text>{this.state.searchData?.total}</Text>条
                        </View>
                        <ScrollViewHoc load={this.load} filterClassName='.searchTs' navHeight={this.props.store.indexStore.navHeight}>
                            <View className='w  row for_top pd_btm'>
                                {
                                    this.state.searchData?.records?.map((item) => {
                                        return <View key={item.bookId}><BookboxRowBig {...item} /></View>
                                    })
                                }
                            </View>
                        </ScrollViewHoc>
                    </View>
            }
        </View>

    }
}

export default CustomNavbar(Search, { title: "搜索", isToBack: true })
