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_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/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/invite_friends.dart';
import 'package:huixiang/qr/qr_code_scan.dart';
import 'package:huixiang/qr/qr_share.dart';
import 'package:huixiang/retrofit/data/examine_instance.dart';
import 'package:huixiang/setting/about_page.dart';
import 'package:huixiang/setting/account_security_page.dart';
import 'package:huixiang/setting/binding_phone_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/platform_code_page.dart';
import 'package:huixiang/setting/platform_pay_code.dart';
import 'package:huixiang/setting/platform_pay_code_success.dart';
import 'package:huixiang/setting/setting_page.dart';
import 'package:huixiang/setting/treaty_page.dart';
import 'package:huixiang/store/report_assess%20.dart';
import 'package:huixiang/store/shop_details_page.dart';
import 'package:huixiang/store/shopping/activity_prefecture_details.dart';
import 'package:huixiang/store/shopping/shopping_goods_details.dart';
import 'package:huixiang/store/shopping/shopping_home/bargain_details.dart';
import 'package:huixiang/store/shopping/shopping_home/group_details.dart';
import 'package:huixiang/store/shopping/shopping_home/group_page_details.dart';
import 'package:huixiang/store/shopping/shopping_home/search_page.dart';
import 'package:huixiang/store/shopping/shopping_mall_home.dart';
import 'package:huixiang/setting/user_service_page.dart';
import 'package:huixiang/store/store_html.dart';
import 'package:huixiang/store/store_order.dart';
import 'package:huixiang/settlement/settlement.dart';
import 'package:huixiang/store/store_view/product_meals_sku.dart';
import 'package:huixiang/test_page.dart';
import 'package:huixiang/union/location_map_page.dart';
import 'package:huixiang/union/union_select_city.dart';
import 'package:huixiang/utils/ImgCachePath.dart';
import 'package:huixiang/vip/user_vip_service_page.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 '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/help_farmers/help_farmers_page.dart';
import 'home/home_view/activity_list.dart';
import 'home/start_page.dart';
import 'home/trading_card_page.dart';
import 'home/welfare_exchange.dart';
import 'home/welfare_page.dart';
import 'login/login_store_select.dart';
import 'login/new_login_page.dart';
import 'login/phone_address_page.dart';
import 'main_page.dart';
import 'message/system_details.dart';
import 'message/system_notice.dart';
import 'mine/coupon_page.dart';
import 'mine/edit_signature.dart';
import 'mine/invitation_record.dart';
import 'mine/manage_address_page.dart';
import 'mine/mine_greenery.dart';
import 'mine/mine_shop_details.dart';
import 'mine/mine_shop_page.dart';
import 'mine/mine_shop_recharge.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/scan_web.dart';
import 'mine/vip_pay_code.dart';
import 'order/bargain_group_order.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") == "tw") {
    locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW');
  } else if(sharedPreferences.containsKey("language") &&
      sharedPreferences.getString("language") == "ch"){
    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,
            title: Platform.isAndroid ? (ExamineInstance.instance.isExamine?"一心回乡":""):"",
            theme: ThemeData(
              primarySwatch: Colors.blue,
              // fontFamily: 'JDZhengHT',
              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: [
              S.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
            localeListResolutionCallback:
                (List<Locale> locales, Iterable<Locale> supportedLocales) {
              print("locale: ${locales[0]}");
              Locale locale;
              if (locales[0].countryCode == "TW") {
                locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW');
              } else if (locales[0].countryCode == "US"){
                locale = Locale.fromSubtags(languageCode: 'en', countryCode: 'US');
              } else{
                locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH');
              }
              return appLocale ?? locale;
            },
            supportedLocales: S.delegate.supportedLocales,
            home: (isFirst ?? true) ? GuidePage() : NewLoginPage(),
            // home: StartPage(isFirst),
            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 NewLoginPage();
                },
                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/bargain_group_order': (context, {arguments}) =>
      BargainGroupOrder(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/store_order': (context, {arguments}) =>
      StoreOrderPage(arguments: arguments),
  '/router/shopping_mall_home': (context, {arguments}) =>
      ShoppingMallHome(arguments: arguments),
  '/router/activity_prefecture_details': (context, {arguments}) =>
      ActivityPrefectureDetails(arguments: arguments),
  '/router/shopping_goods_details': (context, {arguments}) =>
      ShoppingGoodsDetails(arguments: arguments),
  '/router/search_page': (context, {arguments}) =>
      SearchPage(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(arguments:arguments),
  '/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/new_login_page': (context, {arguments}) =>
      NewLoginPage(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(arguments: arguments,),
  '/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(arguments: arguments),
  // '/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/start_page': (context, {arguments}) => StartPage(),
  '/router/test_page': (context, {arguments}) => TestPage(),
  '/router/communityFollow': (context, {arguments}) => CommunityFollow(arguments:arguments),
  '/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/group_details': (context, {arguments}) =>
      GroupDetails(arguments:arguments),
  '/router/bargain_details': (context, {arguments}) =>
      BargainDetails(arguments:arguments),
  '/router/group_page_details': (context, {arguments}) =>
      GroupPageDetails(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(),
  '/router/welfare_page': (context, {arguments}) =>
      WelfarePage(),
  '/router/invite_friends': (context, {arguments}) =>
      InviteFriends(),
  '/router/report_assess': (context, {arguments}) =>
      ReportAssess(),
  '/router/shop_details_page': (context, {arguments}) =>
      ShopDetailsPage(arguments: arguments,),
  '/router/mine_greenery': (context, {arguments}) =>
      MineGreenery(),
  '/router/mine_shop_page': (context, {arguments}) =>
      MineShopPage(),
  '/router/mine_shop_recharge': (context, {arguments}) =>
      MineShopRecharge(arguments: arguments,),
  '/router/mine_shop_details': (context, {arguments}) =>
      MineShopDetails(arguments:arguments,),
  '/router/coupon_page': (context, {arguments}) =>
      CouponPage(),
  '/router/welfare_exchange': (context, {arguments}) =>
      WelfareExchange(),
  '/router/account_security_page': (context, {arguments}) =>
      AccountSecurityPage(),
  '/router/platform_code_page': (context, {arguments}) =>
      PlatformCodePage(arguments:arguments),
  '/router/platform_pay_code': (context, {arguments}) =>
      PlatformPayCode(arguments:arguments),
  '/router/platform_pay_code_success': (context, {arguments}) =>
      PlatformPayCodeSuccess(arguments:arguments),
  '/router/phone_address_page': (context, {arguments}) =>
      PhoneAddressPage(),
  '/router/product_meals_sku': (context, {arguments}) =>
      ProductMealsSku(arguments:arguments),
  '/router/user_vip_service_page': (context, {arguments}) =>
      UserVipServicePage(),
  '/router/help_farmers_page': (context, {arguments}) =>
      HelpFarmersPage(),
  '/router/scan_web': (context, {arguments}) =>
      ScanWeb(arguments:arguments),
  '/router/vip_pay_code': (context, {arguments}) =>
      VipPayCode(),
  '/router/system_notice': (context, {arguments}) =>
      SystemNotice(),
  '/router/store_html': (context, {arguments}) =>
      StoreHtml(arguments:arguments),
  '/router/login_store_select': (context, {arguments}) =>
      LoginStoreSelect(arguments:arguments),
  '/router/binding_phone_page': (context, {arguments}) =>
      BindingPhonePage(arguments:arguments),
  '/router/trading_card_page': (context, {arguments}) =>
      TradingCardPage(),
  '/router/union_select_city': (context, {arguments}) =>
      UnionSelectCity(arguments:arguments),
};