import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:badges/badges.dart' as badges;

import '../api/index.dart';
import '../models/index.dart';
import '../style/index.dart';
import '../utils/index.dart';

///
///放置公共的 stateless widget 方便调用 减少代码
///

enum O2DialogAction { positive, cancel }

class O2UI {
  static PopupMenuButton webviewPopupMenu(VoidCallback onTap) =>
      PopupMenuButton(
        itemBuilder: (ctx) {
          return [
            // 复制地址
            PopupMenuItem(
              onTap: onTap,
              child: Text('common_webview_copy_link'.tr),
            )
          ];
        },
      );

  ///Default matrix
  static List<double> get _matrix => [
        1, 0, 0, 0, 0, //R
        0, 1, 0, 0, 0, //G
        0, 0, 1, 0, 0, //B
        0, 0, 0, 1, 0, //A
      ];

  ///Generate a matrix of specified saturation
  ///[sat] A value of 0 maps the color to gray-scale. 1 is identity.
  static List<double> _saturation(double sat) {
    final m = _matrix;
    final double invSat = 1 - sat;
    final double R = 0.213 * invSat;
    final double G = 0.715 * invSat;
    final double B = 0.072 * invSat;
    m[0] = R + sat;
    m[1] = G;
    m[2] = B;
    m[5] = R;
    m[6] = G + sat;
    m[7] = B;
    m[10] = R;
    m[11] = G;
    m[12] = B + sat;
    return m;
  }

  /// 带角标的 组件
  static Widget badgeView(int number, Widget child) {
    return badges.Badge(
        badgeContent: Text('$number',
            style: TextStyle(color: Colors.white, fontSize: 12)),
        showBadge: number > 0,
        child: child);
  }

  /// 显示状态栏
  static void showStatusBar() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
  }

  /// 全屏 不显示状态栏
  static void hideStatusBar() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
  }

  /// 所有子组件都变成黑白组件
  static Widget greyWidget(Widget child, bool needGrey) {
    return ColorFiltered(
      colorFilter: ColorFilter.matrix(_saturation(needGrey ? 0 : 1)),
      child: child,
    );
  }

  static AppBar baseBar(String title, {List<Widget> actions = const []}) {
    return AppBar(
      title: Text(
        title,
        style:
            const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      actions: actions,
    );
  }

  /// 黑色半透明背景
  static Widget blackTransparentCard(Widget child,
      {double radius = 4.0,
      double width = double.infinity,
      double height = double.infinity}) {
    return Container(
        decoration: BoxDecoration(
            color: AppColor.blackTransparentBackground,
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        width: width,
        height: height,
        child: child);
  }

  /// 白色半透明背景
  static Widget whiteTransparentCard(Widget child,
      {double radius = 4.0,
      double width = double.infinity,
      double height = double.infinity}) {
    return Container(
        decoration: BoxDecoration(
            color: AppColor.whiteTransparentBackground,
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        width: width,
        height: height,
        child: child);
  }

  /// 没有数据
  static Widget noResultView(BuildContext context) {
    return Center(
      child: Text('no_more_data'.tr,
          textAlign: TextAlign.center,
          style: Theme.of(context).textTheme.bodySmall),
    );
  }

  static Widget oneLineText(String text, {TextStyle? style}) {
    return Text(
      text,
      softWrap: true,
      textAlign: TextAlign.left,
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
      style: style,
    );
  }

  ///
  /// 列表的section
  ///
  static Widget sectionOutBox(Widget child, BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.background,
      child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16), child: child),
    );
  }

  ///
  ///
  static Widget lineWidget(String title, Widget right,
      {GestureTapCallback? ontap}) {
    return ontap == null
        ? Padding(
            padding: const EdgeInsets.only(top: 10, bottom: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              mainAxisSize: MainAxisSize.max,
              children: [Text(title), const SizedBox(width: 10), right],
            ))
        : InkWell(
            onTap: ontap,
            child: Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(title),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        right,
                        const Icon(
                          Icons.keyboard_arrow_right,
                          color: AppColor.hintText,
                          size: 22,
                        )
                      ],
                    )
                  ],
                )));
  }

  static Widget rightArrow() {
    return const Icon(
      Icons.keyboard_arrow_right,
      color: AppColor.hintText,
      size: 22,
    );
  }

  ///
  /// 用户头像
  ///
  static Widget personAvatar(String personDn, double radius,
      {Color backgroundColor = Colors.white}) {
    var personIconUrl = OrganizationControlService.to.iconUrl(personDn);
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    return CircleAvatar(
      radius: radius,
      backgroundColor: backgroundColor,
      backgroundImage: NetworkImage(personIconUrl, headers: headers),
    );
  }

  ///
  /// 用户头像 在线Image
  ///
  static Widget personNetworkImage(String personDn) {
    var personIconUrl = OrganizationControlService.to.iconUrl(personDn);
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    return Image.network(personIconUrl, fit: BoxFit.cover, headers: headers);
  }

  /// 底部弹出菜单栏
  ///
  /// 简化
  static void showBottomSheetWithMenuData(
      BuildContext? context, List<SheetMenuData> menus) {
    if (context == null) {
      return;
    }
    if (menus.isEmpty) {
      return;
    }
    final widgets = menus
        .map((e) => ListTile(
              onTap: () {
                Navigator.pop(context);
                e.onTap();
              },
              title: Align(
                alignment: Alignment.center,
                child: Text(e.title,
                    style: Theme.of(context).textTheme.bodyMedium),
              ),
            ))
        .toList();
    showBottomSheetWithCancel(context, widgets);
  }

  /// 底部弹出菜单栏
  static void showBottomSheetWithCancel(
      BuildContext? context, List<Widget> widgets,
      {String? cancelText, VoidCallback? cancelPressed, String? title}) {
    if (widgets.isEmpty) {
      return;
    }
    if (context == null) {
      return;
    }
    cancelText ??= 'cancel'.tr;
    List<Widget> list = [];
    if (title != null && title.isNotEmpty) {
      list.add(Padding(
          padding: const EdgeInsets.only(top: 10, bottom: 20, left: 16, right: 16),
          child: Align(
              alignment: Alignment.center,
              child: Text(title,
                  style: Theme.of(context).textTheme.bodySmall))));
    }
    list.addAll(widgets);
    list.add(Container(
      color: Theme.of(context).colorScheme.background,
      height: 4,
    ));
    list.add(ListTile(
      onTap: () {
        Navigator.pop(context);
        if (cancelPressed != null) {
          cancelPressed();
        }
      },
      title: Align(
        alignment: Alignment.center,
        child: Text(cancelText, style: Theme.of(context).textTheme.bodyLarge),
      ),
    ));

    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SafeArea(child: Wrap(children: list));
        });
  }

  /// 底部弹出菜单栏
  ///
  /// 列表数量多的用这个
  static void showBottomSheetLongList(
      BuildContext? context, List<Widget> widgets,
      {String? cancelText, VoidCallback? cancelPressed, String? title}) {
    if (widgets.isEmpty) {
      return;
    }
    if (context == null) {
      return;
    }
    cancelText ??= 'cancel'.tr;
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SafeArea(
              child: Column(
            children: [
              Visibility(
                  visible: (title != null && title.isNotEmpty),
                  child: Padding(
                      padding: const EdgeInsets.only(top: 10, bottom: 10),
                      child: Align(
                          alignment: Alignment.center,
                          child: Text(title ?? '',
                              style: Theme.of(context).textTheme.bodySmall)))),
              Expanded(
                flex: 1,
                child: ListView(
                  children: widgets,
                ),
              ),
              Container(
                color: Theme.of(context).colorScheme.background,
                height: 4,
              ),
              ListTile(
                onTap: () {
                  Navigator.pop(context);
                  if (cancelPressed != null) {
                    cancelPressed();
                  }
                },
                title: Align(
                  alignment: Alignment.center,
                  child: Text(cancelText!,
                      style: Theme.of(context).textTheme.bodyLarge),
                ),
              )
            ],
          ));
        });
  }

  ///
  /// alert 提示框
  ///
  static void showAlert(BuildContext? context, String message,
      {String? title, String? okText, VoidCallback? okPressed}) {
    if (context != null) {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text(title ?? 'alert'.tr),
              content: Text(message),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (okPressed != null) {
                        okPressed();
                      }
                    },
                    child: Text(okText ?? 'confirm'.tr))
              ],
            );
          });
    }
  }

  ///
  ///确认框
  ///
  static void showConfirm(BuildContext? context, String message,
      {String? title,
      String? okText,
      String? cancelText,
      VoidCallback? okPressed,
      VoidCallback? cancelPressed}) {
    if (context != null) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return AlertDialog(
              title: Text(title ?? 'alert'.tr),
              content: Text(message),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (cancelPressed != null) {
                        cancelPressed();
                      }
                    },
                    child: Text(cancelText ?? 'cancel'.tr)),
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (okPressed != null) {
                        okPressed();
                      }
                    },
                    child: Text(okText ?? 'confirm'.tr))
              ],
            );
          });
    }
  }

  /// 确认框
  static void showConfirmWithActions(
      BuildContext? context, String message, List<DialogActionData> actions,
      {String? title}) {
    if (context != null) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return AlertDialog(
              title: Text(title ?? 'alert'.tr),
              content: Text(message),
              actions: actions
                  .map((e) => TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                        if (e.pressedCall != null) {
                          e.pressedCall!();
                        }
                      },
                      child: Text(e.title ?? 'confirm'.tr)))
                  .toList(),
            );
          });
    }
  }

  ///
  /// 自定义view的dialog
  ///
  static Future<O2DialogAction?> showCustomDialog(
    BuildContext? context,
    String title,
    Widget content, {
    String? positiveBtnText,
    String? cancelBtnText,
  }) {
    if (context == null) {
      return Future.value(null);
    }
    return showDialog<O2DialogAction>(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text(title),
            content: content,
            actions: <Widget>[
              TextButton(
                style: TextButton.styleFrom(
                  foregroundColor: AppColor.hintText,
                ),
                child: Text(cancelBtnText ?? 'cancel'.tr),
                onPressed: () {
                  Navigator.pop(context, O2DialogAction.cancel);
                },
              ),
              TextButton(
                child: Text(positiveBtnText ?? 'confirm'.tr),
                onPressed: () {
                  Navigator.pop(context, O2DialogAction.positive);
                },
              ),
            ],
          );
        });
  }
}
