import { View, Text, PickerView, PickerViewColumn } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { useTranslation } from "react-i18next";
import '@components/input/LimitPickers.scss'
import { TimeFormatter } from "@/utils/time_format";
import { AtActivityIndicator } from 'taro-ui';
import React from "react";


let currentValueList;
const Component = forwardRef((props: {
    themeColor?: string, title?: string,
    min: number,
    max: number,
    current: number,
    onChange: Function,
    onCancel: Function,

    duration?: number,
    isFast?: boolean,
    isEnd?: boolean,
    endTimestamp?: number,
    isTimeout?: boolean,
    isLoading?: boolean
}, ref) => {
    const today = new Date();
    const [loaded, setLoaded] = useState(false)
    const [values, setValues] = useState([0, today.getHours(), today.getMinutes()])
    const [days, setDays] = useState(['0'])
    const [todayIndex, setTodayIndex] = useState(0)
    const { t } = useTranslation()
    const hours: number[] = [];
    var color = props.themeColor ? props.themeColor : '#ff0000'
    var alpha = alphaToHex(0.4)
    for (let i = 0; i <= 23; i++) {
        hours.push(i);
    }
    const minutes: number[] = [];
    for (let i = 0; i <= 59; i++) {
        minutes.push(i);
    }


    function resetPickerData() {
        if (currentValueList) {
            setValues(currentValueList)
        }
    }

    useImperativeHandle(ref, () => ({
        resetPickerData: resetPickerData
    }));


    useEffect(() => {
        var minDate = new Date(props.min)
        var maxDate = new Date(props.max)
        var currentDate = new Date(props.current)
        minDate.setHours(0)
        minDate.setMinutes(0)
        minDate.setSeconds(0)
        minDate.setMilliseconds(0)
        maxDate.setHours(0)
        maxDate.setMinutes(0)
        maxDate.setSeconds(0)
        maxDate.setMilliseconds(0)
        // 计算两个日期的时间戳差异（以毫秒为单位）
        const timeDifference = Math.abs(maxDate.getTime() - minDate.getTime());

        // 将时间戳差异转换为天数
        const count = Math.ceil(timeDifference / (1000 * 3600 * 24));
        var list: any = [];
        var selIndex = 0;
        for (var i = 0; i <= count; i++) {
            var dt = new Date(props.min + i * 24 * 3600 * 1000)
            const month = dt.getMonth() + 1;
            const day = dt.getDate();
            // const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
            const weekday = TimeFormatter.getDayOfWeek(dt.getDay(), true);
            // const formattedDate = global.language == 'en' ? `${weekday} ${TimeFormatter.getMonth(month)} ${day}` : `${TimeFormatter.getMonth(month)}${day}日 ${weekday}`;
            const formattedDate = global.language == 'en' ? `${TimeFormatter.getMonth(month)} ${day}` : `${TimeFormatter.getMonth(month)}${day}日`;
            var today1 = new Date();
            var yesterday = new Date(today1.getTime() - 24 * 3600 * 1000)
            if (dt.getMonth() == currentDate.getMonth() && dt.getDate() == currentDate.getDate()) {
                selIndex = i
            }
            if (dt.getMonth() == today1.getMonth() && dt.getDate() == today1.getDate()) {
                list.push(TimeFormatter.getTodayUnit());
                setTodayIndex(i)
            }
            else if (dt.getMonth() == yesterday.getMonth() && dt.getDate() == yesterday.getDate()) {
                list.push(TimeFormatter.getYesterdayUnit());
            }
            else {
                list.push(formattedDate);
            }
        }
        setDays(list)
        currentValueList = [selIndex, currentDate.getHours(), currentDate.getMinutes()]
        setValues([selIndex, currentDate.getHours(), currentDate.getMinutes()])
        setTimeout(() => {
            setValues([selIndex, currentDate.getHours(), currentDate.getMinutes()])
        }, 50)
        setLoaded(true)
    }, [])

    function alphaToHex(alpha) {
        var alphaValue = Math.round(alpha * 255); // 将透明度乘以255并四舍五入
        var hexValue = alphaValue.toString(16); // 将整数转换为十六进制字符串
        if (hexValue.length === 1) {
            hexValue = "0" + hexValue; // 如果十六进制字符串只有一位，补零
        }
        return hexValue;
    }

    function cancel(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        props.onCancel()
    }

    function confirm(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }

        var date = new Date();
        date.setDate(new Date(props.max).getDate() - (days.length - values[0] - 1));
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const time = `${year}-${expandZero(month)}-${expandZero(day)}T${expandZero(hours[values[1]])}:${expandZero(minutes[values[2]])}:${expandZero((new Date(global.set_time)).getSeconds())}`;
        if (getTimestamp(time) > global.set_time) {
            setValues([todayIndex, (new Date(global.set_time)).getHours(), (new Date(global.set_time)).getMinutes()])
            setTimeout(() => {
                setValues([todayIndex, (new Date(global.set_time)).getHours(), (new Date(global.set_time)).getMinutes()])
            }, 300);
            Taro.showToast({
                icon: 'none',
                title: t('feature.common.toast.min_time_value'),
            })
            return
        }


        props.onChange(new Date(time).getTime())
    }

    function expandZero(num: number): string {
        return num < 10 ? `0${num}` : `${num}`;
    }

    function getTimestamp(dateTimeString: string): number {
        const timestamp = Date.parse(dateTimeString);
        return timestamp;
    }

    function onPickerChange(e) {
        setValues(e.detail.value)
    }

    function getEndTime() {
        var date = new Date(props.max);
        date.setDate(date.getDate() - (days.length - values[0] - 1));
        date.setHours(values[1])
        date.setMinutes(values[2])
        var newDate = new Date(date.getTime() + props.duration!).getTime()
        if (global.language == 'en') {
            return TimeFormatter.dateDescription(newDate, true) + ' at ' + TimeFormatter.timeDescription(newDate)
        }
        return TimeFormatter.dateDescription(newDate, true) + ' ' + TimeFormatter.timeDescription(newDate)
    }

    function getEndTimestamp(timestamp) {
        if (global.language == 'en') {
            return TimeFormatter.dateDescription(timestamp, true) + ' at ' + TimeFormatter.timeDescription(timestamp)
        }
        return TimeFormatter.dateDescription(timestamp, true) + ' ' + TimeFormatter.timeDescription(timestamp)
    }


    function pickerTimeText() {
        if (props.isTimeout) {
            if (props.isFast) {
                return t('feature.track_time_duration.console.real_fast_end_tip', { time: getEndTimestamp(props.endTimestamp!) })
            }
            else {
                return t('feature.track_time_duration.console.real_sleep_end_tip', { time: getEndTimestamp(props.endTimestamp!) })
            }
        }
        if (props.isFast) {
            if (props.isEnd) {
                return t('feature.track_time_duration.console.real_fast_end_tip', { time: getEndTimestamp(props.endTimestamp!) })
            }
            return t('feature.track_time_duration.console.real_fast_start_tip', { time: getEndTime() })
        }
        else {
            if (props.isEnd) {
                return t('feature.track_time_duration.console.real_sleep_end_tip', { time: getEndTimestamp(props.endTimestamp!) })
            }
            return t('feature.track_time_duration.console.real_sleep_start_tip', { time: getEndTime() })

        }
    }

    function pickerDetail() {
        return <View style={{ display: 'flex', flexDirection: 'column', opacity: loaded ? 1 : 0 }}>
            <Text className='modal_title' style={{ color: color }}>{props.title ? props.title : '测试标题 '}</Text>
            <View style={{ backgroundColor: 'transparent', position: 'relative' }}>
                <PickerView
                    itemStyle={{ color: '#fff', margin: 0, padding: 0 }}
                    value={values}
                    className="picker"
                    maskClass="picker-mask"
                    style={{ color: '#fff' }}
                    onChange={onPickerChange}
                    immediateChange={true}
                    indicatorStyle='height: 50px;color:red;'>
                    <PickerViewColumn style='flex:0 0 45%'>
                        {days.map(item => {
                            return (
                                <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',height:50 }}>{item}</View>
                            );
                        })}
                    </PickerViewColumn>
                    <PickerViewColumn>
                        {hours.map(item => {
                            return (
                                <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',height:50 }}>{item < 10 ? `0${item}` : item}</View>
                            );
                        })}
                    </PickerViewColumn>
                    <PickerViewColumn>
                        {minutes.map(item => {
                            return (
                                <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',height:50 }}>{item < 10 ? `0${item}` : item}</View>
                            );
                        })}
                    </PickerViewColumn>
                </PickerView>
            </View>
            <Text className="pickerEndTime" style={{ color: props.isTimeout ? 'red' : '#ffffff' }}>{pickerTimeText()}</Text>
            <View className='modal_operate'>
                <View className='modal_btn' style={{ backgroundColor: color + alpha }} onClick={cancel}>
                    <Text className='modal_cancel_text' style={{ color: color, fontWeight: 'bold' }}>{t('feature.common.picker_cancel_btn')}</Text>
                </View>
                <View className='btn_space' />
                <View className='modal_btn' style={{ backgroundColor: color, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', opacity: props.isLoading ? 0.6 : 1 }} onClick={confirm}>
                    {
                        props.isLoading && process.env.TARO_ENV == 'rn' && <View style={{ display: 'flex', overflow: 'hidden', height: 20, marginRight: 5 }}><AtActivityIndicator mode="center" color="#000" /></View>
                    }

                    <Text className='modal_confirm_text' style={{ color: '#000', fontWeight: 'bold' }}>{t('feature.common.picker_confirm_btn')}</Text>
                </View>


            </View>
        </View>
    }

    return pickerDetail()
})

export default React.memo(Component);