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 [filterHeight, setFilterHeight] = useState(0)
    const lastScrollTop = useRef(0); // 用于跟踪上一次滚动位置
    // 获取分类列表
    useEffect(() => {
        if (pageShow) {
            console.log("获取分类列表")
            let { workDirection } = classifyStore
            getBookCategoryList(workDirection).then((res: any) => {
                if (res?.data?.code === 200) {
                    classifyStore.setData({ classifyData: res?.data?.data })
                    callBacn(false)
                }
            })
        }
    }, [classifyStore.workDirection, pageShow]); // Dependency array, runs effect only once on mount and unmount
    //获取书籍列表
    useEffect(() => {
        if (pageShow) {
            console.log("获取书籍列表")
            let { workDirection } = classifyStore
            let { categoryId } = classifyStore
            lastScrollTop.current = 0
            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 {
                        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)
    }
 
    return (
        <View className='index'>
            {classifyStore?.classifyData?.length > 0 && <View style={{ background: "#fff" }} className='classList' >
                <BookTypeTabs open={open} onCallback={callBacn} typeValue={classifyStore?.classifyData} typeTabIndex={classifyStore.categoryId} workDirection={classifyStore.workDirection} ></BookTypeTabs>
            </View>}
            <View>

            </View>
            <View onTouchStart={() => {
                if (open) {
                    callBacn(false);
                }
            }} >
                <ScrollView
                    lowerThreshold={filterHeight}
                    // refresherTriggered={this.state.isShow}
                    style={{ height: `calc(100vh - ${filterHeight+10}px)` }}
                    onScrollToLower={load}
                    scrollTop={lastScrollTop.current}
                    onScroll={(evt: any) => {
                        const top = evt.detail.scrollTop;
                        // 判断滚动方向
                        // if (top > lastScrollTop.current && open) {
                        //     // 向下滚动，执行关闭操作
                        //     if (top > 100) {
                        //         callBacn(false);
                        //     }
                        // } else if (top < lastScrollTop.current && !open) {
                        //     // 向上滚动，执行打开操作
                        //     if (top < 100) {
                        //         callBacn(true);
                        //     }
                        // }
                       
                        // 更新 lastScrollTop 以供下一次判断
                        lastScrollTop.current = top;
                    }}
                    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,
});
