

import TabBar from "@/components/navigation/TabBar";
import { rpxToPx } from "@/utils/tools";
import { View, Text, Image, ScrollView, Button, Block } from "@tarojs/components";
import Taro, { useDidShow, useRouter, useShareAppMessage } from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useRef, useState } from "react";
import { followUser, getFriendMoments, getMyFriends, getUserDashBoard } from "@/services/friend";
import FriendGuide from "./guide";
import EmptyContent from "./empty_content";
import MomentItem from "./moment_item";
import { useTranslation } from "react-i18next";
import { windows } from "@/services/health";
import { setFastWithSleep, setFinishSetup, setLongFast, setRefreshs, setWindows } from "@/store/health";
import { getInfoSuccess } from "@/store/user";
import showActionSheet from "@/components/basic/ActionSheet";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import './moment.scss'
import ListFooter from "@/_health/components/list_footer";
import { MainColorType } from "@/context/themes/color";
import dayjs from "dayjs";
import { IconClose, IconMenu } from "@/components/basic/Icons";
import MomentShare from "./moment_share";
import NoRecord from "@/_health/components/no_record";
import ShareBtn from "@/components/basic/ShareBtn";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import MomentDetailShare from "./moment_detail_share";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import shareTitle from "./moment_unit";



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

let timer;

let myScrollTop = 0

export default function MomentMain() {
    const user = useSelector((state: any) => state.user);


    const observerObjBottom = Taro.createIntersectionObserver().relativeToViewport({ bottom: 100 })
    const [loading, setLoading] = useState(false)
    const [noMore, setNoMore] = useState(false)
    const [friends, setFriends] = useState<any>([])
    const [count, setCount] = useState(0)

    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;

    const [itemLayouts, setItemLayouts] = useState<any>([])
    const [itemHeights, setItemHeights] = useState<any>([])
    const [isPulling, setIsPulling] = useState(false)
    const [pageTop, setPageTop] = useState(0)
    const scrollRef = useRef()


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

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

    const [loaded, setLoaded] = useState(false)
    const [homeType, setHomeType] = useState('NO_FRIEND')
    const [dashBoard, setDashBoard] = useState<any>(null)
    const [moments, setMoments] = useState<any>([])
    const [page, setPage] = useState(1)
    const [endSignal, setEndSignal] = useState(0)

    const [closeGuide, setCloseGuide] = useState(false)
    const [showGuide,setShowGuide] = useState(false)
    const [showShareGuide, setShowShareGuide] = useState(false)
    const [shareInfo, setShareInfo] = useState<any>(null)
    const query = Taro.createSelectorQuery()

    const dispatch = useDispatch()
    const { t } = useTranslation()

    const momentsRef = useRef(moments)

    useEffect(() => {

        dayjs.locale(global.language == 'en' ? 'en' : 'zh-cn');
        require('moment/locale/en-gb')
        require('moment/locale/zh-cn')

        timer = setInterval(() => {
            setCount(count => count + 1)
        }, 1000)

        Taro.eventCenter.on('followUser', listenFollowUser)
        Taro.eventCenter.on('unfollowUser', listenUnfollowUser)
        Taro.eventCenter.on('refreshMoments', refreshMoments)
        Taro.eventCenter.on('moment_share', momentShare)

        Taro.eventCenter.on('refresh_timeline', refreshItem)
        //Taro.eventCenter.trigger('refresh_timeline',(res as any).feed_item)
        return () => {
            Taro.eventCenter.off('followUser')
            Taro.eventCenter.off('unfollowUser')
            Taro.eventCenter.off('refreshMoments')
            Taro.eventCenter.off('moment_share')
            Taro.eventCenter.off('refresh_timeline')
            clearInterval(timer)
        }




    }, [])

    useEffect(() => {
        momentsRef.current = moments;
    }, [moments])

    function listenFollowUser(e) {
        myFriends()
    }

    function listenUnfollowUser(e) {
        myFriends()
    }

    function refreshMoments(e) {
        myFriends()
    }

    function refreshItem(e) {
        if (!e) return
        const { link, moment, user } = e
        var list = JSON.parse(JSON.stringify(momentsRef.current))
        list.map((item) => {
            if (item.link.event_id == link.event_id) {
                if (link) {
                    item.link = e.link
                }
                if (moment) {
                    item.moment = e.moment
                }
                if (user) {
                    item.user = e.user
                }
            }
        })
        setMoments(list)
    }

    function momentShare(e) {
        setShareInfo(e)
        setShowShareGuide(true)
        // var dt = scrollRef.current
        // query.select(`#myscrollview`).boundingClientRect().exec(res=>{
        //     debugger
        // })
    }



    useEffect(() => {
        myFriends()
        if (router.params.type == 'share') {
            if (global.shareTicket) {
                Taro.getShareInfo({
                    shareTicket: global.shareTicket,
                    success(result) {
                        updateRelation(result)
                    },
                })
            }
            else {
                updateRelation(null)
            }
        }
    }, [user.isLogin])


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

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

        observerObjBottom.observe('#footer', (res) => {
            setEndSignal(endSignal => endSignal + 1)
            // if (moments.length==0) return
            // loadMore()
        })
    }, [moments])

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

    function measureItemLayouts() {
        if (moments.length <= 10) {
            moments.forEach((item, index) => {
                query.select(`#history2-${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 {
            moments.forEach((item, index) => {
                if (index >= itemLayouts.length) {
                    query.select(`#history2-${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)
    }

    useDidShow(() => {
        getDashBoard()
    })

    function myFriends() {
        if (!user.isLogin) {
            setLoaded(true)
            Taro.hideLoading()
            return
        }
        setItemHeights([])
        setItemLayouts([])


        getDashBoard()

        getMoments(1)
    }

    function onRefresh() {
        setIsPulling(true)
        getMoments(1)
        getDashBoard()
    }

    function getMoments(index) {
        setPage(index)
        getFriendMoments({
            page: index,
            limit: 10
        }).then(res => {
            setIsPulling(false)
            if (index == 1) {
                setMoments((res as any).data)
            }
            else {
                setMoments([...moments, ...(res as any).data])
            }
            setLoading(false)

            if ((res as any).data.length == 0) {
                setNoMore(true)
            }
            else {
                setNoMore(false)
            }

        }).catch(e => {
            setIsPulling(false)
            setLoading(false)
            setLoaded(true)
            Taro.hideLoading()
        })
    }

    function getDashBoard() {
        getUserDashBoard().then(res => {
            setLoaded(true)
            setHomeType((res as any).homepage_type)
            setDashBoard(res)
            Taro.hideLoading()
        }).catch(e => {
            setLoaded(true)
            Taro.hideLoading()
        })
    }

    function updateRelation(obj) {
        if (!user.isLogin) {
            Taro.setStorageSync('share_uid', router.params.uid)
            Taro.setStorageSync('share_info', JSON.stringify(obj))
            return
        }
        if (user.id != router.params.uid) {
            var params: any = {
                follow_origin: obj ? 'WECHAT_GROUP_CHAT' : 'WECHAT_PRIVATE_CHAT',
                user_id: router.params.uid,
            }
            if (obj) {
                params.wechat = obj
            }
            followUser(params).then(res => {
                myFriends()
            })
        }
    }




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

    function more() {
        showActionSheet({
            title: '',
            itemList: ['个人主页', '我的搭子', '消息通知'],
            success: (index) => {
                switch (index) {
                    case 0:
                        jumpPage('/_moment/pages/home?uid=' + user.id)
                        break;
                    case 1:
                        jumpPage('/_moment/pages/relation')
                        break
                    case 2:
                        jumpPage('/_moment/pages/message')
                        break
                }
            }
        })
    }

    function friendGuide() {
        return <View style={{ position: 'fixed', left: 0, top: 0, width: rpxToPx(750), height: '100vh', zIndex: 100 }}>
            <View style={{ height: navigationBarHeight, width: rpxToPx(750), backgroundColor: '#fff' }} />
            {/* <View onClick={() => {
                setCloseGuide(true)
            }}>关闭</View> */}
            {
                user.isLogin && <View style={{
                    position: 'absolute', left: 10, top: navigationBarHeight - 44, width: 44, height: 44,
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}
                    onClick={() => {
                        // setCloseGuide(true)
                        setShowGuide(false)
                    }}
                >
                    <IconClose color="#000" width={30} height={30} />
                </View>
            }

            <FriendGuide closeShare={()=>{
                setTimeout(()=>{
                    setShowGuide(false)
                },500)
            }}/>
            {
                process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
            }</View>
    }

    function empty() {
        return <View style={{ position: 'fixed', left: 0, top: 0, width: rpxToPx(750), height: '100vh', zIndex: 100 }}>
            <View style={{ height: navigationBarHeight, width: rpxToPx(750), backgroundColor: '#fff' }} />
            {
                user.isLogin && <View style={{
                    position: 'absolute', left: 10, top: navigationBarHeight - 44, width: 44, height: 44,
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}
                    onClick={() => {
                        setCloseGuide(true)
                    }}
                >
                    <IconClose color="#000" width={30} height={30} />
                </View>
            }
            <EmptyContent friends={dashBoard.friends} />
            {
                process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
            }
        </View>
    }

    function shareGuideContent() {
        console.log(shareInfo)
        return <Block><View className="share_guide_bg" style={{ top: 0 }} onClick={(e) => {
            if (process.env.TARO_ENV == 'weapp') {
                e.stopPropagation()
            }
            setShowShareGuide(false)
        }}>
            <View className="share_guide_card" onClick={(e) => {
                if (process.env.TARO_ENV == 'weapp') {
                    e.stopPropagation()
                }

            }}>
                <Image className="share_guide_avatar" mode="aspectFill" src={shareInfo.join.user.avatar} />
                <View className="h34 bold" style={{ marginTop: rpxToPx(60), marginBottom: rpxToPx(60) }}>{shareTitle(t, shareInfo.join.user)}</View>
                <ShareBtn onClick={() => {
                    setShowShareGuide(false)
                }}>
                    <NewButton
                        title="分享给微信好友"
                        type={NewButtonType.fill}
                        width={rpxToPx(480)}
                        height={rpxToPx(96)}
                        color={MainColorType.success}
                        onClick={() => {

                        }}
                    />
                </ShareBtn>
            </View>
        </View>
        </Block>
    }

    function listDetail() {
        return <View >
            <View style={{
                position: 'fixed',
                top: 0,
                left: 0,
                zIndex: 10,
                height: navigationBarHeight, width: rpxToPx(750), backgroundColor: '#f5f5f5', 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 style={{ fontWeight: 'bold', }}>{t('health.moments')}</View>
                    <View onClick={more} style={{ position: 'absolute', left: 10, top: 0, bottom: 0, width: 44, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <IconMenu color="#000" width={rpxToPx(40)} />
                    </View>
                    <View onClick={()=>{
                        setShowGuide(true)
                    }} style={{ position: 'absolute', left: 54, top: 0, bottom: 0, width: 44, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Image src={require('@assets/_health/wechat.png')} style={{ width: rpxToPx(48), height: rpxToPx(48) }} />
                        {/* <Button openType="share" style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, opacity: 0 }} /> */}
                    </View>
                </View>
            </View>
            <ScrollView style={{
                marginTop: navigationBarHeight,
                height: '90vh'
            }}
                enableBackToTop
                ref={scrollRef}
                id="myscrollview"
                scrollY={showShareGuide ? false : true}
                refresherEnabled={true}
                upperThreshold={70}
                // scrollTop={showShareGuide ? pageTop : undefined}
                // lowerThreshold={140}
                refresherBackground={MainColorType.g05}
                onRefresherRefresh={onRefresh}
                refresherTriggered={isPulling}
                onScroll={onScroll}
                onScrollToUpper={() => {
                    // setPage(1)
                    // if (moments.length > 10) {
                    //     setMoments(moments.slice(0, 10))
                    //     setItemHeights(itemHeights.slice(0, 10))
                    //     setItemLayouts(itemLayouts.slice(0, 10))
                    // }

                }}
            // onScrollToLower={props.loadMore}
            >
                <View style={{ backgroundColor: '#fff', minHeight: '100vh', paddingTop: rpxToPx(30), paddingBottom: 100 }}>
                    {
                        dashBoard && dashBoard.new_message && <View className="new_message_bg">

                            <View className="new_message" onClick={() => {
                                jumpPage('/_moment/pages/message')
                            }}>
                                {
                                    dashBoard.new_message.avatars.map((item, index) => {
                                        return <Image className="message_avatar" src={item} key={index} style={{ zIndex: 9 - index, marginLeft: index == 0 ? rpxToPx(8) : -15 }} />
                                    })
                                }
                                <View className="h26 bold" style={{ color: '#fff', minWidth: rpxToPx(260), textAlign: 'center' }}>{dashBoard.new_message.message_tip}</View>
                            </View>
                        </View>
                    }
                    {
                        moments.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={`history2-${index}`}>
                                <MomentItem data={item} del={
                                    () => {
                                        var list = JSON.parse(JSON.stringify(moments))
                                        list.splice(index, 1)
                                        setMoments(list)
                                    }
                                } />
                            </View>
                        })
                    }
                    {
                        moments.length == 0 && <NoRecord style={{ marginTop: rpxToPx(160) }} />
                    }

                    <ListFooter noMore={noMore} loading={loading} />
                    <View id="footer" style={{ width: 1, height: 1 }}></View>
                </View>
            </ScrollView>
            <Block>
                {
                    showShareGuide && <MomentDetailShare user={shareInfo.join.user} btnColor={getThemeColor(shareInfo.join.window)}
                        cover={shareInfo.moment && shareInfo.moment.media && shareInfo.moment.media.length > 0 ? shareInfo.moment.media[0].url : null} />
                }
            </Block>
            <Block>
                {
                    showShareGuide && shareGuideContent()
                }
            </Block>
            {
                process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
            }
            {/* {
                homeType == 'NO_FRIEND' && !closeGuide && friendGuide()
            } */}
            {
                showGuide && friendGuide()
            }
            {
                homeType == 'NO_MOMENT' && !closeGuide && empty()
            }


        </View>

    }

    function content() {
        if (!loaded) {
            return <View >
                {
                    process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
                }
            </View>
        }
        if (!user.isLogin) {
            return friendGuide()
        }


        return listDetail()
        return <View >
            <View style={{
                position: 'fixed',
                top: 0,
                left: 0,
                zIndex: 10,
                height: navigationBarHeight, width: rpxToPx(750), backgroundColor: '#fff', 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>{t('health.moments')}</View>
                    <View onClick={more} style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 80, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>More</View>
                </View>
            </View>
            <View style={{ backgroundColor: '#fff', minHeight: '100vh', paddingTop: navigationBarHeight, marginTop: rpxToPx(60), paddingBottom: 100 }}>
                {
                    dashBoard && dashBoard.new_message && <View className="new_message_bg">

                        <View className="new_message" onClick={() => {
                            jumpPage('/_moment/pages/message')
                        }}>
                            {
                                dashBoard.new_message.avatars.map((item, index) => {
                                    return <Image className="message_avatar" src={item} key={index} style={{ zIndex: 9 - index, marginLeft: index == 0 ? rpxToPx(8) : -15 }} />
                                })
                            }
                            <View className="h26 bold" style={{ color: '#fff', minWidth: rpxToPx(260), textAlign: 'center' }}>{dashBoard.new_message.message_tip}</View>
                        </View>
                    </View>
                }
                {
                    moments.map((item, index) => {
                        if (itemLayouts.length >= index + 1 && pageTop > 0) {
                            if (Math.abs(itemLayouts[index] - pageTop) > 2000) {
                                return <View style={{ height: itemHeights[index] }} id={`history-${index}`}>
                                </View>
                            }
                            // if (Math.abs(itemLayouts[index] - pageTop) > 1500) {
                            //     return <View style={{
                            //         height: itemHeights[index], display: 'flex',
                            //         paddingLeft: rpxToPx(40),
                            //         paddingRight: rpxToPx(40),
                            //         boxSizing: 'border-box',
                            //         flexDirection: 'row'
                            //     }} id={`history-${index}`}>
                            //         <TimelineDate timestamp={item.window_range.start_timestamp}
                            //             pre_timestamp={index > 0 ? list[index - 1].window_range.start_timestamp : null}
                            //         />
                            //         <View style={{
                            //             display: 'flex', flexDirection: 'column', flex: 1,
                            //             width: rpxToPx(552), height: itemHeights[index] - rpxToPx(60), backgroundColor: '#fafafa'
                            //         }}>
                            //         </View>
                            //     </View>
                            // }

                        }
                        return <View key={index} id={`history-{index}`}>
                            <MomentItem data={item} />
                        </View>
                    })
                }

                <ListFooter noMore={noMore} loading={loading} />

            </View>


            {
                process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
            }
        </View>
    }

    return <View>

        {
            content()
        }
        <MomentShare />

    </View>


    return <View>
        <ScrollView scrollY style={{ height: '100vh' }}>
            <Button openType="share">分享</Button>
            <View>好友数量{count}</View>
            {
                friends.map((item, index) => {
                    return <View key={index}>
                        <Image src={item.avatar} style={{ width: 70, height: 70 }} />
                        <Text>{item.nickname}</Text>
                        <Text>{item.relation}</Text>
                    </View>
                })
            }
            <View style={{ height: '100vh', backgroundColor: 'pink', width: rpxToPx(750) }} id="a"></View>
            <View style={{ height: '100vh', backgroundColor: 'blue', width: rpxToPx(750) }} id="b"></View>
            <View style={{ height: '100vh', backgroundColor: 'yellow', width: rpxToPx(750) }} id="c"></View>
            <View style={{ height: '100vh', backgroundColor: 'green', width: rpxToPx(750) }} id="d"></View>
            <View style={{ height: '100vh', backgroundColor: 'red', width: rpxToPx(750) }} id="e"></View>
        </ScrollView>
        {
            process.env.TARO_ENV == 'weapp' && <TabBar index={4} />
        }
    </View>
}