
import 'dart:async';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/account/model/user_entity.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/provider/theme_provider.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/routers/routers.dart';
import 'package:liftmanager/utils/image_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:provider/provider.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {

//  Push _push = Push();
//  StreamSubscription<String> _receiveDeviceToken;
//  StreamSubscription<Message> _receiveMessage;
//  StreamSubscription<Message> _receiveNotification;
//  StreamSubscription<String> _launchNotification;
//  StreamSubscription<String> _resumeNotification;

  int _status = 0;
  List<String> _guideList = ["app_start_1", "app_start_2", "app_start_3","app_start_4"];
  Timer _subscription;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await SpUtil.getInstance();
      // 由于SpUtil未初始化，所以MaterialApp获取的为默认主题配置，这里同步一下。
      Provider.of<ThemeProvider>(context,listen: false).syncTheme();
      if (SpUtil.getBool(Constant.keyGuide, defValue: true)){
        /// 预先缓存图片，避免直接使用时因为首次加载造成闪动
        _guideList.forEach((image){
          precacheImage(ImageUtils.getAssetImage(image), context);
        });
      }
      _initSplash();
    });

//    _receiveDeviceToken =
//        _push.receiveDeviceToken().listen(_handleReceiveDeviceToken);
//    _receiveMessage = _push.receiveMessage().listen(_handleReceiveMessage);
//    _receiveNotification =
//        _push.receiveNotification().listen(_handleReceiveNotification);
//    _launchNotification =
//        _push.launchNotification().listen(_handleLaunchNotification);
//    _resumeNotification =
//        _push.resumeNotification().listen(_handleResumeNotification);
//
//    _push.startWork(enableDebug: false);
  }

//  void _handleReceiveDeviceToken(String deviceToken) async {
//    print('receiveDeviceToken: $deviceToken - ${await _push.getDeviceToken()}');
//    _showTips('receiveDeviceToken', deviceToken);
//  }
//
//  void _handleReceiveMessage(Message message) {
//    print(
//        'receiveMessage: ${message.title} - ${message.content} - ${message.customContent}');
//    _showTips('receiveMessage',
//        '${message.title} - ${message.content} - ${message.customContent}');
//  }
//
//  void _handleReceiveNotification(Message notification) {
//    print(
//        'receiveNotification: ${notification.title} - ${notification.content} - ${notification.customContent}');
//    _showTips('receiveNotification',
//        '${notification.title} - ${notification.content} - ${notification.customContent}');
//  }
//
//  void _handleLaunchNotification(String customContent) {
//    print('launchNotification: $customContent');
//    _showTips('launchNotification', customContent);
//  }
//
//  void _handleResumeNotification(String customContent) {
//    print('resumeNotification: $customContent');
//    _showTips('resumeNotification', customContent);
//  }

  void _showTips(String title, String content) {
//    showCupertinoDialog(
//      context: context,
//      builder: (BuildContext context) {
//        return CupertinoAlertDialog(
//          title: Text(title),
//          content: Text(content),
//          actions: <Widget>[
//            CupertinoDialogAction(
//              child: const Text('朕知道了～'),
//              onPressed: () {
//                Navigator.of(context).pop();
//              },
//            ),
//          ],
//        );
//      },
//    );
  }

  @override
  void dispose() {
    _subscription?.cancel();

//    if (_receiveDeviceToken != null) {
//      _receiveDeviceToken.cancel();
//    }
//    if (_receiveMessage != null) {
//      _receiveMessage.cancel();
//    }
//    if (_receiveNotification != null) {
//      _receiveNotification.cancel();
//    }
//    if (_launchNotification != null) {
//      _launchNotification.cancel();
//    }
//    if (_resumeNotification != null) {
//      _resumeNotification.cancel();
//    }
    super.dispose();
  }


  void _initGuide() {
    setState(() {
      _status = 1;
    });
  }

  void _initSplash(){
    _subscription = Timer(Duration(milliseconds: 1500),()=>Stream.value(2).listen((_){
      if (SpUtil.getBool(Constant.keyGuide, defValue: true)) {
        SpUtil.putBool(Constant.keyGuide, false);
        _initGuide();
      } else {
        if(SpUtil.getString(Constant.accessToken).length >0){
          _goMain();
        }else{
          // _goLogin();
          custom_login();
        }
      }
    }));
  }

  _goLogin(){
    NavigatorUtils.push(context, AccountRouter.loginPage, replace: true);
  }

  _goMain(){
    NavigatorUtils.push(context, Routers.home, clearStack: true);
  }


  // ignore: non_constant_identifier_names
  void custom_login(){
    showLoading(context, "游客登录中...");
    ApiService(context: context).login("12345678910", Utils.generateMd5("123456789"),
        onSuccess: (UserEntity res) {
//          FlutterStars.SpUtil.putObject(Constant.user, res);
      dismissLoading(context);
      User().setCurrentUser(res);
      print("==============");
      NavigatorUtils.push(context, Routers.home, clearStack: true);
    }, onError: (code, errMsg) {
      toasts(errMsg);
      _goLogin();
      dismissLoading(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        child: _status == 0 ? Image.asset(
          ImageUtils.getImgPath("start_page", format: "png"),
          width: double.infinity,
          fit: BoxFit.fill,
          height: double.infinity,
        ) : Swiper(
          key: const Key('swiper'),
          itemCount: _guideList.length,
          loop: false,
          itemBuilder: (_, index){
            return LoadAssetImage(
              _guideList[index],
              key: Key(_guideList[index]),
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            );
          },
          onTap: (index){
            if (index == _guideList.length - 1){
              // _goLogin();
              custom_login();
            }
          },
        )
    );
  }
}
