import { clearTimeRecords, getClockRecords } from "@/services/trackTimeDuration";
import { View, Text, ScrollView } from "@tarojs/components";
import { usePullDownRefresh, useReachBottom, useReady, useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import Schedule from '@/features/trackTimeDuration/components/Schedule'
import MetricHistory from "@/features/trackSomething/components/MetricHistory";
import ActivityHistory from "@/features/trackSomething/components/ActivityHistory";
import { activityRecords, clearMetricRecords, cleartActivityRecords, metricRecords } from "@/services/trackSomething";
import Taro from "@tarojs/taro";
import Layout from "@/components/layout/layout";
import NoData from "@/components/view/NoData";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import { useSelector } from "react-redux";
import RecordFastSleep from "@/features/trackTimeDuration/components/RecordFastSleep";
import './RecordsHistory.scss'

export default function Page() {
    const router = useRouter();
    const pageSize = 10
    const [pageIndex, setPageIndex] = useState(1)
    const [records, setRecords] = useState<any[]>([])
    const [counter, setCounter] = useState(0)
    const [timerId, setTimerId] = useState(null)
    const [showErrorPage, setShowErrorPage] = useState(false)
    const { refreshList } = router.params
    const [triggered, setTriggered] = useState(false)
    const [showModal, setShowModal] = useState(false)
    const [modalDetail, setModalDetail] = useState<any>({})
    const [total, setTotal] = useState(0)
    const [isLoading, setIsLoading] = useState(false)
    const [loaded,setLoaded] = useState(false)
    const user = useSelector((state: any) => state.user);


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

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

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

        const id = setInterval(() => {
            setCounter((prevCounter) => prevCounter + 1);
        }, 1000);

        setTimerId(id as any);
    };


    useReady(() => {
        refresh()
    })

    usePullDownRefresh(() => {
        console.log('aaa')
        refresh()
    })

    useReachBottom(() => {
        more()
        // setPageIndex(pageIndex+1)
        // getHistory()
    })

    function refresh() {
        setIsLoading(true)
        setPageIndex(1)
        getHistory(1)
    }

    function more() {
        if (total <= records.length || isLoading) {
            return;
        }
        setIsLoading(true)
        var page = pageIndex + 1
        setPageIndex(page)
        getHistory(page)
    }

    function getHistory(page = pageIndex) {
        if (page == 1)
            setTriggered(true)
        if (router.params.type == 'time') {
            getClockRecords({
                page: page,
                limit: pageSize,
                only_finished: true
            }).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }
        else if (router.params.type == 'activity') {
            activityRecords(
                {
                    page: page,
                    limit: pageSize,
                    code: '_walk'
                }
            ).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }
        else if (router.params.type == 'metric') {
            metricRecords(
                {
                    page: page,
                    limit: pageSize,
                    code: router.params.code
                }
            ).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }

    }

    function removeItem(item) {
        setRecords(records.filter(i => i.id != item.id))
    }

    global.clearHistory = () => {
        // var page = Taro.getCurrentPages()[0]
        // debugger
        // page.refresh()
        Taro.showModal({
            title: '提示',
            content: '确认删除全部记录？',
            success: (res) => {
                if (res.confirm) {
                    doClear()
                }
            }
        })

    }

    function doClear() {
        if (router.params.type == 'activity') {
            cleartActivityRecords({
                code: '_walk'
            }).then(res => {
                refresh()
                global.refreshActivity()
                // router.params.refreshList()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
        else if (router.params.type == 'metric') {
            clearMetricRecords({
                code: router.params.code
            }).then(res => {
                refresh()
                global.refreshMetric()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
        else if (router.params.type == 'time') {
            clearTimeRecords().then(res => {
                refresh()
                // global.refreshMetric()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
    }

    function detail() {
        if (router.params.type == 'time') {
            return <View>
                {
                    user.test_user && <Text style={{ color: '#fff', position: 'absolute', right: 50, top: 0 }} onClick={() => global.clearHistory()}>删除全部</Text>
                }
                {
                    records.map((item, index) => {
                        return <RecordFastSleep key={index} data={item} type='record' delSuccess={(item) => removeItem(item)} />
                        // return <Schedule key={index} data={item} type="record" delSuccess={(item) => removeItem(item)} />
                    })
                }
            </View>
        }
        if (router.params.type == 'metric') {
            return <MetricHistory records={records} />
        }
        if (router.params.type == 'activity') {
            return <ActivityHistory records={records} />
        }
    }

    return <View style={{ position: 'relative' }}>
        <Layout children={showErrorPage ? <NoData refresh={() => { refresh() }} /> : detail()}
            title={router.params.title}
            type={TemplateType.flex}
            refresh={() => { refresh() }}
            triggered={triggered}
            more={() => { more() }}
            titleShowStyle={NaviBarTitleShowType.scrollToShow}
        />
        {
            loaded && records.length == 0 && <View className="no_records_bg">
                <Text className="no_records">无记录</Text>
            </View>
        }

        {
            showModal && modalDetail
        }
    </View>

    // return <View className="container">

    //     {
    //         (router.params.type == 'metric' || router.params.type == 'activity') && <View style={{ height: 50, fontSize: 30, color: '#fff' }} onClick={clear}>删除全部</View>
    //     }
    //     <ScrollView scrollY style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
    //         onScrollToLower={more} enableFlex
    //     // onRefresh={refresh}
    //     >
    //         {
    //             router.params.type == 'time' && records.map((item, index) => {
    //                 return <Schedule key={index} data={item} type="record" delSuccess={(item) => removeItem(item)} />
    //             })
    //         }
    //         {
    //             router.params.type == 'metric' && <MetricHistory records={records} />
    //         }
    //         {
    //             router.params.type == 'activity' && <ActivityHistory records={records} />
    //         }
    //     </ScrollView>
    // </View>;
}