import Buttons from "@/components/basic/Buttons";
import { setPlan } from "@/services/trackTimeDuration";
import { setScenario, setStep } from "@/store/scenario";
import { View, Text, PageContainer, Image } from "@tarojs/components";
import "./SetSchedule.scss";
import Taro, { useDidShow, useReady } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Footer from "@/components/layout/Footer";
import PickerViews from "@/components/input/PickerViews";
import { durationDatas, durationIndex, durationTime, pickerDurations } from "../hooks/Console";
import { TimeFormatter } from "@/utils/time_format";
import Modal from "@/components/layout/Modal";
import TimePicker from "@/features/common/TimePicker";
import { SetScheduleBtn } from "@/features/common/SpecBtns";
import Layout from "@/components/layout/layout";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import { useTranslation } from "react-i18next";
import { ColorType } from "@/context/themes/color";
import TitleView from "./TitleView";
import { jumpPage } from "../hooks/Common";
import { kIsIOS, rpxToPx, vibrate } from "@/utils/tools";
import { PixelRatio } from "react-native";
import { clientId } from "@/services/user";
import showAlert from "@/components/basic/Alert";
import { OneSignal } from 'react-native-onesignal';

let useNavigation;

// let JPush;
let Linking;
let checkNotification, uploadPermissions,PushNotification;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
    Linking = require('react-native').Linking;
    // JPush = require('jpush-react-native').default;
    checkNotification = require('@/utils/native_permission_check').checkNotification;
    uploadPermissions = require('@/utils/native_permission_check').uploadPermissions;
    PushNotification = require('react-native-push-notification')
}
export default function Component() {
    const isFastFirst = true;
    const { t } = useTranslation()
    const dispatch = useDispatch();
    const canvasRef = useRef(null);
    const [scenario] = useState(useSelector((state: any) => state.scenario))
    // const scenario = useSelector((state: any) => state.scenario);
    const common = useSelector((state: any) => state.common);

    const [isOpen, setIsOpen] = useState(false)
    const [isTimeOpen, setIsTimeOpen] = useState(false)
    const [btnDisable, setBtnDisable] = useState(false)

    const pickerRef = useRef<any>(null);
    // const [count,setCount] = useState(0)
    const [beginChange, setBeginChange] = useState(true)
    const [operateType, setOperateType] = useState(0)
    const [isModalTimePicker, setIsModalTimePicker] = useState(false)

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



    var scheduleObj: { start_time: any; end_time: any; };
    if (scenario.name == 'FAST') {
        scheduleObj = scenario.schedule.fast
    }
    else if (scenario.name == 'SLEEP') {
        scheduleObj = scenario.schedule.sleep
    }
    else {
        if (scenario.step == 'fast') {
            scheduleObj = scenario.schedule.fast
        }
        else {
            scheduleObj = scenario.schedule.sleep
        }
    }



    const [startTime, setStartTime] = useState(scheduleObj.start_time)
    const [endTime, setEndTime] = useState(scheduleObj.end_time)

    global.startTime = startTime
    global.endTime = endTime
    const [pickerValue, setPickerValue] = useState(durationIndex(scheduleObj.start_time, scheduleObj.end_time, common))

    const [hours, setHours] = useState(durationTime(scheduleObj.start_time, scheduleObj.end_time)[0])
    const [minutes, setMinutes] = useState(durationTime(scheduleObj.start_time, scheduleObj.end_time)[1])
    const [chooseStart, setChooseStart] = useState(true)
    const [count, setCount] = useState(0)
    const [authStatus, setAuthStatus] = useState('')


    useEffect(() => {
        if (global.schedule_fast && scenario.step == 'fast') {
            scheduleObj = global.schedule_fast
        }
        if (global.schedule_sleep && scenario.step == 'sleep') {
            scheduleObj = global.schedule_sleep
        }
        setStartTime(scheduleObj.start_time)
        setEndTime(scheduleObj.end_time)
        setPickerValue(durationIndex(scheduleObj.start_time, scheduleObj.end_time, common))
        setHours(durationTime(scheduleObj.start_time, scheduleObj.end_time)[0])
        setMinutes(durationTime(scheduleObj.start_time, scheduleObj.end_time)[1])

        if (kIsIOS) {
            var Jto = require('react-native').NativeModules.NativeBridge;
            Jto.getNotificationAuthStatus()
            require('react-native').NativeAppEventEmitter.addListener('notificationResult', (data) => {
                setAuthStatus(data)
                global.notification = data
                uploadPermissions()
            })
            require('react-native').NativeAppEventEmitter.addListener('operateNotificationResult', (data) => {
                global.notification = data
                navigation.popToTop()
                uploadPermissions()
            })
        }
        else {
            OneSignal.Notifications.canRequestPermission().then((status) => {
                if (status) {
                    OneSignal.Notifications.getPermissionAsync().then((res) => {
                        if (res) {
                            global.notification = 'authorized'
                            uploadPermissions()
                        }
                        else {
                            global.notification = 'denied'
                            uploadPermissions()
                        }
                    })
                }
                else {
                    global.notification = 'not_determined'
                    uploadPermissions()
                }
            })
        }

    }, [])

    useEffect(() => {
        if (isOpen || isTimeOpen) {
            global.disableCanvasGesture = true
        }
        else {
            global.disableCanvasGesture = false
        }
    }, [isOpen, isTimeOpen])


    useDidShow(() => {
        setCount(count + 1)
    })


    function checkPermission() {
        start()
        // const test = require('@/utils/push').default
        // test()
    }

    function start() {
        if (scenario.name == 'FAST' || scenario.name == 'SLEEP') {
            setBtnDisable(true)
            setPlan({
                scenario: scenario.name,
                schedule: scenario.name == 'FAST' ? {
                    fast: {
                        start_time: startTime,
                        end_time: endTime,
                    }
                } : {
                    sleep: {
                        start_time: startTime,
                        end_time: endTime,
                    }
                }
            }).then(res => {
                setBtnDisable(false)
                if (global.checkData) {
                    global.checkData()
                }
                if (global.indexPageRefresh) {
                    global.indexPageRefresh()
                }

                // if (process.env.TARO_ENV == 'weapp') {
                //     Taro.navigateBack({ delta: 3 })
                // }
                // else {
                //     navigation.popToTop()
                // }

                // setTimeout(() => {
                popScheduleAlert(scenario, startTime)

                // }, 1000)
            }).catch(e => {
                setBtnDisable(false)
            })
        }
        else {
            if ((scenario.step == 'fast' && isFastFirst) || (scenario.step == 'sleep' && !isFastFirst)) {
                var obj = JSON.parse(JSON.stringify(scenario))
                if (isFastFirst) {
                    obj.schedule.fast = {
                        start_time: startTime,
                        end_time: endTime,
                    }
                    dispatch(setStep('sleep'))
                    dispatch(setScenario(obj))
                }
                else {
                    obj.schedule.sleep = {
                        start_time: startTime,
                        end_time: endTime,
                    }
                    dispatch(setStep('fast'))
                    dispatch(setScenario(obj))
                }

                saveTempCache(startTime, endTime)

                jumpPage('/pages/clock/SetSchedule', 'SetSchedule', navigation)
            }
            else {
                commit()
            }
        }
    }

    function saveTempCache(strStart, strEnd) {
        if (scenario.step == 'fast') {
            global.schedule_fast = {
                start_time: strStart,
                end_time: strEnd,
            }
        }
        if (scenario.step == 'sleep') {
            global.schedule_sleep = {
                start_time: strStart,
                end_time: strEnd,
            }
        }

    }

    function commit() {
        setBtnDisable(true)
        setPlan({
            scenario: scenario.name,
            schedule: {
                fast: {
                    start_time: isFastFirst ? scenario.schedule.fast.start_time : startTime,
                    end_time: isFastFirst ? scenario.schedule.fast.end_time : endTime,
                }, sleep: {
                    start_time: !isFastFirst ? scenario.schedule.sleep.start_time : startTime,
                    end_time: !isFastFirst ? scenario.schedule.sleep.end_time : endTime,
                }
            }
        }).then(res => {
            setBtnDisable(false)
            dispatch(setStep('fast'))
            if (global.checkData) {
                global.checkData()
            }

            if (global.indexPageRefresh) {
                global.indexPageRefresh()
            }

            // if (process.env.TARO_ENV == 'weapp') {
            //     Taro.navigateBack({ delta: 4 })
            // }
            // else {
            //     navigation.popToTop()
            // }

            // setTimeout(() => {
            popMixScheduleAlert(scenario.schedule.fast.start_time, startTime)

            // }, 1000)

        }).catch(e => {
            setBtnDisable(false)
        })
    }

    function popScheduleAlert(scenario, startTime) {
        PushNotification.checkPermissions((res)=>{
            //允许授权
            if (res.authorizationStatus == 2){
                showAlert({
                    title: t('feature.track_time_duration.reminders.schedule_title'),
                    content: scenario.name == 'FAST' ?
                        t('feature.track_time_duration.reminders.enable_schedule_fast_content', { time: startTime }) :
                        t('feature.track_time_duration.reminders.enable_schedule_sleep_content', { time: startTime }),
                    showCancel: false,
                    confirmText: t('feature.track_time_duration.reminders.ok'),
                    cancel: () => {
                        navigation.popToTop()
                    },
                    confirm: () => {
                        navigation.popToTop()
                    },
                })
            }
            else {
                showAlert({
                    title: t('feature.track_time_duration.reminders.schedule_title'),
                    content: scenario.name == 'FAST' ?
                        t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
                        t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
                    cancelText: t('feature.track_time_duration.reminders.later'),
                    confirmText: t('feature.track_time_duration.reminders.open'),
                    showCancel: true,
                    cancel: () => {
                        navigation.popToTop()
                    },
                    confirm: () => {
                        if (authStatus != 'not_determined') {
                            navigation.popToTop()
                        }
                        checkNotification()
                        // Linking.openURL('app-settings:notifications')
                    }
                })
            }
        })
    }

    function popMixScheduleAlert(time1, time2) {
        console.log(time1, time2)
        PushNotification.checkPermissions((res)=>{
            //允许授权
            if (res.authorizationStatus == 2){
                showAlert({
                    title: t('feature.track_time_duration.reminders.schedule_title'),
                    content: t('feature.track_time_duration.reminders.enable_schedule_mix_content', { time1: time1, time2: time2 }),
                    showCancel: false,
                    confirmText: t('feature.track_time_duration.reminders.ok'),
                    cancel: () => {
                        navigation.popToTop()
                    },
                    confirm: () => {
                        navigation.popToTop()
                    },
                })
            }
            else {
                showAlert({
                    title: t('feature.track_time_duration.reminders.schedule_title'),
                    content:
                        t('feature.track_time_duration.reminders.schedule_mix_content'),
                    cancelText: t('feature.track_time_duration.reminders.later'),
                    confirmText: t('feature.track_time_duration.reminders.open'),
                    showCancel: true,
                    cancel: () => {
                        navigation.popToTop()
                    },
                    confirm: () => {
                        if (authStatus != 'not_determined') {
                            navigation.popToTop()
                        }
                        checkNotification()
                        // Linking.openURL('app-settings:notifications')
                    }

                })
            }
        })
    }

    function onStartTimeChange(e: string) {
        setIsTimeOpen(false)
        setBeginChange(true)
        setStartTime(e)

        setPickerValue(durationIndex(e, endTime, common))
        setHours(durationTime(e, endTime)[0])
        setMinutes(durationTime(e, endTime)[1])
        saveTempCache(e, endTime);
        if (global.updateDial)
            global.updateDial(e, endTime)
    }

    function onEndTimeChange(e: string) {
        setIsTimeOpen(false)
        setBeginChange(false)
        setEndTime(e)
        setPickerValue(durationIndex(startTime, e, common))
        setHours(durationTime(startTime, e)[0])
        setMinutes(durationTime(startTime, e)[1])
        saveTempCache(startTime, e);
        if (global.updateDial)
            global.updateDial(startTime, e)
    }



    function showPicker() {
        setIsOpen(true)
    }

    function durationChange(e) {
        var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step

        var h = parseInt(count / 60)
        var m = count % 60
        setHours(h)
        setMinutes(m)
        setPickerValue(e)
        setIsOpen(false)
        if (beginChange) {
            var strEnd = TimeFormatter.calculateTimeByTimeRange(count, startTime, true)

            setEndTime(strEnd);
            saveTempCache(startTime, strEnd)
            if (global.updateDial)
                global.updateDial(startTime, strEnd)
        }
        else {
            var strStart = TimeFormatter.calculateTimeByTimeRange(count, endTime, false)

            setStartTime(strStart);
            saveTempCache(strStart, endTime)
            if (global.updateDial)
                global.updateDial(strStart, endTime)
        }

    }

    global.startDuration = (type) => {
        setOperateType(type)
    }

    global.updateDuration = (start, end) => {
        var startCount = parseInt(start.split(':')[0]) * 60 + parseInt(start.split(':')[1])
        var endCount = parseInt(end.split(':')[0]) * 60 + parseInt(end.split(':')[1])
        if (operateType == 1 && startCount % 30 == 0) {
            vibrate()
        }
        else if (operateType == 2 && endCount % 30 == 0) {
            vibrate()
        }
        else if (operateType == 3 && (startCount % 30 == 0 || endCount % 30 == 0)) {
            vibrate()
        }

        setStartTime(start)
        setEndTime(end)
        setPickerValue(durationIndex(start, end, common))
        setHours(durationTime(start, end)[0])
        setMinutes(durationTime(start, end)[1])
        saveTempCache(start, end)
    }


    global.endDuration = () => {
        setOperateType(0)
    }

    function layoutContent() {
        return <PickerViews ref={pickerRef}
            onChange={durationChange}
            items={durationDatas(common)}
            value={pickerValue} height={200}
            title={scenario.step == 'fast' ?
                t('feature.track_time_duration.dial.picker_fast_schedule_duration') :
                t('feature.track_time_duration.dial.picker_sleep_schedule_duration')}
            themeColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
            showBtns={true} onCancel={() => { setIsOpen(false); }} />
    }

    function pickerTitle() {
        if (scenario.step == 'fast') {
            if (chooseStart) {
                return t('feature.track_time_duration.dial.picker_fast_schedule_start_time');
            }
            return t('feature.track_time_duration.dial.picker_fast_schedule_end_time');
        }
        else {
            if (chooseStart) {
                return t('feature.track_time_duration.dial.picker_sleep_schedule_start_time');
            }
            return t('feature.track_time_duration.dial.picker_sleep_schedule_end_time');
        }
    }


    function timeContent() {
        return <TimePicker time={chooseStart ? startTime : endTime}
            color={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
            title={pickerTitle()}
            confirm={chooseStart ? onStartTimeChange : onEndTimeChange}
            cancel={() => { setIsTimeOpen(false) }} />
    }

    function getTargetDesc() {
        var count = 24 * 60 - (hours * 60 + minutes)
        var leftHours = Math.floor(count / 60)
        var leftMinutes = count % 60
        return scenario.step == 'fast' ? t('page.set_schedule.fast_target_desc', {
            target_time: (hours > 0 ? hours + TimeFormatter.getHoursUnit(hours) : '') + (minutes > 0 ? minutes + TimeFormatter.getMinutesUnit(minutes) : ''),
            left_time: (leftHours > 0 ? leftHours + TimeFormatter.getHoursUnit(leftHours) : '') + (leftMinutes > 0 ? leftMinutes + TimeFormatter.getMinutesUnit(leftMinutes) : '')
        }) :
            t('page.set_schedule.sleep_target_desc', {
                target_time: (hours > 0 ? hours + TimeFormatter.getHoursUnit(hours) : '') + (minutes > 0 ? minutes + TimeFormatter.getMinutesUnit(minutes) : ''),
                left_time: (leftHours > 0 ? leftHours + TimeFormatter.getHoursUnit(leftHours) : '') + (leftMinutes > 0 ? leftMinutes + TimeFormatter.getMinutesUnit(leftMinutes) : '')
            })
    }

    function detail() {
        var isNextDay: boolean = parseInt(startTime.split(':')[0]) * 60 + parseInt(startTime.split(':')[1]) > parseInt(endTime.split(':')[0]) * 60 + parseInt(endTime.split(':')[1])


        return <View style={{ height: Taro.getSystemInfoSync().screenHeight - 200, flexDirection: 'column', display: 'flex' }}>
            {/* <Text className="subtitle">{t('page.set_schedule.fast_subtitle')}</Text> */}
            <TitleView title={scenario.step == 'fast' ? t('page.set_schedule.fast_title') : t('page.set_schedule.sleep_title')}
                subTitle={t('page.set_schedule.fast_subtitle')}
                titleColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
            />

            <View style={{ color: '#fff', marginTop: rpxToPx(64) }}>
                <Text className="cell_header">{scenario.step == 'fast' ? t('page.set_schedule.fast_target') : t('page.set_schedule.sleep_target')}</Text>
                <View className="cell_full" style={{
                    marginLeft: rpxToPx(46),
                    marginRight: rpxToPx(46),
                    paddingLeft: rpxToPx(40),
                    paddingRight: rpxToPx(40),

                }} onClick={() => { setIsModalTimePicker(false); setIsOpen(true) }}>
                    <Text className="cell_title">{t('feature.track_time_duration.dial.duration')}</Text>
                    <Text className="cell_value" style={{ color: scenario.step == 'fast' ? ColorType.fast : ColorType.sleep }}>{hours > 0 ? hours + TimeFormatter.getHoursUnit(hours) : ''}{minutes > 0 ? minutes + TimeFormatter.getMinutesUnit(minutes) : ''}</Text>
                    <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                </View>
                <Text className="cell_footer">{getTargetDesc()}</Text>

                <View style={{ height: rpxToPx(60) }} />
                <Text className="cell_header">{scenario.step == 'fast' ? t('page.set_schedule.fast_schedule') : t('page.set_schedule.sleep_schedule')}</Text>
                <View className="cell_top" onClick={() => {
                    setIsModalTimePicker(true)
                    setChooseStart(true)
                    setIsTimeOpen(true)
                }}>
                    <Text className="cell_title">{t('feature.track_time_duration.dial.start_time')}</Text>
                    <Text className="cell_value" style={{ color: scenario.step == 'fast' ? ColorType.fast : ColorType.sleep }}>{startTime}</Text>
                    <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                    <View className="cell_line" style={{ height: 1 / PixelRatio.get() }} />
                </View>
                <View className="cell_bottom" onClick={() => {
                    setIsModalTimePicker(true)
                    setChooseStart(false)
                    setIsTimeOpen(true)
                }}>
                    <Text className="cell_title">{t('feature.track_time_duration.dial.end_time')}</Text>
                    {
                        isNextDay &&
                        <Text className="next_day">{t('page.set_schedule.next_day')}</Text>
                    }

                    <Text className="cell_value" style={{ color: scenario.step == 'fast' ? ColorType.fast : ColorType.sleep }}>{endTime}</Text>
                    <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                </View>
                <Text className="cell_footer">{scenario.step == 'fast' ? t('page.set_schedule.fast_schedule_desc', {
                    start_time: startTime, end_time: endTime, the_next_day:
                        isNextDay ? t('page.set_schedule.the_next_day') : ''
                }) :
                    t('page.set_schedule.sleep_schedule_desc', {
                        start_time: startTime, end_time: endTime, the_next_day:
                            isNextDay ? t('page.set_schedule.the_next_day') : ''
                    })}</Text>
                {/* <Text className="cell_footer">计划每日18:00开始断食，次日10:00结束断食。</Text> */}
            </View>

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

            <Footer>
                <SetScheduleBtn title={(scenario.step == 'fast' && scenario.name == 'FAST_SLEEP') ? t('feature.common.btn_set_and_next') : t('feature.common.btn_set_and_done')}
                    lowLight={operateType != 0}
                    isFast={scenario.step == 'fast'}
                    disable={btnDisable}
                    onClick={() => checkPermission()} />
            </Footer>

            {
                (isOpen || isTimeOpen) && <PageContainer style={{ backgroundColor: '#1c1c1c' }}
                    overlayStyle={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
                    customStyle={{ backgroundColor: '#1c1c1c' }}
                    closeOnSlideDown={false}
                    onAfterLeave={() => { setIsOpen(false); setIsTimeOpen(false) }}
                    show={isOpen || isTimeOpen} round={true} overlay={true} position='bottom'
                >
                    {
                        isTimeOpen ? timeContent() : layoutContent()
                    }
                </PageContainer>
            }

            {/* <PageContainer style={{ backgroundColor: '#1c1c1c' }}
        overlayStyle='background-color:rgba(0,0,0,0.9)'
        custom-style='background-color:#1c1c1c'
        closeOnSlideDown={false}
        onAfterLeave={() => { setIsOpen(false); setIsTimeOpen(false) }}
        show={isOpen || isTimeOpen} round={true} overlay={true} position='bottom'
      >
        {
          isModalTimePicker?timeContent():layoutContent()
        }
      </PageContainer> */}
            {/* {
                isOpen && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={() => {
                    setIsOpen(false)
                    durationChange(pickerRef.current.getConfirmData())
                }} />
            }
            {
                isTimeOpen && <Modal children={timeContent()} dismiss={() => setIsTimeOpen(false)} confirm={() => {
                    setIsTimeOpen(false)
                }} />
            } */}

        </View>
    }

    return <Layout
        titleColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
        title={scenario.step == 'fast' ? t('page.set_schedule.fast_title') : t('page.set_schedule.sleep_title')}
        titleShowStyle={NaviBarTitleShowType.scrollToShow} type={TemplateType.customHeader}>
        {
            detail()
        }
    </Layout>;
}