import { View, Text, Image, ScrollView } from "@tarojs/components";
import './MetricHistory.scss'
import RecordItem from "@/features/common/RecordItem";
import { deleteActivityRecord } from "@/services/trackSomething";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import Modal from "@/components/layout/Modal";
import { ModalType, TimelineType } from "@/utils/types";
import Timeline from "@/components/view/Timeline";
import { TimeFormatter } from "@/utils/time_format";
import './ActivityHistory.scss'
import CenterContentTitleModal from "@/features/common/CenterContentTitleModal";
import { useRouter } from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import Taro from "@tarojs/taro";

export default function Component(props: { records: any[] }) {
    const user = useSelector((state: any) => state.user);
    const [list, setList] = useState(props.records)
    const [showModal, setShowModal] = useState(false)
    const [modalItem, setModalItem] = useState(null)
    const { t } = useTranslation()
    const router = useRouter();
    useEffect(() => {
        setList(props.records)
    }, [props.records])
    function formateDate(date: string) {
        //yyyyMMdd转换成日期，如果是今天，返回今天，如果是昨天，返回昨天，如果是昨天之前，返回日期
        const dt = new Date(date.substring(0, 4) + '/' +
            date.substring(4, 6) + '/' +
            date.substring(6));

        const now = new Date();

        const diff = now.getTime() - dt.getTime();
        const day = 1000 * 60 * 60 * 24;

        if (diff < day) {
            return '今天';
        } else if (diff < 2 * day) {
            return '昨天';
        } else {
            return date.substring(0, 4) + '-' +
                date.substring(4, 6) + '-' +
                date.substring(6)//dt.toISOString().slice(0, 10);
        }
    }
    function formateHourMinutes(timestamp: number) {
        var date = new Date(timestamp)
        var hour = date.getHours()
        var minutes = date.getMinutes()
        return `${hour < 10 ? '0' + hour : hour}:${minutes < 10 ? '0' + minutes : minutes}`
    }

    function clear() {

    }

    function deleteRecord(record: any) {

        deleteActivityRecord({ id: record.id }).then(res => {
            list.splice(list.findIndex(item => item.records[0].id == record.id), 1)
            setList([...list])
            global.refreshActivity()
        })
    }

    function schedules(item) {
        console.log(item)
        var timelineItems: any = [];
        for (var i = item.records.length - 1; i > 0; i--) {
            var type = item.records[i].type == 'total' ? t('feature.track_something.activity.total') :
                item.records[i].type == 'sync' ? t('feature.track_something.activity.sync') : t('feature.track_something.activity.check')
            timelineItems.push(
                {
                    status: 'done',
                    title: type + item.records[i].items[0].value + '步',
                    content: TimeFormatter.timelineFormatTime(item.records[i].timestamp),
                    date: TimeFormatter.dateDescription(item.records[i].timestamp),
                    color: item.records[i].type == 'sync' ? '#fff' : router.params.themeColor
                }
            )
        }
        return <View style={{ display: 'flex', flexDirection: 'column' }}>
            <Text className="box_title">{t('feature.track_something.activity.pop_title')}</Text>
            <Text className="box_subtitle">{TimeFormatter.getMonthAndDayByDate(item.date)}</Text>
            <ScrollView style={{ maxHeight: 400 }} scrollY>
                <View style={{ display: 'flex', alignItems: 'center', position: 'relative', width: '100%', flexDirection: 'column' }}>

                    <Timeline items={timelineItems} type={TimelineType.timeFirst} showLastLine={TimeFormatter.getMonthAndDayByDate(item.date) == '今天'} />

                </View>
            </ScrollView>

        </View>

    }

    function showDetail(item) {
        setModalItem(item)
        setShowModal(true)
        // var node = (<Modal children={schedules(item)}
        //     modalType={ModalType.center}
        //     cancelCatchMove={true}
        //     dismiss={() => {
        //         global.showModal(false, null)
        //     }}
        //     confirm={() => { }} />);
        // global.showModal(true, node);
    }
    var lastYearStr = '2023年'

    return <View style={{ display: 'flex', flexDirection: 'column' }}>

        {
            user.test_user && <Text style={{ color: '#fff', position: 'absolute', right: 50, top: 0 }} onClick={() => global.clearHistory()}>删除全部</Text>
        }
        {
            (list as any).map(item => {
                var showYear = lastYearStr != TimeFormatter.getYearByDate(item.date) && lastYearStr != '2023年'
                lastYearStr = TimeFormatter.getYearByDate(item.date)
                return <View style={{ display: 'flex', flexDirection: 'column' }}>
                    {
                        showYear && <Text className="year" style={{ backgroundColor: global.isDebug ? 'red' : 'transparent' }}>{TimeFormatter.getYearByDate(item.date)}</Text>
                    }
                    <Text className="operate_day" style={{ backgroundColor: global.isDebug ? 'red' : 'transparent' }}>{TimeFormatter.getMonthAndDayByDate(item.date)}</Text>

                    <RecordItem onClick={() => showDetail(item)} delete={() => deleteRecord(item.records[0])}>
                        <View className="operate_item">
                            <Text className="value" style={{ backgroundColor: global.isDebug ? 'red' : 'transparent' }}>{item.records[0].items[0].value}</Text>
                            <Text className="unit">步</Text>
                            <View style={{ flex: 1 }} />
                            <Text className="time">{formateHourMinutes(item.records[0].timestamp)}</Text>
                            <Image className="operate_arrow" src={require('@assets/images/arrow3.png')} />
                        </View>
                    </RecordItem>

                </View>
            })
        }
        {
            showModal && <Modal children={schedules(modalItem)}
                modalType={ModalType.center}
                cancelCatchMove={true}
                dismiss={() => {
                    setShowModal(false)
                }}
                confirm={() => { }} />
        }
    </View>
}