import 'dart:io';
import 'dart:ui';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/address/address_map_page.dart';
import 'package:huixiang/address/edit_address_page.dart';
import 'package:huixiang/article/hot_article_details_page.dart';
import 'package:huixiang/article/video_playback_page.dart';
import 'package:huixiang/community/community_details.dart';
import 'package:huixiang/community/release_dynamic.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/founder_story_page.dart';
import 'package:huixiang/integral/integral_detailed_page.dart';
import 'package:huixiang/integral/integral_page.dart';
import 'package:huixiang/integral_store/integral_store_details_page.dart';
import 'package:huixiang/login/login_page.dart';
import 'package:huixiang/message/main_message_page.dart';
import 'package:huixiang/message/system_message.dart';
import 'package:huixiang/mine/coupons_page.dart';
import 'package:huixiang/mine/edit_name.dart';
import 'package:huixiang/mine/mine_card_invalid_page.dart';
import 'package:huixiang/mine/mine_card_page.dart';
import 'package:huixiang/mine/mine_wallet_page.dart';
import 'package:huixiang/mine/recharge_page.dart';
import 'package:huixiang/mine/user_info_page.dart';
import 'package:huixiang/mine/vip_balance_page.dart';
import 'package:huixiang/mine/vip_card_page.dart';
import 'package:huixiang/mine/vip_detail_page.dart';
import 'package:huixiang/order/edit_remarks_page.dart';
import 'package:huixiang/order/exchange_history_page.dart';
import 'package:huixiang/order/exchange_order_page.dart';
import 'package:huixiang/order/exchange_order_success_page.dart';
import 'package:huixiang/order/exchange_order_detail_page.dart';
import 'package:huixiang/order/logistics_information_page.dart';
import 'package:huixiang/order/order_detail_page.dart';
import 'package:huixiang/order/order_history_page.dart';
import 'package:huixiang/order/store_selector_page.dart';
import 'package:huixiang/order/write_off_page.dart';
import 'package:huixiang/order/write_off_success_page.dart';
import 'package:huixiang/qr/qr_code_scan.dart';
import 'package:huixiang/qr/qr_share.dart';
import 'package:huixiang/setting/about_page.dart';
import 'package:huixiang/setting/help_feedback_page.dart';
import 'package:huixiang/setting/logout_ing.dart';
import 'package:huixiang/setting/logout_page.dart';
import 'package:huixiang/setting/permission_setting_page.dart';
import 'package:huixiang/setting/setting_page.dart';
import 'package:huixiang/setting/treaty_page.dart';
import 'package:huixiang/setting/user_service_page.dart';
import 'package:huixiang/store/store_order.dart';
import 'package:huixiang/settlement/settlement.dart';
import 'package:huixiang/test_page.dart';
import 'package:huixiang/union/location_map_page.dart';
import 'package:huixiang/utils/ImgCachePath.dart';
import 'package:huixiang/view_widget/activity_poster.dart';

import 'package:huixiang/web/web_page.dart';
import 'package:huixiang/union/union_details_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/web/web_turntable_activity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_register.dart';
import 'package:tpns_flutter_plugin/android/xg_android_api.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';

import 'community/community_view/class_details.dart';
import 'community/headlines/headlines_column_details.dart';
import 'community/new_community_details.dart';
import 'community/photo_view_gallery_screen.dart';
import 'community/report/report_notice.dart';
import 'community/report/report_page.dart';
import 'community/report/report_success.dart';
import 'home/guide_page.dart';
import 'home/home_view/activity_list.dart';
import 'main_page.dart';
import 'message/system_details.dart';
import 'mine/edit_signature.dart';
import 'mine/invitation_record.dart';
import 'mine/manage_address_page.dart';
import 'mine/mine_view/community_follow.dart';
import 'mine/mine_vip/binding_assistant_card.dart';
import 'mine/mine_vip/legal_right_details.dart';
import 'mine/mine_vip/mine_attainment_page.dart';
import 'mine/mine_vip/mine_vip_core.dart';
import 'mine/personal_page.dart';
import 'order/exchange_write_off_page.dart';
import 'mine/release_page.dart';
import 'mine/roll_center_page.dart';

void main() async {
  if (Platform.isAndroid) {
    SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle(statusBarColor: Colors.transparent));
  }
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  Locale locale;
  if (sharedPreferences.containsKey("language") &&
      sharedPreferences.getString("language") == "zh") {
    locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW');
  } else {
    locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH');
  }
  ImgCachePath();
  // initSdk();
  bool isFirst = sharedPreferences.getBool("isFirst");

  runApp(MyApp(locale, isFirst));
  // FlutterBugly.postCatchedException((){
  // });
  // FlutterBugly.init(androidAppId: "204f207673",iOSAppId: "8bb92ba0f6");
}

// final XgFlutterPlugin xgFlutterPlugin = XgFlutterPlugin();



EventBus eventBus = EventBus(sync: true);

Route lastRoutePage;
class MyApp extends StatelessWidget {
  final Locale appLocale;
  final bool isFirst;

  MyApp(this.appLocale, this.isFirst);

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
        data: const MediaQueryData(
          size: Size(375, 812),
        ),
        child: ScreenUtilInit(
          designSize: Size(375, 812),
          builder: () => MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              primarySwatch: Colors.blue,
              textTheme: TextTheme(
                button: TextStyle(fontSize: 24.sp),
                bodyText1: TextStyle(fontSize: 12.sp),
                bodyText2: TextStyle(fontSize: 16.sp),
              ),
            ),
            localeResolutionCallback: (locale, supportedLocales) {
              print("locale: $locale");
              print("supportedLocales: $supportedLocales");
              return appLocale ?? locale;
            },
            localizationsDelegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              S.delegate
            ],
            localeListResolutionCallback:
                (List<Locale> locales, Iterable<Locale> supportedLocales) {
              print("locale: ${locales[0]}");
              return appLocale ?? locales[0];
            },
            supportedLocales: S.delegate.supportedLocales,
            home: (isFirst ?? true) ? GuidePage() : LoginPage(),
            builder: EasyLoading.init(
              builder: (context, widget) {
                ScreenUtil.setContext(context);
                return MediaQuery(
                  data: MediaQuery.of(context).copyWith(
                    textScaleFactor: AppUtils.textScale(context),
                  ),
                  child: FlutterSmartDialog(child: widget),
                );
              },
            ),
            onGenerateRoute: (settings) {
              final String name = settings.name;
              if(lastRoutePage?.settings?.name == name){
                if(lastRoutePage?.settings?.name == "/router/personal_page"
                    && lastRoutePage.navigator != null)
                  lastRoutePage.navigator.pop();

              }
              final Function pageContentBuilder = routers[name];
              if (pageContentBuilder != null) {
                final Route route = CupertinoPageRoute(
                  builder: (context) {
                    return pageContentBuilder(context,
                        arguments: settings.arguments);
                  },
                  settings: settings,
                );
                lastRoutePage = route;
                return route;
              }
              return MaterialPageRoute(
                //未找到页面配置进入登录页
                builder: (context) {
                  return LoginPage();
                },
                settings: settings,
              );
            },
          ),
        ));
  }
}

Map<String, WidgetBuilder> routers = <String, WidgetBuilder>{
  '/router/exchange_order_success_page': (context, {arguments}) =>
      ExchangeOrderSuccessPage(arguments: arguments),
  '/router/logistics_information_page': (context, {arguments}) =>
      LogisticsInformationPage(arguments: arguments),
  '/router/exchange_write_offPage': (context, {arguments}) =>
      ExchangeWriteOffPage(arguments: arguments),
  '/router/integral_store_page': (context, {arguments}) =>
      IntegralStoreDetailsPage(arguments: arguments),
  '/router/manage_address_page': (context, {arguments}) =>
      ManageAddressPage(arguments: arguments),
  '/router/exchange_order_page': (context, {arguments}) =>
      ExchangeOrderPage(arguments: arguments),
  // '/router/mine_vip_level_page': (context, {arguments}) =>
  //     MineVipLevelPage(arguments: arguments),
  '/router/mine_vip_core': (context, {arguments}) =>
      MineVipCore(arguments: arguments),
  '/router/legal_right_details': (context, {arguments}) =>
      LegalRightDetails(arguments: arguments),
  '/router/binding_assistant_card': (context, {arguments}) =>
      BindingAssistantCard(),
  '/router/order_history_page': (context, {arguments}) =>
      OrderHistoryPage(arguments: arguments),
  '/router/union_detail_page': (context, {arguments}) =>
      UnionDetailsPage(arguments: arguments),
  '/router/address_edit_page': (context, {arguments}) =>
      EditAddressPage(arguments: arguments),
  '/router/vip_details_page': (context, {arguments}) =>
      VipDetailPage(arguments: arguments),
  '/router/order_details': (context, {arguments}) =>
      OrderDetailPage(arguments: arguments),
  // '/router/hot_article_details_page': (context, {arguments}) => HotArticleDetailsPage(),
  '/router/write_off_page': (context, {arguments}) =>
      WriteOffPage(arguments: arguments),
  '/router/hot_article_details_page': (context, {arguments}) =>
      HotArticleDetailsPage(),
  '/router/store_order': (context, {arguments}) =>
      StoreOrderPage(arguments: arguments),
  '/router/vip_balance': (context, {arguments}) =>
      VipBalancePage(arguments: arguments),
  '/router/exchange_order_details': (context, {arguments}) =>
      ExchangeOrderDetailPage(),
  '/router/location_map': (context, {arguments}) =>
      LocationMap(arguments: arguments),
  '/router/settlement': (context, {arguments}) =>
      Settlement(arguments: arguments),
  '/router/integral_detailed_page': (context, {arguments}) =>
      IntegralDetailedPage(),
  '/router/write_off_success_page': (context, {arguments}) =>
      WriteOffSuccessPage(),
  '/router/exchange_history_page': (context, {arguments}) =>
      ExchangeHistoryPage(),
  '/router/permission_setting': (context, {arguments}) =>
      PermissionSettingPage(),
  '/router/login_page': (context, {arguments}) =>
      LoginPage(arguments: arguments),
  '/router/edit_name': (context, {arguments}) => EditName(arguments: arguments),
  '/router/edit_signature': (context, {arguments}) => EditSignature(arguments: arguments),
  '/router/mine_card_invalid': (context, {arguments}) => MineCardInvalidPage(),
  '/router/store_selector_page': (context, {arguments}) => StoreSelectorPage(),
  '/router/video_playback_page': (context, {arguments}) => VideoPlaybackPage(),
  '/router/web_page': (context, {arguments}) => WebPage(arguments: arguments),
  '/router/web_turntable_activity': (context, {arguments}) => WebTurntableActivity(),
  '/router/help_feedback_page': (context, {arguments}) => HelpFeedbackPage(),
  '/router/founder_story_page': (context, {arguments}) => FounderStoryPage(),
  '/router/system_msg_page': (context, {arguments}) => SystemMessagePage(),
  '/router/edit_remarks_page': (context, {arguments}) => EditRemarksPage(),
  // '/router/hot_article_page': (context, {arguments}) => HotArticlePage(),
  '/router/address_map_page': (context, {arguments}) => AddressMapPage(),
  '/router/roll_center_page': (context, {arguments}) => RollCenterPage(),
  '/router/release_dynamic': (context, {arguments}) => ReleaseDynamic(),
  '/router/community_details': (context, {arguments}) =>
      CommunityDetails(arguments: arguments),
  '/router/new_community_details': (context, {arguments}) =>
      NewCommunityDetails(arguments: arguments),
  '/router/user_info_page': (context, {arguments}) => UserInfoPage(),
  '/router/recharge_page': (context, {arguments}) => RechargePage(),
  '/router/mine_wallet': (context, {arguments}) => MineWalletPage(),
  '/router/integral_page': (context, {arguments}) => IntegralPage(),
  '/router/vip_card_page': (context, {arguments}) => VipCardPage(),
  '/router/msg_page': (context, {arguments}) => MainMessagePage(),
  '/router/coupons_page': (context, {arguments}) => CouponsPage(),
  '/router/setting_page': (context, {arguments}) => SettingPage(),
  '/router/qr_scan': (context, {arguments}) => QrCodeScanPage(),
  '/router/treaty_page': (context, {arguments}) => TreatyPage(),
  '/router/mine_card': (context, {arguments}) => MineCardPage(),
  '/router/guide_Page': (context, {arguments}) => GuidePage(),
  '/router/about_page': (context, {arguments}) => AboutPage(),
  '/router/qr_share': (context, {arguments}) => QrSharePage(),
  '/router/main_page': (context, {arguments}) => MainPage(arguments: arguments),
  '/router/test_page': (context, {arguments}) => TestPage(),
  '/router/communityFollow': (context, {arguments}) => CommunityFollow(),
  '/router/releasePage': (context, {arguments}) => ReleasePage(),
  '/router/activity_list': (context, {arguments}) => ActivityList(),
  '/router/class_details': (context, {arguments}) =>
      ClassDetails(arguments: arguments),
  '/router/mine_attainment_page': (context, {arguments}) =>
      MineAttainmentPage(arguments: arguments),
  '/router/headlines_column_details': (context, {arguments}) =>
      HeadlinesColumnDetails(arguments: arguments),
  '/router/photo_view_gallery_screen': (context, {arguments}) =>
      PhotoViewGalleryScreen(),
  '/router/system_details': (context, {arguments}) =>
      SystemDetails(arguments: arguments),
  '/router/invitation_record': (context, {arguments}) =>
      InvitationRecord(),
  '/router/personal_page': (context, {arguments}) =>
      PersonalPage(arguments:arguments),
  '/router/report_page': (context, {arguments}) =>
      ReportPage(arguments:arguments),
  '/router/report_notice': (context, {arguments}) =>
      ReportNotice(),
  '/router/report_success': (context, {arguments}) =>
      ReportSuccess(),
  '/router/logout_page': (context, {arguments}) =>
      LogoutPage(),
  '/router/logout_ing': (context, {arguments}) =>
      LogoutIng(),
  '/router/user_service_page': (context, {arguments}) =>
      UserServicePage(),
};