import { forwardRef, useEffect, useRef, useState } from 'react'
import Taro, { useShareAppMessage } from '@tarojs/taro'
import { useDidHide, useDidShow } from '@tarojs/taro'
import { observer, inject } from 'mobx-react'
import { ScrollView, View } from '@tarojs/components'
import './index.less'
//==========components组件引用========================
import TopNavBar from '@src/components/TopNavBar/index'
import BookboxRowBig from '@src/components/PupPetry/BookBox/BookboxRowBig'
import BookTypeTabs from '@src/components/PupPetry/BookTypeTabs'
import Empty from '@src/components/Empty'
import { Store } from '@src/app'
import useApi from '@src/Hook/useApi'
import { getBookCategoryList } from '@src/server/classify'
import { share } from '@src/utils'


interface Props {
    store: Store;
}

const Index = forwardRef((props: Props) => {
    const { classifyStore, indexStore } = props.store
    const { getBookPageList } = useApi()
    const [pageShow, setPageShow] = useState(false)//防止小程序切换页面组件不会被真实卸载,阻止不必要的操作
    const [open, setOpen] = useState(false)
    const [showEmpty, setShowEmpty] = useState(false)
    const [isSetOpen, setIsSetOpen] = useState(true)
    const [filterHeight, setFilterHeight] = useState(0)
    const timeRef = useRef<any>()
    // 获取分类列表
    useEffect(() => {
        if (pageShow) {
            console.log("获取分类列表")
            let { workDirection } = classifyStore
            getBookCategoryList(workDirection).then((res: any) => {
                if (res?.data?.code === 200) {
                    classifyStore.setData({ classifyData: res?.data?.data })
                }
            })
        }
    }, [classifyStore.workDirection, pageShow]); // Dependency array, runs effect only once on mount and unmount
    //获取书籍列表
    useEffect(() => {
        if (pageShow) {
            console.log("获取书籍列表")
            let { workDirection } = classifyStore
            let { categoryId } = classifyStore
            categoryId.id != 0 && classifyStore.categoryId && getList({ workDirection, categoryId: categoryId.id, pageNum: 1, pageSize: 10, type: 'class' }).then((res: any) => {
                if (res?.data?.data?.total === 0) {
                    setShowEmpty(true)
                } else {
                    setShowEmpty(false)
                }
            })
        }
    }, [classifyStore.workDirection, classifyStore.categoryId, pageShow])
    // 使用 useDidShow 代替 onShow
    useDidShow(() => {
        setPageShow(true)
    });
    // 使用 useDidHide 如果需要在页面隐藏时做一些处理
    useDidHide(() => {
        // setPageShow(false)
    });
    //下拉加载
    const load = () => {
        return new Promise((resolve, reject) => {
            let { size, total, records } = classifyStore.bookList
            let pageSize = size + 10
            let { workDirection } = classifyStore
            let { categoryId } = classifyStore
            if (records?.length >= total) {
                Taro.showToast({
                    title: '没有更多了~~',
                    duration: 2000,
                    icon: 'none'
                })
                reject()
                return
            } else {
                getList({ workDirection, categoryId: categoryId.id, pageNum: 1, pageSize, type: 'class' }).then((res: any) => {
                    if (res?.data?.data?.total === 0) {
                        setShowEmpty(true)
                    } else {
                        console.log("isSetOpen", isSetOpen)
                        setShowEmpty(false)
                    }
                    resolve(true)
                })
            }
        })
    }
    const getList = async (params) => {
        return getBookPageList(params)
    }
    // 分享
    useShareAppMessage(async () => {
        // 获取当前页面栈
        const pages = Taro.getCurrentPages()
        // 获取栈顶的页面，即当前页面
        const currentPage = pages[pages.length - 1]
        // 获取页面的路径和参数
        const route = currentPage.route // 页面路径
        if (route) {
            let shareInfo = await share({ pagePath: route })
            let { sharePicUrl, shareTitles, pageName, pagePath } = shareInfo
            return {
                title: shareTitles || app.appInfo?.appName + '-' + pageName,
                path: pagePath || undefined,
                imageUrl: sharePicUrl || undefined
            }
        }
        return {}
    })

    const callBacn = (b) => {
        Taro.createSelectorQuery()
            .select('.classList') // 选择器，用于选择要获取信息的元素
            .boundingClientRect() // 获取节点的布局信息
            .exec((res) => {
                if (res[0]) {
                    const height = res[0].height; // 获取元素的高度
                    setFilterHeight(height + indexStore.navHeight);
                } else {
                    console.log("未找到指定元素");
                }
            });
        setOpen(b)
    }
    useEffect(() => {
        callBacn(false)
    }, [])
    return (
        <View className='index'>
            {classifyStore?.classifyData?.length > 0 && <View style={{ background: "#fff" }} className='classList' onClick={() => { setIsSetOpen(false) }}>
                <BookTypeTabs open={open} onCallback={callBacn} typeValue={classifyStore?.classifyData} typeTabIndex={classifyStore.categoryId} workDirection={classifyStore.workDirection} ></BookTypeTabs>
            </View>}
            <View>

            </View>
            <View onTouchStart={() => {
                setIsSetOpen(true)
            }} >
                <ScrollView
                    lowerThreshold={filterHeight}
                    // refresherTriggered={this.state.isShow}
                    style={{ height: `calc(100vh - ${filterHeight + 10}px)` }}
                    onScrollToLower={load}
                    onScroll={(evt: any) => {
                        let top = evt.detail.scrollTop
                        if(timeRef.current){
                            clearTimeout(timeRef.current)
                        }
                        timeRef.current=setTimeout(()=>{
                            if (isSetOpen) {
                                if (top > 100 && open) {
                                    callBacn(false)
                                }
                                if (top < 100 && !open) {
                                    callBacn(true)
                                }
                            }
                        },100)
                       
                    }}
                    className="scrollview"
                    scrollY={true}
                    refresherDefaultStyle="black"
                // scrollWithAnimation={true}
                >
                    <View className='w  row for_top1 pd_btm'>
                        {
                            classifyStore?.bookList?.records?.length > 0 && classifyStore?.bookList?.records?.map((item, index) => {
                                return <>
                                    <View key={item.bookId} ><BookboxRowBig {...item} /></View>
                                </>
                            })
                        }
                        {
                            showEmpty && <Empty />
                        }
                    </View>
                </ScrollView>
            </View>
        </View>

    );
});
export default TopNavBar(inject('store')(observer(Index)), {
    tab: true,
    tabVal: [{ value: 0, text: "男生" }, { value: 1, text: "女生" }],
    backgroundColor: '#fff',
    color: "#333",
    search: false,
});
