home_page.dart 11.6 KB
import 'dart:async';
import 'dart:convert';

//import 'package:fake_push/fake_push.dart' as fake;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:one_key/models/message.dart';
import 'package:one_key/pages/message/message_page.dart';
import 'package:one_key/pages/my/my_page.dart';
import 'package:one_key/pages/notebook/notebook_page.dart';
import 'package:one_key/provider/message_dialog_model.dart';
import 'package:one_key/provider/message_model.dart';
import 'package:one_key/provider/my_model.dart';
import 'package:one_key/provider/notebook_model.dart';
import 'package:one_key/provider/update_model.dart';
import 'package:one_key/provider/user_model.dart';
import 'package:one_key/res/colors.dart';
import 'package:one_key/utils/log_util.dart';
import 'package:one_key/utils/navigator_util.dart';
import 'package:one_key/utils/utils.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget{

  final int initialIndex;//初始tab

  HomePage({this.initialIndex=1});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage>{

//  信鸽推送
//  fake.Push _push = fake.Push();
//  StreamSubscription<String> _receiveDeviceToken;
//  StreamSubscription<fake.Message> _receiveMessage;
//  StreamSubscription<fake.Message> _receiveNotification;
//  StreamSubscription<String> _launchNotification;
//  StreamSubscription<String> _resumeNotification;

//  极光推送
  final JPush jpush = new JPush();

  List<Widget> pages = List<Widget>();
  int _currIndex = 1;
  Color _activeColor = MyColours.color_2bb5b7;
  Color _defaultColor = MyColours.color_bfbfbf;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.v("home_initState");
    _currIndex=widget.initialIndex;
    pages
      ..add(ChangeNotifierProvider<MessageModel>(
        create: (_)=>MessageModel(),
        child: MessagePage(),
      ))
      ..add(ChangeNotifierProvider<NoteBookModel>(
        create: (_)=>NoteBookModel(),
        child: NoteBookPage(),
      ))
      ..add(ChangeNotifierProvider<MyModel>(
        create: (_)=>MyModel(),
        child: MyPage(),
      ));
    initJPush();
//    initXinge();
    WidgetsBinding.instance.addPostFrameCallback((_){
      if(widget.initialIndex==0)return;
      getUntreatedMessage();
//      UpdateModel updateModel=new UpdateModel();
//      updateModel.checkUpdate(context);
    });
  }


  Future<void> initJPush() async {
    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
            LogUtil.v("flutter onReceiveNotification: $message");
            Map<String,dynamic> messageMap=(json.decode(message["extras"]["cn.jpush.android.EXTRA"]) as Map<String,dynamic>)["extras"];
            Provider.of<MessageDialogModel>(context,listen: false).addMessage(context,Message.fromJson(messageMap));
          }, onOpenNotification: (Map<String, dynamic> message) async {
        LogUtil.v("flutter onOpenNotification: $message");
        NavigatorUtil.goHomePage(context,initialIndex: 0);
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        LogUtil.v("flutter onReceiveMessage: $message");
      }, onReceiveNotificationAuthorization:
          (Map<String, dynamic> message) async {
        LogUtil.v("flutter onReceiveNotificationAuthorization: $message");
      });
    } on PlatformException {}

    jpush.setup(
      appKey: "27ceb79c44af41ad99202f7a", //你自己应用的 AppKey
      channel: "theChannel",
      production: false,
      debug: true,
    );

    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: false));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      LogUtil.v("flutter get registration id : $rid");
      userTokenInit(rid);
    });
    jpush.isNotificationEnabled().then((bool value) {
      if (!value) {
        //没有打开通知
        jpush.openSettingsForNotification();
      }
    });
  }

  //初始化信鸽推送
  void initXinge(){
//    _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: !_isReleaseMode());
//
//    // 第二次打开应用再调用
//    SharedPreferences.getInstance().then((SharedPreferences sharedPref) {
//      if (sharedPref.getBool('firstStart') ?? true) {
//        sharedPref.setBool('firstStart', false);
//      } else {
//        _push.areNotificationsEnabled().then((bool isEnabled) {
//          if (!isEnabled) {
//            showCupertinoDialog(
//              context: context,
//              builder: (BuildContext context) {
//                return CupertinoAlertDialog(
//                  title: const Text('提示'),
//                  content: const Text('开启通知权限可收到更多优质内容'),
//                  actions: <Widget>[
//                    CupertinoDialogAction(
//                      child: const Text('取消'),
//                      onPressed: () {
//                        Navigator.of(context).pop();
//                      },
//                    ),
//                    CupertinoDialogAction(
//                      child: const Text('设置'),
//                      onPressed: () {
//                        _push.openNotificationsSettings();
//                        Navigator.of(context).pop();
//                      },
//                    ),
//                  ],
//                );
//              },
//            );
//          }
//        });
//      }
//    });
  }

  bool _isReleaseMode() {
    return const bool.fromEnvironment('dart.vm.product');
  }

  void _handleReceiveDeviceToken(String deviceToken) async {
//    String token=await _push.getDeviceToken();
//    print('receiveDeviceToken: $deviceToken - $token');
//    userTokenInit2(token);
  }

//  void _handleReceiveMessage(fake.Message message) {
//    print(
//        'receiveMessage: ${message.title} - ${message.content} - ${message.customContent}');
//  }
//
//  void _handleReceiveNotification(fake.Message notification) {
//    print(
//        'receiveNotification: ${notification.title} - ${notification.content} - ${notification.customContent}');
//
//  }
//
//  void _handleLaunchNotification(String customContent) {
//    print('launchNotification: $customContent');
//
//  }
//
//  void _handleResumeNotification(String customContent) {
//    print('resumeNotification: $customContent');
//
//  }

  //初始化推送token
  userTokenInit(String registrationId){
    UserModel userModel=Provider.of<UserModel>(context,listen: false);
    userModel.registrationId=registrationId;
    Map<String,String> params={
      "sid":userModel.user.sellerid,
      "account":userModel.user.account,
      "registrationId":registrationId
    };
    userModel.userTokenInit(context, params);
  }

  //初始化推送token
  userTokenInit2(String token){
    UserModel userModel=Provider.of<UserModel>(context,listen: false);
    userModel.token=token;
    Map<String,String> params={
      "sid":userModel.user.sellerid,
      "account":userModel.user.account,
      "user_token":token
    };
    userModel.userTokenInit(context, params);
  }

  //获取未处理在线预订消息
  getUntreatedMessage(){
    UserModel userModel=Provider.of<UserModel>(context,listen: false);
    Map<String,String> params={
      "sid":userModel.user.sellerid,
      "type_id":"10",
      "status":"0",
      "offset":"0",
      "limit":"100",
    };
    MessageDialogModel messageModel=Provider.of<MessageDialogModel>(context,listen: false);
    messageModel.getUntreatedMsg(context, params);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        iconSize: ScreenUtil().setWidth(70),
        unselectedFontSize: ScreenUtil().setSp(22),
        selectedFontSize: ScreenUtil().setSp(22),
        backgroundColor: MyColours.color_ffffff,
        items: [
          BottomNavigationBarItem(
            icon: Image(
              image: AssetImage("assets/message_default.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            activeIcon: Image(
              image: AssetImage("assets/message_selected.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            title: Text(
              "消息中心",
              style: TextStyle(
                  color: _currIndex == 0 ? _activeColor : _defaultColor,fontSize: ScreenUtil().setSp(22)),
            ),
          ),
          BottomNavigationBarItem(
            icon: Image(
              image: AssetImage("assets/notebook_default.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            activeIcon: Image(
              image: AssetImage("assets/notebook_selected.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            title: Text(
              "预定本",
              style: TextStyle(
                  color: _currIndex == 1 ? _activeColor : _defaultColor,fontSize: ScreenUtil().setSp(22)),
            ),
          ),
          BottomNavigationBarItem(
            icon: Image(
              image: AssetImage("assets/my_default.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            activeIcon: Image(
              image: AssetImage("assets/my_selected.png"),
              width: ScreenUtil().setWidth(70),
              height: ScreenUtil().setWidth(70),
            ),
            title: Text(
              "我的",
              style: TextStyle(
                  color: _currIndex == 2 ? _activeColor : _defaultColor,fontSize: ScreenUtil().setSp(22)),
            ),
          ),
        ],
        type: BottomNavigationBarType.fixed,
        currentIndex: _currIndex,
        onTap: (int index) {
          if (_currIndex != index) {
            setState(() {
              _currIndex = index;
            });
            if(_currIndex==2){
              Utils.changeStatusColor(color: MyColours.color_2bb5b7);
            }else{
              Utils.changeStatusColor(color: MyColours.color_ffffff);
            }
          }
        },
      ),
      body: SafeArea(child: pages[_currIndex]),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
//    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();
    LogUtil.v("home_dispose");
  }
}