import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:base_app/res/index.dart';
import 'package:base_app/ui/pages/main_page.dart';
import 'package:base_app/ui/pages/splash_page.dart';
import 'package:dio/dio.dart';
import 'package:fluintl/fluintl.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:oktoast/oktoast.dart';

import 'blocs/application_bloc.dart';
import 'blocs/bloc_provider.dart';
import 'blocs/main_bloc.dart';
import 'common/common.dart';
import 'common/global.dart';
import 'common/sp_helper.dart';
import 'data/net/dio_util.dart';
import 'models/common/language_model.dart';
import 'ui/pages/user/user_login_page.dart';

/// APP核心入口文件
Future<void> main() async {
  Global.init(() {
    runApp(BlocProvider<ApplicationBloc>(
      bloc: ApplicationBloc(),
      child: BlocProvider(child: MyApp(), bloc: MainBloc()),
    ));
  });
  // 高德地图配置
  await enableFluttifyLog(false);
  await AmapService.init(
    iosKey: '		8fcba5276758c8e0b25c5f263c481db2',
    androidKey: 'af843eb87ac0e88dac6c08147579ae0e',
  );
}

/// MyApp核心入口界面
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  Locale _locale; // 地区化，国际化用
  Color _themeColor = Colours.app_main; // 主题色

  @override
  void initState() {
    super.initState();
    setInitDir(initStorageDir: true);
    // setLocalizedSimpleValues(localizedSimpleValues); // 配置简单多语言资源
    setLocalizedValues(localizedValues); // 配置多语言资源
    init();
  }

  void init() {
    _init();
    _initListener();
    _loadLocale();
  }

  // 初始化Dio配置
  void _init() {
    DioUtil.openDebug(); // 开启调试模式
    Options options = DioUtil.getDefOptions();
    String baseUrl = SpUtil.getString(Constant.key_url); // baseUrl设置
    options.baseUrl = baseUrl;
    String token = SpUtil.getString(BaseConstant.keyAppToken); // token
    if (ObjectUtil.isNotEmpty(token)) {
      Map<String, dynamic> _headers = new Map();
      _headers["token"] = token;
      options.headers = _headers;
    }
    HttpConfig config = new HttpConfig(options: options); // config
    DioUtil().setConfig(config);
  }

  /// 初始化监听
  void _initListener() {
    final ApplicationBloc bloc = BlocProvider.of<ApplicationBloc>(context);
    bloc.appEventStream.listen((value) {
      // 监听语言变化和专题变化
      _loadLocale();
    });
  }

  /// 初始化应用语言和默认应用主题颜色
  void _loadLocale() {
    setState(() {
      // 优先读取本地设置
      LanguageModel model =
          SpUtil.getObj(Constant.keyLanguage, (v) => LanguageModel.fromJson(v));
      if (model != null) {
        _locale = new Locale(model.languageCode, model.countryCode);
      } else {
        _locale = null;
      }
      // 获取系统颜色，先获取本地设置，默认blue
      String _colorKey = SpHelper.getThemeColor();
      if (themeColorMap[_colorKey] != null)
        _themeColor = themeColorMap[_colorKey];
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return OKToast(
        //toast
        child: MaterialApp(
      routes: {
        //静态路由
        BaseConstant.routeMain: (ctx) => MainPage(),
        BaseConstant.routeLogin: (ctx) => UserLoginPage(),
      },
      home: new SplashPage(),
      theme: ThemeData.light().copyWith(
        primaryColor: _themeColor, // 主色：影响标题栏等组件
        accentColor: _themeColor, // 次主色，决定很多组件的背景色
        indicatorColor: Colors.white, //TabBar选中项中指示器颜色
      ),
      locale: _locale,
      localizationsDelegates: [
        // 本地化代理类
        GlobalMaterialLocalizations.delegate, //提供Material组件库不同语言的字符串值
        GlobalWidgetsLocalizations.delegate, //定义了默认的文本方向
        GlobalCupertinoLocalizations.delegate, // 提供了Cupertinio组件库不同语言的字符串值
        CustomLocalizations.delegate // fluintl 本地化代理
      ],
      supportedLocales: CustomLocalizations.supportedLocales, // 支持本地化语言集合
    ));
  }
}
