import { View, Text, Image } from "@tarojs/components";
import './MetricHistory.scss'
import RecordItem from "@/features/common/RecordItem";
import { deleteMetricRecord } from "@/services/trackSomething";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { TimeFormatter } from "@/utils/time_format";
import { ColorType } from "@/context/themes/color";
import { rpxToPx } from "@/utils/tools";
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 [selReference, setSelReference] = useState(global.selMetricItem && global.selMetricItem.references.length > 0 ? global.selMetricItem.references[0] : null)
    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 TimeFormatter.getTodayUnit();
        } else if (diff < 2 * day) {
            return TimeFormatter.getYesterdayUnit();
        } 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 deleteRecord(record: any) {
        deleteMetricRecord({ id: record.id }).then(res => {
            list.map(item => {
                var index = item.records.findIndex(item => item.id == record.id);
                if (index >= 0)
                    item.records.splice(index, 1)
            })
            for (let i = list.length; i > 0; i--) {
                if (list[i - 1].records.length == 0) {
                    list.splice(i - 1, 1)
                }
            }
            // console.log(list)
            setList(JSON.parse(JSON.stringify(list)))
            global.refreshMetric()
        })
    }

    function showMore() {
        var list:any = []
        global.selMetricItem.references.map((item)=>{
            list.push((item as any).standard)
        })
        Taro.showActionSheet({
            itemList: list,
            success: function (res) {
                // console.log(res.tapIndex)
                setSelReference(global.selMetricItem.references[res.tapIndex])
            },
            fail: function (res) {
                console.log(res.errMsg)
            }
        })
    }

    function metricStandard() {
        if (global.selMetricItem && global.selMetricItem.references.length > 0) {
            return <View style={{ display: 'flex', flexDirection: 'column', position: 'relative' }}>
                <Text className="cell_header">{selReference.standard}</Text>
                <Text onClick={showMore} style={{ color: global.selMetricItem.theme_color, position: 'absolute', right: rpxToPx(86), top: -rpxToPx(10) }}>More</Text>
                {
                    selReference.categories.map((item, index) => {
                        var cellClassName = 'cell_full'
                        var showLine = false
                        if (selReference.categories.length > 1) {
                            if (index == 0) {
                                cellClassName = 'cell_top'
                                showLine = true
                            }
                            else if (index == selReference.categories.length - 1) {
                                cellClassName = 'cell_bottom'
                                showLine = false
                            }
                            else {
                                cellClassName = 'cell_center'
                                showLine = true
                            }
                        }
                        return <View className={cellClassName} key={index}>
                            <Text className="cell_title" style={{ color: global.selMetricItem.theme_color }}>{item.value_range}</Text>
                            <Text className="cell_value" style={{ color: '#fff' }}>{item.category}</Text>
                            {
                                showLine && <View className="cell_line" style={{ height: 1 }} />
                            }
                        </View>
                    })
                }

            </View>
        }
    }

    var lastYearStr = '2025年'
    return <View style={{ display: 'flex', flexDirection: 'column' }}>
        {
            user.test_user && <Text style={{ color: '#fff', position: 'absolute', right: 50, top: 0 }} onClick={() => global.clearHistory()}>删除全部</Text>
        }
        {
            metricStandard()
        }
        {
            (list as any).map(item => {
                var showYear = lastYearStr != TimeFormatter.getYearByDate(item.date)
                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>
                    {
                        item.records.map(record => {
                            return <RecordItem delete={() => deleteRecord(record)}>
                                <View className="operate_item1">
                                    {/* <View className="status_bg">
                                       
                                    </View>
                                    <View style={{ width: 12 }} /> */}
                                    <Text className="value" style={{ backgroundColor: global.isDebug ? 'red' : 'transparent' }}>{record.items[0].value}</Text>
                                    {
                                        record.items.length > 1 && <Text className="value">/{record.items[1].value}</Text>
                                    }
                                    {
                                        record.items.length > 2 && <Text className="value">/{record.items[2].value}</Text>
                                    }
                                    <Text className="unit">{record.items[0].unit}</Text>
                                    <View style={{ flex: 1 }} />
                                    <Text className="time">{formateHourMinutes(record.timestamp)}</Text>

                                </View>
                            </RecordItem>
                        })
                    }
                </View>
            })
        }

    </View>
}