import { recordCheck } from "@/services/trackTimeDuration";
import { View, Text, PickerView } from "@tarojs/components";
import trackTimeService, { machine } from "@/store/trackTimeMachine"
import { useEffect, useRef, useState } from "react";
import { TimeFormatter } from "@/utils/time_format";
import TimePickers from '@/components/input/TimePickers'
import { useSelector } from "react-redux";
import Taro from "@tarojs/taro";
import LimitPickers from '@/components/input/LimitPickers';
import { endFast, endSleep, startFast, startSleep } from "../actions/TrackTimeActions";
import { durationDatas, durationIndex, getTitle, pickerDurations } from "../hooks/Console";
import PickerViews from "@/components/input/PickerViews";
import Modal from "@/components/layout/Modal";
import Stepper from "@/components/input/Stepper";
import { EndFastBtn, EndSleepBtn, StartFastBtn, StartSleepBtn } from "@/features/common/SpecBtns";
import Box from "@/components/layout/Box";
import './Console.scss'

export default function Component() {
    const scenario = useSelector((state: any) => state.scenario);
    const time = useSelector((state: any) => state.time);
    const [key, setKey] = useState('');
    const [value, setValue] = useState('');
    const user = useSelector((state: any) => state.user);
    const common = useSelector((state: any) => state.common);
    const [isFast, setIsFast] = useState(true);
    const [fastDuration, setFastDuration] = useState<number>(0);
    const [sleepDuration, setSleepDuration] = useState<number>(0);

    const [isOpen, setIsOpen] = useState(false);
    const [showModal, setShowModal] = useState(false);
    const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])
    const [isOpenDurationPicker, setIsOpenDurationPicker] = useState(false)
    const limitPickerRef = useRef(null)
    const durationPickerRef = useRef(null)


    useEffect(() => {
        getStateDetail();
    }, [machine.context.checkData]);

    useEffect(() => {
        getStateDetail();
    }, [machine.context.currentStatus])

    useEffect(() => {
        trackTimeService.onTransition(state => {
            if ((state.value as any).FAST_SLEEP) {
                setKey('FAST_SLEEP');
                setValue((state.value as any).FAST_SLEEP);
            }
            if ((state.value as any).FAST) {
                setKey('FAST');
                setValue((state.value as any).FAST);
            }
            if ((state.value as any).SLEEP) {
                setKey('SLEEP');
                setValue((state.value as any).SLEEP);
            }
        });
    }, []);

    function getStateDetail() {
        var state = trackTimeService.getSnapshot().value
        if ((state as any).FAST_SLEEP) {
            setKey('FAST_SLEEP');
            setValue((state as any).FAST_SLEEP);
            if ((state as any).FAST_SLEEP == 'WAIT_FOR_START' || (state as any).FAST_SLEEP == 'ONGOING3') {
                setIsFast(true);
            }
            else if ((state as any).FAST_SLEEP == 'ONGOING1') {
                setIsFast(false);
            }
        }
        if ((state as any).FAST) {
            setKey('FAST');
            setValue((state as any).FAST);
            setIsFast(true);
        }
        if ((state as any).SLEEP) {
            setKey('SLEEP');
            setValue((state as any).SLEEP);
            setIsFast(false);
        }

        var checkData = machine.context.checkData;
        if (checkData) {
            var current_record = (checkData as any).current_record;
            if (current_record.fast) {
                var fastCount = current_record.fast.target_end_time - current_record.fast.target_start_time
                setFastDuration(fastCount)
                setFastPickerValue(durationIndex(current_record.fast.target_start_time, current_record.fast.target_end_time, common))
            }

            if (current_record.sleep) {
                var sleepCount = current_record.sleep.target_end_time - current_record.sleep.target_start_time

                setSleepDuration(sleepCount)
                setSleepPickerValue(durationIndex(current_record.sleep.target_start_time, current_record.sleep.target_end_time, common))
            }
        }
    }


    function showPicker() {
        setShowModal(true)
        setIsOpen(true)
        global.set_time = new Date().getTime()
        console.log(global.set_time)
    }

    function hidePicker() {
        setIsOpen(false)
        setTimeout(() => {
            setShowModal(false)
        }, 1000)
    }

    function testLayout() {
        if (!user.test_user) {
            return <View />
        }
        var current_record = machine.context.checkData ? (machine.context.checkData as any).current_record : null;
        if (current_record == null) {
            return <View />
        }
        var isStart = false;
        if (value == 'WAIT_FOR_START' || value == 'ONGOING1') {
            isStart = true
        }
        var isFast = false;
        switch (value) {
            case 'WAIT_FOR_START':
            case 'ONGOING':
                {
                    isFast = (scenario.name == 'FAST' || scenario.name == 'FAST_SLEEP')
                }
                break;
            case 'ONGOING1':
            case 'ONGOING2':
                {
                    isFast = false;
                }
                break
            case 'ONGOING3':
                {
                    isFast = true;
                }
                break;


        }



        return <View style={{ color: '#fff', paddingTop: 30, paddingLeft: 30, display: 'flex', flexDirection: 'column' }}>
            <Text>check scenario:{isFast ? 'fast' : 'sleep'}</Text>
            <Text>check type:{isStart ? 'start' : 'end'}</Text>
            <Text style={{ marginTop: 30 }}>picker restriction</Text>
            <Text style={{ marginLeft: 50 }}>min:{TimeFormatter.formatTimestamp(global.limit)}</Text>
            <Text style={{ marginLeft: 50 }}>pick:{TimeFormatter.formatTimestamp(global.picker_time)}</Text>
            <Text style={{ marginLeft: 50 }}>max{TimeFormatter.formatTimestamp(global.set_time)}</Text>

            <Text style={{ marginTop: 30 }}>now:{TimeFormatter.formatTimestamp(new Date().getTime())}</Text>
            <Text>elapsed:{TimeFormatter.calculateTimeDifference(global.picker_time, new Date().getTime())}</Text>

            <Text style={{ marginTop: 30 }}>real start:{isStart ? '-' : TimeFormatter.formatTimestamp(isFast ? current_record.fast.real_start_time : current_record.sleep.real_start_time)}</Text>
            <Text>real duration:{isStart ? '-' : TimeFormatter.calculateTimeDifference(isFast ? current_record.fast.real_start_time : current_record.sleep.real_start_time, new Date().getTime())}</Text>
        </View>
    }


    function layoutContent() {
        var limit = global.set_time - 7 * 3600 * 1000 * 24;
        global.limit = limit
        var current_record = machine.context.checkData ? (machine.context.checkData as any).current_record : null;
        if (current_record && current_record.last_real_check_time) {
            limit = current_record.last_real_check_time
            global.limit = limit
            //当set_time秒数<=latest_record_time秒数时,最小限制时间戳需+1分钟
            if (new Date(global.set_time).getSeconds() <= new Date(current_record.last_real_check_time).getSeconds()) {
                limit = limit + 60 * 1000
            }
        }

        var color = isFast ? '#aaff00' : '#00ffff'
        if (value == 'ONGOING2') {
            color = '#00ffff'
        }

        var checkData = machine.context.checkData;
        var current = (checkData as any).current_record
        var title = getTitle(current)


        return <LimitPickers ref={limitPickerRef} limit={limit} limitDay={8}
            themeColor={color}
            title={title}
            onCancel={hidePicker} onChange={(e) => {
                pickerConfirm(e)
                hidePicker()
            }} />
    }

    function pickerConfirm(t: number) {
        var date = new Date(t)
        var setDate = new Date(global.set_time);
        date.setMilliseconds(setDate.getMilliseconds());
        date.setSeconds(setDate.getSeconds());

        t = date.getTime();

        if (isFast) {
            if (value == 'WAIT_FOR_START') {
                startFast(t, fastDuration);
            }
            else {
                endFast(t)
            }
        }
        else {
            if (value == 'WAIT_FOR_START' || value == 'ONGOING1') {
                startSleep(t, sleepDuration);
            }
            else {
                endSleep(t)
            }
        }
    }

    function mixedBtns() {
        var checkData = machine.context.checkData;
        var current = (checkData as any).current_record
        return <View style={{ display: 'flex', marginTop: 22 }}>
            {
                (value == 'WAIT_FOR_START' || value == 'DONE') &&
                <StartFastBtn onClick={showPicker} />
            }
            {
                (value == 'ONGOING' || value == 'ONGOING3') &&
                <EndFastBtn onClick={showPicker} lowLight={current.fast.target_end_time > new Date().getTime()} />
            }
            {
                value == 'ONGOING1' && <StartSleepBtn onClick={showPicker} />
            }
            {
                value == 'ONGOING2' && <EndSleepBtn onClick={showPicker} lowLight={current.sleep.target_end_time > new Date().getTime()} />

            }
        </View>
    }

    function textAlpha() {
        var checkData = machine.context.checkData;
        var current = (checkData as any).current_record
        if (value == 'WAIT_FOR_START' || value == 'DONE') {
            return 1;
        }

        if (value == 'ONGOING' || value == 'ONGOING3') {
            if (current.scenario == 'SLEEP') {
                return current.sleep.target_end_time > new Date().getTime() ? 0.4 : 1
            }
            return current.fast.target_end_time > new Date().getTime() ? 0.4 : 1
        }
        if (value == 'ONGOING1')
            return 1//current.sleep.target_start_time > new Date().getTime()?0.4:1
        if (value == 'ONGOING2')
            return current.sleep.target_end_time > new Date().getTime() ? 0.4 : 1
        return 1
    }

    function fastBtns() {
        return <View style={{ display: 'flex', marginTop: 22 }}>
            {
                value == 'ONGOING' ? <EndFastBtn onClick={showPicker} lowLight={textAlpha() != 1} /> : <StartFastBtn onClick={showPicker} />
            }
        </View>
    }

    function sleepBtns() {
        return <View style={{ display: 'flex', marginTop: 22 }}>
            {
                value == 'ONGOING' ? <EndSleepBtn onClick={showPicker} lowLight={textAlpha() != 1} /> : <StartSleepBtn onClick={showPicker} />
            }
        </View>
    }

    function durationChange(e) {
        var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step
        isFast ? setFastDuration(count * 60000) : setSleepDuration(count * 60000);
        isFast ? setFastPickerValue(e) : setSleepPickerValue(e)

        setIsOpenDurationPicker(false)
    }

    function login() {
        Taro.navigateTo({
            url: '/pages/account/ChooseAuth'
        })
    }

    function durationFormate() {
        if (isFast) {
            var t = fastDuration / 60000
            var hour = Math.floor(t / 60)
            var minute = Math.floor(t % 60)
            return `${hour > 0 ? hour + '小时' : ''}${minute > 0 ? minute + '分钟' : ''}`
        }
        else {
            var t = sleepDuration / 60000
            var hour = Math.floor(t / 60)
            var minute = Math.floor(t % 60)
            return `${hour > 0 ? hour + '小时' : ''}${minute > 0 ? minute + '分钟' : ''}`
        }

    }

    function showDurationPicker() {
        setIsOpenDurationPicker(true)
    }

    if (!user.isLogin) {
        return <View style={{ display: 'flex', flexDirection: 'column', width: '100%', alignItems: 'center' }}>
            <Text>16:00</Text>
            {/* <PickerViews onChange={() => { }} items={[pickerDurations()]} value={[12 * 15]} /> */}
            {/* <TimePickers time={isFast ? fastStr : sleepStr} content="" change={handlePickerChange} isPickerView={true} /> */}
            <Text style={{ color: '#AAFF00' }} onClick={login}>Start Fast</Text>
        </View>
    }


    function durationPickerContent() {
        var color = isFast ? '#aaff00' : '#00ffff'
        if (value == 'ONGOING2') {
            color = '#00ffff'
        }
        var checkData = machine.context.checkData;
        var current = (checkData as any).current_record
        var title = getTitle(current)
        return <View style={{ color: '#fff', backgroundColor: 'transparent' }}>
            <PickerViews ref={durationPickerRef}
                onChange={durationChange}
                items={durationDatas(common)}
                value={isFast ? fastPickerValue : sleepPickerValue}
                themeColor={color}
                title={title}
                showBtns={true} onCancel={() => { setIsOpenDurationPicker(false) }} />
        </View>
    }

    function minus() {
        if (isFast) {
            var count = fastDuration - 5 * 60 * 1000
            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration - 5 * 60 * 1000

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function plus() {
        if (isFast) {
            var count = fastDuration + 5 * 60 * 1000
            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration + 5 * 60 * 1000

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function disableMinus() {
        if (isFast) {
            if (fastDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    function disablePlus() {
        if (isFast) {
            if (fastDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    var textColor = '#AAFF00'
    if (!isFast) {
        textColor = '#00FFFF'
    }

    return (
        <Box >
            <View  style={{ display:'flex',flexDirection: 'column',alignItems: 'center', flexShrink: 0 }}>
                {
                    value == 'ONGOING' && <View>
                        <Text className="counter_text" style={{ color: textColor, opacity: textAlpha() }}>{(machine.context.checkData as any).current_record.scenario == 'FAST' ?
                            TimeFormatter.countdown((machine.context.checkData as any).current_record.fast.target_end_time) :
                            TimeFormatter.countdown((machine.context.checkData as any).current_record.sleep.target_end_time)}</Text>
                    </View>
                }
                {
                    (value == 'ONGOING1' || value == 'WAIT_FOR_START') && <Stepper child={
                        <Text className="stepper_text" style={{ color: textColor, opacity: textAlpha() }} onClick={showDurationPicker}>{durationFormate()}</Text>
                    } minus={minus} plus={plus} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                    // <Text style={{marginBottom:10}} onClick={showDurationPicker}>时长：{durationFormate()}</Text>
                }
                {
                    machine.context.checkData && value == 'ONGOING2' && <View>
                        <Text className="counter_text" style={{ color: '#00ffff', opacity: textAlpha() }}>{TimeFormatter.countdown((machine.context.checkData as any).current_record.sleep.target_end_time)}</Text>
                    </View>
                }

                {
                    machine.context.checkData && value == 'ONGOING3' && <View>
                        <Text className="counter_text" style={{ color: textColor, opacity: textAlpha() }}>{TimeFormatter.countdown((machine.context.checkData as any).current_record.fast.target_end_time)}</Text>
                    </View>
                }

                <View>
                    {
                        key === 'FAST_SLEEP' && mixedBtns()
                    }
                    {
                        key === 'FAST' && fastBtns()
                    }
                    {
                        key === 'SLEEP' && sleepBtns()
                    }
                </View>
                {
                    showModal && isOpen && <Modal testInfo={testLayout()} children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={() => {
                        var picker = limitPickerRef.current;
                        pickerConfirm((picker as any).getConfirmData());
                        setIsOpen(false);
                    }} />
                }
                {
                    isOpenDurationPicker && <Modal children={durationPickerContent()} dismiss={() => setIsOpenDurationPicker(false)} confirm={() => {
                        var picker = durationPickerRef.current;
                        durationChange((picker as any).getConfirmData());
                        setIsOpenDurationPicker(false);
                    }} />
                }
            </View>
        </Box>
    )
}