import { View, Text, Image } from "@tarojs/components";
import { useEffect, 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 from "@tarojs/taro";
import { getThemeColor } from "./hooks/health_hooks";
import { TimeFormatter } from "@/utils/time_format";

let lastMode = ''
export default function MainHistory(props: { type?: string, fast_type?: string }) {
    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 healthRef = useRef(health)


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

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


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

    }, [health.mode])

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

    function more() {
        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
        }
        records(params).then(res => {
            setLoaded(true)
            if (index == 1) {
                setList((res as any).data)
                setTotal((res as any).total)
            }
            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)
            }

        })
    }

    if (!loaded)
        return <View />

    return <View style={{ width: rpxToPx(750), marginTop: rpxToPx(35) }}>
        {/* <Calendar year={2024} month={8}/> */}
        {/* <View style={{
            // position: 'sticky',
            top: 0,
            height: 50,
            backgroundColor: 'blue',
            zIndex: 100
        }} /> */}
        {
            (list.length > 0 || health.mode == 'EAT') && <View className="recent">
                <Text className="h34 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(52),
                paddingBottom:rpxToPx(38),
                backgroundColor:'#fff'
             }}>
                <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" />
                        })
                    }
                    <Image src={require('@assets/_health/cell_arrow.png')} style={{
                        width:rpxToPx(24),
                        height:rpxToPx(24),
                        marginLeft:rpxToPx(4),

                    }}/>
                </View>
            </View>
        }
        {
            list.map((item, index) => {
                return <View ref={refDemo} id={'history_id_0'} key={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>
            })
        }
        {
            (list.length > 0) && (total == list.length) && <Text className="no_more">没有更多了</Text>
        }
    </View>
}