import React, { useEffect, useMemo, useState } from 'react';
import { observer, inject } from 'mobx-react';
import { useDidHide, useDidShow, useShareAppMessage } from '@tarojs/taro';
//==========components组件引用========================
import TopNavBar1 from '@src/components/TopNavBar/index1';
import ScrollViewHoc from '@src/components/ScrollView';
import { Store } from '@src/app';
import useApi from '@src/Hook/useApi';
import BannerBox from '@src/components/PupPetry/BannerBox'
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import BookHead from '@src/components/PupPetry/BookHead';
import BookHotTabs from '@src/components/PupPetry/BookHotTabs';
import BookboxColumnSmall from '@src/components/PupPetry/BookBox/BookboxColumnSmall';
import BookboxRowMiddle from '@src/components/PupPetry/BookBox/BookboxRowMiddle';
import BookboxColumnBig from '@src/components/PupPetry/BookBox/BookboxColumnBig';
import { share } from '@src/utils';
import BookboxRowBig from '@src/components/PupPetry/BookBox/BookboxRowBig';

interface Props {
    store: Store;
}
const Index: React.FC<Props> = ({ store }) => {
    const { bookStore, indexStore } = store
    const { indexComponents, getBookPageList } = useApi()
    const [pageShow, setPageShow] = useState(false)//防止小程序切换页面组件不会被真实卸载,阻止不必要的操作
    const [oldworkDirection, setoldworkDirection] = useState<any>(null)
    // 首页配置信息
    const indexConfig = useMemo(() => {
        let obj = {}
        let thatPage = app?.appInfo?.appPageComponentList?.find(item => item.pagePath === 'pages/index/index')
        let thatWd = thatPage?.appComponentListVOS?.find(item => item.workDirection === bookStore.workDirection)
        thatWd?.appComponentListVOS?.forEach((item, index) => {
            return obj[item.componentType] = { ...item, eq: index }
        })
        return obj
    }, [indexComponents, pageShow, bookStore.workDirection, indexStore.isLogin])
    // 页面显示请求数据
    useEffect(() => {
        if (pageShow) {
            console.log("页面显示请求数据")
            indexCompontent()
        }
    }, [pageShow, bookStore.workDirection, app.appInfo]); // Dependency array, runs effect only once on mount and unmount
    // 使用 useDidShow 代替 onShow
    useDidShow(() => {
        // 分享消息配置
        setPageShow(true)
        // log("Page is shown or brought to foreground");
    });
    // 使用 useDidHide 如果需要在页面隐藏时做一些处理
    useDidHide(() => {
        setPageShow(false)
        // log("Page is hidden or sent to background");
    });
    // 处理首页展示的组件的请求
    const indexCompontent = () => {
        // 小程序的组件配置
        Object.keys(indexConfig)?.forEach(key => {
            switch (key) {
                case "banners"://轮播
                    getBanners()
                    break;
                case "hot_books"://今日热书
                    getToDayHotBooks()
                    break;
                case "hot_category"://热门分类
                    getHotCategory()
                    break;
                    {/* 重磅新书 new_books*/ }
                case "new_books":
                    getNewBooks()
                    break;
                    {/* 热门推荐 hot_rec*/ }
                case "hot_rec":
                    getHotRec()
                    break;
                    {/* 口碑佳作 best_reviews*/ }
                case "best_reviews":
                    getBestReviews()
                    break;
                    {/* 经典热书 classic_books*/ }
                case "classic_books":
                    getClassicBooks()
                    break;
                    {/* 必看好书 best_books*/ }
                case "best_books":
                    getBestBooks()
                    break;
                    {/* 猜你喜欢 guess_like*/ }
                case "guess_like":
                    getGuessLike({ pageSize: 20, pageNum: 1 })
                    break;
            }
        })
    }
    // 获取banners
    const getBanners = () => {
        indexComponents?.banners(bookStore.workDirection)
    }
    // 获取热门分类
    const getHotCategory = () => {
        indexComponents?.hot_category(bookStore.workDirection).then((res: any) => {
            let data = res?.data?.data
            if (data?.bookCategoryList?.length > 0) {
                if (!bookStore?.bookList?.total || oldworkDirection !== bookStore?.workDirection) {
                    getHotBooks(data?.bookCategoryList?.[0].id)
                    setoldworkDirection(bookStore.workDirection)
                }
            }
        })
    }
    // 热门分类书籍
    const getHotBooks = (categoryId) => {
        if (categoryId) {
            getBookPageList({ pageNum: 1, pageSize: 8, workDirection: bookStore.workDirection, categoryId, type: 'index' })
        }
    }
    // 今日热书
    const getToDayHotBooks = () => {
        indexComponents?.hot_books(bookStore.workDirection)
    }
    // 重磅新书
    const getNewBooks = () => {
        indexComponents?.new_books(bookStore.workDirection)
    }
    // 经典
    const getClassicBooks = () => {
        indexComponents?.classic_books(bookStore.workDirection)
    }
    // 口碑
    const getBestReviews = () => {
        indexComponents?.best_reviews(bookStore.workDirection)
    }
    // 热门推荐
    const getHotRec = () => {
        indexComponents?.hot_rec(bookStore.workDirection)
    }
    // 必看
    const getBestBooks = () => {
        indexComponents?.best_books(bookStore.workDirection)
    }
    // 猜喜欢
    const getGuessLike = (page) => {
        indexComponents?.guess_like({ workDirection: bookStore.workDirection, ...page })
    }
    //下拉加载
    const load = async () => {
        if (indexConfig['guess_like']) {
            return new Promise((resolve, reject) => {
                let { size, total, records } = indexStore?.indexGuessLike?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]
                let pageSize = size + 20
                if (records?.length >= total) {
                    Taro.showToast({
                        title: '没有更多了~~',
                        duration: 2000,
                        icon: 'none'
                    })
                    reject()
                    return
                } else {
                    getGuessLike({ pageSize, pageNum: 1 })
                    resolve(true)
                }
            })
        }
    }
    // 分享
    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 startMessage = () => {
        console.log('开始');
    };

    const completeMessage = () => {
        console.log('完成');
    };
    console.log("bookStore?.bookList", bookStore?.bookList?.total)
    return <ScrollViewHoc load={load} filterClassName='.searchTs' navHeight={indexStore.navHeight}>
        <TopNavBar1 {...{
            tab: true,
            tabVal: [{ value: 0, text: "男生" }, { value: 1, text: "女生" }],
            backgroundColor: '#fff',
            color: "#333",
            search: true,
        }}>
            <View style={{ display: "flex", flexFlow: 'column' }}>
                {/* 轮播 */}
                {indexConfig['banners'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BannerBox data={indexStore?.indexBanners || []} />
                </View>}
                {/* 今日热门 */}
                {indexConfig['hot_books'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexHotBooks?.showRightButton} title={indexStore?.indexHotBooks?.name || "今日热书"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=今日热书&dataName=indexHotBooks` })
                    }}></BookHead>
                    <View ><BookboxRowMiddle {...indexStore?.indexHotBooks?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.[0]} /></View>
                    <View className='w row'>
                        {
                            indexStore?.indexHotBooks?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index > 0 && index < 5) {
                                    return <View key={index}><BookboxColumnSmall {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 热门分类 */}
                {indexConfig['hot_category'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexHotCategory?.showRightButton} title={indexStore?.indexHotCategory?.name || "热门分类"} fitTitle="全部分类" imgUrl={require('../../icon/right.png')} fitOnBack={() => { Taro.switchTab({ url: '/pages/classify/index' }) }} />
                    <BookHotTabs hotValue={indexStore?.indexHotCategory?.bookCategoryList || []} onBack={(value) => {
                        getHotBooks(value)
                    }} />
                    <View className='w row4'>
                        {
                            bookStore?.bookList?.records?.map((item, index) => {
                                return <View key={index}><BookboxColumnSmall {...item} /></View>
                            })
                        }
                    </View>
                </View>}
                {/* 重磅新书 new_books*/}
                {indexConfig['new_books'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexNewBooks?.showRightButton} title={indexStore?.indexNewBooks?.name || "重磅新书"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=重磅新书&dataName=indexNewBooks` })
                    }} />
                    <View className='w row'>
                        {
                            indexStore?.indexNewBooks?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index < 3) {
                                    return <View key={index}><BookboxColumnBig {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 热门推荐 hot_rec*/}
                {indexConfig['hot_rec'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexHotRec?.showRightButton} title={indexStore?.indexHotRec?.name || "热门推荐"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=热门推荐&dataName=indexHotRec` })
                    }} />
                    <View className='w  row for_top'>
                        {
                            indexStore?.indexHotRec?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index < 3) {
                                    return <View key={index}><BookboxRowBig {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 口碑佳作 best_reviews*/}
                {indexConfig['best_reviews'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexBestReviews?.showRightButton} title={indexStore?.indexBestReviews?.name || "口碑佳作"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=口碑佳作&dataName=indexBestReviews` })
                    }} />
                    <View className='w row'>
                        {
                            indexStore?.indexBestReviews?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index < 4) {
                                    return <View key={index}><BookboxColumnSmall {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 经典热书 classic_books*/}
                {indexConfig['classic_books'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexClassicBooks?.showRightButton} title={indexStore?.indexClassicBooks?.name || "经典热书"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=经典热书&dataName=indexClassicBooks` })
                    }} />
                    <View className='w row'>
                        {
                            indexStore?.indexClassicBooks?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index < 8) {
                                    return <View key={index}><BookboxColumnSmall {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 必看好书 best_books*/}
                {indexConfig['best_books'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexBestBooks?.showRightButton} title={indexStore?.indexBestBooks?.name || "必看好书"} fitTitle="更多" imgUrl={require('../../icon/right.png')} fitOnBack={() => {
                        Taro.navigateTo({ url: `/pages/indexMore/index?title=必看好书&dataName=indexBestBooks` })
                    }} />
                    <View className='w  row for_top'>
                        {
                            indexStore?.indexBestBooks?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.map((item, index) => {
                                if (index < 3) {
                                    return <View key={index}><BookboxRowBig {...item} /></View>
                                }
                            })
                        }
                    </View>
                </View>}
                {/* 猜你喜欢 guess_like*/}
                {indexConfig['guess_like'] && <View style={{ order: indexConfig['banners'].eq }}>
                    <BookHead showBtn={indexStore?.indexGuessLike?.showRightButton} title={indexStore?.indexGuessLike?.name || "猜你喜欢"} />
                    <View className='w  row for_top pd_btm'>
                        {
                            indexStore?.indexGuessLike?.[app?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.records?.map((item, index) => {
                                return <View key={index}><BookboxRowBig {...item} /></View>
                            })
                        }
                    </View>
                </View>}
            </View>
        </TopNavBar1>

    </ScrollViewHoc>
};
export default inject('store')(observer(Index))