import JournalCover from "@/features/journal/components/journal_cover";
import { getJournals } from "@/services/health";
import { View, Text, Image, ScrollView } 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, { useRouter } 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";
import { TimeFormatter } from "@/utils/time_format";
import { useTranslation } from "react-i18next";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import { useSelector } from "react-redux";
import { IconClose } from "@/components/basic/Icons";
import TargetProgress from "@/_health/components/target_progress";
import NoRecord from "@/_health/components/no_record";

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

export default function Journal() {
    const health = useSelector((state: any) => state.health);
    const [journals, setJournals] = useState<any>([])
    const [isPulling, setIsPulling] = useState(false)
    const [itemLayouts, setItemLayouts] = useState<any>([])
    const [itemHeights, setItemHeights] = useState<any>([])
    const [showDate, setShowDate] = useState(false)
    const [date, setDate] = useState('')
    const [loaded, setLoaded] = useState(false)
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = useState(false)
    const { t } = useTranslation()
    const [pageTop, setPageTop] = useState(0)

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

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

    const [window, setWindow] = useState(router.params.type ?? '')
    const items = ['FAST', 'SLEEP', 'EAT', 'ACTIVE']

    const [showTip, setShowTip] = useState(router.params.show_tip == '1')
    const [showBadge, setShowBadge] = useState(router.params.show_badge == '1')
    // useEffect(() => {

    // }, [])

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

    useEffect(() => {
        console.log('last show status', showDate)
    }, [showDate])

    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)
        setPage(index)
        var params: any = {
            page: index,
            limit: 10,
        }
        params.window = window
        getJournals(params).then(res => {
            setLoaded(true)
            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 = []
            var heights: any = []
            res.forEach((rect, index) => {
                if (rect) {
                    layouts[index] = rect.top + myScrollTop
                    heights[index] = rect.height
                }
            });
            setItemLayouts(layouts)
            setItemHeights(heights)
        })
    }

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

        if (top > 60) {

            Taro.setNavigationBarTitle({
                title: pageTitle()
            })
        }
        else {
            Taro.setNavigationBarTitle({
                title: ''
            })
        }


        if (itemLayouts.length > 0) {
            var i = -1
            var dt = ''
            journals.forEach((item, index) => {
                if (top >= itemLayouts[index] - 50) {
                    i = index
                    var currentDate = (journals[index].date + '').substring(0, 6)
                    dt = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'
                }
            })

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

        // if (itemLayouts.length > 0 && itemLayouts[0] > top) {
        //     setShowDate(false)
        //     setDate('')
        //     console.log(itemLayouts[0], showDate, date, top, e.detail.deltaY)
        // }
        // else {
        //     console.log(itemLayouts[0], showDate, date, top, e.detail.deltaY)
        // }

    }

    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={{ display: 'flex', flexDirection: 'row', marginBottom: rpxToPx(12), overflow: 'hidden', flexShrink: 0 }} key={index}>
            {
                array.length > 0 && <JournalCover imgs={array} />
            }
            <View style={{
                display: 'flex',
                flexDirection: 'column',
                // flex: 1,
                overflow: 'hidden',
                backgroundColor: array.length == 0 ? '#fafafa' : 'transparent',
                paddingLeft: array.length == 0 ? rpxToPx(20) : 0,
                paddingRight: array.length == 0 ? rpxToPx(20) : 0,
                paddingTop: array.length == 0 ? rpxToPx(12) : 0,
                paddingBottom: array.length == 0 ? rpxToPx(12) : 0,
                marginRight: rpxToPx(40),
                flexShrink: 0
            }}>
                {

                    window.events.map((item2, index2) => {
                        if (item2.moments && item2.moments[0].type == 'PIC') return <View key={index2 * 1000} />
                        return <TimeTitleDesc
                            key={index2 * 1000}
                            className="line1"
                            style={{ width: array.length > 0 ? rpxToPx(350) : rpxToPx(512) }}
                            timeObj={item2.time}
                            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 historyYear(index) {
        var showDate = false;
        var dateStr2: any = ''
        if (index == 0) {
            var currentDate = global.language == 'en' ? dayjs(journals[index].timestamp).format('YYYY') : dayjs(journals[index].timestamp).format('YYYY年')
            var now = global.language == 'en' ? dayjs().format('YYYY') : dayjs().format('YYYY年')

            if (currentDate != now) {
                showDate = true
                dateStr2 = currentDate
            }


        }
        else {
            var currentDate = global.language == 'en' ? dayjs(journals[index].timestamp).format('YYYY') : dayjs(journals[index].timestamp).format('YYYY年')
            var now = global.language == 'en' ? dayjs(journals[index - 1].timestamp).format('YYYY') : dayjs(journals[index - 1].timestamp).format('YYYY年')
            if (currentDate != now) {
                showDate = true
                dateStr2 = currentDate
            }
        }
        if (showDate) {
            return <View className="history_year_month h42 bold" style={{ marginBottom: rpxToPx(60) }}>{dateStr2}</View>
        }
        return <View />
    }

    function historyDate(item, index) {
        if (index == 0) {
            if (global.language == 'zh' && TimeFormatter.isToday(item.timestamp)) {
                return '今天'
            }
            if (global.language == 'zh' && TimeFormatter.isYesterday(item.timestamp)) {
                return '昨天'
            }
            return dayjs(item.timestamp).format('DD')
        }
        if (dayjs(item.timestamp).format('MM-DD') ==
            dayjs(journals[index - 1].timestamp).format('MM-DD')) {
            return ''
        }
        if (global.language == 'zh' && TimeFormatter.isToday(item.timestamp)) {
            return '今天'
        }
        if (global.language == 'zh' && TimeFormatter.isYesterday(item.timestamp)) {
            return '昨天'
        }
        return dayjs(item.timestamp).format('DD')
    }

    function historyMonth(item, index) {
        if (index == 0) {
            if (global.language == 'zh' && TimeFormatter.isToday(item.timestamp)) {
                return ''
            }
            if (global.language == 'zh' && TimeFormatter.isYesterday(item.timestamp)) {
                return ''
            }
            return dayjs(item.timestamp).format('MMM')
        }
        if (dayjs(item.timestamp).format('MM-DD') ==
            dayjs(journals[index - 1].timestamp).format('MM-DD')) {
            return ''
        }
        if (global.language == 'zh' && TimeFormatter.isToday(item.timestamp)) {
            return ''
        }
        if (global.language == 'zh' && TimeFormatter.isYesterday(item.timestamp)) {
            return ''
        }
        return dayjs(item.timestamp).format('MMM')
    }

    function journalCellText(index) {
        var windows = journals[index].windows
        var array: any = []
        windows.map(window => {
            window.events.map(event => {
                event.moments && event.moments.map(moment => {
                    array.push({
                        title: moment.title,
                        description: moment.description
                    })
                })
            })

        })
        return array
        if (array.length > 0) {
            return <View style={{ display: 'flex', flexDirection: 'column' }}>
                {
                    array.map((item, index) => {
                        if (index >= 3) return <View key={index * 10000} />
                        return <TimeTitleDesc key={index * 10000}
                            time=''
                            title={item.title}
                            desc={item.description}
                        />
                    })
                }
            </View>
        }
        return <View />
    }

    function journalCell(item, index) {
        // if (item.show_ring) {
        //     if (item.windows) {
        //         return <View key={index}>{
        //             item.windows.map((temp, i) => {
        //                 return <TargetProgress key={i * 1000} showLine={i < item.windows.length - 1 ? true : false}
        //                     color={getThemeColor(temp.window)}
        //                     showRing={true}
        //                     desc={temp.description}
        //                     icon={
        //                         null
        //                     }
        //                     canvasId={`${temp.window}${temp.window_range.start_timestamp}${index}`}
        //                     startTimestamp={temp.window_range.start_timestamp}
        //                     endTimerstamp={temp.window_range.end_timestamp}
        //                 />
        //             })
        //         }</View>

        //     }
        //     return <View key={index} />
        // }
        return <View style={{ display: 'flex', flexDirection: 'column' }}>
            {
                (item.pics.length > 0 || item.texts.length > 0) && <View style={{ display: 'flex', flexDirection: 'row', marginBottom: rpxToPx(12), overflow: 'hidden', flexShrink: 0 }} key={index}>
                    {
                        item.pics.length > 0 && <View onClick={(e) => {
                            if (process.env.TARO_ENV == 'weapp') {
                                e.stopPropagation()
                            }
                            Taro.previewImage({
                                current: item.pics[0],
                                urls: item.pics
                            })
                        }}>
                            <JournalCover imgs={item.pics} />
                        </View>
                    }
                    <View style={{
                        display: 'flex',
                        flexDirection: 'column',
                        // flex: 1,
                        overflow: 'hidden',
                        backgroundColor: item.pics.length == 0 ? '#fafafa' : 'transparent',
                        paddingLeft: item.pics.length == 0 ? rpxToPx(20) : 0,
                        paddingRight: item.pics.length == 0 ? rpxToPx(20) : 0,
                        paddingTop: item.pics.length == 0 ? rpxToPx(12) : 0,
                        paddingBottom: item.pics.length == 0 ? rpxToPx(12) : 0,
                        marginRight: rpxToPx(40),
                        flexShrink: 0
                    }}>
                        {

                            item.texts.map((item2, index2) => {
                                return <TimeTitleDesc
                                    key={index2 * 1000}
                                    className='line1'//{item.pics.length == 0 ? 'line2' : 'line3'}
                                    style={{ width: item.pics.length > 0 ? rpxToPx(350) : rpxToPx(512) }}
                                    time=''
                                    title={item2.title}
                                    desc={item2.description}
                                />
                            })
                        }




                    </View>


                </View>
            }

            {
                item.show_ring && item.windows && <View key={index}>{
                    item.windows.map((temp, i) => {
                        return <TargetProgress key={i * 1000} showLine={i < item.windows.length - 1 ? true : false}
                            color={getThemeColor(temp.window)}
                            showRing={true}
                            desc={temp.description}
                            icon={
                                null
                            }
                            canvasId={`${temp.window}${temp.window_range.start_timestamp}${index}`}
                            startTimestamp={temp.window_range.start_timestamp}
                            endTimerstamp={temp.window_range.end_timestamp}
                        />
                    })
                }</View>


            }
        </View>
    }

    function pageTitle() {
        if (router.params.type == 'EAT') {
            return t('health.title_food_journal')
        }
        else if (router.params.type == 'ACTIVE') {
            return t('health.title_active_journal')
        }
        return t('health.title_journal')
    }

    function markDoneTip() {
        if (health.mode != 'EAT' && health.mode != 'ACTIVE') return
        var scenario = getScenario(health.windows, health.mode)
        if (scenario.status != 'OG') return
        if (!showTip) return

        var strTitle = ''
        if (scenario.archive_timestamp) {
            var today = new Date().getDate()
            var date = new Date(scenario.archive_timestamp).getDate()
            if (today == date) {
                strTitle = t('health.tonight_at', { time: dayjs(scenario.archive_timestamp).format('HH:mm') })
            }
            else {
                strTitle = t('health.tomorrow_at', { time: dayjs(scenario.archive_timestamp).format('HH:mm') })
            }
        }

        return <View className="mark_done_tip" style={{
            backgroundColor: getThemeColor(health.mode) + '1A'
        }}>
            <View style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
                <Text className="h28 bold" style={{ color: getThemeColor(health.mode) }}>{strTitle}</Text>
                <Text className="h24 bold"><Text style={{ fontWeight: 'normal' }}>{t('health.detail_complete_tip_head')}</Text>{t('health.detail_complete_tip_end')}</Text>
            </View>
            <NewButton type={NewButtonType.img} btnStyle={{
                height: rpxToPx(32),
                width: rpxToPx(32)
            }} onClick={() => {
                setShowTip(false)
                if (health.mode == 'EAT') {
                    global.hideEatArchiveTip = true
                }
                else {
                    global.hideActiveArchiveTip = true
                }
            }}>
                <IconClose color={MainColorType.g03} width={rpxToPx(32)} height={rpxToPx(32)} />
            </NewButton>
        </View>
    }

    if (!loaded) return <View />

    // return <recycle-view
    //     batch={true}
    //     id="recycleId"
    //     enableBackToTop
    //     refresherEnabled
    //     upperThreshold={70}
    //     lowerThreshold={80}
    //     refresherBackground={MainColorType.g05}
    //     onRefresherRefresh={() => {
    //         setIsPulling(true)
    //         getJounalsData(1)
    //     }}
    //     refresherTriggered={isPulling}
    //     onScroll={onScroll}
    //     onScrollToLower={() => {
    //         more()
    //     }}
    // >
    //     <View>
    //         <NewHeader type={NewHeaderType.left} title={pageTitle()} />
    //         {
    //             markDoneTip()
    //         }
    //     </View>

    //     {
    //         journals.map((item, index) => {
    //             return <recycle-item key={index}><View key={index}>
    //                 {
    //                     historyYear(index)
    //                 }
    //                 <View className="history_item2" id={`history-${index}`} onClick={() => {
    //                     jumpPage('/pages/account/JournalDetail?date=' + item.date + '&window=' + window) //JSON.stringify(item))
    //                 }}>

    //                     <View className="cell_date" >
    //                         <View className="h42 bold" style={{ lineHeight: rpxToPx(60) + 'px' }}>{historyDate(item, index)}</View>
    //                         <View className="h24 bold" style={{ marginLeft: rpxToPx(6), marginTop: rpxToPx(13), lineHeight: rpxToPx(47) + 'px' }}>{historyMonth(item, index)}</View>
    //                     </View>
    //                     <View style={{ display: 'flex', flexDirection: 'column', flex: 1, width: rpxToPx(552), }}>
    //                         {
    //                             journalCell(item, index)
    //                         }
    //                     </View>
    //                 </View></View>
    //             </recycle-item>
    //         })
    //     }
    //     <View>长列表后面的内容</View>
    // </recycle-view>

    function itemData(index,item) {
        if (itemLayouts.length >= index + 1 && index > 5) {
            if (Math.abs(itemLayouts[index] - pageTop) > 2500) {
                return <View style={{ height: itemHeights[index] }} id={`history-${index}`}>
                    {/* {index} */}
                </View>
            }
        }
        return <View className="history_item2" id={`history-${index}`} onClick={() => {
            jumpPage('/pages/account/JournalDetail?date=' + item.date + '&window=' + window) //JSON.stringify(item))
        }}>

            <View className="cell_date" >
                <View className="h42 bold" style={{ lineHeight: rpxToPx(60) + 'px' }}>{historyDate(item, index)}</View>
                <View className="h24 bold" style={{ marginLeft: rpxToPx(6), marginTop: rpxToPx(13), lineHeight: rpxToPx(47) + 'px' }}>{historyMonth(item, index)}</View>
            </View>
            <View style={{ display: 'flex', flexDirection: 'column', flex: 1, width: rpxToPx(552), }}>
                {
                    journalCell(item, index)
                }
            </View>
        </View>
    }


    return <StickyDateList onRefresherRefresh={() => {
        setIsPulling(true)
        getJounalsData(1)
    }} isPulling={isPulling}
        onScroll={onScroll}
        showDate={showDate}
        date={date}
        loadMore={() => {
            more()
        }}
    ><View style={{ display: 'flex', flexDirection: 'column', minHeight: rpxToPx(464), backgroundColor: '#f5f5f5' }}>

            <NewHeader type={NewHeaderType.left} title={pageTitle()} />
            {
                markDoneTip()
            }
            <View style={{ minHeight: '100vh', backgroundColor: '#fff', paddingTop: rpxToPx(60) }}>
                {
                    journals.map((item, index) => {


                        return <View key={index}>
                            {
                                historyYear(index)
                            }
                            {
                                itemData(index,item)
                            }
                            </View>
                            
                    })
                }
                {
                    loaded && journals.length == 0 && <NoRecord />
                }
            </View>
            <ListFooter noMore={(journals.length > 0) && (total == journals.length)} loading={loading} />
        </View></StickyDateList>
}