import { PickerView, PickerViewColumn, View, Text } from "@tarojs/components";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import './LimitPickers.scss'
import Taro from "@tarojs/taro";
import React from "react";
import { useTranslation } from "react-i18next";
import { TimeFormatter } from "@/utils/time_format";
// export default function Component(props: { limit: number, onChange: Function, onCancel: Function,isRealTime?:boolean,limitDay?:number,time?:number,ref?:any }) {

let todayIndex = -1
const Component = forwardRef((props: {
    limit: number, onChange: Function, onCancel: Function,
    isRealTime?: boolean, limitDay?: number, time: number, themeColor?: string, title?: string,
    isFast?: boolean,
    endTimestamp?: number
}, ref) => {

    const days: string[] = [];
    const today = new Date();

    const pickerDate = new Date(props.time + 3 * 24 * 3600 * 1000)
    var color = props.themeColor ? props.themeColor : '#ff0000'
    var alpha = alphaToHex(0.4)
    const [values, setValues] = useState([3, today.getHours(), today.getMinutes()])
    const [isDisableConfirm, setIsDisableConfirm] = useState(false)
    const [count, setCount] = useState(0)
    // const [todayIndex,setTodayIndex] = useState(-1)
    const { t } = useTranslation()

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

    useEffect(() => {
        global.picker_time = global.set_time
        if (props.time) {
            var date = new Date(props.time)
            setValues([3, date.getHours(), date.getMinutes()])
        }
    }, [])
    // useEffect(() => {
    //     setValues([6, today.getHours(), today.getMinutes()])
    // }, [props.limit])

    useEffect(() => {
        var now = new Date();
        if (!props.isRealTime) {
            now = new Date(global.set_time);
        }

        now.setDate(today.getDate() - ((props.limitDay ? props.limitDay - 1 : 6) - values[0]));
        now.setHours(values[1])
        now.setMinutes(values[2])
        global.picker_time = now.getTime()
    }, [values])



    for (let i = props.limitDay ? props.limitDay - 1 : 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(pickerDate.getDate() - i);

        const month = date.getMonth() + 1;
        const day = date.getDate();
        // const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
        const weekday = TimeFormatter.getDayOfWeek(date.getDay(), true);
        const formattedDate = global.language == 'en' ? `${weekday} ${TimeFormatter.getMonth(month)} ${day}` : `${TimeFormatter.getMonth(month)}${day}日 ${weekday}`;
        var today1 = new Date();
        var yesterday = new Date(today1.getTime() - 24 * 3600 * 1000)
        if (date.getMonth() == today1.getMonth() && date.getDate() == today1.getDate()) {
            days.push(TimeFormatter.getTodayUnit());
            todayIndex = i
        }
        else if (date.getMonth() == yesterday.getMonth() && date.getDate() == yesterday.getDate()) {
            days.push(TimeFormatter.getYesterdayUnit());
        }
        else {
            days.push(formattedDate);
        }

    }

    const hours: number[] = [];


    for (let i = 0; i <= 23; i++) {
        hours.push(i);
    }

    const minutes: number[] = [];
    for (let i = 0; i <= 59; i++) {
        minutes.push(i);
    }



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

    function getDaysDiff(date: Date): number {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const targetDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        targetDate.setHours(0, 0, 0, 0);

        const timeDiff = today.getTime() - targetDate.getTime();
        const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

        return daysDiff;
    }

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


    }

    function onPickerEnd(e) {

    }

    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(pickerDate.getDate() - (6 - values[0]));
        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
        }


        else {
            var limitDate = new Date(props.limit)

            if (getTimestamp(time) < props.limit) {

                if (limitDate.getDate() == new Date(props.time).getDate()) {
                    setValues([3, limitDate.getHours(), limitDate.getMinutes()])
                    setTimeout(() => {
                        setValues([3, limitDate.getHours(), limitDate.getMinutes()])
                    }, 300)
                }
                else {
                    setValues([2, limitDate.getHours(), limitDate.getMinutes()])
                    setTimeout(() => {
                        setValues([2, limitDate.getHours(), limitDate.getMinutes()])
                    }, 300)
                }

                Taro.showToast({
                    icon: 'none',
                    title: t('feature.common.toast.max_time_value'),
                })
                return
            }
        }

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

        // if (!props.isRealTime) {
        //     date = new Date(global.set_time);
        //     date.setDate(today.getDate() - ((props.limitDay ? props.limitDay - 1 : 6) - values[0]));
        // }

        // 
        // date.setHours(values[1])
        // date.setMinutes(values[2])
        // props.onChange(date.getTime())
    }

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

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

    function pickerTimeText() {
        if (props.isFast) {
            return `原定于${getEndTimestamp(props.endTimestamp!)}结束`
        }
        else {
            return `原定于${getEndTimestamp(props.endTimestamp!)}起床`
        }
    }

    function pickerDetail() {
        return <View style={{ display: 'flex', flexDirection: 'column' }}>
            <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}
                    onPickEnd={onPickerEnd}
                    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' }}>{item}</View>
                            );
                        })}
                    </PickerViewColumn>
                    <PickerViewColumn>
                        {hours.map(item => {
                            return (
                                <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>{item < 10 ? `0${item}` : item}</View>
                            );
                        })}
                    </PickerViewColumn>
                    <PickerViewColumn>
                        {minutes.map(item => {
                            return (
                                <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>{item < 10 ? `0${item}` : item}</View>
                            );
                        })}
                    </PickerViewColumn>
                </PickerView>

                {/* <View className="point_bg1 ">
                <Text style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>:</Text>
            </View> */}
            </View>
            <Text className="pickerEndTime" style={{color:'red'}}>{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 }} onClick={confirm}>
                    <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);;