import { Component, PropsWithChildren, useEffect, useRef, useState } from 'react'
import { View, Text, Button, Input, Picker, Swiper, SwiperItem, Icon } from '@tarojs/components'
import '../index/index.scss'
import './Clock.scss'
// import './context/locales/index'
import '@/context/locales/index'
import Taro, { useDidShow, usePageScroll, useReady, useRouter, useShareAppMessage } from '@tarojs/taro'
// import ComponentA from './component'


import { useDispatch, useSelector } from 'react-redux';
import { getInfoSuccess, logoutSuccess } from '@/store/user';
import { wxPubFollow } from '@/services/permission';
import { gobalConfigs, staticResources, uploadSessionKey } from '@/services/common';
import Clocks from '@/features/trackTimeDuration/components/Clock';
import Console from '@/features/trackTimeDuration/components/Console';
import Schedule from '@/features/trackTimeDuration/components/Schedule';
import { getChecks, getClocks } from '@/services/trackTimeDuration';
import { setScenario } from '@/store/scenario';
import trackTimeService from '@/store/trackTimeMachine';
import { setWXFollow } from '@/store/permission';
import Tooltip from '@/components/view/Tooltip'
import RequestType, { thirdPartRequest } from '@/services/thirdPartRequest'
import { setConfigs } from '@/store/common'
import RecordFastSleep from '@/features/trackTimeDuration/components/RecordFastSleep'
import Box from '@/components/layout/Box'
import Layout from '@/components/layout/layout'
import { CheckBoxType, NaviBarTitleShowType, TemplateType } from '@/utils/types'
import { updateScenario } from '@/store/time'
import { showModal } from '@/store/modal'
import { ConsoleType, changeConsoleStatus } from '@/store/console'
import TitleView from '@/features/trackTimeDuration/components/TitleView'
import StatusIndicator from '@/features/trackTimeDuration/components/StatusIndicator'
import { useTranslation } from 'react-i18next'
import TableCellHeader from '@/components/layout/TableCellHeader'
import SectionHeader from '@/components/layout/SectionHeader'
import Header from '@/components/layout/Header'
import { TimeFormatter } from '@/utils/time_format'
import NoData from '@/components/view/NoData'
import { ColorType } from '@/context/themes/color'
import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'
import DemoA from './demoA'
import { ScrollView } from 'react-native-gesture-handler'
// import TabBar from '../../components/Tabbar';

// import Rings from '@components/view/Rings';

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}


export default function IndexPage() {
    const dispatch = useDispatch();
    const { t } = useTranslation()
    const [checkData, setCheckData] = useState(null)
    const user = useSelector((state: any) => state.user);
    const time = useSelector((state: any) => state.time);
    const common = useSelector((state: any) => state.common);
    const consoleData = useSelector((state: any) => state.console);
    const [counter, setCounter] = useState(0)
    const [timerId, setTimerId] = useState(null)
    const [needShowAddTip, setNeedShowAddTip] = useState(false)
    const [showErrorPage, setErrorPage] = useState(false)

    const [swiperIndex, setSwiperIndex] = useState(0)
    const [autoPlay, setAutoPlay] = useState(false)

    const [showModal, setShowModal] = useState(false)
    const [modalDetail, setModalDetail] = useState<any>({})

    const [showModal2, setShowModal2] = useState(false)
    const [modalDetail2, setModalDetail2] = useState<any>({})
    const [showSingleFastEnd, setShowSingleFastEnd] = useState(false)
    const [consoleStatus, setConsoleStatus] = useState(consoleData.status)

    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    global.dispatch = dispatch;

    global.checkData = () => {
        console.log('refresh clock data')
        getCheckData()
    }

    useEffect(() => {
        global.consoleType = 'idle'
        dispatch(staticResources() as any);
    }, [])

    useEffect(() => {
        getCheckData()
    }, [time.status])

    useEffect(() => {
        setConsoleStatus(consoleData.status)
        switch (consoleData.status) {
            case ConsoleType.end:
                setTimeout(() => {
                    dispatch(changeConsoleStatus({ status: ConsoleType.idle }))
                }, 2000)

                break
        }
    }, [consoleData.status])

    useEffect(() => {
        if (user.isLogin) {
            //检查用户是否添加过小程序
            checkAddToMini();
            //检查session是否过期
            checkSession()
            getCheckData()
        }
    }, [user.isLogin])

    function checkSession() {
        if (process.env.TARO_ENV === 'weapp') {
            thirdPartRequest(RequestType.RequestTypeCheckSession).then(res => {
            }).catch(err => {
                console.log('session_key 已经失效，需要更新登录code')
                thirdPartRequest(RequestType.RequestTypeWXLogin).then(result => {
                    uploadSessionKey({ type: 'WX_MP', code: (result as any).code });
                })
            })
        }
    }

    function checkAddToMini() {
        process.env.TARO_ENV == 'weapp' &&
            wx.checkIsAddedToMyMiniProgram({
                success: (res) => {
                    if (!res.added) {
                        setNeedShowAddTip(true)
                    }
                },
                fail: (e) => {
                }
            });
    }

    useEffect(() => {
        startTimer();
        return () => {
            // 在组件卸载时清除定时器
            if (timerId) {
                clearInterval(timerId);
            }
        };
    }, [timerId]);

    const startTimer = () => {
        // 避免重复启动定时器
        if (timerId) {
            return;
        }

        const id = setInterval(() => {
            setCounter((prevCounter) => prevCounter + 1);
            //每天0点刷新一下打卡数据
            var now = new Date()
            if (now.getHours() == 0 && now.getMinutes() == 0) {
                getCheckData()
            }
        }, 1000);

        setTimerId(id as any);
    };


    useReady(async () => {
        debugger
        const userData = await getStorage('userData');
        debugger
        if (userData) {
            dispatch(getInfoSuccess(JSON.parse(userData as string)) as any);
            setTimeout(() => {
                checkWXPubFollow()
                getCheckData()

            }, 200)

        }
    })

    if (process.env.TARO_ENV == 'weapp') {
        useShareAppMessage((e) => {
            return {
                title: t('share.title'),
                path: 'pages/clock/Clock'
            }
        })
    }

    function clearTempScenarioCache() {
        global.schedule_fast = null
        global.schedule_sleep = null
        Taro.removeStorage({
            key: 'tempScenario',
            success: function (res) {
            }
        })
    }

    usePageScroll((e) => {
    })

    useDidShow(() => {
        if (process.env.TARO_ENV == 'weapp') {
            // global.updateTab(0)
            if (user.isLogin) {
                checkWXPubFollow()
            }
        }

        clearTempScenarioCache()
    })

    global.refreshTime = () => {
        getCheckData()
    }

    global.showSingleFastEnd = () => {
        setShowSingleFastEnd(true)
    }

    function tapClock() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
        }
    }

    function getCheckData() {
        getClocks().then(res => {
            setErrorPage(false)
            dispatch(updateScenario((res as any).current_record))
            dispatch(setConfigs((res as any).time_input_schema));
            dispatch(setScenario((res as any).scenario));

            if ((res as any).theme_color) {
                global.fastColor = (res as any).theme_color.fast
                global.sleepColor = (res as any).theme_color.sleep
            }

            global.scenario = (res as any).current_record.scenario;
            const currentState = trackTimeService.getSnapshot();
            let json = {};
            var key = (res as any).current_record.scenario
            var status = (res as any).current_record.status
            json[key] = status
            currentState.value = json;
            setCheckData(res as any)

            if ((res as any).current_record.status != 'ONGOING1') {
                setSwiperIndex(0)
            }
            else {
                if (global.consoleType == 'going') {
                    setShowSingleFastEnd(true)
                    setTimeout(() => {
                        setShowSingleFastEnd(false)
                        setSwiperIndex(1)
                        setAutoPlay(true)
                        global.consoleType = 'end'
                        dispatch(changeConsoleStatus({ status: ConsoleType.end }))
                        setTimeout(() => {
                            global.consoleType = 'idle'
                        }, 2000)
                    }, 500)
                }
                else {
                }
            }

        }).catch(e => {
            console.log('aaa')
            if (!checkData) {
                console.log('this is a test')
                setErrorPage(true)
            }
            else {
                console.log('sss')
            }
        })
    }

    function checkWXPubFollow() {
        var params;
        if (global.forceRefreshWXPub) {
            params = {
                force_refresh: true
            }
        }
        global.forceRefreshWXPub = false
        wxPubFollow(params).then(res => {
            dispatch(setWXFollow((res as any).wx_pub_followed));
            console.log('当前的关注状态' + (res as any).wx_pub_followed);

        })
    }

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    function schedule() {
        if (!user.isLogin) {
            return <View />
        }
        return <Schedule data={(checkData as any).current_record} />
    }

    function needSwiper() {
        var isNeed = time.scenario == 'FAST_SLEEP' &&
            (time.status == 'WAIT_FOR_START' ||
                time.status == 'ONGOING1' ||
                time.status == 'ONGOING2')
        if (showSingleFastEnd) {
            return false;
        }
        return isNeed
    }

    global.showClockModal = (isShow: boolean, detail: any) => {
        setShowModal(isShow)
        setModalDetail(detail)
    }

    global.showClockModal2 = (isShow: boolean, detail: any) => {
        setShowModal2(isShow)
        setModalDetail2(detail)
    }

    function headerView() {
        return <TitleView title={t('page.clock.title')} showAddBtn={true}>
            <StatusIndicator />
        </TitleView>
    }

    function errorView() {
        if (showErrorPage) {
            return <NoData refresh={() => { getCheckData() }} />
        }
        return <View />
    }

    function consoleView() {
        if (!checkData) {
            return <View />
        }
        return <View className='console_bg'>
            {
                needSwiper() ? <Swiper className='swiper' indicatorColor='#333'
                    indicatorActiveColor='#999'
                    current={swiperIndex}
                    autoplay={autoPlay}
                    duration={300}
                    interval={300}
                    indicator-offset={[0, -30]}
                    indicator-height={30}
                    indicatorDots={global.consoleType == 'idle'}
                    onChange={(e) => {
                        setSwiperIndex(e.detail.current)
                        if (e.detail.current == 0)
                            setAutoPlay(false)
                    }}
                >
                    <SwiperItem className='swiperItem'>
                        <Console />

                    </SwiperItem>

                    <SwiperItem className='swiperItem'>
                        <Console isNextStep={true} />
                    </SwiperItem>
                </Swiper> :
                    <Console isNextStep={showSingleFastEnd} />

            }
        </View>
    }


    function detail() {
        return (
            <Layout type={TemplateType.customHeader} header={headerView()} title={t('page.clock.title')} titleShowStyle={NaviBarTitleShowType.scrollToShow}>
                <View style={{ flex: 1, flexDirection: 'column', display: 'flex', backgroundColor: '#000', color: '#fff' }}>
                    {
                        needShowAddTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
                    }

                    <Box>
                        <View className='clock_bg' onClick={tapClock}>
                            <Clocks />
                        </View>
                    </Box>
                    {
                        errorView()
                    }
                    {
                        user.isLogin && consoleView()
                    }
                    {
                        user.isLogin && checkData && schedule()
                    }

                    {
                        user.isLogin && <View style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
                            {
                                checkData && (checkData as any).latest_record &&
                                <SectionHeader top={48} bottom={24} title={t('feature.track_time_duration.record_fast_sleep.header.latest_record')}>
                                    <Header title='' action={() => {
                                        jumpPage('/pages/common/RecordsHistory?type=time&title=time')
                                    }} />
                                </SectionHeader>
                            }
                        </View>
                    }
                    {
                        user.isLogin && checkData && (checkData as any).latest_record &&
                        <RecordFastSleep type='latest' data={(checkData as any).latest_record} delSuccess={getCheckData} />
                    }
                    <View style={{ height: 100 }} />
                </View>

                {
                    showModal && modalDetail
                }
                {
                    showModal2 && modalDetail2
                }

            </Layout>
        )
    }

    // if (process.env.TARO_ENV == 'rn')
    //     return <View />

    return <ScrollView>
        {
            detail()
        }
    </ScrollView>
}
