import { View, Image } from "@tarojs/components";
import './time_record.scss'
import Taro, { useRouter, useShareAppMessage } from "@tarojs/taro";
import { rpxToPx } from "@/utils/tools";
import { MainColorType } from "@/context/themes/color";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { useEffect, useState } from "react";
import NewDateTimePicker from "@/_health/base/new_date_time_picker";
import dayjs from "dayjs";
import RingProgress from "../components/ring_progress";
import NewDurationPicker, { DurationPickerType } from "@/_health/base/new_durationpicker";
import { IconArrow, IconClose } from "@/components/basic/Icons";
import { useSelector } from "react-redux";
import { TimeFormatter } from "@/utils/time_format";
import { addEvents } from "@/services/health";
import Modal from "@/components/layout/Modal.weapp";
import { getDurationArc, getStartArc } from "@/features/health/hooks/health_hooks";
import ShareBtn from "@/components/basic/ShareBtn";
import PickerCard from "../components/picker_card";

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

export default function TimeRecord() {
    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;
    const record = useSelector((state: any) => state.record);
    const [enterTime] = useState(new Date().getTime())

    const [showDatePicker, setShowDatePicker] = useState(false)
    const [showDurationPicker, setShowDurationPicker] = useState(false)
    const [showEndDatePicker, setShowEndDatePicker] = useState(false)
    const [count, setCount] = useState(0)
    const [status, setStatus] = useState('WFS')
    const [info, setInfo] = useState<any>(null)
    const [loaded, setLoaded] = useState(false)
    const [showHighlight, setShowHighlight] = useState(false)
    const [showShare, setShowShare] = useState(false)
    const [shareUrl, setShareUrl] = useState('')

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

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }

    const { scenario } = router.params

    if (process.env.TARO_ENV == 'weapp') {
        useShareAppMessage((e) => {
            return {
                title: '分享标题',
                path: 'pages/clock/Clock',
                imageUrl: shareUrl
            }
        })
    }


    useEffect(() => {
        const { events } = record
        events.map((item) => {
            if (item.scenario == scenario) {
                setInfo(item)
                setStatus(item.status)
                setLoaded(true)
            }
        })
        downloadFile()
        timer = setInterval(() => {
            if (showDatePicker || showEndDatePicker || showDurationPicker) return
            setCount(count => count + 1)
        }, 1000)
        return () => {
            clearInterval(timer)
        }
    }, [])

    function downloadFile() {
        Taro.downloadFile({
            url: 'https://background-pictures.oss-cn-beijing.aliyuncs.com/inapp/checkmark.png',
            success: (res) => {
                if (res.statusCode === 200) {
                    global.checkImg = res.tempFilePath

                } else {
                }
            },
            fail: (err) => {
            }
        });
    }

    function tapClock() {
        if (status == 'WFS')
            setShowDurationPicker(true)
    }

    function start() {
        // var date = TimeFormatter.stringToDate(selDate, time)
        // date.setMilliseconds(new Date(enterTimestmap).getMilliseconds())


        var params: any = {
            scenario: scenario, //ACTIVITY
            type: 'INTERVAL',
            sub_type: scenario,

            time: {
                start_timestamp: new Date().getTime(),
                duration: info.time.duration
            }
        }

        if (router.params.join_id) {
            params.join_key = router.params.join_id
        }




        // if (event_id && event_id != 'undefined') {
        //     params.event_id = event_id
        // }

        // if (is_temp) {
        //     params.event = window == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
        // }
        // params.op_page = window == 'EAT' ? 'HOME_EAT' : 'HOME_ACTIVE'


        params.extra = {
            set_time: global.set_time ? global.set_time : new Date().getTime(),
            confirm_time: new Date().getTime()
        }
        // console.log('打卡提交数据', params)
        // if (posting) return
        // setPosting(true)
        addEvents(params).then(res => {
            Taro.eventCenter.trigger('refreshClockIndex')
            setShowHighlight(true)
            setTimeout(() => {
                setShowHighlight(false)
            }, 3000)
            setInfo((res as any).data)
            setStatus((res as any).data.status)
            // Taro.showToast({
            //     title: '成功',
            //     icon: 'success'
            // })
        })
    }

    function end() {
        var params: any = {
            scenario: scenario, //ACTIVITY
            type: 'INTERVAL',
            sub_type: scenario,

            time: {
                end_timestamp: new Date().getTime()
            }
        }

        if (router.params.join_id) {
            params.join_key = router.params.join_id
        }


        params.extra = {
            set_time: global.set_time ? global.set_time : new Date().getTime(),
            confirm_time: new Date().getTime()
        }
        addEvents(params).then(res => {
            setShowHighlight(true)
            setTimeout(() => {
                setShowHighlight(false)
            }, 3000)
            Taro.eventCenter.trigger('refreshClockIndex')
            setInfo((res as any).data)
            setStatus((res as any).data.status)
            setShareUrl('')
            // Taro.showToast({
            //     title: '成功',
            //     icon: 'success'
            // })
        })
    }

    function update(params) {
        var data: any = {
            id: info.id,
            time: {
                ...params
            }
        }
        addEvents(data).then(res => {
            Taro.eventCenter.trigger('refreshClockIndex')
            setInfo((res as any).data)
            setShowDatePicker(false)
            setShowDurationPicker(false)
            setShowEndDatePicker(false)
        })
    }


    function tapStart() {
        setShowDatePicker(true)
    }

    function tapGoal() {
        setShowDurationPicker(true)
    }

    function ringExtra() {
        if (status == 'WFS') {
            const count = info.time.duration / 1000
            var str = TimeFormatter.formateDurationBySeconds(count)

            return {
                header: '',
                value: str,
                footer: 'Edit',
                color: MainColorType.orange
            }
        }
        var percent = 100 * (new Date().getTime() - info.time.start_timestamp) / info.time.duration
        percent = parseInt(percent + '')
        return {
            header: '',
            value: TimeFormatter.countdown(info.time.start_timestamp),
            footer: `ELAPSED ${percent}%`,
            color: MainColorType.g02
        }
    }

    function getBackground() {
        var time = record.time
        if (!time) return '#fff'
        const { background_colors } = time
        if (!background_colors) {
            return '#fff'
        }
        else if (background_colors.length == 1) {
            return background_colors[0]
        }
        return `linear-gradient(to bottom, ${background_colors[0]}, ${background_colors[1]})`
    }
    if (!loaded) {
        return <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <View className="main_bg" style={{ background: getBackground() }} />
        </View>
    }

    function doneComponent() {
        if (status == 'DONE') {
            return <View className="share_bg" style={{ justifyContent: 'flex-start' }}>
                {
                    shareUrl.length == 0 && <View className="share_canvas"><RingProgress
                        radius={125} canvasId="helloworld_share2"
                        //scale={0.75}
                        count={count}
                        bgRing={{
                            color: 'rgba(255,255,255,1)',
                            width: 35
                        }}
                        real={{
                            color: MainColorType.orange,
                            width: 5,
                            start: getStartArc(info.time.start_timestamp),
                            duration: getDurationArc(info.time.start_timestamp, info.time.end_timestamp)
                        }}
                        extra={ringExtra()}
                        isCompleted
                        shareCover={
                            url => {
                                setShareUrl(url)
                            }
                        }
                    /></View>
                }

                <View className="navi_bar" style={{ height: navigationBarHeight }}>
                    <View style={{
                        position: 'absolute',
                        left: 0,
                        right: 0,
                        bottom: 0,
                        height: 44,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <View style={{
                            position: 'absolute',
                            width: rpxToPx(92),
                            height: rpxToPx(64),
                            left: 22,
                            top: 22 - rpxToPx(32)
                        }}
                            onClick={() => {
                                Taro.navigateBack()
                            }}>
                            <IconClose color="#fff" width={rpxToPx(64)} height={rpxToPx(64)} />
                        </View>
                    </View>

                </View>
                <View className="share_card" style={{ background: MainColorType.orange, marginTop: rpxToPx(26) + navigationBarHeight }}>
                    {
                        shareUrl.length > 0 ? <Image src={shareUrl} style={{ width: rpxToPx(900), height: rpxToPx(720) }} /> :
                            <View style={{ width: rpxToPx(900), height: rpxToPx(720), backgroundColor: MainColorType.g02 }} />
                    }
                    {
                        <View className="operate_content" style={{ marginTop: rpxToPx(40) }}>
                            <View className="operate_item" onClick={() => {
                                setShowDatePicker(true)
                            }}>
                                <View className="g02 h24">STARTED</View>
                                <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.start_timestamp, true)}</View>
                                <View className="h30 bold" style={{ color: MainColorType.white }}>Edit Start</View>
                            </View>
                            <View className="operate_item" onClick={() => {
                                setShowEndDatePicker(true)
                            }}>
                                <View className="g02 h24">FINISHED</View>
                                <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.end_timestamp, true)}</View>
                                <View className="h30 bold" style={{ color: MainColorType.white }}>Edit Finish</View>
                            </View>
                        </View>
                    }
                </View>
                <ShareBtn>
                    <NewButton
                        type={NewButtonType.fill}
                        color={MainColorType.success}
                        width={rpxToPx(698)}
                        height={rpxToPx(108)}
                        title="Send to friends"
                    />
                </ShareBtn>

            </View>
        }
    }

    function render() {

        return <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <View className="main_bg" style={{ background: getBackground() }} />
            <View className="navi_bar" style={{ height: navigationBarHeight }}>
                <View style={{
                    position: 'absolute',
                    left: 0,
                    right: 0,
                    bottom: 0,
                    height: 44,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }}>
                    <Image src={require('@assets/_health/navi_back.png')} style={{
                        position: 'absolute',
                        width: rpxToPx(92),
                        height: rpxToPx(64),
                        left: 0,
                        top: 22 - rpxToPx(32)
                    }}
                        onClick={() => {
                            Taro.navigateBack()
                        }}
                    />
                    <View className="h36 bold">upcoming fast</View>
                </View>
            </View>
            <View style={{ height: navigationBarHeight }} />
            <View className="progress_card">
                <View onClick={() => {
                    tapClock()
                    // setShowDurationPicker(true)
                }}>
                    <RingProgress
                        radius={125} canvasId="helloworld"
                        //scale={0.75}
                        count={count}
                        bgRing={{
                            color: 'rgba(255,255,255,0.25)',
                            width: 35
                        }}
                        target={{
                            color: 'rgba(255,255,255,0.5)',
                            width: 35,
                            start: status == 'WFS' ? getStartArc(new Date().getTime()) : getStartArc(info.time.start_timestamp),
                            duration: status == 'WFS' ? getDurationArc(new Date().getTime(), new Date().getTime() + info.time.duration) : getDurationArc(info.time.start_timestamp, info.time.start_timestamp + info.time.duration)
                        }}
                        real={status == 'WFS' ? null : {
                            color: MainColorType.orange,
                            width: 35,
                            start: getStartArc(info.time.start_timestamp),
                            duration: getDurationArc(info.time.start_timestamp, new Date().getTime())
                        }}
                        extra={ringExtra()}
                    />
                </View>
                {
                    status == 'OG' && <View className="operate_content">
                        <View className="operate_item" onClick={() => {
                            setShowDatePicker(true)
                        }}>
                            <View className="g02 h24">STARTED</View>
                            <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.start_timestamp, true)}</View>
                            <View className="h30 bold" style={{ color: MainColorType.orange }}>Edit Start</View>
                        </View>
                        <View className="operate_item" onClick={() => {
                            setShowDurationPicker(true)
                        }}>
                            <View className="g02 h24">{TimeFormatter.formateDurationBySeconds(info.time.duration / 1000)} Goal</View>
                            <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.target_end_timestamp, true)}</View>
                            <View className="h30 bold" style={{ color: MainColorType.orange }}>Edit Goal</View>
                        </View>
                    </View>
                }
                {
                    status == 'WFS' && <NewButton
                        type={NewButtonType.fill}
                        title="Start fasting"
                        width={rpxToPx(490)}
                        height={rpxToPx(96)}
                        color={MainColorType.orange}
                        onClick={start}
                    />
                }

                {
                    status == 'OG' && <NewButton
                        type={NewButtonType.fill}
                        title="End fasting"
                        width={rpxToPx(490)}
                        height={rpxToPx(96)}
                        color={MainColorType.orange}
                        onClick={end}
                    />
                }
                {
                    status == 'OG' && <View className="share_icon">
                        <Image onClick={() => {
                            setShareUrl('')
                            setShowShare(true)
                        }} src={require('@assets/_health/wechat.png')} style={{
                            width: rpxToPx(72),
                            height: rpxToPx(72)
                        }} />
                    </View>
                }


            </View>
            {
                status == 'WFS' && <View className="eat_card" onClick={() => {
                    Taro.redirectTo({
                        url: `./log_record?scenario=${scenario == 'FAST' ? 'MEAL' : 'ACTIVITY'}`
                    })
                }}>
                    <View className="h30 bold">Or share your meals</View>
                    <View className="h24 g02" style={{ marginTop: rpxToPx(12) }}>if you haven't started fasting yet</View>
                    <View className="eat_card_arrow">
                        <IconArrow width={rpxToPx(34)} color={MainColorType.g02} />
                    </View>
                </View>
            }

            {
                status == 'OG' && <View className="eat_card" style={{ height: rpxToPx(120) }} onClick={() => {
                    Taro.redirectTo({
                        url: `./log_record?scenario=${scenario == 'FAST' ? 'MEAL' : 'ACTIVITY'}`
                    })
                }}>
                    <View className="h24 g02" style={{ marginTop: rpxToPx(12) }}>How are you feeling?</View>
                    <View className="eat_card_arrow">
                        <IconArrow width={rpxToPx(34)} color={MainColorType.g02} />
                    </View>
                </View>
            }


            {/* {
            showDurationPicker && <Modal
                testInfo={null}
                dismiss={() => {
                    setShowDurationPicker(false)
                }}
                confirm={() => { }}>
                {
                    <NewDurationPicker type={DurationPickerType.normal} value={info.time.duration} onChange={(e) => {
                        console.log(e)
                        var obj = JSON.parse(JSON.stringify(info))
                        obj.time.duration = e
                        setInfo(obj)
                    }} />
                }
            </Modal>
        } */}
            {
                showShare && <View className="share_bg">
                    {
                        shareUrl == '' && <View className="share_canvas">
                            <RingProgress
                                radius={125} canvasId="helloworld_share"
                                //scale={0.75}
                                count={count}
                                bgRing={{
                                    color: 'rgba(255,255,255,0.25)',
                                    width: 35
                                }}
                                target={{
                                    color: 'rgba(255,255,255,0.5)',
                                    width: 35,
                                    start: status == 'WFS' ? getStartArc(new Date().getTime()) : getStartArc(info.time.start_timestamp),
                                    duration: status == 'WFS' ? getDurationArc(new Date().getTime(), new Date().getTime() + info.time.duration) : getDurationArc(info.time.start_timestamp, info.time.start_timestamp + info.time.duration)
                                }}
                                real={status == 'WFS' ? null : {
                                    color: MainColorType.orange,
                                    width: 35,
                                    start: getStartArc(info.time.start_timestamp),
                                    duration: getDurationArc(info.time.start_timestamp, new Date().getTime())
                                }}
                                extra={ringExtra()}
                                shareBg={[record.time.background_colors[0], record.time.background_colors[1]]}
                                shareCover={
                                    url => {
                                        setShareUrl(url)
                                    }
                                }
                            />
                        </View>
                    }
                    <View className="navi_bar" style={{ height: navigationBarHeight }}>
                        <View style={{
                            position: 'absolute',
                            left: 0,
                            right: 0,
                            bottom: 0,
                            height: 44,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                            <View style={{
                                position: 'absolute',
                                width: rpxToPx(92),
                                height: rpxToPx(64),
                                left: 22,
                                top: 22 - rpxToPx(32)
                            }}
                                onClick={() => {
                                    setShowShare(false)
                                }}>
                                <IconClose color="#fff" width={rpxToPx(64)} height={rpxToPx(64)} />
                            </View>
                        </View>
                    </View>
                    <View className="share_card" style={{ background: record.time.background_colors[1] }}>
                        {
                            shareUrl.length > 0 ? <Image src={shareUrl} style={{ width: rpxToPx(900), height: rpxToPx(720) }} /> :
                                <View style={{ width: rpxToPx(900), height: rpxToPx(720), backgroundColor: MainColorType.g02 }} />
                        }
                        {
                            status == 'OG' && <View className="operate_content" style={{ marginTop: rpxToPx(40) }}>
                                <View className="operate_item">
                                    <View className="g02 h24">STARTED</View>
                                    <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.start_timestamp, true)}</View>
                                </View>
                                <View className="operate_item">
                                    <View className="g02 h24">{TimeFormatter.formateDurationBySeconds(info.time.duration / 1000)} Goal</View>
                                    <View className="h44 bold" style={{ marginTop: rpxToPx(8), marginBottom: rpxToPx(8) }}>{TimeFormatter.dateTimeFormate(info.time.target_end_timestamp, true)}</View>
                                </View>
                            </View>
                        }
                    </View>
                    <ShareBtn>
                        <NewButton
                            type={NewButtonType.fill}
                            color={MainColorType.success}
                            width={rpxToPx(698)}
                            height={rpxToPx(108)}
                            title="Send to friends"
                        />
                    </ShareBtn>
                </View>
            }
        </View>
    }
    return <View>
        {
            status == 'DONE' ? doneComponent() : render()
        }
        {
            showDatePicker && <PickerCard onClose={() => { setShowDatePicker(false) }}
                value={info.time.start_timestamp}
                type="datetime"
                onConfirm={(e) => {
                    update({
                        start_timestamp: e
                    })
                    console.log(e)
                    // var obj = JSON.parse(JSON.stringify(info))
                    // obj.time.duration = e
                    // setInfo(obj)
                }}
            />
        }
        {
            showEndDatePicker && <PickerCard onClose={() => { setShowDatePicker(false) }}
                value={info.time.end_timestamp}
                type="datetime"
                onConfirm={(e) => {
                    update({
                        end_timestamp: e
                    })
                    console.log(e)
                    // var obj = JSON.parse(JSON.stringify(info))
                    // obj.time.duration = e
                    // setInfo(obj)
                }}
            />
        }
        {
            showDurationPicker && <PickerCard onClose={() => { setShowDurationPicker(false) }}
                value={info.time.duration}
                type="duration"
                onConfirm={(e) => {
                    var obj = JSON.parse(JSON.stringify(info))
                    obj.time.duration = e
                    setInfo(obj)
                    if (status == 'WFS') return
                    update({
                        duration: e
                    })
                }}
            />
        }
    </View>
}