import { View, Text, Image, ScrollView } from "@tarojs/components";
import './home.scss'
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { followUser, getFriendMoments, getUserMoments, getUserProfile, unfollowUser } from "@/services/friend";
import { useSelector } from "react-redux";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { rpxToPx } from "@/utils/tools";
import { MainColorType } from "@/context/themes/color";
import showActionSheet from "@/components/basic/ActionSheet";
import ListFooter from "@/_health/components/list_footer";
import RecentItem from "../components/recent_item";
import { useTranslation } from "react-i18next";
import NoRecord from "@/_health/components/no_record";

let useRoute;
let useNavigation;
let scenario = '';
if (process.env.TARO_ENV == 'rn') {
    useRoute = require("@react-navigation/native").useRoute
    useNavigation = require("@react-navigation/native").useNavigation
}
let timer
export default function UserHome() {

    const user = useSelector((state: any) => state.user);
    const [profile, setProfile] = useState<any>(null)
    const [loaded, setLoaded] = useState(false)
    const [loadedList, setLoadedList] = useState(false)
    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;



    const [loading, setLoading] = useState(false)
    const [noMore, setNoMore] = useState(false)
    const [itemLayouts, setItemLayouts] = useState<any>([])
    const [itemHeights, setItemHeights] = useState<any>([])
    const [pageTop, setPageTop] = useState(0)
    const [page, setPage] = useState(1)
    const [endSignal, setEndSignal] = useState(0)
    const [list, setList] = useState<any>([])
    const query = Taro.createSelectorQuery()
    const { t } = useTranslation()

    const [myScrollTop, setMyScrollTop] = useState(0)
    const [count, setCount] = useState(0)


    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }

    useEffect(() => {
        getProfile()
        moments(1)
    }, [])

    useEffect(() => {
        timer = setInterval(() => {
            setCount(count => count + 1)
        }, 1000)
        return () => {
            clearInterval(timer)
        }
    }, [])

    useEffect(() => {
        if (list.length == 0) return

        setTimeout(() => {
            measureItemLayouts()
        }, 300)

        if (process.env.TARO_ENV == 'weapp') {
            const observerObjBottom = Taro.createIntersectionObserver().relativeToViewport({ bottom: 100 })
            observerObjBottom.observe('#footer', (res) => {
                setEndSignal(endSignal => endSignal + 1)
                // console.log(moments.length)
                // if (moments.length==0) return
                // loadMore()
            })
        }

    }, [list])

    useEffect(() => {
        if (moments.length == 0) return
        // loadMore()
    }, [endSignal])

    function getProfile() {
        getUserProfile({ user_id: router.params.uid }).then(res => {
            setProfile(res)
            setLoaded(true)
        })
    }

    function loadMore() {
        if (loading) return;
        if (noMore) return;
        setLoading(true)
        var index = page;
        index++;
        setPage(index)
        moments(index)
    }

    function moments(index) {
        setPage(index)
        var params: any = {
            user_id: router.params.uid,
            page: index,
            limit: 10
        }
        if (index != 1 && list.length > 0) {
            params.last_timestamp = list[list.length - 1].time.timestamp
        }
        getUserMoments(params).then(res => {
            if (index == 1) {
                setList((res as any).data)
            }
            else {
                setList([...list, ...(res as any).data])
            }
            setLoading(false)
            setLoadedList(true)
            if ((res as any).data.length == 0) {
                setNoMore(true)
            }
            else {
                setNoMore(false)
            }
        })
    }

    function measureItemLayouts() {
        if (process.env.TARO_ENV == 'rn') return
        if (list.length <= 10) {
            list.forEach((item, index) => {
                query.select(`#history3-${index}`).boundingClientRect()
            });
            query.exec((res) => {
                var layouts: any = []
                var heights: any = []
                res.forEach((rect, index) => {
                    if (rect) {
                        layouts[index] = rect.top + myScrollTop
                        heights[index] = rect.height
                    }
                });
                setItemLayouts(layouts)
                setItemHeights(heights)
            })
        }
        else {
            list.forEach((item, index) => {
                if (index >= itemLayouts.length) {
                    query.select(`#history3-${index}`).boundingClientRect()
                }
            });
            query.exec((res) => {
                var layouts: any = []
                var heights: any = []
                res.forEach((rect, index) => {

                    if (rect) {
                        layouts[index] = rect.top + myScrollTop
                        heights[index] = rect.height
                    }
                });
                setItemLayouts([...itemLayouts, ...layouts])
                setItemHeights([...itemHeights, ...heights])
            })

        }
    }

    function onScroll(e) {
        // var top = e.detail.scrollTop
        // myScrollTop = top
        var top = e.detail.scrollTop - e.detail.deltaY
        // myScrollTop = e.detail.scrollTop
        setPageTop(top)
        setMyScrollTop(e.detail.scrollTop)
    }

    function tapFollow() {
        var params: any = {
            follow_origin: 'WECHAT_PRIVATE_CHAT',
            user_id: router.params.uid,
        }
        followUser(params).then(res => {
            getProfile()
            Taro.eventCenter.trigger('followUser', router.params.uid)
        })
    }

    function tapFollowing() {
        showActionSheet({
            title: `不再关注“${profile.nickname}”，他的动态将不出现在搭子圈`,
            itemList: ['不再关注'],
            success: (res) => {
                if (res == 0) {
                    unfollowUser(profile.id).then(res => {
                        Taro.eventCenter.trigger('unfollowUser', router.params.uid)
                        getProfile()
                    })
                }
            }
        })
    }

    if (!loaded) return <View />

    // console.log(list.length,pageTop,itemLayouts,)
    return <ScrollView style='height:100vh'
        enableBackToTop
        scrollY={true}
        // refresherEnabled={props.onRefresherRefresh}
        // upperThreshold={70}
        lowerThreshold={140}
        // refresherBackground={MainColorType.g05}
        // onRefresherRefresh={props.onRefresherRefresh}
        // refresherTriggered={props.isPulling}
        onScroll={onScroll}
        onScrollToUpper={() => {
            setPage(1)
            setPageTop(0)
            if (moments.length > 10) {
                setList(list.slice(0, 10))
                setItemHeights(itemHeights.slice(0, 10))
                setItemLayouts(itemLayouts.slice(0, 10))
            }

        }}
        onScrollToLower={loadMore}
    ><View>
            <View className="home_top">
                <Image className="cover" mode="aspectFill" src={profile.cover} />
                <Image className="home_avatar" src={profile.avatar} />
                <View className="home_nickname bold">{profile.nickname}</View>
                <View style={{
                    position: process.env.TARO_ENV=='rn'?'absolute':'fixed',
                    top: 0,
                    left: 0,
                    zIndex: 10,
                    height: navigationBarHeight, width: rpxToPx(750), backgroundColor: pageTop >= rpxToPx(380) ? '#f5f5f5' : 'transparent', display: 'flex',
                    flexDirection: 'column', justifyContent: 'flex-end'
                }}>
                    <View style={{ height: 44, width: rpxToPx(750), position: 'relative', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                        {/* <View onClick={() => {
                            Taro.navigateBack()
                        }} style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 80, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Back</View> */}
                        <Image src={require('@assets/_health/navi_back.png')} style={{
                            position: 'absolute',
                            width: rpxToPx(92),
                            height: rpxToPx(64),
                            left: 0,
                            top: 22 - rpxToPx(32)
                        }}
                            onClick={() => {
                                Taro.navigateBack()
                            }}
                        />
                        <Text style={{
                            color: pageTop >= rpxToPx(380) ? '#000' : 'transparent'
                        }} className="bold">{profile.nickname}</Text>
                    </View>
                </View>
            </View>
            <View style={{ height: rpxToPx(62) }}></View>
            {
                router.params.uid != user.id && <View style={{ marginLeft: rpxToPx(45) }}>
                    {
                        profile.relation == 'FRIEND' || profile.relation == 'FOLLOWING' ?
                            // <NewButton type={NewButtonType.fill}
                            //     width={rpxToPx(665)}
                            //     height={rpxToPx(72)}
                            //     title="following"
                            //     color={MainColorType.g02}
                            //     onClick={tapFollowing}
                            // />
                            <View onClick={tapFollowing} className="following h30 bold">{t('health.following2')}</View>

                            : <NewButton type={NewButtonType.fill}
                                width={rpxToPx(665)}
                                height={rpxToPx(72)}
                                title={t('health.follow')}
                                color={MainColorType.blue}
                                onClick={tapFollow}
                            />
                    }
                </View>
            }
            {/* <View style={{height:rpxToPx(60)}}/> */}
            {
                list.map((item, index) => {
                    if (itemLayouts.length >= index + 1 && pageTop > 0 && index > 5) {
                        if (Math.abs(itemLayouts[index] - pageTop) > 2500) {
                            return <View style={{ height: itemHeights[index] }} id={`history—temp-${index}`}>
                            </View>
                        }

                    }
                    return <View key={index} id={`history3-${index}`}>
                        <RecentItem data={item} index={index} />
                    </View>
                })
            }
            {
                loadedList && list.length == 0 && <NoRecord />
            }
            <ListFooter noMore={noMore} loading={loading} />
            <View id="footer" style={{ width: 1, height: 1 }}></View>
        </View>
    </ScrollView>
}