import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/main/home/controller.dart';
import 'package:flyinsono/pages/user/user_center/controller.dart';
import 'package:get/get.dart';

///用户头像页面
class UserAvatar extends StatelessWidget {
  const UserAvatar({
    Key? key,
    this.size = 70,
    this.borderSize = 0,
    this.borderColor,
  }) : super(key: key);

  /// 头像大小
  final double size;

  /// 边框线大小
  final double borderSize;

  /// 边框颜色
  final Color? borderColor;

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      width: size,
      height: size,
      decoration: BoxDecoration(
        border: borderSize > 0
            ? Border.all(
                color: borderColor ?? Colors.white,
                width: borderSize,
              )
            : null,
        borderRadius: BorderRadius.circular(size),
      ),
      clipBehavior: Clip.antiAlias,
      child: FObx(
        () {
          return FImage(
            image: (Store.user.avatar.isEmpty
                ? AssetImage("assets/images/avatar_man.png")
                : NetworkImage(Store.user.avatar)) as ImageProvider,
            gaplessPlayback: true,
            errorBuilder: (context, error, stackTrace) {
              return FImage.asset(
                'assets/images/avatar_man.png',
                fit: BoxFit.cover,
              );
            },
          );
        },
      ),
    );
  }
}

///用户头像入口页面
class HomeUserAvatarEnterance extends StatelessWidget implements FWidget {
  final _navController = Get.find<HomeNavigatorController>();
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      width: 90,
      alignment: Alignment.center,
      child: FInk(
        child: FInkWell(
          onTap: () => _openUserAvatar(),
          child: UserAvatar(size: 55),
        ),
      ),
    );
  }

  void _openUserAvatar() {
    _navController.onRouterToPersonCenter.emit(this, null);
    _navController.changePage(-1); //清除左导航状态
    if (GetInstance().isRegistered<UserCenterController>()) {
      _navController.backTo(RouteNames.User.Center, true);
      Get.find<UserCenterController>().loadData();
    } else {
      router.offAll(
        RouteNames.User.Center,
        id: NavIds.HOME,
      );
    }
  }
}

///主页中的用户头像菜单
class HomeUserAvatarMenu extends StatelessWidget
    implements FInteractiveContainer {
  HomeUserAvatarMenu({
    this.pageName = 'HomeUserAvatarMenu',
    this.size = 50,
  });

  @override
  final String pageName;

  /// 头像大小
  final double size;

  /// 临时，是否机构管理员
  final _isPrincipal = true;

  /// 下拉菜单控制器
  final _controller = CustomPopupMenuController();

  @override
  FWidget build(BuildContext context) {
    return FCustomPopupMenu(
      controller: _controller,
      position: PreferredPosition.bottom,
      horizontalMargin: 20,
      child: UserAvatar(
        size: size,
        borderSize: 2.8,
      ),
      arrowColor: const Color(
        0xffffffff,
      ),
      arrowSize: 20,
      menuBuilder: () => ClipRRect(
        borderRadius: BorderRadius.circular(
          12,
        ),
        child: FContainer(
          padding: const EdgeInsets.symmetric(
            horizontal: 14,
          ),
          color: const Color(
            0xffffffff,
          ),
          child: FIntrinsicWidth(
            stepWidth: 10,
            child: FColumn(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildAvatar(),
                FDivider(
                  color: Colors.grey[400],
                  thickness: 1,
                  height: 1,
                ),
                _buildMenuItems(),
              ],
            ),
          ),
        ),
      ),
      pressType: PressType.singleClick,
    );
  }

  FWidget _buildMenuItems() {
    return FContainer(
      padding: EdgeInsets.symmetric(vertical: 18),
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          if (_isPrincipal) ...[
            _FunctionItem(
              this,
              Icons.home_outlined,
              i18nBook.homePage.organizationInfo.t,
              () {
                PromptBox.toast(i18nBook.common.underDevelopment.t);
              },
            ),
            _FunctionItem(
              this,
              Icons.receipt_long_sharp,
              i18nBook.user.orgTemplate.t,
              () {
                PromptBox.toast(i18nBook.common.underDevelopment.t);
              },
            ),
            _FunctionItem(
              this,
              Icons.devices_other_sharp,
              i18nBook.homePage.organizationDevices.t,
              () {
                PromptBox.toast(i18nBook.common.underDevelopment.t);
              },
            ),
            _FunctionItem(
              this,
              Icons.collections_bookmark_outlined,
              i18nBook.homePage.organizationEntries.t,
              () {
                PromptBox.toast(i18nBook.common.underDevelopment.t);
              },
            ),
          ],
          _FunctionItem(
            this,
            Icons.exit_to_app_sharp,
            i18nBook.auth.signOut.t,
            () async {
              Store.app.setBusy(i18nBook.homePage.loginingOut.t);
              await Store.user.handelLogOut();
              Store.app.cancelBusy();
              router.offAll(RouteNames.Auth.AuthBoard);
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildAvatar() {
    return FContainer(
      padding: const EdgeInsets.symmetric(
        vertical: 18,
      ),
      child: FRow(
        children: [
          FContainer(
            padding: EdgeInsets.symmetric(
              horizontal: 12,
            ),
            child: FInk(
              child: FInkWell(
                onTap: () {
                  _controller.hideMenu();
                  Future.microtask(
                    () {
                      router.offAll(
                        RouteNames.User.Center,
                        id: NavIds.HOME,
                      );
                    },
                  );
                },
                child: const UserAvatar(
                  size: 55,
                ),
              ),
            ),
          ),
          FContainer(
            margin: const EdgeInsets.only(
              left: 6,
            ),
            padding: const EdgeInsets.only(
              top: 8,
            ),
            constraints: BoxConstraints(
              maxWidth: _isPrincipal ? 200 : 130,
            ),
            child: FObx(
              () => FText(
                Store.user.displayName,
                style: TextStyle(
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

///功能条目
class _FunctionItem extends FStatelessWidget {
  const _FunctionItem(
      this.businessParent, this.iconData, this.title, this.onTap);
  final FInteractiveContainer businessParent;
  final IconData iconData;
  final String title;
  final VoidCallback onTap;

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      margin: const EdgeInsets.symmetric(horizontal: 6),
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          businessParent: businessParent,
          name: title,
          onTap: onTap,
          child: FColumn(
            children: [
              FIcon(
                iconData,
                size: 30,
              ),
              FText(
                title,
                style: TextStyle(
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
