import { Component, PropsWithChildren } from 'react'
import './app.scss'
import '@/context/locales/index'
import { Provider, useDispatch } from 'react-redux'
import store from './store/store'
import { View } from '@tarojs/components'
import GlobalModal from './components/layout/GlobalModal'
import Taro from '@tarojs/taro'
import { getInfoSuccess } from './store/user'
import { uploadLocalPushInfo } from './features/trackTimeDuration/actions/TrackTimeActions'


// import { StatusBar } from 'react-native'
// import jgPush from './utils/push.rn'


// import 'taro-ui/dist/style/index.scss'

let LogBox;
let StatusBar;
let ActionSheetProvider;
let messaging;
let PushNotification;
if (process.env.TARO_ENV == 'rn') {
  LogBox = require("react-native").LogBox
  StatusBar = require("react-native").StatusBar
  ActionSheetProvider = require('@expo/react-native-action-sheet').ActionSheetProvider
  messaging = require('@react-native-firebase/messaging').default
  PushNotification = require('react-native-push-notification')
}



const App: React.FC<PropsWithChildren> = ({ children }) => {

  // const dispatch = useDispatch();




  // if (process.env.TARO_ENV == 'rn') {
  //   global.language = 'en'
  //   PushNotification.configure({
  //     // onRegister: function (token) {
  //     //     console.log('TOKEN:', token);
  //     // },

  //     onNotification: function (notification) {
  //       console.log('NOTIFICATION:', notification);
  //       setTimeout(() => {
  //         uploadLocalPushInfo(notification)
  //       }, 3000)

  //       // notification.finish(PushNotificationIOS.FetchResult.NoData);
  //     },

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

  //     // popInitialNotification: true,
  //     // requestPermissions: true,
  //   });

  //   // messaging().setBackgroundMessageHandler(async remoteMessage => {
  //   //   console.log('Message is handled in the background!', remoteMessage);
  //   // });
  //   // alert(Intl.DateTimeFormat().resolvedOptions().timeZone)
  // }
  if (process.env.TARO_ENV == 'weapp') {
    loadWXCache()
    global.isDebug = Taro.getStorageSync('isDebug')

    const updateManager = Taro.getUpdateManager()
    updateManager.onUpdateReady(function () {
      Taro.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            updateManager.applyUpdate();
          }
        }
      });
    });
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
      Taro.showModal({
        title: '已经有新版本喽~',
        content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
        showCancel: false,
      });
    });

  }
  else {
    //关闭其中某些yellow警告
    loadRNCache()
    LogBox.ignoreLogs(['Warning: ...']); // Ignore log notification by message
    LogBox.ignoreAllLogs();//Ignore all log notifications

    // const test = require('./utils/push').default
    // test()
    // jgPush()
    // const JPush = require('jpush-react-native')

    // JPush.init({ appKey: "4fcc3e237eec4c4fb804ad49", channel: "dev", production: false });
    // //连接状态
    // JPush.addConnectEventListener(result => {
    //   console.log(result)
    //   debugger
    // })
    // console.log('rn jpush init')

    // //通知回调
    // var notificationListener = result => {
    //   console.log("notificationListener:" + JSON.stringify(result))
    //   alert(JSON.stringify(result))
    // };
    // JPush.addNotificationListener(notificationListener);
    // //本地通知回调
    // var localNotificationListener = result => {
    //   console.log("localNotificationListener:" + JSON.stringify(result))
    // };
    // JPush.addLocalNotificationListener(localNotificationListener);
    // //自定义消息回调
    // var customMessageListener = result => {
    //   console.log("customMessageListener:" + JSON.stringify(result))
    // };
    // JPush.addCustomMessageListener(customMessageListener);
    // //应用内消息回调
    // JPush.pageEnterTo("HomePage") // 进入首页，当页面退出时请调用 JPush.pageLeave('HomePage')
    // var inappMessageListener = result => {
    //   console.log("inappMessageListener:" + JSON.stringify(result))
    //   alert(JSON.stringify(result))
    // };
    // JPush.addInappMessageListener(inappMessageListener);
    // //tag alias事件回调
    // var tagAliasListener = result => {
    //   console.log("tagAliasListener:" + JSON.stringify(result))
    // };
    // JPush.addTagAliasListener(tagAliasListener);
    // //手机号码事件回调
    // var mobileNumberListener = result => {
    //   console.log("mobileNumberListener:" + JSON.stringify(result))
    // };
    // JPush.addMobileNumberListener(mobileNumberListener);

  }

  function loadWXCache() {
    //   var showDayRing = Taro.getStorageSync('showDayRing') || false;
    //   var showNightRing = Taro.getStorageSync('showNightRing') || false;
    //   dispatch(showDay(showDayRing))
    //   dispatch(showNight(showNightRing))
    //   var gps = Taro.getStorageSync('gps')
    //   if (gps) {
    //     global.locationDetail = JSON.parse(gps)
    //   }
    var userData = Taro.getStorageSync('userData')
    if (userData) {
      global.token = JSON.parse(userData).token
      // dispatch(getInfoSuccess(JSON.parse(userData)));
    }



  }

  async function loadRNCache() {
    var userData = await getStorage('userData')
    if (userData) {
      global.token = JSON.parse(userData).token
    }
    // else {
    //   //测试直接登录
    //   global.token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMTE0Nzg0NGE5NDIyODk1MmE5Zjc2OTdjYWJjYmU3Y2UiLCJpc3MiOiJmYXN0Iiwibmlja25hbWUiOiJGYXN0ZXIiLCJ0eXAiOiJCZWFyZXIiLCJzZXNzaW9uX3N0YXRlIjoiZWQxMGY5Yzk1YjcxMjdhZThlZjU5ZDI4MTFlNWI1MWUiLCJleHAiOjE3NDY2NzIyMDYsImlhdCI6MTcxNTEzNjIwNn0.fbVPua1K9eDteWqrDBjaB8l8MrchwCp_JiuwQ222wU0'
    // }
  }

  async function getStorage(key: string) {
    try {
      const res = await Taro.getStorage({ key });
      return res.data;
    } catch {
      return '';
    }
  }

  if (process.env.TARO_ENV == 'rn') {
    return <ActionSheetProvider>

      <Provider store={store}>

        <StatusBar barStyle='light-content' backgroundColor="#000" />
        {children}
      </Provider>

    </ActionSheetProvider>
  }

  return <Provider store={store}>
    {children}
  </Provider>
}

// class App extends Component<PropsWithChildren> {

//   componentDidMount () {}

//   componentDidShow () {}

//   componentDidHide () {}

//   // this.props.children 是将要会渲染的页面
//   render () {
//     return this.props.children
//   }
// }
export default App
