import { View, Image, Text, Button } from "@tarojs/components";
import { useLoad, useRouter, useShareAppMessage } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import './JournalDetail.scss'
import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import { rpxToPx } from "@/utils/tools";
import { MainColorType } from "@/context/themes/color";
import TimeTitleDesc from "@/_health/components/time_title_desc";
import CoverList from "@/_health/components/cover_list";
import ListFooter from "@/_health/components/list_footer";
import { TimeFormatter } from "@/utils/time_format";
import TargetProgress from "@/_health/components/target_progress";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import formatMilliseconds from "@/utils/format_time";
import SingleImage from "@/_health/components/single_img";
import { journalDetail } from "@/services/health";
import { useTranslation } from "react-i18next";
import { IconShare } from "@/components/basic/Icons";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { SHARE_COVER_URL } from "@/services/http/api";

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 JournalDetail() {
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [shareUser, setShareUser] = useState<any>(null)
    const [imgs, setImgs] = useState<any>([])
    const [events, setEvents] = useState<any>([])
    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()
    }
    const [data, setData] = useState<any>()
    const [date, setDate] = useState<any>(router.params ? router.params.date : 0)
    // const [detail, setDetail] = useState(JSON.parse(router.params.detail))

    useEffect(() => {
        if (date || router.params.window) {
            var params: any = {
                window: router.params.window
            }
            if (router.params.uid) {
                params.share_user_id = router.params.uid
            }
            journalDetail(date, params).then(res => {
                if ((res as any).windows.length > 0 &&
                    (res as any).windows[0].events.length > 0 &&
                    (res as any).windows[0].events[0].time
                ) {
                    setTitle((res as any).windows[0].events[0].time.timestamp)
                }
                if ((res as any).share_user) {
                    setShareUser((res as any).share_user)
                }

                setData(res)
                updateData(res)
                setLoaded(true)
            })
        }

    }, [])

    if (process.env.TARO_ENV == 'weapp' && global.allowShare) {
        useShareAppMessage((e) => {
            var { timestamp } = data
            var shareDate = ''
            if (TimeFormatter.isToday(timestamp)) {
                shareDate = global.language == 'en' ? 'Today\'s' : '今日'
            }
            else if (TimeFormatter.isYesterday(timestamp)) {
                shareDate = global.language == 'en' ? 'Yesterday\'s' : '昨日'
            }
            else if (TimeFormatter.isTimestampInThisWeek(timestamp)) {
                shareDate = global.language == 'en' ? (dayjs(timestamp).format('dddd') + '\'s') : dayjs(timestamp).format('dddd')
            }
            else {
                shareDate = global.language == 'en' ? dayjs(timestamp).format('MMMM D') : dayjs(timestamp).format('MMMD日')
            }
            var title = t('health.share_all_journal', { date: shareDate })
            var defaultImg = SHARE_COVER_URL + 'my_journal.jpg'
            if (router.params.window == 'EAT') {
                title = t('health.share_food_journal', { date: shareDate })
                defaultImg = SHARE_COVER_URL + 'my_meal_journal.jpg'
            }
            else if (router.params.window == 'ACTIVE') {
                title = t('health.share_activity_journal', { date: shareDate })
                defaultImg = SHARE_COVER_URL + 'my_activity_journal.jpg'
            }

            const uid = router.params.uid

            var imageUrl = imgs.length > 0 ? imgs[0] : defaultImg
            var nickname = shareUser ? shareUser.nickname : user.nickname
            if (nickname.length > 10) {
                nickname.substring(0, 10) + '...'
            }

            return {
                title: nickname + ': ' + title,
                path: `pages/account/JournalDetail?date=${date}&uid=${uid ?? user.id}&window=${router.params.window}`,
                imageUrl: imageUrl
                // imageUrl:'/src/assets/_health/share_01.jpg'
            }
        })
    }

    // useLoad((res2) => {
    //     console.log('share:', res2)
    //     if (res2.date && res2.uid) {
    //         setDate(res2.date)
    //         journalDetail(res2.date, { window: res2.window,share_user_id:res2.uid }).then(res => {
    //             console.log('dsasfads',res)
    //             if ((res as any).windows.length > 0 &&
    //                 (res as any).windows[0].events.length > 0 &&
    //                 (res as any).windows[0].events[0].time
    //             ) {
    //                 setTitle((res as any).windows[0].events[0].time.timestamp)
    //             }
    //             // console.log('aaaaa')
    //             setData(res)
    //             updateData(res)
    //             setLoaded(true)
    //         })
    //     }
    // })

    function setTitle(timestamp) {
        var title = ''
        var t = parseInt(timestamp + '')
        if (TimeFormatter.isToday(t)) {
            title = TimeFormatter.getTodayUnit()
        }
        else if (TimeFormatter.isYesterday(t)) {
            title = TimeFormatter.getYesterdayUnit()
        }
        else {
            if (global.language == 'en') {
                title = dayjs(t).format('dddd, MMM D')
            }
            else {
                title = dayjs(t).format('MMMD日 dddd')
            }
        }
        Taro.setNavigationBarTitle({
            title: title
        })
    }

    function updateData(obj) {
        var array: any = []

        obj.windows.map(item => {
            item.events.map(tem => {
                array.push(tem)
            })
        })
        const sortedArray = array.sort((a, b) => {
            return a.time.timestamp - b.time.timestamp;
        });

        // 返回一个新数组
        const newArray = [...sortedArray];

        // const order = {
        //     'FAST_START': 1,
        //     'FAST_END': 2,
        //     'SLEEP_BEDTIME': 3,
        //     'SLEEP_WAKE_UP': 4
        // }

        // // 分离出需要排序的项和其他项
        // const otherItems = newArray.filter(item => !order[item.event]);
        // const fastStartItems = newArray.filter(item => order[item.event]);

        // // 排序 fastStartItems
        // fastStartItems.sort((a, b) => {
        //     return (order[a.event] || 0) - (order[b.event] || 0);
        // });

        // // 合并其他项和排序后的 fastStartItems
        // const result = otherItems.concat(fastStartItems);



        let array2: any = []
        obj.windows.map(item => {
            item.events.map(event => {
                event.moments && event.moments.map(moment => {
                    if (moment.media && moment.media.length > 0) {
                        moment.media.map(media => {
                            array2.push(media.url)
                        })
                    }
                })

            })
        })
        obj.imgs = array2


        setImgs(obj.imgs)
        // setEvents(result)
        setEvents(newArray)
    }


    function preview(url) {

        Taro.previewImage({
            current: url,
            urls: imgs
        })
    }

    function dayTag(event, moment) {
        // debugger
        // if (!data ||data.length==0) return ''

        // // if (event.event == 'FAST_END' || event.event == 'SLEEP_WAKE_UP') {
        // var data = events.filter(item => {
        //     if (event.event == 'FAST_END') {
        //         return item.event == 'FAST_START'
        //     }
        //     if (event.event == 'SLEEP_WAKE_UP') {
        //         return item.event == 'SLEEP_BEDTIME'
        //     }
        // })
        var begin = data.timestamp//data[0].time.timestamp

        var end = moment ? moment.time.timestamp : event.time.timestamp
        return TimeFormatter.dayTagText(begin, end)
        // }
        // return ''
    }

    function eventList(detail, index) {
        // const list = detail.moments
        return <View key={index} style={{ marginBottom: rpxToPx(24) }}>
            {
                detail.show && <TimeTitleDesc
                    timeObj={detail.time}
                    time={dayjs(detail.time.timestamp).format('HH:mm')}
                    title={detail.title}
                    dayTag={dayTag(detail, null)}
                    desc=''
                />
            }
            {
                detail.moments && detail.moments.map((moment, j) => {
                    return (moment.title || moment.description) && <View key={j * 10} style={{ flexDirection: 'column', display: 'flex' }}>
                        <TimeTitleDesc
                            showPoint={detail.show}
                            timeObj={moment.time}
                            time={dayjs(moment.time.timestamp).format('HH:mm')}
                            title={moment.title}
                            dayTag={dayTag(detail, moment)}
                            desc={moment.description}
                        />
                    </View>
                })
            }
        </View>
    }

    function backHome() {
        Taro.reLaunch({
            url: '/pages/clock/Clock'
        })
    }

    if (!loaded) return <View />




    return <View style={{ backgroundColor: '#fff' }}>
        <View className="journal_detail">
            <Image className="header_avatar" src={shareUser ? shareUser.avatar : user.avatar} mode="aspectFill" />
            <View className="jounal_content">
                <Text className="journal_nickname">{shareUser ? shareUser.nickname : user.nickname}</Text>
                <View style={{ flexDirection: 'column', display: 'flex', marginTop: rpxToPx(24) }}>
                    {
                        events.map((item, index) => {
                            return eventList(item, index)
                        })
                    }
                </View>


                <View className="img_container" style={{ marginTop: 0, marginBottom: rpxToPx(17) }}>
                    {
                        imgs.length == 1 ? <SingleImage url={imgs[0]} /> : <CoverList
                            imgs={imgs}
                            count={imgs.length}
                        />
                    }
                </View>

                {
                    data.windows.map((item, index) => {
                        return <TargetProgress key={index} showLine={true}
                            color={getThemeColor(item.window)}
                            showRing={true}
                            desc={item.description}
                            icon={
                                null
                            }
                            canvasId={`${item.window}${item.window_range.start_timestamp}${index}`}
                            startTimestamp={item.window_range.start_timestamp}
                            endTimerstamp={item.window_range.end_timestamp}
                        />
                    })
                }
                <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: rpxToPx(17), }}>
                    <Text className="h24" style={{ color: MainColorType.g02, lineHeight: rpxToPx(60) + 'px' }}>{t(data.publish.edited ? 'health.journal_updated' : 'health.journal_created', {
                        date_time: global.language == 'en' ?
                            dayjs(data.publish.timestamp).format('MMM D HH:mm') :
                            dayjs(data.publish.timestamp).format('M月D日 HH:mm')
                    })}</Text>
                    {
                        global.allowShare && <View className="share_btn_bg">
                            <View className="share_icon_bg">
                                <IconShare color={MainColorType.link + 'cc'} width={rpxToPx(32)} />
                            </View>
                            <Button className="share_btn" openType="share">1</Button>
                        </View>
                    }

                </View>
                {/* <Text className="h24" style={{ color: MainColorType.g02, marginTop: rpxToPx(17), lineHeight: rpxToPx(60) + 'px' }}>发布于{dayjs(data.publish_timestamp).format('M月D日 HH:mm')}</Text> */}
            </View>

            {
                router.params.uid && <View className="main_footer" style={{ backgroundColor: '#fff' }}>
                    <NewButton
                        type={NewButtonType.fill}
                        color={MainColorType.success}
                        title={t('health.back_home')}
                        width={rpxToPx(646)}
                        height={rpxToPx(96)}
                        onClick={backHome}
                    />
                </View>
            }


        </View>
        <ListFooter />
    </View>
}