import React, { useEffect, useMemo, useState } from 'react';
import { observer, inject } from 'mobx-react';
import { useDidHide, useDidShow } from '@tarojs/taro';
//==========components组件引用========================
import TopNavBar from '@src/components/TopNavBar';
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';


interface Props {
    store: Store;
}
const Index: React.FC<Props> = ({ store }) => {
    const { appInfoStore, bookStore, indexStore } = store
    const { indexComponents, getBookPageList } = useApi(appInfoStore)
    const [pageShow, setPageShow] = useState(false)//防止小程序切换页面组件不会被真实卸载,阻止不必要的操作
    // 首页配置信息
    const indexConfig = useMemo(() => {
        let obj = {}
        let thatPage = appInfoStore?.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])
    // 页面显示请求数据
    useEffect(() => {
        if (pageShow) {
            indexCompontent()
        }
    }, [pageShow, appInfoStore.token, bookStore.workDirection, appInfoStore.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)
        bookStore.setData({ bookList: [] })
        // 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;
            }
        })
    }
    // 获取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) {
                getHotBooks(data?.bookCategoryList?.[0].id)
            }
        })
    }
    // 热门分类书籍
    const getHotBooks = (categoryId) => {
        if (categoryId) {
            getBookPageList({ pageNum: 1, pageSize: 8, workDirection: bookStore.workDirection, categoryId })
        }
    }
    // 今日热书
    const getToDayHotBooks = () => {
        indexComponents?.hot_books(bookStore.workDirection)
    }
    return <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?.[appInfoStore?.appInfo?.appCategory === 1 ? "longBookInfoAppVOS" : "shortBookInfoAppVOS"]?.[0]} /></View>
            <View className='w row'>
                {
                    indexStore?.indexHotBooks?.[appInfoStore?.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>}
    </View>
};
export default TopNavBar(inject('store')(observer(Index)), {
    tab: true,
    tabVal: [{ value: 0, text: "男生" }, { value: 1, text: "女生" }],
    backgroundColor: '#fff',
    color: "#333",
    search: true
});