import { WindowStatusType, WindowType } from "@/utils/types";
import { View, Text, Image } from "@tarojs/components";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import './MainConsole.scss'
import { jumpPage } from "../trackTimeDuration/hooks/Common";
import Modal from "@/components/layout/Modal.weapp";
import { MainColorType } from "@/context/themes/color";
import ConsolePicker from "../trackTimeDuration/components/ConsolePicker";
import { clockTimes, makeDone, updateEventDuration, updateSchedule, updateTarget } from "@/services/health";
import TimePicker from "../common/TimePicker";
import showActionSheet from "@/components/basic/ActionSheet";
import { rpxToPx } from "@/utils/tools";
import { setMode, setShowActionTip } from "@/store/health";
import { getCountownTime, getDuration, getScenario, getThemeColor, getWindowStatus } from "./hooks/health_hooks";
import { IconCellArrow, IconMore } from "@/components/basic/Icons";
import DurationPicker from "@/_health/components/duration_picker";
import Taro from "@tarojs/taro";
import { systemLocation } from "@/services/common";
import { TimeFormatter } from "@/utils/time_format";
import { clearLocation } from "@/services/user";
import OnBoard from "@/_health/components/onboard";

let useNavigation;
let min = 0
let max = 0
let defaultTimestamp = 0

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

export default function MainConsole(props: { type: WindowType }) {
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [showPicker, setShowPicker] = useState(false)
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [durationPicker, setDurationPicker] = useState(false)
    const [operateType, setOperateType] = useState('')
    const [btnDisable, setBtnDisable] = useState(false)
    const [selItem, setSelItem] = useState<any>(null)

    const limitPickerRef = useRef(null)
    const dispatch = useDispatch()

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


    useEffect(() => {

    }, [props.type])

    function edit(item) {
        if (item.scenario != 'FAST' && item.scenario != 'SLEEP') {
            return
        }

        if (item.action == 'NA' || item.action == 'POST_MOMENT' || 'SLEEP_WAKE_UP' == item.action) {
            return;
        }
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        console.log(item)
        setSelItem(item)
        setShowPicker(true)
    }


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

        setSelItem(item)

        switch (item.action) {
            case 'START':
                {
                    defaultTimestamp = new Date().getTime()
                    min = defaultTimestamp - 1 * 24 * 3600 * 1000
                    max = defaultTimestamp

                    setOperateType('startFast')
                    setShowTimePicker(true)
                }
                return;
            case 'END':
                {
                    defaultTimestamp = new Date().getTime()
                    // defaultTimestamp = e ? new Date().getTime() : logEventTimestamp
                    min = defaultTimestamp - 1 * 24 * 3600 * 1000
                    max = defaultTimestamp
                    setOperateType('endFast')
                    setShowTimePicker(true)
                }
                return;
            case 'MARK_DONE':
                {
                    setBtnDisable(true)
                    clockTimes({
                        check_items: [{
                            schedule_id: item.schedule_id,
                            date: dayjs().format('YYYYMMDD'),
                            timestamp: new Date().getTime()
                        }]
                    }).then(res => {
                        // dispatch(setShowActionTip({
                        //     isShow: true,
                        //     isCompleted: (selItem.event == 'FAST_END' || selItem.event == 'SLEEP_WAKE_UP')
                        // }))
                        // setBtnDisable(false)
                        // setShowTimePicker(false)
                        global.refreshWindow()
                        global.refreshHistory()
                    }).catch(e => {
                    })
                }
                return;

        }
        jumpPage(`/_health/pages/add_moment?moment=${JSON.stringify(item)}&title=${item.title}&schedule_id=${item.schedule_id}&event_id=${item.event_id}`)
    }

    function operateTitle(item) {
        switch (item.action) {
            case 'START':
            case 'END':
                return '打卡'
            case 'MARK_DONE':
                return 'Action'
        }
        return '记录'
    }

    function itemTitle(item: any) {
        // if (health.mode == 'DAY' || health.mode == 'NIGHT') {
        //     return item.title
        // }
        if (item.real) {
            return dayjs(item.real.timestamp).format('HH:mm')
        }
        if (!item.target || !item.target.timestamp) {
            return item.time_label
        }
        return dayjs(item.target.timestamp).format('HH:mm')
    }

    function itemValue(item: any) {
        let themeColor: any = getThemeColor(health.mode)
        const scenario = getScenario(health.windows, health.mode)
        if (item.action == 'END' && !scenario.real) {
            themeColor = '#B2B2B2'
        }
        if (health.mode == 'DAY' || health.mode == 'NIGHT') {
            return null
        }
        if (item.action && item.action != 'NA') {
            if (health.mode == 'FAST' || health.mode == 'SLEEP') {
                if (item.action == 'POST_MOMENT') {
                    return <IconCellArrow color='#B2B2B2' width={rpxToPx(34)} />
                }

            }
            else if (health.mode == 'ACTIVE' && item.action == 'POST_MOMENT') {
                return <View className="timeline_operate" style={{ color: themeColor, backgroundColor: '#fff', borderColor: themeColor, borderWidth: 1, borderStyle: 'solid' }} onClick={() => record(item)}>{operateTitle(item)}</View>
            }
            return <View className="timeline_operate" style={{ color: themeColor, backgroundColor: themeColor + '1A' }} onClick={() => record(item)}>{operateTitle(item)}</View>
        }

        return <View />
    }

    function tapTimeline(item, inex) {
        if (health.mode == 'DAY' || health.mode == 'NIGHT') {
            return;
        }
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        if (!item.event_id) {
            return
        }
        jumpPage(`/_health/pages/timeline_detail?event_id=${item.event_id}&schedule_id=${item.schedule_id}`)
    }

    function timelineItem(item: any, index: number, count: number) {
        return <View key={index} className="timeline_item" onClick={() => tapTimeline(item, index)}>
            <View className="timeline_left">
                <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', height: rpxToPx(28) }}>
                    {
                        !item.reminder && <Image src={require('@assets/images/notification_off.png')} className='notification_icon' />
                    }
                    <Text className="timeline_title">{itemTitle(item)}</Text>
                </View>


                <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', marginTop: rpxToPx(5) }}>
                    <Text className="timeline_time" onClick={() => edit(item)}>{item.title}</Text>
                </View>
                {
                    (item.moment && item.moment.description) ? <Text className="timeline_desc">{item.moment.description}</Text> : <View className="timeline_thirdspace" />
                }

            </View>
            <View style={{ flex: 1 }} />

            {
                item.moment && item.moment.media && item.moment.media.length > 0 && <Image
                    src={item.moment.media[0].url}
                    mode="aspectFill"
                    className="console_item_img" />
            }
            {
                itemValue(item)
            }
            {/* {
                item.action && item.action != 'NA' && 
            } */}
            <View className="border_footer_line" style={{ left: count - 1 == index ? -rpxToPx(64) : rpxToPx(64) }} />
        </View>
    }

    function timeContent() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowPicker(false)
            }}
            confirm={() => { }}>
            {
                pickerContent()
            }
        </Modal>
    }

    function pickerContent() {
        const timestamp = selItem.target.timestamp
        const strTime = dayjs(timestamp).format('HH:mm')

        var title, color;
        switch (selItem.scenario) {
            case 'FAST':
                title = selItem.event == 'FAST_END' ? '结束断食' : '开始断食'
                color = MainColorType.fast
                break;
            case 'SLEEP':
                title = selItem.event == 'SLEEP_WAKE_UP' ? '结束睡眠' : '开始睡眠'
                color = MainColorType.sleep
        }

        return <TimePicker time={strTime}
            color={color}
            title={title}
            confirm={(e) => {
                confirmPickerTime(e)
            }}
            cancel={() => {
                setShowPicker(false)
            }} />
    }

    function confirmPickerTime(strTime) {
        if (selItem.event == 'FAST_END') {
            const obj = health.windows.fast_eat.fast.timeline[0]
            if (obj.action == 'POST_MOMENT' || obj.action == 'NA') {
                const format = dayjs(obj.target.timestamp).format(`YYYY-MM-DDT${strTime}:ss`)
                var t = new Date(format).getTime()
                if (t <= obj.target.timestamp) {
                    t += 24 * 3600 * 1000
                }
                updateTarget(t, obj.event_id).then(res => {
                    global.refreshWindow()
                    global.refreshHistory()
                    setShowPicker(false)
                })
                return;
            }
        }
        else if (selItem.event == 'SLEEP_WAKE_UP') {
            const obj = health.windows.sleep_active.sleep.timeline[0]
            if (obj.action == 'POST_MOMENT' || obj.action == 'NA') {
                const format = dayjs(obj.target.timestamp).format(`YYYY-MM-DDT${strTime}:ss`)
                var t = new Date(format).getTime()
                if (t <= obj.target.timestamp) {
                    t += 24 * 3600 * 1000
                }
                updateTarget(t, obj.event_id).then(res => {
                    global.refreshWindow()
                    global.refreshHistory()
                    setShowPicker(false)
                })
                return;
            }
        }

        updateSchedule({
            time: strTime,
            event: selItem.event,
            title: selItem.title,
            is_all_day: false
        }, selItem.schedule_id).then(res => {
            global.refreshWindow()
            global.refreshHistory()
            setShowPicker(false)
        })
    }

    function modalContent() {
        global.set_time = new Date().getTime()
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowTimePicker(false)
            }}
            confirm={() => { }}>
            {
                timePickerContent()
            }
        </Modal>
    }

    function timePickerContent() {
        var title, color;
        switch (selItem.scenario) {
            case 'FAST':
                title = selItem.event == 'FAST_END' ? '结束断食' : '开始断食'
                color = MainColorType.fast
                break;
            case 'SLEEP':
                title = selItem.event == 'SLEEP_WAKE_UP' ? '结束睡眠' : '开始睡眠'
                color = MainColorType.sleep
                break
        }

        var endTimestamp = 0
        if (selItem.envent == 'FAST_END') {
            endTimestamp = new Date().getTime()//fastData.target.end_time
        }

        var duration = 24 * 3600 * 1000//fastData.target.duration

        global.set_time = new Date().getTime()

        return <View className="modal_content">
            <ConsolePicker ref={limitPickerRef}
                themeColor={color}
                title={title}
                onCancel={() => {
                    setShowTimePicker(false)
                }}
                min={min}
                max={max}
                current={defaultTimestamp}
                duration={duration}
                endTimestamp={endTimestamp}
                isFast={true}
                isEnd={operateType == 'endFast'}
                isTimeout={false}
                isLoading={btnDisable}
                onChange={(e) => {
                    pickerConfirm(e, null)
                    global.pauseIndexTimer = false
                }}
            />
        </View>
    }

    function pickerConfirm(t1: number, event: any) {
        if (btnDisable) {
            return
        }
        global.scenario = 'FAST'
        setBtnDisable(true)
        clockTimes({
            check_items: [{
                schedule_id: selItem.schedule_id,
                date: dayjs(t1).format('YYYYMMDD'),
                timestamp: t1,
                extra: {
                    set_time: global.set_time ? global.set_time : new Date().getTime(),
                    confirm_time: new Date().getTime()
                }
            }]
        }).then(res => {
            dispatch(setShowActionTip({
                isShow: true,
                isCompleted: (selItem.event == 'FAST_END' || selItem.event == 'SLEEP_WAKE_UP')
            }))
            setBtnDisable(false)
            setShowTimePicker(false)
            global.refreshWindow()
            global.refreshHistory()
        }).catch(e => {
            setBtnDisable(false)
        })
    }

    function more() {
        var list: any = []
        switch (health.mode) {
            case 'DAY':
            case 'NIGHT':
                list = ['设置提醒', '设置位置']
                break;
            case 'FAST':
            case 'SLEEP':
                {
                    const obj = getScenario(health.windows, health.mode)
                    if (obj.window_id) {
                        list.push('编辑本次时长')
                        if (obj.timeline && obj.timeline[0].moment) {
                            list.push('删除本次记录')
                        }
                    }
                    list.push('编辑日程列表')

                }
                break;
            case 'EAT':
                {
                    list = [
                        'Add Snack',
                        '编辑日程列表',
                    ]

                    if (getScenario(health.windows, health.mode).window_id) {
                        list.push('Make done')
                    }
                }
                break;
            case 'ACTIVE':
                {
                    list = [
                        '记录一次活动',
                        '编辑日程列表',
                    ]

                    if (getScenario(health.windows, health.mode).window_id) {
                        list.push('Make done')
                    }
                }
                break;

        }



        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            title: 'Oprate Title',
            itemList: list,
            success: (res) => {
                tapActionSheet(res)
            }
        });
    }

    function tapActionSheet(index) {
        switch (index) {
            case 0:
                {
                    switch (health.mode) {
                        case 'DAY':
                        case 'NIGHT':
                            jumpPage('/_health/pages/schedules?mode=' + health.mode)
                            break;
                        case 'FAST':
                        case 'SLEEP':
                            {
                                const obj = getScenario(health.windows, health.mode)
                                if (obj.window_id) {
                                    //编辑本次时长
                                    setDurationPicker(true)
                                }
                                else {
                                    jumpPage('/_health/pages/schedules?mode=' + health.mode)
                                }
                            }
                            break;
                        case 'EAT':
                            //add snack
                            jumpPage(`/_health/pages/add_moment?title=加餐&is_temp=${true}`)
                            break;
                        case 'ACTIVE':
                            //记录一次活动
                            jumpPage(`/_health/pages/add_moment?title=&is_temp=${true}`)
                            break;
                    }
                }
                break;
            case 1:
                {
                    switch (health.mode) {
                        case 'EAT':
                            jumpPage('/_health/pages/schedules?mode=' + health.mode)
                            break;
                        case 'FAST':
                        case 'SLEEP':
                            const obj = getScenario(health.windows, health.mode)
                            if (obj.window_id) {
                                //del record
                                jumpPage('/_health/pages/schedules?mode=' + health.mode)
                                console.log('zzzzzzzzz')
                            }
                            else {

                            }
                            break;
                        case 'ACTIVE':
                            jumpPage('/_health/pages/schedules?mode=' + health.mode)
                            break;
                        case 'DAY':
                        case 'NIGHT':
                            chooseLocation()
                            break;
                    }
                }
                break;
            case 2:
                {
                    switch (health.mode) {
                        case 'EAT':
                        case 'ACTIVE':
                            tapMakeDone()
                            break;
                    }
                }
                break;
        }
    }

    function tapMakeDone() {
        makeDone(getScenario(health.windows, health.mode).window_id).then(res => {
            global.refreshWindow()
            global.refreshHistory()
        })
    }

    function detail() {
        const { day, night } = health.windows.night_day
        const { fast, eat } = health.windows.fast_eat
        const { sleep, active } = health.windows.sleep_active
        let list: any = []
        switch (health.mode) {
            case 'DAY':
                list = day.timeline
                if (active.onboard == false) {
                    return <OnBoard title='你还没有开启位置授权'
                        desc="获取准确的日出日落信息需要您开启微信运动授权，点击下方按钮进行授权"
                        btnTitle="去开启"
                        onClick={chooseLocation}
                    />
                }
                break;
            case 'NIGHT':
                list = night.timeline
                if (active.onboard == false) {
                    return <OnBoard title='你还没有开启位置授权'
                        desc='获取准确的日出日落信息需要您开启微信运动授权，点击下方按钮进行授权'
                        btnTitle="去开启"
                        onClick={chooseLocation}
                    />
                }
                break;
            case 'FAST':
                list = fast.timeline
                break;
            case 'EAT':
                list = eat.timeline
                break;
            case 'SLEEP':
                list = sleep.timeline
                break;
            case 'ACTIVE':
                list = active.timeline
                if (active.onboard == false) {
                    return <OnBoard title={list[0].title}
                        desc="Subtitle"
                        btnTitle="Action"
                        onClick={() => {
                            jumpPage('/_health/pages/active_plan?schedule=' + JSON.stringify(list.length > 0 ? list[0] : '{}'))
                        }}
                    />
                }
                break;
        }

        return <View>
            {
                list.map((item, index) => {
                    return timelineItem(item, index, list.length)
                })
            }
        </View>
    }

    function switchText() {
        switch (health.mode) {
            case 'FAST':
                return 'Switch to Eat'
            case 'EAT':
                return 'Switch to Fast'
            case 'DAY':
                return 'Switch to Night'
            case 'NIGHT':
                return 'Switch to Daylight'
            case 'SLEEP':
                return 'Switch to Activity'
            case 'ACTIVE':
                return 'Switch to Sleep'

        }
        return ''
    }

    function tapSwitchBtn() {
        switch (health.mode) {
            case 'FAST':
                dispatch(setMode('EAT'));
                break
            case 'EAT':
                dispatch(setMode('FAST'));
                break
            case 'DAY':
                dispatch(setMode('NIGHT'));
                break
            case 'NIGHT':
                dispatch(setMode('DAY'));
                break
            case 'SLEEP':
                dispatch(setMode('ACTIVE'));
                break
            case 'ACTIVE':
                dispatch(setMode('SLEEP'));
                break

        }
    }

    function windowStatus() {
        var statusType = getWindowStatus(health.windows, health.mode)
        switch (statusType) {
            case WindowStatusType.open:
                return 'New open'
            case WindowStatusType.process:
                return 'In process'
            case WindowStatusType.upcoming:
                return 'Upcoming'
        }
        return ''
    }

    function tapClearLocation() {
        Taro.showModal({
            title: '提示',
            content: '确认清除位置数据?',
            success: function (res) {
                if (res.confirm) {
                    clearLocation().then(res => {
                        global.refreshWindow()
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }

    function chooseLocation() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        Taro.chooseLocation({
            // latitude: authInfo && authInfo.lat ? authInfo.lat : undefined,
            // longitude: authInfo && authInfo.lat ? authInfo.lng : undefined,
            success: function (res) {
                uploadLocation(res)
            },
            fail(res) {
                Taro.showToast({
                    title: '位置修改失败!\n请重新选择就近位置',
                    icon: 'none'
                })
            },
            complete(res) {

            }
        })
    }

    function uploadLocation(res) {
        var today = new Date()
        var yesterday = new Date(today.getTime() - 24 * 3600 * 1000)
        var tomorrow = new Date(today.getTime() + 24 * 3600 * 1000 * 5)
        var strYesterday = `${yesterday.getFullYear()}-${TimeFormatter.padZero(yesterday.getMonth() + 1)}-${TimeFormatter.padZero(yesterday.getDate())}`
        var strTomorrow = `${tomorrow.getFullYear()}-${TimeFormatter.padZero(tomorrow.getMonth() + 1)}-${TimeFormatter.padZero(tomorrow.getDate())}`

        systemLocation({
            lat: res.latitude,
            lng: res.longitude,
            name: res.name,
            address: res.address,
            date_start: strYesterday,
            date_end: strTomorrow,
            coordinate_system_standard: process.env.TARO_ENV == 'weapp' ? 'GCJ-02' : 'WGS-84'
        }).then(data => {
            global.refreshWindow()
        })
    }

    function updateDuration(duration) {
        setDurationPicker(false)
        const scenario = getScenario(health.windows, health.mode)
        updateEventDuration(scenario.timeline[0].event_id, duration).then(res => {
            global.refreshWindow()
        })
    }

    function timePointClass() {
        if (getWindowStatus(health.windows, health.mode) == WindowStatusType.process) {
            return 'time_point time_point_animation'
        }
        return 'time_point'
    }
    return <View className="main-console-bg">
        <Image className="main_arrow" src={require('@assets/images/center_arrow.png')} />
        <View className="main_summary">
            {/* <View className="main_summary_status" style={{ color: getThemeColor(health.mode) }}>{windowStatus()}</View> */}
            <View className="main_summary_time" style={{ color: getWindowStatus(health.windows, health.mode) == WindowStatusType.upcoming ? '#B2B2B2' : '#000' }}>{getCountownTime(health.windows, health.mode)}
                <View className={timePointClass()}
                    style={{ backgroundColor: getWindowStatus(health.windows, health.mode) == WindowStatusType.upcoming ? '#B2B2B2' : getThemeColor(health.mode) }} />
            </View>
            <Text className="main_summary_duration">Total {getDuration(health.windows, health.mode)}</Text>
            <View className="border_footer_line" />
        </View>
        <View style={{ backgroundColor: '#fff', width: rpxToPx(750) }}>
            {
                detail()
            }
            {
                health.mode == 'ACTIVE' && <View onClick={() => {
                    var list = getScenario(health.windows, health.mode).timeline
                    jumpPage('/_health/pages/active_plan?schedule=' + JSON.stringify(list.length > 0 ? list[0] : '{}'))
                }}>测试</View>
            }
        </View>
        <View className="main_footer">
            <Text className="main_footer_text" onClick={tapSwitchBtn}>{switchText()}</Text>
            {/* {
                (health.mode == 'EAT' || health.mode == 'ACTIVE') && <Text style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={more}>更多</Text>
            } */}
            {/* {
                (health.mode == 'DAY' || health.mode == 'NIGHT') && <Text onClick={chooseLocation}>选择位置</Text>
            } */}
            {
                (health.mode == 'DAY' || health.mode == 'NIGHT') && <Text onClick={tapClearLocation}>清除位置</Text>
            }
            <View className="main_footer_more" onClick={more}>
                <IconMore color="#b2b2b2" width={17} />
            </View>

        </View>
        {
            health.mode == 'ACTIVE' && <View className="console_active_bg" onClick={() => {
                if (!user.isLogin) {
                    jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
                    return
                }
                jumpPage('/_health/pages/move')
            }}>
                <View className="console_active">
                    <Image className="active_icon" src={require('@assets/_health/walk.png')} />
                    <Text className="active_text">Move More</Text>
                    <Image className="cell_arrow" src={require('@assets/_health/cell_arrow.png')} />
                </View>

            </View>
        }
        <View className="circle" />

        {
            showTimePicker && modalContent()
        }
        {
            showPicker && timeContent()
        }
        {
            durationPicker && <DurationPicker
                done={(time) => {
                    updateDuration(time)
                }}
                dismiss={() => {
                    setDurationPicker(false)
                }} time={getScenario(health.windows, health.mode).target.duration} />
        }
    </View>
}