import JournalCover from "@/features/journal/components/journal_cover";
import { getJournals } from "@/services/health";
import { View, Text, Image } from "@tarojs/components";
import { useEffect, useState } from "react";
import './Journal.scss'
import dayjs from "dayjs";
import { rpxToPx } from "@/utils/tools";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import NewHeader, { NewHeaderType } from "@/_health/components/new_header";
import Taro from "@tarojs/taro";
import StickyDateList from "@/_health/components/sticky_date_list";
import { MainColorType } from "@/context/themes/color";
import ListFooter from "@/_health/components/list_footer";
import TimeTitleDesc from "@/_health/components/time_title_desc";

export default function Journal() {
    const [journals, setJournals] = useState<any>([])
    const [isPulling, setIsPulling] = useState(false)
    const [itemLayouts, setItemLayouts] = useState<any>([])
    const [showDate, setShowDate] = useState(false)
    const [date, setDate] = useState('')

    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        getJounalsData(1)
    }, [])

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

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

    function getJounalsData(index = 1) {
        setLoading(true)
        getJournals({
            page: index,
            limit: 10
        }).then(res => {
            let list = (res as any).data
            list.forEach(element => {
                let array: any = []
                element.windows.map(item => {
                    item.events.map(event => {
                        event.moments && event.moments.map(moment => {
                            if (moment.media && moment.media.length > 0) {
                                moment.media.map(media => {
                                    array.push(media.url)
                                })
                            }
                        })

                    })
                })
                element.imgs = array
            });
            setLoading(false)
            if (index == 1) {


                setTotal((res as any).total)
                setJournals(list)
                setIsPulling(false)
            }
            else {
                setJournals([...journals, ...list])
            }
        }).catch(e => {
            setLoading(false)
        })
    }

    function measureItemLayouts() {
        const query = Taro.createSelectorQuery()
        journals.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 = ''
            journals.forEach((item, index) => {
                if (top >= itemLayouts[index] - 50) {
                    i = index
                    var currentDate = (journals[index].date + '').substring(0, 6)
                    date = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'
                }
            })

            setShowDate(i != -1)
            setDate(date)
        }
        else {
            setShowDate(false)
            setDate('')
        }
    }

    function getTitle(item) {
        if (item.title) {
            return item.title;
        }
        if (item.moments) {
            return item.moments[0].title
        }
        return ''
    }

    function journalItem(window, index) {
        var array: any = [];
        window.events.map(event => {
            event.moments && event.moments.map(moment => {
                if (moment.media && moment.media.length > 0) {
                    moment.media.map(media => {
                        array.push(media.url)
                    })
                }
            })
        })
        return <View style={{ flex: 1, display: 'flex', flexDirection: 'row', marginBottom: rpxToPx(12), overflow: 'hidden' }} key={index}>
            {
                array.length > 0 && <JournalCover imgs={array} />
            }
            <View style={{
                display: 'flex',
                flexDirection: 'column',
                flex: 1,
                overflow: 'hidden',
                backgroundColor: array.length == 0 ? '#f5f5f5' : 'transparent',
                padding: array.length == 0 ? rpxToPx(20) : 0,
                marginRight: rpxToPx(40)
            }}>
                {

                    window.events.map((item2, index2) => {
                        return <TimeTitleDesc
                            key={index2 * 1000}
                            className="line1"
                            style={{ width: array.length > 0 ? rpxToPx(370) : rpxToPx(532) }}
                            time={dayjs(item2.time.timestamp).format('HH:mm')}
                            title={getTitle(item2)}
                            desc={item2.moments && item2.moments.length > 0 ? item2.moments[0].description : ''}
                        />
                    })
                }



            </View>
        </View>
    }

    function historyMonth(index, preIndex) {
        var showDate = false;
        var dateStr = ''
        if (index == 0) {
            var currentDate = (journals[index].date + '').substring(0, 6)
            var now = dayjs().format('YYYYMM')

            showDate = true
            dateStr = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'

        }
        else {
            var currentDate = (journals[index].date + '').substring(0, 6)
            var now = (journals[index - 1].date + '').substring(0, 6)
            if (currentDate != now) {
                showDate = true
                // dateStr = currentDate
                dateStr = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'
            }
        }
        if (showDate) {
            return <View className="history_year_month h30 g01">{dateStr}</View>
        }
        return <View />
    }

    return <StickyDateList onRefresherRefresh={() => {
        setIsPulling(true)
        getJounalsData()
    }} isPulling={isPulling}
        onScroll={onScroll}
        showDate={showDate}
        date={date}
        loadMore={() => {
            more()
        }}
    ><View style={{ display: 'flex', flexDirection: 'column' }}>
            <NewHeader type={NewHeaderType.left} title="Journal" />
            {
                journals.map((item, index) => {
                    return <View key={index}>
                        {
                            historyMonth(index, index - 1)
                        }
                        <View className="album_item" id={`history-${index}`} onClick={() => {
                            jumpPage('/pages/account/JournalDetail?detail=' + JSON.stringify(item))
                        }}>

                            <Text className="cell_date">{(item.date + '').substring(6, 9)}</Text>
                            <View style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
                                {
                                    item.windows.map((window, i) => {
                                        return journalItem(window, i)
                                    })
                                }
                            </View>
                            <View className="border_footer_line" />
                        </View></View>
                })
            }
            <ListFooter noMore={(journals.length > 0) && (total == journals.length)} />
        </View></StickyDateList>
}