import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:huixiang/community/community_page.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/home_page.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/mine/mine_page.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/union/union_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/utils/bridge.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/native_event_handler.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MainPage();
  }
}

class _MainPage extends State<MainPage> with WidgetsBindingObserver {
  List<Widget> _widgetOptions;

  List<String> icons;
  // List<String> iconn;

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("-didChangeAppLifecycleState-" + state.toString());
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: //从后台切换前台,界面可见
        pushRoute();
        break;
      case AppLifecycleState.paused: // 界面不可见,后台
        break;
      case AppLifecycleState.detached: // APP结束时调用
        break;
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    EasyLoading.instance
      ..indicatorType = EasyLoadingIndicatorType.circle
      // ..indicatorType = EasyLoadingIndicatorType.wave
      // ..indicatorType = EasyLoadingIndicatorType.threeBounce
      ..loadingStyle = EasyLoadingStyle.dark
      ..indicatorSize = 35.0
      ..backgroundColor = Colors.white
      ..progressColor = Colors.green
      ..progressWidth = 3.0
      ..userInteractions = false
      ..dismissOnTap = false;

    pushRoute();

    _widgetOptions = <Widget>[
      // BrandPage(),
      HomePage((index) {
        setState(() {
          pageController.jumpToPage(index);
        });
      }),
      // MainHomePage(),
      UnionPage(),
      CommunityPage(),
      MinePage(),
    ];

    icons = [
      "assets/svg/jingbi.svg",
      "assets/svg/lianmeng.svg",
      "assets/svg/shequn.svg",
      "assets/svg/wode.svg",
    ];
    // iconn = [
    //   "assets/image/icon_brand_n.png",
    //   "assets/image/icon_bi_n.png",
    //   "assets/image/icon_meng_n.png",
    //   "assets/image/icon_wo_n.png",
    // ];

    eventBus.on<EventType>().listen((event) {
      if (event.type < 3) {
        setState(() {});
      }
    });

    queryUserInfo();

    if (Platform.isAndroid) {
      xgFlutterPlugin.getXgAndroidApi().addNativeEventHandler(
        MyNativeEventHandler(
          (String title, String message, String customContent, int type) {
            print("xgPushClickAction2: $customContent");
            SharedPreferences.getInstance().then((value) {
              value.setString("pushData", customContent);
            });
          },
        ),
      );
    }

    /// @typed: 1文章  2活动  3店铺   4积分商品   5订单
    xgFlutterPlugin.addEventHandler(xgPushClickAction: (event) async {
      print("xgPushClickAction1: $event");
      if (event["actionType"] == 2) return event;
      if (Platform.isAndroid
          ? (event["actionType"] == 0)
          : (event["xg"]["msgtype"] == 1) &&
              event[Platform.isAndroid ? "customMessage" : "custom"] != null) {
        SharedPreferences.getInstance().then((value) {
          value.setString("pushData",
              event[Platform.isAndroid ? "customMessage" : "custom"]);
        });
        if (ModalRoute.of(context).isActive &&
            ModalRoute.of(context).isCurrent) {
          pushRoute();
        } else {
          Navigator.of(context)
              .pushNamedAndRemoveUntil('/router/main_page', (route) => false);
        }
      }
      return event;
    }, onReceiveNotificationResponse: (event) async {
      print("onReceiveNotificationResponse: ${event.toString()}");
      return event;
    }, onReceiveMessage: (event) async {
      print("onReceiveMessage: ${event.toString()}");
      return event;
    }, onRegisteredDone: (event) async {
      print("onRegisteredDone: ${event.toString()}");
      return event;
    }, xgPushDidBindWithIdentifier: (event) async {
      print("xgPushDidBindWithIdentifier: ${event.toString()}");
      return event;
    });
  }

  pushRoute() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if (sharedPreferences.getString("token") == null ||
        sharedPreferences.getString("token") == "") return;
    String startIntent = await Bridge.getStartIntent();
    print("intent:$startIntent");
    String pushData = "";
    if (startIntent != null && startIntent != "") {
      pushData = startIntent;
      // pushData = """{"typed":1,"info":"1420304936817655808"}""";
    } else {
      pushData = sharedPreferences.getString("pushData");
    }
    if (pushData == null || pushData == "") return;
    Map<String, dynamic> pushMap = jsonDecode(pushData);
    if (pushMap != null) {
      String routeName = "";
      Map<String, dynamic> params = {};
      switch (pushMap["typed"]) {
        case 1:
          routeName = "/router/store_detail_page";
          params["articleId"] = pushMap["info"];
          break;
        case 2:
          routeName = "/router/store_detail_page";
          params["activityId"] = pushMap["info"];
          break;
        case 3:
          routeName = "/router/union_detail_page";
          params["id"] = pushMap["info"];
          break;
        case 4:
          routeName = "/router/integral_store_page";
          params["goodsId"] = pushMap["info"];
          break;
        case 5:
          routeName = "/router/order_details";
          params["id"] = pushMap["info"];
          break;
      }
      sharedPreferences.setString("pushData", "");
      print("xgPushClickAction: routeName: $routeName");
      if (routeName != "") {
        Navigator.of(context).pushNamed(routeName, arguments: params);
      }
    }
  }

  queryUserInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if (sharedPreferences.getString("token") == null ||
        sharedPreferences.getString("token") == "") return;
    BaseData<UserInfo> baseDate = await ApiService(
      Dio(),
      context: context,
      token: sharedPreferences.getString('token'),
    ).queryInfo().catchError((onError) {});
    sharedPreferences.setString('user', jsonEncode(baseDate.data));

    String mobile = baseDate.data.phone;
    if (mobile != null && mobile != "") {
      xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER);
      // xgFlutterPlugin.unbindWithIdentifier(identify: mobile, bindType: XGBindType.account)
      xgFlutterPlugin.bindWithIdentifier(
          identify: mobile, bindType: XGBindType.account);
    }
  }

  requestPermission() async {
    if (!await Permission.storage.isGranted) {
      await Permission.storage.request();
    }
  }

  final PageController pageController = PageController(initialPage: 0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        child: PageView(
          controller: pageController,
          children: _widgetOptions,
          physics: NeverScrollableScrollPhysics(),
          onPageChanged: (index) {
            clickIndex = index;
            setState(() {});
          },
        ),
      ),
      extendBody: true,
      bottomNavigationBar: Container(
        alignment: Platform.isAndroid ? Alignment.center : Alignment.topCenter,
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha(12),
              offset: Offset(0, 2),
              blurRadius: 4,
              spreadRadius: 0,
            )
          ],
          borderRadius: BorderRadius.vertical(
            top: Radius.circular(4),
          ),
        ),
        height: 82.h,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // bottomNavigationBigItem(S.of(context).pinpai, 0),
            bottomNavigationItem(S.of(context).main_menu1, 0),
            bottomNavigationItem(S.of(context).main_menu2, 1),
            bottomNavigationItem(S.of(context).main_menu3, 2),
            bottomNavigationItem(S.of(context).main_menu4, 3),
          ],
        ),
      ),
    );
  }

  var clickIndex = 0;

  Widget bottomNavigationItem(text, index) {
    var isSelected = index == clickIndex;
    return Expanded(
      child: InkWell(
        onTap: () {
          setState(() {
            clickIndex = index;
            // if (index == 1) {
            //   debugDumpApp();
            // }
            pageController.jumpToPage(clickIndex);
          });
        },
        child: Container(
          width: 45.w,
          child: Column(
            mainAxisAlignment: Platform.isAndroid
                ? MainAxisAlignment.center
                : MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              if (Platform.isIOS)
                SizedBox(
                  height: 4.h,
                ),
              // AnimatedCrossFade(
              //   firstChild: SvgPicture.asset(
              //     icons[index],
              //     width: 30,
              //     height: 30,
              //     fit: BoxFit.contain,
              //   ),
              //   // Image.asset(
              //   //   icons[index],
              //   //   width: 30,
              //   //   height: 30,
              //   //   fit: BoxFit.contain,
              //   // ),
              //   secondChild: Image.asset(
              //     iconn[index],
              //     width: 30,
              //     height: 30,
              //     fit: BoxFit.contain,
              //   ),
              //   crossFadeState: isSelected
              //       ? CrossFadeState.showFirst
              //       : CrossFadeState.showSecond,
              //   duration: Duration(milliseconds: 200),
              // ),
              SvgPicture.asset(
                icons[index],
                width: 30,
                height: 30,
                color: isSelected ? Color(0xFF32A060) : Color(0xFFE6E6E6),
                fit: BoxFit.contain,
              ),
              Text(
                text,
                style: TextStyle(
                  fontSize: 10,
                  fontWeight: MyFontWeight.semi_bold,
                  color: Color(isSelected ? 0xFF4C4C4C : 0xFFA29E9E),
                ),
              ),
            ],
          ),
        ),
      ),
      flex: 1,
    );
  }

  // Widget bottomNavigationBigItem(text, index) {
  //   var isSelected = index == clickIndex;
  //   return Expanded(
  //     child: InkWell(
  //       onTap: () {
  //         setState(() {
  //           clickIndex = index;
  //           pageController.jumpToPage(clickIndex);
  //         });
  //       },
  //       child: Container(
  //         width: 45.w,
  //         alignment: Alignment.center,
  //         child: AnimatedCrossFade(
  //           firstCurve: Curves.easeIn,
  //           secondCurve: Curves.ease,
  //           sizeCurve: Curves.easeInOut,
  //           duration: Duration(milliseconds: 50),
  //           firstChild: Container(
  //             padding: EdgeInsets.all(4),
  //             height: 82.h,
  //             alignment:
  //                 Platform.isAndroid ? Alignment.center : Alignment.topCenter,
  //             child: Image.asset(
  //               icons[index],
  //               width: 45,
  //               height: 45,
  //               fit: BoxFit.contain,
  //             ),
  //           ),
  //           secondChild: Column(
  //             mainAxisAlignment: Platform.isAndroid
  //                 ? MainAxisAlignment.center
  //                 : MainAxisAlignment.start,
  //             crossAxisAlignment: CrossAxisAlignment.center,
  //             children: [
  //               if (Platform.isIOS)
  //                 SizedBox(
  //                   height: 4.h,
  //                 ),
  //               Image.asset(
  //                 iconn[index],
  //                 width: 30,
  //                 height: 30,
  //                 fit: BoxFit.contain,
  //               ),
  //               SizedBox(
  //                 height: 1.h,
  //               ),
  //               Text(
  //                 text,
  //                 style: TextStyle(
  //                   fontSize: 10.sp,
  //                   fontWeight: MyFontWeight.semi_bold,
  //                   color: Color(isSelected ? 0xFF4C4C4C : 0xFFA29E9E),
  //                 ),
  //               ),
  //             ],
  //           ),
  //           crossFadeState: isSelected
  //               ? CrossFadeState.showFirst
  //               : CrossFadeState.showSecond,
  //         ),
  //       ),
  //     ),
  //     flex: 1,
  //   );
  // }
}