import { View, Image } from "@tarojs/components";
import './PhotoWall.scss'
import Taro, { usePullDownRefresh, useReachBottom, useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import NewTimePicker from "@/_health/base/new_timepicker";
import { getAlbums } from "@/services/health";
import ListFooter from "@/_health/components/list_footer";
import Layout from "@/components/layout/layout";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import NoRecord from "@/_health/components/no_record";
import { useTranslation } from "react-i18next";

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

const scale = '?x-oss-process=image/resize,w_150,limit_0'

export default function PhotoWall() {
    const screenWidth = Taro.getWindowInfo().screenWidth
    const space = 2
    const itemWidth = (screenWidth - space * 2) / 3.0

    const pageSize = 10
    const [pageIndex, setPageIndex] = useState(1)
    const [triggered, setTriggered] = useState(false)
    const [list, setList] = useState<any>([])
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = useState(false)
    const [loaded, setLoaded] = useState(false)

    const {t} = useTranslation()

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

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

    useEffect(() => {
        refresh()
        Taro.setNavigationBarTitle({
            title:t('health.photo_wall')
        })
        // getAlbumsData(router.params.window)
    }, [])

    usePullDownRefresh(() => {
        refresh()
    })

    function refresh() {
        getList(1)
    }
    useReachBottom(() => {
        more()
        // setPageIndex(pageIndex+1)
        // getHistory()
    })

    function more() {
        if (total <= pageIndex*pageSize || loading) {
            return;
        }
        var page = pageIndex + 1
        getList(page)
    }


    function getList(page) {
        if (loading) return

        setPageIndex(page)
        setLoading(true)
        if (page == 1)
            setTriggered(true)
        getAlbums({
            page: page,
            limit: pageSize,
            window: router.params.window
        }).then(res => {
            var array: any = [];

            (res as any).data.map(item => {
                array.push(...item.images)
            })
            // setList(array)
            setLoaded(true)
            setLoading(false)
            setTriggered(false)
            if (page == 1) {
                setTotal((res as any).total)
                setList(array)
            } else {
                setList(list.concat(array))
            }

            Taro.stopPullDownRefresh()
            // setMedias((res as any).data)
        })
    }

    function getCountImgs(index) {
        // var imgs:any = []
        const start = Math.max(0, index - 10)
        const end = Math.min(list.length, index + 10 + 1)

        return list.slice(start, end)
    }

    function detail() {
        return <View style={{ display: 'flex', flexDirection: 'column' }}>
            <View className="photo_wall2">
                {
                    list.map((item, index) => {
                        return <Image key={index}
                            src={item + scale}
                            mode="aspectFill"
                            onClick={() => {
                                Taro.previewImage({
                                    current: item,
                                    urls: getCountImgs(index)
                                })
                            }}
                            style={{ width: itemWidth, height: itemWidth, backgroundColor: '#f5f5f5', marginBottom: space }} />
                    })
                }
                <View style={{ width: itemWidth, height: itemWidth }} />
                <View style={{ width: itemWidth, height: itemWidth }} />
            </View>
            {
                loaded && pageIndex*pageSize >= total && <ListFooter noMore={true} />
            }

        </View>
    }

    return <View style={{ position: 'relative' }}>
        <Layout children={detail()}
            // title={router.params.title}
            
            isFastSleepTheme={router.params.type == 'time'}
            secondPage={true}
            titleColor={'#fff'}
            title={t('health.photo_wall')}
            type={TemplateType.customHeader}
            refresh={() => { refresh() }}
            triggered={triggered}
            more={() => { more() }}
            titleShowStyle={NaviBarTitleShowType.scrollToShow}
        />
        {
            loaded && list.length == 0 && <NoRecord />
        }

    </View>
}