import { API_LOCAL_PUSHES, API_MIX_CLOCKS } from "@/services/http/api";
import { request } from "@/services/http/request";
import { recordCheck } from "@/services/trackTimeDuration";
import trackTimeService from "@/store/trackTimeMachine"
import { isIOS, kIsIOS } from "@/utils/tools";
// import {PushNotification} from 'react-native-push-notification'
import Taro from "@tarojs/taro";
import dayjs from 'dayjs'

let PushNotification, Importance, NativeModules;
if (process.env.TARO_ENV == 'rn') {
    PushNotification = require('react-native-push-notification')
    Importance = require('react-native-push-notification').Importance
    NativeModules = require('react-native').NativeModules
}

export const startFast = (start_time: number, duration: number) => {
    return new Promise((resolve, reject) => {
        // duration = duration < 3600 * 1000 ? 3600 * 1000 : duration;
        const extra = {
            set_time: global.set_time,
            confirm_time: new Date().getTime(),
        }
        recordCheck({
            action: 'FAST_START',
            real_check_time: start_time,
            target_duration: duration,
            extra: extra
        }).then(res => {
            resolve(res)
            trackTimeService.send({ type: 'START_FAST' });
            // getLocalPush()
        }).catch(e => {
            reject(e)
        });
    });
}

export const endFast = (start_time: number) => {
    return new Promise((resolve, reject) => {
        const extra = {
            set_time: global.set_time,
            confirm_time: new Date().getTime(),
        }
        recordCheck({
            action: 'FAST_END',
            real_check_time: start_time,
            extra: extra
        }).then(res => {
            trackTimeService.send({ type: 'END_FAST' });
            trackTimeService.send({ type: 'RESET' });
            trackTimeService.send({ type: global.scenario });
            resolve(res)
            // getLocalPush()
        }).catch(e => {
            reject(e)
        });
    });
}


export const startSleep = (start_time: number, duration: number) => {
    // duration = duration < 3600 * 1000 ? 3600 * 1000 : duration;
    const extra = {
        set_time: global.set_time,
        confirm_time: new Date().getTime(),
    }
    return new Promise((resolve, reject) => {
        recordCheck({
            action: 'SLEEP_START',
            real_check_time: start_time,
            target_duration: duration,
            extra: extra
        }).then(res => {
            trackTimeService.send({ type: 'START_SLEEP' });
            resolve(res)
            // getLocalPush()
        }).catch(e => {
            reject(e)
        });
    });
}
export const endSleep = (start_time: number) => {
    const extra = {
        set_time: global.set_time,
        confirm_time: new Date().getTime(),
    }
    return new Promise((resolve, reject) => {
        recordCheck({
            action: 'SLEEP_END',
            real_check_time: start_time,
            extra: extra
        }).then(res => {
            trackTimeService.send({ type: 'END_SLEEP' });
            resolve(res)
            // getLocalPush()
        }).catch(e => {
            reject(e)
        });
    });
}

export const batchClocks = (params: any) => {
    const extra = {
        set_time: global.set_time,
        confirm_time: new Date().getTime(),
    }
    return new Promise((resolve, reject) => {
        request({
            url: API_MIX_CLOCKS, method: 'POST', data: { extra: extra, ...params }
        }).then(res => {
            resolve(res);
        }).catch(e => {
            if (global.postBtnUpdateStatus)
                global.postBtnUpdateStatus('idle')
            reject(e)
        })
    })
}

export const uploadLocalPushInfo = (params) => {
    request({
        url: API_LOCAL_PUSHES, method: 'POST', data: {
            id: params.messageId,
            result: 'SUCCESS'
        }
    })
}

export const getLocalPush = () => {
    if (process.env.TARO_ENV == 'rn') {
        PushNotification.checkPermissions((res) => {
            console.log('notification status begin')
            console.log('notification status', res)
            //允许授权
            if ((kIsIOS && res.authorizationStatus == 2) || (!kIsIOS && res.alert)) {
                request({
                    url: API_LOCAL_PUSHES, method: 'GET', data: {}
                }).then(res => {
                    const { messages } = res as any;
                    if (messages.length == 0) {
                        return;
                    }
                    // PushNotification.configure({
                    //     onRegister: function (token) {
                    //         console.log('TOKEN:', token);
                    //     },

                    //     onNotification: function (notification) {
                    //         console.log('NOTIFICATION:', notification);
                    //         // notification.finish(PushNotificationIOS.FetchResult.NoData);
                    //     },

                    //     permissions: {
                    //         alert: true,
                    //         badge: true,
                    //         sound: true,
                    //     },

                    //     popInitialNotification: true,
                    //     // requestPermissions: true,
                    // });
                    // PushNotification.cancelAllLocalNotifications()

                    if (kIsIOS) {
                        var Jto = require('react-native').NativeModules.NativeBridge;
                        Jto.addLocalPush(messages)
                        return;
                    }
                    else {
                        const { NativeBridge } = NativeModules
                        NativeBridge.addLocalPush(JSON.stringify(messages))
                        return;
                    }


                    messages.map((item, index) => {
                        if (kIsIOS) {
                            setTimeout(() => {
                                var Jto = require('react-native').NativeModules.NativeBridge;
                                Jto.addLocalPush(item)
                            }, index * 1000)
                        }
                        else {
                            PushNotification.createChannel({
                                channelId: item.id, // (required)
                                channelName: "My channel", // (required)
                                channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
                                playSound: true, // (optional) default: true
                                soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
                                importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
                                vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
                            }, (created) => {
                                if (item.mode == 'ONCE') {
                                    console.log('leon 9528')
                                    if (new Date().getTime() <= item.once) {
                                        console.log('leon 9529')
                                        PushNotification.localNotificationSchedule({
                                            //... You can use all the options from localNotifications
                                            channelId: item.id,
                                            title: item.title,
                                            message: item.body,// + '\nPress for actions >>', // (required)
                                            date: new Date(new Date().getTime() + 10 * 1000),
                                            // date: new Date(item.once), // in 60 secs
                                            allowWhileIdle: true, // (optional) set notification to work while on doze, default: false
                                            messageId: item.id,
                                            // repeatType:'minute',
                                            /* Android Only Properties */

                                        })
                                    }

                                }
                                else if (item.mode == 'RECURRING') {
                                    console.log('leon 9527')
                                    const { time, repeat_type } = item.recurring;
                                    const date = dayjs().format('YYYY-MM-DD')
                                    const { NativeBridge } = NativeModules
                                    NativeBridge.addLocalPush(item.title, item.body + '\nPress for actions >>', time)
                                    return;

                                    PushNotification.localNotificationSchedule({
                                        //... You can use all the options from localNotifications
                                        channelId: item.id,
                                        title: item.title,
                                        message: item.content + '  ', // (required)
                                        date: new Date(date + 'T' + time), // in 60 secs
                                        allowWhileIdle: true, // (optional) set notification to work while on doze, default: false
                                        messageId: item.id,
                                        repeatType: repeat_type,
                                        // repeatType:'minute',
                                        /* Android Only Properties */

                                    })
                                }
                            })
                        }

                    })

                    console.log('notificatin push set', messages)
                })
            }
        });

    }

}

