import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { getAlbums, getAlbumsStat } from "@/services/health";
import { View, Text, Image, ScrollView } from "@tarojs/components";
import { useEffect, useState } from "react";
import './Album.scss'
import '@/features/health/History.scss'
import NewHeader, { NewHeaderType } from "@/_health/components/new_header";
import { rpxToPx } from "@/utils/tools";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { MainColorType } from "@/context/themes/color";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import StickyDateList from "@/_health/components/sticky_date_list";
import ListFooter from "@/_health/components/list_footer";
import CoverList from "@/_health/components/cover_list";
import { TimeFormatter } from "@/utils/time_format";
import { useTranslation } from "react-i18next";
import RightArrowRow from "@/_health/components/right_arrow_row";

let myScrollTop = 0
export default function Album() {

    const [medias, setMedias] = useState<any>([])
    const [window, setWindow] = useState('')
    const [stat, setStat] = useState<any>(null)
    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)
    const { t } = useTranslation()

    useEffect(() => {
        getAlbumsData('')
    }, [])

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

    function more() {
        if (loading) return;
        if (total == medias.length) return;
        var index = page;
        index++;
        setPage(index)
        getAlbumsData(window, index)
    }

    function getAlbumsData(str, index = 1) {
        // setIsPulling(true)
        setLoading(true)
        getAlbums({
            page: index,
            limit: 10,
            window: str
        }).then(res => {
            if (index == 1) {
                setMedias((res as any).data)
                setTotal((res as any).total)
            }
            else {
                setMedias([...medias, ...(res as any).data])
            }
            setIsPulling(false)
            setLoading(false)

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

        getAlbumsStat().then(res => {
            setStat(res)
        })
    }

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

    //         showDate = true
    //         dateStr = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'
    //     }
    //     else {
    //         var currentDate = (medias[index].date + '').substring(0, 6)
    //         var now = (medias[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 />
    // }

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

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

        if (e.detail.scrollTop > 60) {
            Taro.setNavigationBarTitle({
                title: t('health.photos')
            })
        }
        else {
            Taro.setNavigationBarTitle({
                title: ''
            })
        }

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

                    date = currentDate.substring(0, 4) + '年' + currentDate.substring(4, 6) + '月'
                }
            })

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

    function historyYear(index) {
        var showDate = false;
        var dateStr2: any = ''
        if (index == 0) {
            var currentDate = global.language == 'en' ? dayjs(medias[index].timestamp).format('YYYY') : dayjs(medias[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(medias[index].timestamp).format('YYYY') : dayjs(medias[index].timestamp).format('YYYY年')
            var now = global.language == 'en' ? dayjs(medias[index - 1].timestamp).format('YYYY') : dayjs(medias[index - 1].timestamp).format('YYYY年')
            if (currentDate != now) {
                showDate = true
                dateStr2 = currentDate
            }
        }
        if (showDate) {
            return <View className="history_year_month h42 bold">{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(medias[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(medias[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')
    }


    return <StickyDateList onRefresherRefresh={() => {
        setIsPulling(true)
        setPage(1)
        getAlbumsData(window, 1)
    }} isPulling={isPulling}
        onScroll={onScroll}
        showDate={showDate}
        date={date}
        loadMore={more}
    >
        <View style={{ display: 'flex', flexDirection: 'column' }}>
            <NewHeader type={NewHeaderType.left} title={t('health.photos')} />
            {/* {stat && <ScrollView style={{ width: rpxToPx(750), flexDirection: 'row', display: 'flex', height: rpxToPx(72) }} scrollX enableFlex showScrollbar={false}>
                <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
                <NewButton type={NewButtonType.img} onClick={() => {
                    setWindow('')
                    getAlbumsData('')
                }}>
                    <View className="streak_toolbar_btn"
                        style={{ backgroundColor: window == '' ? '#B2B2B21A' : 'transparent' }}
                    >
                        <Text className={window == '' ? 'bold h30' : 'h30'}
                            style={{ color: window == '' ? '#000' : MainColorType.g01, marginRight: 5 }}>全部 </Text>
                        <Text className="h20" style={{ color: window == '' ? '#000' : MainColorType.g01 }}>{stat.total}</Text>
                    </View>
                </NewButton>

                {
                    stat.items.map((item, index) => {
                        return <View key={index}>
                            <NewButton type={NewButtonType.img} onClick={() => {
                                setWindow(item.window)
                                getAlbumsData(item.window)
                            }}>
                                <View className="streak_toolbar_btn"
                                    style={{ backgroundColor: window == item.window ? getThemeColor(item.window) + '1A' : 'transparent' }}
                                >
                                    <Text className={window == item.window ? 'bold h30' : 'h30'}
                                        style={{ color: window == item.window ? getThemeColor(item.window) : MainColorType.g01, marginRight: 5 }}>{item.window} </Text>
                                    <Text className="h20" style={{ color: window == item.window ? getThemeColor(item.window) : MainColorType.g01 }}>{' ' + item.image_count}</Text>
                                </View>
                            </NewButton>
                        </View>
                    })
                }
                <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
            </ScrollView>} */}
            {/* <View style={{ height: rpxToPx(36) }} /> */}

            {/* <View className="photo_wall" onClick={() => {
                jumpPage('/pages/account/PhotoWall?window=' + window)
            }}>
                <View style={{ flex: 1 }} />
                <Text className="photo_wall_text">Photo Wall</Text>
                <Image className="photo_wall_arrow" src={require('@assets/_health/arrow2.png')} />
                <View className="album_line" />
            </View> */}

            <RightArrowRow title={t('health.photo_wall')} onClick={() => {
                jumpPage('/pages/account/PhotoWall?window=' + window)
            }} />
            {
                medias.map((item, index) => {
                    return <View key={index} id={`history-${index}`} style={{ display: 'flex', flexDirection: 'column', paddingTop: rpxToPx(6), backgroundColor: '#fff' }}>
                        {
                            historyYear(index)
                        }
                        <View className="history_item2" style={{ paddingRight: rpxToPx(30) }}>
                            <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>
                            {/* <Text className="cell_date">{(item.date + '').substring(6, 9)}</Text> */}
                            <View style={{ display: 'flex', flex: 1 }}>
                                <CoverList
                                    imgs={item.images}
                                    count={item.images.length}
                                />
                                {/* <View className="media" style={{ marginRight: item.images.length == 4 ? 80 : 0 }}>
                                    {
                                        item.images.map((photo, i) => {
                                            return <Image onClick={() => {
                                                Taro.previewImage({
                                                    current: photo,
                                                    urls: item.images
                                                })
                                            }} mode="aspectFill" src={photo} key={i * 900} className="media_item" />
                                        })
                                    }
                                </View> */}
                            </View>
                            {/* <View className="border_footer_line" /> */}
                        </View>
                    </View>
                })
            }
            <View style={{ height: rpxToPx(40), flexShrink: 0, backgroundColor: '#fff' }} />
            <ListFooter noMore={(medias.length > 0) && (total == medias.length)} />
        </View>
    </StickyDateList>
}