import { View, Text, Image } from "@tarojs/components";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import { records } from "@/services/health";
import './History.scss'
import Calendar from "./calendar";
import { useSelector } from "react-redux";
import HistoryItem from "./HistoryItem";
import { rpxToPx } from "@/utils/tools";
import { jumpPage } from "../trackTimeDuration/hooks/Common";
import Taro, { useReady } from "@tarojs/taro";
import { getThemeColor } from "./hooks/health_hooks";
import { TimeFormatter } from "@/utils/time_format";
import dayjs from "dayjs";
import { MainColorType } from "@/context/themes/color";
import { IconArrow, IconCellArrow } from "@/components/basic/Icons";
import NoRecord from "@/_health/components/no_record";
import ListFooter from "@/_health/components/list_footer";

let lastMode = ''
export default forwardRef((props: { type?: string, fast_type?: string, updateDate?: any, refreshSuccess?: any }, ref) => {
    const [itemLayouts, setItemLayouts] = useState<any>([])
    const [list, setList] = useState<any>([])
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    const [loaded, setLoaded] = useState(false)
    const refDemo = useRef()
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [loading, setLoading] = useState(false)
    const healthRef = useRef(health)

    useImperativeHandle(ref, () => ({
        onScroll: onScroll,
        refresh: refresh,
        more: more
    }))

    useEffect(() => {
        if (list.length > 0) {
            setTimeout(() => {
                measureItemLayouts()
            }, 300)
        }
    }, [list])


    useEffect(() => {
        if (!user.isLogin) {
            setList([])
        }
    }, [user.isLogin])

    global.refreshHistory = () => {
        refresh()
    }

    useEffect(() => {
        if (props.type) {
            loadData(1)
        }
    }, [props.type])


    useEffect(() => {
        if (lastMode != health.mode) {
            lastMode = health.mode
            loadData(1)
        }

    }, [health.mode])

    function measureItemLayouts() {
        const query = Taro.createSelectorQuery()
        list.forEach((item, index) => {
            query.select(`#history-${index}`).boundingClientRect()
        });
        query.exec((res) => {
            var layouts: any = []
            res.forEach((rect, index) => {
                if (rect) {
                    layouts[index] = rect.top
                }
            });
            setItemLayouts(layouts)
        })
    }

    function onScroll(e) {
        var top = e.detail.scrollTop
        if (itemLayouts.length > 0) {
            var i = -1
            var date = ''
            list.forEach((item, index) => {
                if (top >= itemLayouts[index] - 50) {
                    i = index
                    date = dayjs(item.window_range.start_timestamp).format('YYYY年M月')
                }
            })
            if (props.updateDate) {
                props.updateDate({
                    show: i != -1,
                    date: date
                })
            }
        }
        else {
            if (props.updateDate) {
                props.updateDate({
                    show: false,
                    date: ''
                })
            }

        }
    }

    function refresh() {
        loadData(1)
        setPage(1)
    }

    function more() {
        if (loading) return;
        if (total == list.length) return;
        var index = page;
        index++;
        setPage(index)
        loadData(index)
    }

    function loadData(index: number) {
        var params: any = {
            window: props.type ? props.type : health.mode,
            limit: 10,
            page: index
        }
        if (props.fast_type) {
            params.fast_type = props.fast_type
        }
        setPage(index)
        setLoading(true)
        records(params).then(res => {
            setLoading(false)
            setLoaded(true)
            if (index == 1) {
                setList((res as any).data)
                setTotal((res as any).total)
                if (props.refreshSuccess) {
                    props.refreshSuccess()
                }
            }
            else {
                setList([...list, ...(res as any).data])
            }

            // if ((res as any).data.length > 0) {
            //     setTimeout(() => {
            //         // var array:any = [];
            //         // (res as any).data.map((item,index)=>{
            //         //     array.push('#history_id_'+index)
            //         // })
            //         // var ids = array.join(',')
            //         // console.log(array)
            //         // console.log(ids)
            //         const query = Taro.createSelectorQuery();
            //         query.selectAll('#history_id_0').boundingClientRect((rect) => {
            //             console.log(rect)
            //         }).exec();
            //     }, 1000)
            // }

        }).catch(e => {
            setLoading(false)
        })
    }

    function historyMonth(index) {
        var showDate = false;
        var dateStr = ''
        if (index == 0) {
            var currentDate = dayjs(list[index].window_range.start_timestamp).format('YYYY年M月')
            var now = dayjs().format('YYYY年M月')

            showDate = true
            dateStr = currentDate

        }
        else {
            var currentDate = dayjs(list[index].window_range.start_timestamp).format('YYYY年M月')
            var now = dayjs(list[index - 1].window_range.start_timestamp).format('YYYY年M月')
            if (currentDate != now) {
                showDate = true
                dateStr = currentDate
            }
        }
        if (showDate) {
            return <View className="history_year_month h30 g01">{dateStr}</View>
        }
        return <View />
    }

    if (!loaded || health.mode == 'DAY' || health.mode == 'NIGHT')
        return <View />

    if (!user.isLogin) return <View />

    return <View style={{ width: rpxToPx(750), marginTop: rpxToPx(36) }}>
        {
            (list.length >= 0 || health.mode == 'EAT') && <View className="recent">
                <Text className="h50 bold" >Recent</Text>
                {
                    health.mode == 'EAT' && <View onClick={() => {
                        jumpPage('/_health/pages/archive')
                    }}>
                        <Image className="archive" src={require('@assets/_health/archive.png')} />
                    </View>
                }

                {/* <View className="border_footer_line" /> */}
            </View>
        }
        {
            health.mode == 'EAT' && health.eatArchived && health.eatArchived.archived && <View style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                paddingTop: rpxToPx(36),
                paddingBottom: rpxToPx(36),
                backgroundColor: '#fff',
                position: 'relative'
            }}>
                <View className="archived_bg" onClick={() => {
                    jumpPage('/_health/pages/archive')
                }}>
                    <Text className="archived_text" style={{ color: getThemeColor(health.mode) }}>[{health.eatArchived.real_count}/{health.eatArchived.target_count} Meals] Archived {TimeFormatter.dateDescription(new Date(health.eatArchived.timestamp).getTime(), true, false)}</Text>
                    {
                        health.eatArchived.images.map((item, index) => {
                            return <Image src={item} key={index} className="archived_img" mode="aspectFill" />
                        })
                    }
                    <IconArrow color={MainColorType.g03} width={rpxToPx(34)} />
                    {/* <IconCellArrow color={MainColorType.g03} width={rpxToPx(34)} /> */}
                    {/* <Image src={require('@assets/_health/cell_arrow.png')} style={{
                        width: rpxToPx(24),
                        height: rpxToPx(24),
                        marginLeft: rpxToPx(4),

                    }} /> */}
                </View>
                <View className="border_footer_line" />
            </View>
        }
        {
            list.length == 0 && <NoRecord />
        }
        {
            list.map((item, index) => {
                return <View id={`history-${index}`} key={index}>
                    {
                        historyMonth(index)
                    }
                    <HistoryItem
                        data={item}
                        preData={index > 0 ? list[index - 1] : null}
                        index={index}
                        mode={props.type ?? health.mode}
                        fast_type={props.fast_type}
                        onClick={() => {
                            jumpPage('/_health/pages/moment_detail')
                        }} />
                    {/* {
                        props.type == 'EAT' && <HistoryEatItem data={item} index={index} />
                    }
                    {
                        props.type == 'FAST' && <HistoryFastItem data={item} index={index} />
                    }
                    {
                        props.type == 'ACTIVE' && <HistoryActiveItem data={item} index={index} />
                    }
                    {
                        props.type == 'SLEEP' && <HistorySleepItem data={item} index={index} />
                    } */}
                </View>
            })
        }
        <ListFooter noMore={(list.length > 0) && (total == list.length)} />
    </View>
})