import { View, Text,Image } 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";

export default function Component(props: { records: any[] }) {
    const user = useSelector((state: any) => state.user);
    const [list, setList] = useState(props.records)
    const isDebugModel = false
    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) {
        var timelineItems: any = [];
        for (var i = item.records.length - 1; i > 0; i--) {
            var type = item.records[i].type == 'total' ? '总计' : item.records[i].type == 'sync' ? '同步' : '打卡'
            timelineItems.push(
                {
                    status: 'done',
                    title: type + item.records[i].items[0].value + '步',
                    content: TimeFormatter.timelineFormatTime(item.records[i].timestamp),
                }
            )
        }

        return <CenterContentTitleModal title= {formateDate(item.date + '')}>
            <Timeline items={timelineItems} type={TimelineType.timeSecond} />
        </CenterContentTitleModal>
        // return <View style={{ display: 'flex', width: '100%', flexDirection: 'column', alignItems: 'center' }}>
        //     <View style={{display:'flex',flexDirection:'row',width:'100%'}}>
        //         <Text className="modalTitle">{formateDate(item.date + '')}</Text>
        //     </View>
        //     <Timeline items={timelineItems} type={TimelineType.timeSecond} />
        // </View>
    }

    function showDetail(item) {
        var node = (<Modal children={schedules(item)}
            modalType={ModalType.center}
            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:isDebugModel?'red':'transparent'}}>{TimeFormatter.getYearByDate(item.date)}</Text>
                    }
                    <Text className="operate_day" style={{backgroundColor:isDebugModel?'red':'transparent'}}>{TimeFormatter.getMonthAndDayByDate(item.date)}</Text>

                    <RecordItem onClick={() => showDetail(item)} delete={() => deleteRecord(item.records[0])}>
                        <View className="operate_item">
                            {/* <View className="status_bg">
                                <Text className="status_text">{item.records[0].type == 'total' ? '总计' : item.records[0].type == 'sync' ? '同步' : '打卡'}</Text>
                            </View>
                            <View style={{ width: 12 }} /> */}
                            <Text className="value" style={{backgroundColor:isDebugModel?'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>
            })
        }
    </View>

    // 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 => {
    //             return <View style={{ display: 'flex', flexDirection: 'column' }}>
    //                 <Text className="operate_day">{formateDate(item.date + '')}</Text>
    //                 {
    //                     item.records.map(record => {
    //                         return <RecordItem delete={() => deleteRecord(record)}>
    //                             <View className="operate_item">
    //                                 <View className="status_bg">
    //                                     <Text className="status_text">{record.type == 'total' ? '总计' : record.type == 'sync' ? '同步' : '打卡'}</Text>
    //                                 </View>
    //                                 <View style={{ width: 12 }} />
    //                                 <Text className="value">{record.items[0].value}</Text>
    //                                 <Text className="unit">步</Text>
    //                                 <View style={{ flex: 1 }} />
    //                                 <Text className="time">{formateHourMinutes(record.timestamp)}</Text>
    //                             </View>
    //                         </RecordItem>
    //                     })
    //                 }
    //             </View>
    //         })
    //     }
    // </View>
}