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 { View } from '@tarojs/components'
import './index.less'
//==========components组件引用========================
import TopNavBar from '@src/components/TopNavBar/index'
import ScrollViewHoc from '@src/components/ScrollView'
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)
    // 获取分类列表
    useEffect(() => {
        if (pageShow) {
            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) {
            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 refresh = async () => {
        let { workDirection } = classifyStore
        let { categoryId } = classifyStore
        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)
            }
        })
    }
    //下拉加载
    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 {}
    })
    return (
        <View className='index'>
            {classifyStore?.classifyData?.length > 0 && <View style={{ background: "#fff" }} className='classList' onClick={() => { setIsSetOpen(false) }}>
                <BookTypeTabs open={open} onCallback={setOpen} typeValue={classifyStore?.classifyData} typeTabIndex={classifyStore.categoryId} workDirection={classifyStore.workDirection} ></BookTypeTabs>
            </View>}
            <View onTouchStart={() => { setIsSetOpen(true) }}>
                <ScrollViewHoc
                    callback={(top) => {
                        if (isSetOpen) {
                            if (top > 100 && open) {
                                setOpen(false)
                            }
                            if (top < 100 && !open) {
                                setOpen(true)
                            }
                        }
                    }} load={load} refresh={refresh} reloadState={open} filterClassName='.classList' navHeight={indexStore.navHeight}>
                    <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>
                </ScrollViewHoc>
            </View>
        </View>

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