import 'dart:async';
import 'package:chat/chat/ChatPage.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/translate_hk_data_mgr.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/SystemEditPage.dart';
import 'package:chat/home/find_page.dart';
import 'package:chat/home/realtimehelper/real_time_helper_page.dart';
import 'package:chat/home/unread_dot_widget.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/file_preview_local.dart';
import 'package:chat/utils/local_notification_util.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/receive_share_file.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sound_util.dart';
import 'package:chat/utils/version_update_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:chat/home/ConversActionPage.dart';
import 'package:chat/home/ProfilePage.dart';
import 'package:flutter/services.dart';
import 'package:location_permissions/location_permissions.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:chat/utils/my_bottom_navigation_bar.dart' as myBottm;

import 'friend_page.dart';

class NavigationIconView {
  final BottomNavigationBarItem item;

  NavigationIconView({
    Key key,
    String title,
    IconData icon,
    int type,
    EdgeInsets iconMargin,
    double iconSize = 24,
    bool isCenter = false,
    bool isShowdot = false,
  }) : item = BottomNavigationBarItem(
            activeIcon: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                isCenter
                    ? Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              color: const Color(0x82008DED),
                              blurRadius: 5.5,
                            ),
                          ],
                          gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: <Color>[
                                const Color(0xFF11E6FF),
                                const Color(0xFF008AFF),
                              ]),
                        ),
                        margin: EdgeInsets.only(bottom: 4),
                        width: iconSize + 10,
                        height: iconSize + 10,
                      )
                    : Container(),
                Container(
                    margin: isCenter
                        ? EdgeInsets.only(bottom: 8, right: 6)
                        : iconMargin ?? EdgeInsets.zero,
                    child: Icon(icon,
                        size: iconSize,
                        color:
                            isCenter ? Colors.white : Constants.BlueTextColor)),
              ],
            ),
            title: Text(''),
            backgroundColor: Colors.white,
            icon: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                isCenter
                    ? Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              color: const Color(0x82008DED),
                              blurRadius: 5.5,
                            ),
                          ],
                          gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: <Color>[
                                const Color(0xFF11E6FF),
                                const Color(0xFF008AFF),
                              ]),
                        ),
                        margin: EdgeInsets.only(bottom: 4),
                        width: iconSize + 10,
                        height: iconSize + 10,
                      )
                    : Container(),
                Container(
                    margin: isCenter
                        ? EdgeInsets.only(bottom: 8, right: 6)
                        : iconMargin ?? EdgeInsets.zero,
                    child: isShowdot
                        ? UnreadDot(
                            child: Icon(icon,
                                size: iconSize,
                                color: Constants.BottomIconGreyColor),
                            type: type)
                        : Icon(icon,
                            size: iconSize,
                            color: isCenter
                                ? Colors.white
                                : Constants.BottomIconGreyColor))
                    // child: Icon(icon,
                    //     size: iconSize,
                    //     color: isCenter
                    //         ? Colors.white
                    //         : Constants.BottomIconGreyColor))
              ],
            ));
}

class HomeMain extends StatefulWidget {
  HomeMain({Key key}) : super(key: key);
  _HomeMainState createState() => _HomeMainState();
}

class _HomeMainState extends State<HomeMain> {
  List<Widget> _pages;
  int _currentIndex = 0;
  List<NavigationIconView> _navigationViews;
  List<String> _titles = [];
  DateTime lastPopTime;
  Timer time;

  @override
  void initState() {

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    super.initState();
    LocalNotificationUtil.instance.initState(context);
    HttpUtil().checkReceiptCache();
    HttpUtil().getSettingInfo();

    MessageMgr().on('Receive AudioChat Request', receiveAudioChatRequest);
    MessageMgr().on('Login Out', loginOut);
    MessageMgr().on('PostContact', postContact);
    MessageMgr().on('Show My Profile', showMyProfile);
    MessageMgr().on('test_Permission', msgTestPermission);
    MessageMgr().on(MessageMgr.RECEIVE_THIRD_SHARE, goShareInfo);
    MessageMgr().on(MessageMgr.TRANSLATE_HK_RECEIVE_ORDER, receiveTranslateOrder);
    MessageMgr().on(MessageMgr.TRANSLATE_HK_START_CHAT, startTranslateHKChat);

    ///初始化语音播放是外放还是听筒-默认外放
    SoundUtils.instance.initPlayMode();

    postContact(null);
    postLoaction();
    locationSchedule();
    HttpUtil().saveMobileInfo();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      VersionUtils.versionUpdate(context);
      ReceiveShareFile.start();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    Provider.of<RefNameProvider>(context, listen: false).init();
  }

  showMyProfile(args) {
    setState(() {
      _currentIndex = _pages.length - 1;
      UserData().homemainIndex = _currentIndex;
    });
  }

  //三分钟获取一次位置信息
  void locationSchedule() {
    time = Timer.periodic(Duration(milliseconds: 180000), (timer) async {
      postLoaction();
    });
  }

  postLoaction() async {
    if (UserData().hasLocationPermission) {
      UserData().getCurrentPosition(callback: (loc) async {
        if (UserData().basicInfo.userId != null) {
          //传给服务器
          Map data = {
            "userId": UserData().basicInfo.userId,
          };
          data['sign'] = TokenMgr().getSign(data);
          data['lat'] = loc.latitude;
          data['lon'] = loc.longitude;
          Response res =
              await HttpUtil().post('location/user/insert', data: data);
          if (res == null) {
            return;
          }
          var resData = res.data;
          print('location/user/insert $resData');
        }
      });
    }
  }

  //上传通讯录
  postContact(args) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int localNum = prefs.getInt(Constants.ContactNum);
    if (UserData().contactList.length != 0 &&
        UserData().contactList.length != localNum &&
        UserData().basicInfo.userId != null) {
      Map data = {
        "userId": UserData().basicInfo.userId,
      };
      data['sign'] = TokenMgr().getSign(data);
      data['list'] = UserData().contactList;
      Response res = await HttpUtil().post('maillist/user/insert', data: data);
      if (res == null) {
        return;
      }
      var resData = res.data;
      if (resData['code'] == 0) {
        prefs.setInt(Constants.ContactNum, UserData().contactList.length);
      }
    }
  }

  @override
  void dispose() {
    MessageMgr().off('Receive AudioChat Request', receiveAudioChatRequest);
    MessageMgr().off('Login Out', loginOut);
    MessageMgr().off('PostContact', postContact);
    MessageMgr().off('Show My Profile', showMyProfile);
    MessageMgr().off('test_Permission', msgTestPermission);
    MessageMgr().off(MessageMgr.RECEIVE_THIRD_SHARE, goShareInfo);
    MessageMgr().off(MessageMgr.TRANSLATE_HK_RECEIVE_ORDER, receiveTranslateOrder);
    MessageMgr().off(MessageMgr.TRANSLATE_HK_START_CHAT, startTranslateHKChat);
    LocalNotificationUtil.instance.dispose();
    if (time != null) {
      time.cancel();
    }
    super.dispose();
  }

  goShareInfo(data) async {
    Future.delayed(Duration(milliseconds: 1000), () {
      Navigator.of(Constants.getCurrentContext()).push(
        new MaterialPageRoute(
          builder: (context) {
            return FilePreview(data);
          },
        ),
      );
    });
  }

  receiveTranslateOrder(var data) async {

    TranslateOrder order = data;

    CustomUI.buildTranslationHelperOrderDialog(context,false,orderId: order.orderId,scenes: order.scenes,desc: order.desc,createTime: order.createTime);
  }

  startTranslateHKChat(var friendID){

    if(TranslateHKMgr().isUser){
      CustomUI.buildTranslationHelperOrderDialog(context,true,userStartChat: (){
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return  ChatPage(
                key: Key('Chat'),
                friendId: friendID,
                isTranslateButler: true,
              );
            },
          ),
        );
      });
    }else{
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return  ChatPage(
              key: Key('Chat'),
              friendId: friendID,
              isTranslateButler: true,
            );
          },
        ),
      );
    }



  }


  msgTestPermission(data) async {
    PermissionStatus status =
        await LocationPermissions().checkPermissionStatus();
    if (status == PermissionStatus.granted) {
      if (UserData().hasLocationPermission == false) {
        UserData().getCurrentPosition();
      }
      UserData().hasLocationPermission = true;
    } else {
      UserData().hasLocationPermission = false;
    }
  }

  receiveAudioChatRequest(args) {
    print('处理连麦消息');
    int friendId = args;

    if (!MsgHandler.isAudioConnect) {
      if (LocalNotificationUtil.isBackground) {
        print('如果在后台,标记不弹');
        MsgHandler.audioChatRequestFriendId = friendId;
      } else {
        HttpUtil().getUserInfo(friendId, (data) {
          var info = UserInfo.fromJson(data);
          AppNavigator.pushAudioChatPage(context, info, true);
        });
      }
    }
  }

  loginOut(args) {
    HttpUtil().postLoginOut(context);
    SystemEditPageState.userLogout();
    showToast(I18n.of(context).otherLogin);
  }

  initValue() {
    _titles = [
      I18n.of(context).park,
      I18n.of(context).radio,
      I18n.of(context).news,
      I18n.of(context).me
    ];

    _navigationViews = [
      NavigationIconView(
          title: _titles[2],
          icon: IconData(
            0xe67c,
            fontFamily: 'iconfont',
          ),
          isShowdot: true,
          iconSize: 29),
      NavigationIconView(
          title: _titles[0],
          isShowdot: true,
          iconMargin: EdgeInsets.only(top: 2),
          type: 5,
          icon: IconData(
            0xe66e,
            fontFamily: 'iconfont',
          ),
          iconSize: 26.5),
      NavigationIconView(
          title: _titles[1],
          icon: IconData(
            0xe656,
            fontFamily: 'iconfont',
          ),
          isCenter: true,
          iconSize: 31),
      NavigationIconView(
          title: _titles[1],
          isShowdot: true,
          icon: IconData(
            0xe60b,
            fontFamily: 'iconfont',
          ),
          type: 6,
          iconSize: 26.5),
      NavigationIconView(
          title: _titles[3],
          icon: IconData(
            0xe67b,
            fontFamily: 'iconfont',
          ),
          iconSize: 26.5),
    ];

    _pages = [
      RealTimeHelperPage(),
      FriendPage(),
      FindPage(),
      ConversActionPage(),
//      GroupChatListPage(),
      ProfilePage(
        userId: UserData().basicInfo.userId,
      ),
    ];

//    _navigationViews = [
//      NavigationIconView(
//          title: _titles[1],
//          isShowdot: true,
//          icon: IconData(
//            0xe60b,
//            fontFamily: 'iconfont',
//          ),
//          type: 1,
//          iconSize: 26.5),
//      NavigationIconView(
//          title: _titles[0],
//          isShowdot: true,
//          iconMargin: EdgeInsets.only(top: 2),
//          type: 5,
//          icon: IconData(
//            0xe663,
//            fontFamily: 'iconfont',
//          ),
//          iconSize: 26.5),
//      NavigationIconView(
//          title: _titles[1],
//          icon: IconData(
//            0xe656,
//            fontFamily: 'iconfont',
//          ),
//          isCenter: true,
//          iconSize: 31),
//
//      NavigationIconView(
//          title: _titles[3],
//          isShowdot: true,
//          icon: IconData(
//            0xe66e,
//            fontFamily: 'iconfont',
//          ),
//          type: 4,
//          iconSize: 26.5),
//
//      NavigationIconView(
//          title: _titles[3],
//          icon: IconData(
//            0xe67b,
//            fontFamily: 'iconfont',
//          ),
//          iconSize: 26.5),
//    ];
//
//    _pages = [
//      ConversActionPage(),
////      RealTimeHelperPage(),
//      FriendPage(),
//      FindPage(),
////      ConversActionPage(),
//      GroupChatListPage(),
//      ProfilePage(
//        userId: UserData().basicInfo.userId,
//      ),
//    ];


  }

  @override
  Widget build(BuildContext context) {
    initValue();

    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
            lastPopTime = DateTime.now();
            showToast(I18n.of(context).confirm_exit);
          } else {
            lastPopTime = DateTime.now();
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
          }
          return new Future.value(false);
        },
        child: Container(
//          color: Colors.white,
          color: AppColors.NewAppbarBgColor,
          child: SafeArea(top: false,child: Scaffold(
//              appBar: PreferredSize(
//                preferredSize: Size.fromHeight(1),
////                child: AppBar(
////                  backgroundColor: AppColors.NewAppbarBgColor,
////                ),
//              ),
              resizeToAvoidBottomPadding: false,
              body: Stack(
                alignment: AlignmentDirectional.bottomStart,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(bottom: 48),
                    color: Constants.LightGreyBackgroundColor,
                    child: SafeArea(
                        top: false,
                        child: IndexedStack(
                          index: _currentIndex,
                          children: _pages,
                        )),
                  ),
                  Positioned(
                    bottom: 0,
                    child: Container(
                      margin: EdgeInsets.only(bottom: 0),
                      child: Image.asset(
                        'assets/images/bg.png',
                        width: Screen.width,
                      ),
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    child: Container(
                      width: Screen.width,
                      height: 0,
                      color: Colors.white,
                    ),
                  ),
                  Container(
                      height: 57,
                      child: myBottm.BottomNavigationBar(
                          elevation: 0,
                          showSelectedLabels: false,
                          showUnselectedLabels: false,
                          //iconSize: 23.5,
                          backgroundColor: Colors
                              .transparent, //Constants.LightGreyBackgroundColor,
                          currentIndex: _currentIndex,
                          type: myBottm.BottomNavigationBarType.fixed,
                          fixedColor: const Color(AppColors.TabIconActive),
                          items:
                          _navigationViews.map((NavigationIconView view) {
                            return view.item;
                          }).toList(),
                          onTap: (int index) {
                            if (_currentIndex == index) {
                              //在当前页面点击不刷新
                              return;
                            }
                            //刷新我的界面数据
                            if (index == 4) {
                              MessageMgr().emit('update_data');
                            }
                            // if (index == 1) {
                            //   MessageMgr().emit('refresh_list_when_no_data');
                            // }
                            MessageMgr().emit('update_system');
                            MessageMgr().emit('do_friend_apply');
//                            LocalNotificationUtil.instance.cleanAllNotifications();
                            setState(() {
                              _currentIndex = index;
                              UserData().homemainIndex = _currentIndex;
                            });
                          })),
                ],
              ))),
        ));
  }
}
