
export 'i18n.dart';
export 'cache.dart';
export 'logger.dart';
export 'request.dart';
export 'user_ext.dart';
export 'size_fit.dart';
export 'net_error.dart';
export 'image_utils.dart';
export 'notification.dart';

import 'package:flutter/material.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';
import 'package:twong/models/index.dart';
import 'package:twong/utils/request.dart';
import 'package:twong/widgets/floading.dart';
import 'package:twong/widgets/loading.dart';
import 'package:twong/widgets/photo_view.dart';

import 'cache.dart';
import 'package:twong/utils/i18n.dart';
import 'package:twong/router/base.dart';
import 'package:twong/widgets/dialog.dart';

import 'logger.dart';

class Utils {
  static String _channel = "android/back/desktop";

  static void showAlert(BuildContext context, {String title, Function ok, String okText, String noText}) {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: title,
              callback: (res) {
                ok?.call();
              }
          );
        }
    );
  }

  static void notOpen () {
    BotToast.showText(text: '功能暂未开放!');
  }

  static String formatRMB(dynamic number, { bool show = false,
    bool sign = false, bool cn = false })
  {
    if(number == null) number = 0;
    num price = 0;
    if(number is num) {
      price = number;
    } else {
      price = double.parse(number.toString());
    }
    var s = "";
    if(sign) {
      s = price > 0 ? "+" : "-";
    }
    if(cn) {
      return "${price.toStringAsFixed(2)}${I18n.cn}";
    }
    return "$s${show ? I18n.$ : ""}${price.toStringAsFixed(2)}";
  }

  static String formatData(num data) {
    return DateTime.fromMillisecondsSinceEpoch(data * 1000).toString();
  }

  static void toLogin() {
    if (Cache.context == null) return;
    Navigator.pushNamed(Cache.context, RouteNames.login);
  }

  static void showPhoto({String image, List<String> images, int index = 0}) {
    if (Cache.context == null) return;
    PhotoListData data;
    if (images != null) {
      data = PhotoListData(index, images);
    } else {
      data = PhotoListData(index, [image]);
    }

    Navigator.pushNamed(Cache.context, RouteNames.picture, arguments: data);
  }

  static Future backDeskTop() async {
    var platform = MethodChannel(_channel);
    try {
      await platform.invokeMethod("back_to_desktop");
    } on PlatformException catch (e) {
      debugPrint(e.toString());
    }
    return Future.value(false);
  }

  static void loading() {
    BotToast.showLoading();
  }

  static void closeLoading() {
    BotToast.closeAllLoading();
  }

  static void showLoading({dynamic data}) {
    var context = Cache.context;
    showGeneralDialog(context: context, pageBuilder: (BuildContext buildContext, Animation<double> animation,
        Animation<double> secondaryAnimation) {
      final Widget pageChild = Builder(builder: (context) {
        return WillPopScope(
          onWillPop: () async {
            return Future.value(false);
          },
          child: Loading(data: data),
        );
      });
      return pageChild;
    });
  }

  static void copyText(dynamic text) {
    Clipboard.setData(ClipboardData(text: text))
        .then((value) {
      BotToast.showText(text: "复制成功");
    }).catchError((err) {
      BotToast.showText(text: "复制失败");
    });
  }

  static Widget get loadingWidget {
    return CircularProgressIndicator();
  }

  static void checkUpdate({Function ok, Function cancel}) {
    AppUpgrade.appUpgrade(
      Cache.context,
      _checkAppInfo(),
      onOk: ok,
      onCancel: cancel,
      iosAppId: '1537411658',
    );
  }

  static Future<AppUpgradeInfo> _checkAppInfo() async {
    return Request.getVersion().then((remote) async {
      var version = await FlutterUpgrade.appInfo;
      Cache.checked = true;
      var local = Version();
      local.version = version.versionName;
      var need = remote > local;
      Log.i("remote:\t${remote.version}\nlocal:\t${local.version}\n"
          "${need ? "need update !" :"already is the latest."}");

      closeLoading();
      if (need) {
        return AppUpgradeInfo(
          title: '新版本${remote.version}',
          contents: ['检测到有新版本更新，是否立即下载？'],
          force: false,
        );
      } else {
        return null;
      }
    });
  }

  static String encodeString(String str, {int start = 3, int end = 4,
    String char = "*"}) {
    var code = "";
    int length = str.length - end - start;
    for(var i = 0; i < length; i ++) {
      code += char;
    }
    return str.replaceRange(start, str.length - end, code);
  }

  static String formatName(String name) {
    if(name.length > 2) {
      return name.substring(0, 1);
    }
    return name;
  }
}