home_page.dart 36 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:one_key/models/new_unmessage_model.dart';
import 'package:one_key/models/pull_marketing_by_uid_model.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/pages/table/table_manager_page.dart';
import 'package:one_key/provider/contact_model.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/table_manager_model.dart';
import 'package:one_key/provider/tools.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/dialog_util.dart';

import 'package:one_key/route/navigator_util.dart';
import 'package:one_key/utils/utils.dart';
import 'package:provider/provider.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:one_key/models/message.dart';

class HomePage extends StatefulWidget {
  final int initialIndex; //初始tab

  final bool needReresh;

  final bool mine;
  final DateTime date;
  final String solt;

  HomePage(
      {this.initialIndex = 1,
      this.needReresh = true,
      this.mine = false,
      this.date,
      this.solt});

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

class HomePageState extends State<HomePage> with WidgetsBindingObserver {
  List<Widget> pages = List<Widget>();
  int _currIndex = 1;
  Color _activeColor = MyColours.color_199095;
  Color _defaultColor = MyColours.color_999999;
  int numPush = 0; //推送消息个数

  Timer timer;
  Timer timerSeller;

  int xgCount = 1; //注册信鸽次数,最多5次

  DateTime lastBack;
  PageController _pageController;
  bool needUpdate = true;
  bool needRefreshTemp = true;
  static const MethodChannel _channel = MethodChannel("com.naji/book");

//实现监听
  Future<dynamic> platformCallHandler(MethodCall call) async {
    switch (call.method) {
      case "getIntent":
        //      dynamic result = await _channel.invokeMethod("getIntent");
        // return result;
        dynamic result = call.arguments;
        print(result);
        _getIntent(result);

        break;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.v("home_initState");
    needRefreshTemp = widget.needReresh;
    _channel.setMethodCallHandler(platformCallHandler); //设置监听

    AzhonAppUpdate.listener(
        //   () {
        //   needUpdate = false;
        //   // print(map['type']);
        // }
        );
    WidgetsBinding.instance.addObserver(this);

    _currIndex = widget.initialIndex;
    _pageController = PageController(initialPage: _currIndex);
    pages
      // ..add(ChangeNotifierProvider<HomeEnterModel>(
      //     create: (_) => HomeEnterModel(),
      //     child: ChangeNotifierProvider<RemarkManagerModel>(
      //       create: (_) => RemarkManagerModel(),
      //       child: SafeArea(child: HomeEnterPage()),
      //     )))
      ..add(SafeArea(
        child: MessagePage(),
      ))
//      ..add(ChangeNotifierProvider<EnterModel>(
//        create: (_) => EnterModel(),
//        child: SafeArea(child: EnterPage(detailEntity:NotebookDetail.def(context),rid: "-1",)),
//      ))
      ..add(ChangeNotifierProvider<NoteBookModel>(
        create: (_) => NoteBookModel(),
        child: SafeArea(
            child: NoteBookPage(
          tabIndex: widget.mine ? 1 : 0,
          date: widget.date,
          solt: widget.solt,
        )),
      ))
      ..add(ChangeNotifierProvider<TableManagerModel>(
        create: (_) => TableManagerModel(),
        child: TableManagerPage(),
      ))
      ..add(ChangeNotifierProvider<MyModel>(
        create: (_) => MyModel(),
        child: MyPage(),
      ));
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initPlatformState();

      List<PullMarketingByUidSunModel> data =
          Provider.of<UserModel>(context, listen: false)
              .pullMarketingByUidSunModel;
      if (data != null) {
        if (data.length > 0) {
          Future.delayed(Duration(milliseconds: 300), () {
            DialogUtil.cupertinoAlertDialog(context,
                title: "全店任务",
                content: "管理员发布了新的任务,请立即查看并完成任务",
                lTitle: "稍后提醒",
                rTitle: "立即查看", lCallback: () {
              print("稍后提醒");
              // 30分钟后重新弹窗
              _startTimerSeller();
            }, rCallback: () {
              _endTimerSeller();
              if (data.length == 1) {
                //进入营销详情
                NavigatorUtil.goSellerMyMarketingRecordsDetailPage(
                    context, data[0].mid,
                    fromNotify: true);
              } else {
                //进入我的客情首页
                NavigatorUtil.goMyCustomerPage(context);
              }
            });
          });
        }
      }
      if (widget.initialIndex == 0 ||
          widget.initialIndex == 1 && needRefreshTemp == false) return;
      _initNotification();
      Future.delayed(Duration(milliseconds: 30000), () {
        ContactModel.getInstance().uploadLocalContact(context);
        if (needUpdate) {
          UpdateModelMy updateModel = new UpdateModelMy();
          updateModel.checkUpdate(context, (version) {
            updateModel.showUpdateDialog(context, version);
          }, showToast: false);
        }
      });

      timer = Timer.periodic(Duration(minutes: 3), (_) {
        _getAllUnMessages();
      });
      _getUnMsgNum();
    });
  }

  _initNotification() async {
    Map param = await Tools().getIntent();
    _getIntent(param);
  }

  _endTimerSeller() {
    if (timerSeller != null) {
      timerSeller.cancel();
    }
  }

  _startTimerSeller() {
    _endTimerSeller();
    timerSeller = Timer.periodic(Duration(minutes: 30), (_) {
      _endTimerSeller();
      List<PullMarketingByUidSunModel> data =
          Provider.of<UserModel>(context, listen: false)
              .pullMarketingByUidSunModel;
      DialogUtil.cupertinoAlertDialog(context,
          title: "全店任务",
          content: "管理员发布了新的任务,请立即查看并完成任务",
          lTitle: "稍后提醒",
          rTitle: "立即查看", lCallback: () {
        print("稍后提醒");
        // 30分钟后重新弹窗
        _startTimerSeller();
      }, rCallback: () {
        _endTimerSeller();
        if (data.length == 1) {
          //进入营销详情
          NavigatorUtil.goSellerMyMarketingRecordsDetailPage(
              context, data[0].mid,
              fromNotify: true);
        } else {
          //进入我的客情首页
          NavigatorUtil.goMyCustomerPage(context);
        }
      });
    });
  }

  //获取点击通知栏的自定义参数
  _getIntent(Map param) async {
    _clearBadge(() {});

    Map notifyParam = param;
    if (Platform.isIOS && param != null) {
      notifyParam = json.decode(param['custom'].toString());
    }
    LogUtil.v(param.toString());
    if (notifyParam != null && notifyParam.isNotEmpty) {
      switch (notifyParam["messageType"]) {
        case "Marketing":
          NavigatorUtil.goSellerMyMarketingRecordsDetailPage(
              context, notifyParam['mid'],
              fromNotify: true);
          break;
        case "10":
          NavigatorUtil.goHandleOnlinePage(
              context, notifyParam["rid"], notifyParam['mid'],
              fromNotify: true);
          break;
        case "11":
          NavigatorUtil.goNotebookDetailPage(
              context, notifyParam['rid'], notifyParam["uid"],
              mid: notifyParam['mid'], fromNotify: true);
          break;
        case "12":
          //在线买单消息 去处理 跳转在线买单处理页面
          NavigatorUtil.goOnlineCheckEditPage(context,
              rid: notifyParam["rid"], fromNotify: true);
          break;
        case "13":
          //在线买单消息 去查看 跳转在线买单详情页面
          NavigatorUtil.goOnlineCheckDetailPage(context,
              rid: notifyParam["rid"], fromNotify: true);
          Map<String, String> params = {
            "sid": Provider.of<UserModel>(context, listen: false).user.sellerid,
            "id": notifyParam['mid'],
            "status": "is_read"
          };
          MessageDialogModel messageDialogModel =
              Provider.of<MessageDialogModel>(context, listen: false);
          await messageDialogModel.setMessageStatus(context, params);
          break;
        case "14":
          //发票详情页面跳转
          NavigatorUtil.goInvoiceDetailPage(context,
              rid: '${notifyParam["rid"]}', fromNotify: true);
          Map<String, String> params = {
            "sid": Provider.of<UserModel>(context, listen: false).user.sellerid,
            "id": notifyParam['mid'],
            "status": "is_read"
          };
          MessageDialogModel messageDialogModel =
              Provider.of<MessageDialogModel>(context, listen: false);
          await messageDialogModel.setMessageStatus(context, params);
          break;
        case "15":
          //店内消息
          NavigatorUtil.goHomePage(context,
              initialIndex: 1,
              needRefresh: false,
              mine: true,
              dateTime:
                  DateTime.parse(notifyParam['ddate'].replaceAll('/', '-'))
                      .millisecondsSinceEpoch,
              solt: notifyParam['ddate_solt']);
          Map<String, String> params = {
            "sid": Provider.of<UserModel>(context, listen: false).user.sellerid,
            "id": notifyParam['mid'],
            "status": "is_read"
          };
          MessageDialogModel messageDialogModel =
              Provider.of<MessageDialogModel>(context, listen: false);
          await messageDialogModel.setMessageStatus(context, params);
          break;
        case "16":
          //经理取消预订
          NavigatorUtil.goNotebookDetailPage(
              context, notifyParam['rid'], notifyParam["uid"],
              mid: notifyParam['mid'], fromNotify: true);
          break;
        case "1":
          NavigatorUtil.goHasOrderFoodPage(context,
              rid: notifyParam["rid"], fromNotify: true);
          // bus.emit("remove_untreated_message_order", notifyParam["rid"]);

          Map<String, String> params = {
            "sid": Provider.of<UserModel>(context, listen: false).user.sellerid,
            "id": notifyParam['mid'],
            "status": "is_read"
          };
          MessageDialogModel messageDialogModel =
              Provider.of<MessageDialogModel>(context, listen: false);
          await messageDialogModel.setMessageStatus(context, params);
          // bus.emit("refresh_untreated_num"); //刷新未读消息数目

          break;
      }
    } else {
      _getAllUnMessages();
    }
  }

  //初始化信鸽推送
  initPlatformState() {
    /// 开启DEBUG
    XgFlutterPlugin().setEnableDebug(false);

    /// 添加回调事件
    XgFlutterPlugin().addEventHandler(
      onRegisteredDeviceToken: (String msg) async {
        print("flutter onRegisteredDeviceToken: $msg");
      },
      onRegisteredDone: (String msg) async {
        String token = "";
        try {
          token = await XgFlutterPlugin.xgToken;
        } catch (e) {
          LogUtil.v("注册失败:${e.toString()}");
//          Utils.showToast("注册失败:${e.toString()}");
        }
        if (token == null || token.isEmpty) {
          LogUtil.v("注册失败:${xgCount.toString()}");
//          Utils.showToast("注册失败:${xgCount.toString()}");
          registerPush();
        } else {
          LogUtil.v("注册成功:$token");
//          Utils.showToast("注册成功:$token");
          userTokenInit(token);
          // XgFlutterPlugin().setAppBadge(0);
        }
      },
      unRegistered: (String msg) async {
        print("flutter unRegistered: $msg");
      },
      onReceiveNotificationResponse: (Map<String, dynamic> msg) async {
        print("flutter onReceiveNotificationResponse $msg");
        numPush++;
        _addBadge();
        Uri u = Uri.parse(msg['activity']);
        String messageType = u.queryParameters['messageType'];
        if (messageType == "Marketing") {
          String mid = u.queryParameters['mid'];
          DialogUtil.cupertinoAlertDialog(context,
              title: "全店任务",
              content: "管理员发布了新的任务,请立即查看并完成任务",
              lTitle: "稍后提醒",
              rTitle: "立即查看", lCallback: () {
            print("稍后提醒");
            // 30分钟后重新弹窗
            _startTimerSeller();
          }, rCallback: () {
            _endTimerSeller();
            //进入营销详情
            NavigatorUtil.goSellerMyMarketingRecordsDetailPage(context, mid,
                fromNotify: true);
          });
        }
      },
      onReceiveMessage: (Map<String, dynamic> msg) async {
        print("flutter onReceiveMessage $msg");
      },
      xgPushDidSetBadge: (String msg) async {
        print("flutter xgPushDidSetBadge: $msg");

        // /// 在此可设置应用角标
        // XgFlutterPlugin().setAppBadge(0);
      },
      xgPushDidBindWithIdentifier: (String msg) async {
        print("flutter xgPushDidBindWithIdentifier: $msg");
      },
      xgPushDidUnbindWithIdentifier: (String msg) async {
        print("flutter xgPushDidUnbindWithIdentifier: $msg");
      },
      xgPushDidUpdatedBindedIdentifier: (String msg) async {
        print("flutter xgPushDidUpdatedBindedIdentifier: $msg");
      },
      xgPushDidClearAllIdentifiers: (String msg) async {
        print("flutter xgPushDidClearAllIdentifiers: $msg");
      },
      xgPushClickAction: (Map<String, dynamic> msg) async {
        print(msg);

        _clearBadge(() {});
        if (Platform.isIOS && msg != null && msg['custom'] != null) {
          Map custom = json.decode(msg['custom'].toString());
          switch (custom["messageType"].toString()) {
            case "Marketing":
              NavigatorUtil.goSellerMyMarketingRecordsDetailPage(
                  context, custom['mid'],
                  fromNotify: true);
              break;
            case "10":
              NavigatorUtil.goHandleOnlinePage(
                  context, custom["rid"].toString(), custom['mid'].toString(),
                  fromNotify: true);
              break;
            case "11":
              NavigatorUtil.goNotebookDetailPage(
                  context, custom['rid'].toString(), custom["uid"].toString(),
                  mid: custom['mid'].toString(), fromNotify: true);
              break;
            case "12":
              //在线买单消息 去处理 跳转在线买单处理页面
              NavigatorUtil.goOnlineCheckEditPage(context,
                  rid: custom["rid"], fromNotify: true);
              break;
            case "13":
              //在线买单消息 去查看 跳转在线买单详情页面
              NavigatorUtil.goOnlineCheckDetailPage(context,
                  rid: custom["rid"], fromNotify: true);
              Map<String, String> params = {
                "sid": Provider.of<UserModel>(context, listen: false)
                    .user
                    .sellerid,
                "id": custom['mid'],
                "status": "is_read"
              };
              MessageDialogModel messageDialogModel =
                  Provider.of<MessageDialogModel>(context, listen: false);
              await messageDialogModel.setMessageStatus(context, params);
              break;
            case "14":
              //发票详情页面跳转
              NavigatorUtil.goInvoiceDetailPage(context,
                  rid: '${custom["rid"]}', fromNotify: true);
              Map<String, String> params = {
                "sid": Provider.of<UserModel>(context, listen: false)
                    .user
                    .sellerid,
                "id": custom['mid'],
                "status": "is_read"
              };
              MessageDialogModel messageDialogModel =
                  Provider.of<MessageDialogModel>(context, listen: false);
              await messageDialogModel.setMessageStatus(context, params);
              break;
            case "15":

              //店内消息
              NavigatorUtil.goHomePage(context,
                  initialIndex: 1,
                  needRefresh: false,
                  mine: true,
                  dateTime: DateTime.parse(custom['ddate'].replaceAll('/', '-'))
                      .millisecondsSinceEpoch,
                  solt: custom['ddate_solt']);

              Map<String, String> params = {
                "sid": Provider.of<UserModel>(context, listen: false)
                    .user
                    .sellerid,
                "id": custom['mid'],
                "status": "is_read"
              };
              MessageDialogModel messageDialogModel =
                  Provider.of<MessageDialogModel>(context, listen: false);
              await messageDialogModel.setMessageStatus(context, params);
              break;
            case "16":
              //经理取消预订
              NavigatorUtil.goNotebookDetailPage(
                  context, custom['rid'].toString(), custom["uid"].toString(),
                  mid: custom['mid'].toString(), fromNotify: true);
              break;
            case "1":
              NavigatorUtil.goHasOrderFoodPage(context,
                  rid: custom["rid"], fromNotify: true);
              // bus.emit("remove_untreated_message_order", notifyParam["rid"]);

              Map<String, String> params = {
                "sid": Provider.of<UserModel>(context, listen: false)
                    .user
                    .sellerid,
                "id": custom['mid'],
                "status": "is_read"
              };
              MessageDialogModel messageDialogModel =
                  Provider.of<MessageDialogModel>(context, listen: false);
              await messageDialogModel.setMessageStatus(context, params);
              // bus.emit("refresh_untreated_num"); //刷新未读消息数目

              break;
          }
        }
      },
    );

    registerPush();
  }

  //注册信鸽
  registerPush() async {
    if (xgCount > 5) return;
    if (Platform.isAndroid) {
      /// 设置OPPO AppKey 和 AppSecret
      if (await XgFlutterPlugin().getXgAndroidApi().isOppoRom()) {
        XgFlutterPlugin().getXgAndroidApi().enableOppoNotification();
        XgFlutterPlugin().getXgAndroidApi().setOppoPushAppId(appId: "30260281");
        XgFlutterPlugin()
            .getXgAndroidApi()
            .setOppoPushAppKey(appKey: "94d77d10e7bb4c60bcf18a84c8ca8bdd");
      }
      // 设置小米 AppID 和 AppKey。
      if (await XgFlutterPlugin().getXgAndroidApi().isMiuiRom()) {
        XgFlutterPlugin()
            .getXgAndroidApi()
            .setMiPushAppId(appId: "2882303761518639456");
        XgFlutterPlugin()
            .getXgAndroidApi()
            .setMiPushAppKey(appKey: "5231863961456");
      } else {
        if (!await XgFlutterPlugin().getXgAndroidApi().isVivoRom()) {
          XgFlutterPlugin()
              .getXgAndroidApi()
              .createNotificationChannelWithSound(
                  channelId: 'high_custom_8',
                  channelName: '新消息通知',
                  enableLights: true,
                  enableSound: true,
                  enableVibration: true,
                  soundFileName: 'tts_voice');
        }
      }
      XgFlutterPlugin().getXgAndroidApi().enableOtherPush();
    }

    /// 启动TPNS服务
    LogUtil.v("register:${xgCount.toString()}");
    XgFlutterPlugin().startXg("1600012876", "INUIMFK21WGH");
    xgCount++;
  }

  void _addBadge() {
    XgFlutterPlugin().setBadge(numPush);
    XgFlutterPlugin().setAppBadge(numPush);
    FlutterAppBadger.updateBadgeCount(numPush);
  }

  void _clearBadge(VoidCallback callback) async {
    numPush = 0;
    XgFlutterPlugin().setBadge(0);
    XgFlutterPlugin().setAppBadge(0);
    FlutterAppBadger.removeBadge();
    callback();
  }

  //初始化推送token
  userTokenInit(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": Platform.isAndroid ? "Android_$token" : "Ios_$token"
    };
    userModel.userTokenInit(context, params);
  }

  // 消息类型ID 1/2/10 提前点餐/新订单(预定)消息/在线预订
  //获取未处理在线预订消息
  getUntreatedMessage(VoidCallback callback) async {
    UserModel userModel = Provider.of<UserModel>(context, listen: false);
    Map<String, String> params = {
      "sid": userModel.user.sellerid,
      // "type_id": "10", //1提前点餐2内部预订10在线预订
      // "status": '0',

      "offset": "0",
      "limit": "100",
    };

    MessageDialogModel messageModel =
        Provider.of<MessageDialogModel>(context, listen: false);
    await messageModel.getUntreatedMsg(context, params, callback);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed: //应用前台可见
        if (widget.initialIndex == 1 && needRefreshTemp == false) {
        } else {
          _clearBadge(() {
            _getAllUnMessages();
          });
        }

        break;
      case AppLifecycleState.inactive:
        print('inactive');
        break;
      case AppLifecycleState.paused:
        print('paused');
        needRefreshTemp = true;
        break;
      case AppLifecycleState.detached:
        print('detached');
        break;

      default:
        break;
    }
  }

  ///获取全部未读消息
  ///

  _getAllUnMessages() {
    MessageDialogModel messageModel =
        Provider.of<MessageDialogModel>(context, listen: false);
    messageModel.messages = [];

    getUntreatedMessage(() {
      if (messageModel.messages.isNotEmpty) {
        //底部弹出布局
        if (!messageModel.showMessageDialog) {
          messageModel.messages.removeWhere((message) {
            if (messageModel.messagesCancelOnlyOneShow.contains(message.id)) {
              return true;
            }
            return false;
          });

          DialogUtil.showMessageDialog(context);
          for (NewUnmessage item in messageModel.messages) {
            if (item.message_type == '11') {
              messageModel.messagesCancelOnlyOneShow.add(item.id);
            }
          }
        } else {
          messageModel.notifyListeners();
        }
        //播放声音
        if (messageModel.messages.length > 1) {
          messageModel.play("-1");
        } else {
          for (NewUnmessage message in messageModel.messages) {
            messageModel.play(message.message_type);
          }
        }
      }
    });
  }

//获取未处理消息数目
  bool _getUnMsgNumUI() {
    MessageModel messageModel =
        Provider.of<MessageModel>(context, listen: true);
    if (messageModel.allUnNum > 0) {
      return true;
    }
    return false;
  }

  //三种分类各自的未读消息数目
  _getUnMsgNum() async {
    UserModel userModel = Provider.of<UserModel>(context, listen: false);
    MessageModel messageModel =
        Provider.of<MessageModel>(context, listen: false);
    Map<String, String> params = {
      "sid": userModel.user.sellerid,
      // "type_id": "10", //1提前点餐2内部预订10在线预订
      // "status": '0',
      "offset": '0',
      "limit": "1000",
    };
    await messageModel.getNewGetUntreatedMsgNum(context, params,
        showLoading: false);
    setState(() {});
  }

  // 系统窗口相关改变回调
  void didChangeMetrics() {
    super.didChangeMetrics();
    print('fffff');
  }

// // 系统亮度改变回调
//   void didChangePlatformBrightness() {
//     super.didChangePlatformBrightness();
//     print('fdddddd');
//   }

// // 文本缩放系数改变回调
//   void didChangeTextScaleFactor() {}

// // 内存不足警告回调
//   void didHaveMemoryPressure() {}

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.init(context, width: 750, height: 1334);
    return new WillPopScope(
      child: Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            iconSize: ScreenUtil().setWidth(48),
            unselectedFontSize: ScreenUtil().setSp(22),
            selectedFontSize: ScreenUtil().setSp(22),
            backgroundColor: MyColours.color_ffffff,
            items: [
              // BottomNavigationBarItem(
              //   icon: Image(
              //     image: AssetImage("assets/enter_order_n.png"),
              //     width: ScreenUtil().setWidth(48),
              //     height: ScreenUtil().setWidth(48),
              //   ),
              //   activeIcon: Image(
              //     image: AssetImage("assets/enter_order_s.png"),
              //     width: ScreenUtil().setWidth(48),
              //     height: ScreenUtil().setWidth(48),
              //   ),
              //   title: Text(
              //     "录入预订",
              //     style: TextStyle(
              //         color: _currIndex == 0 ? _activeColor : _defaultColor,
              //         fontSize: ScreenUtil().setSp(22)),
              //   ),
              // ),
              BottomNavigationBarItem(
                icon: Stack(
                  children: [
                    Image(
                      image: AssetImage("assets/message_default.png"),
                      width: ScreenUtil().setWidth(48),
                      height: ScreenUtil().setWidth(48),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Container(
                        width: ScreenUtil().setWidth(16),
                        height: ScreenUtil().setWidth(16),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(
                                ScreenUtil().setWidth(16)),
                            color: _getUnMsgNumUI()
                                ? MyColours.color_fa5151
                                : Colors.transparent),
                      ),
                    )
                  ],
                ),
                activeIcon: Stack(
                  children: [
                    Image(
                      image: AssetImage("assets/message_selected.png"),
                      width: ScreenUtil().setWidth(48),
                      height: ScreenUtil().setWidth(48),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Container(
                        width: ScreenUtil().setWidth(16),
                        height: ScreenUtil().setWidth(16),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(
                                ScreenUtil().setWidth(16)),
                            color: _getUnMsgNumUI()
                                ? MyColours.color_fa5151
                                : Colors.transparent),
                      ),
                    )
                  ],
                ),
                title: Text(
                  "消息中心",
                  style: TextStyle(
                      color: _currIndex == 0 ? _activeColor : _defaultColor,
                      fontSize: ScreenUtil().setSp(22)),
                ),
              ),
//          BottomNavigationBarItem(
//            icon: Image(
//              image: AssetImage("assets/message_default.png"),
//              width: ScreenUtil().setWidth(48),
//              height: ScreenUtil().setWidth(48),
//            ),
//            activeIcon: Image(
//              image: AssetImage("assets/message_selected.png"),
//              width: ScreenUtil().setWidth(48),
//              height: ScreenUtil().setWidth(48),
//            ),
//            title: Text(
//              "订座",
//              style: TextStyle(
//                  color: _currIndex == 1 ? _activeColor : _defaultColor,
//                  fontSize: ScreenUtil().setSp(22)),
//            ),
//          ),
              BottomNavigationBarItem(
                icon: Image(
                  image: AssetImage("assets/notebook_default.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                activeIcon: Image(
                  image: AssetImage("assets/notebook_selected.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                title: Text(
                  "已预订",
                  style: TextStyle(
                      color: _currIndex == 1 ? _activeColor : _defaultColor,
                      fontSize: ScreenUtil().setSp(22)),
                ),
              ),
              BottomNavigationBarItem(
                icon: Image(
                  image: AssetImage("assets/tablemanage_default.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                activeIcon: Image(
                  image: AssetImage("assets/tablemanage_selected.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                title: Text(
                  "桌位",
                  style: TextStyle(
                      color: _currIndex == 2 ? _activeColor : _defaultColor,
                      fontSize: ScreenUtil().setSp(22)),
                ),
              ),
              BottomNavigationBarItem(
                icon: Image(
                  image: AssetImage("assets/my_default.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                activeIcon: Image(
                  image: AssetImage("assets/my_selected.png"),
                  width: ScreenUtil().setWidth(48),
                  height: ScreenUtil().setWidth(48),
                ),
                title: Text(
                  "我的",
                  style: TextStyle(
                      color: _currIndex == 3 ? _activeColor : _defaultColor,
                      fontSize: ScreenUtil().setSp(22)),
                ),
              ),
            ],
            type: BottomNavigationBarType.fixed,
            currentIndex: _currIndex,
            onTap: (int index) {
              if (_currIndex != index) {
                setState(() {
                  _currIndex = index;
                  _pageController.jumpToPage(index);
                });
                if (_currIndex == 3) {
                  Utils.changeStatusColor(color: MyColours.color_199095);
                } else {
                  Utils.changeStatusColor(color: Colors.white);
                }
              }
            },
          ),
          // bottomNavigationBar: BottomAppBar(
          //   shape: CircularNotchedRectangle(),
          //   child: Container(
          //     height: ScreenUtil().setWidth(98),
          //       // padding: EdgeInsets.fromLTRB(0, 12, 0, 8),
          //       child: Row(
          //           mainAxisSize: MainAxisSize.max,
          //           mainAxisAlignment: MainAxisAlignment.spaceAround,
          //           crossAxisAlignment: CrossAxisAlignment.center,
          //           children: <Widget>[
          //             GestureDetector(
          //                 onTap: () {
          //                   // onTap(0);
          //                 },
          //                 child: Column(
          //                   mainAxisSize: MainAxisSize.min,
          //                   children: <Widget>[
          //                     Image(
          //                       image: AssetImage("assets/my_selected.png"),
          //                       width: ScreenUtil().setWidth(44),
          //                       height: ScreenUtil().setWidth(44),
          //                     ),
          //                     Text(
          //                       "我的",
          //                       style: TextStyle(
          //                           color: _currIndex == 2
          //                               ? _activeColor
          //                               : _defaultColor,
          //                           fontSize: ScreenUtil().setSp(22)),
          //                     )
          //                   ],
          //                 )),
          //             GestureDetector(
          //                 onTap: () {
          //                   // onTap(1);
          //                 },
          //                 child: Column(
          //                   mainAxisSize: MainAxisSize.min,
          //                   children: <Widget>[
          //                     Image(
          //                       image: AssetImage("assets/my_selected.png"),
          //                       width: ScreenUtil().setWidth(44),
          //                       height: ScreenUtil().setWidth(44),
          //                     ),
          //                     Text(
          //                       "我的",
          //                       style: TextStyle(
          //                           color: _currIndex == 2
          //                               ? _activeColor
          //                               : _defaultColor,
          //                           fontSize: ScreenUtil().setSp(22)),
          //                     )
          //                   ],
          //                 )),
          //             Column(
          //               mainAxisSize: MainAxisSize.min,
          //               children: <Widget>[
          //                 Image(
          //                   image: AssetImage("assets/my_selected.png"),
          //                   width: ScreenUtil().setWidth(44),
          //                   height: ScreenUtil().setWidth(44),
          //                 ),
          //                 Text(
          //                   "我的",
          //                   style: TextStyle(
          //                       color:
          //                           _currIndex == 2 ? _activeColor : _defaultColor,
          //                       fontSize: ScreenUtil().setSp(22)),
          //                 )
          //               ],
          //             )
          //           ])),
          // ),
          // body: pages[_currIndex],
          body: PageView(
            controller: _pageController,
            children: pages,
            onPageChanged: (index) {
              setState(() {
                _currIndex = index;
              });
            },
            physics: NeverScrollableScrollPhysics(), //禁止底部滑动
          )),
      onWillPop: () async {
        if (lastBack != null &&
            DateTime.now().millisecondsSinceEpoch -
                    lastBack.millisecondsSinceEpoch <=
                3000) {
          return true;
        }
        lastBack = DateTime.now();
        Utils.showToast("再次返回退出一键订");
        return false;
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    LogUtil.v("home_dispose");
    if (timer != null) {
      timer.cancel();
    }
    if (timerSeller != null) {
      timerSeller.cancel();
    }
    WidgetsBinding.instance.removeObserver(this);
  }
}