import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/utils/window__change_helpler.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/pages/others/title_bar_buttons.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'controller.dart';
import 'state.dart';
import 'widgets/scan_button.dart';

///授权页面
class AuthBoardPage extends FisView<AuthBoardController> implements FPage {
  @override
  String pageName;

  AuthBoardPage({this.pageName = 'AuthBoardPage', Key? key}) : super(key: key);

  /// 当前主页面的高度
  static double bodyHeight = 0;

  @override
  FWidget build(BuildContext context) {
    if (FPlatform.isWindows || FPlatform.isMacOS) {
      rpc.platform.setLoginUserInfoAsync("");
    }
    if (!AuthBoardState.hasRoutePass) {
      // 清除首次入场效果
      Future.delayed(Duration(milliseconds: 500), () {
        AuthBoardState.hasRoutePass = true;
      });
    }
    // 供给子页面计算罩层位置
    controller.currentContext = context;
    return context.fResponsive(
      mobile: (_) => _MobileLayout(this),
      desktop: (_) => _DesktopLayout(this),
    );
  }
}

///授权页面桌面端布局

class _DesktopLayout extends FisView<AuthBoardController> implements FWidget {
  static double _cardWidth = 430.sp, _cardHeight = 590.sp;
  static double _illustrationWidth = 520.sp, _illustrationHeight = 440.sp;
  static double _borderRadius = 10.sp;
  final FPage businessParent;

  _DesktopLayout(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final bool isNormalSize = size.width > 900;
    final cardRightOffset = isNormalSize
        ? (size.width / 2 - _cardWidth) * 0.52
        : (size.width - _cardWidth) / 2;
    double cardTopOffset = (size.height - _cardHeight) / 2;
    if (!isNormalSize) {
      cardTopOffset += 20.sp;
    }

    return FStack(
      children: [
        _ColorBackgroundLayer(
          color: const Color.fromARGB(
            255,
            239,
            246,
            255,
          ),
        ),
        _ImageBackgroundLayer(),
        if (isNormalSize) ...[
          _buildIllustrationLayer((size.width / 2 - _illustrationWidth) * 0.67),
          _buildLogoLayer(
            height: 160.sp,
            top: 20.sp,
            left: 60.sp,
          ),
        ] else
          _buildLogoLayer(
            width: _cardWidth,
            height: 120.sp,
            top: cardTopOffset - 120.sp,
            right: cardRightOffset + 20.sp,
          ),
        _buildCardLayer(
          cardTopOffset,
          cardRightOffset,
          _AuthBody(
            width: _cardWidth,
            height: _cardHeight,
            padding: EdgeInsets.fromLTRB(
              22.sp,
              50.sp,
              22.sp,
              40.sp,
            ),
          ),
        ),
        FObx(() {
          controller.state.currentIndex;

          ///Todo:finlay  推车不显示最小化及关闭按钮
          if (FPlatform.isWindows && !CartSystemPlatform.isCartSystemVersion) {
            return FPositioned(
              top: 0,
              right: 5,
              child: TitleBarButtons(
                WindowChangeHelper.onMinimize,
                WindowChangeHelper.onClose,
                null,
                FTheme.ins.colorScheme.secondary,
                Colors.transparent,
                hoverColor: Color.fromARGB(255, 102, 194, 255),
                hoverIconColor: Colors.white,
              ),
            );
          } else {
            return FSizedBox();
          }
        }),
      ],
    );
  }

  FWidget _buildIllustrationLayer(double left) {
    return FPositioned(
      top: 0,
      bottom: 0,
      left: left,
      child: FContainer(
        width: _illustrationWidth,
        height: _illustrationHeight,
        child: FImage.asset(
          "assets/images/auth/illustration.png",
          fit: BoxFit.fitWidth,
        ),
      ),
    );
  }

  FWidget _buildLogoLayer({
    required double top,
    double? width,
    required double height,
    double? left,
    double? right,
  }) {
    if (Global.isRemoveLogo) {
      return FSizedBox();
    }
    return FPositioned(
      top: top,
      left: left,
      right: right,
      child: FContainer(
        width: width,
        child: FCenter(
          child: FImage.asset(
            _getLogoPngByLanguage(),
            height: height,
          ),
        ),
      ),
    );
  }

  String _getLogoPngByLanguage() {
    if (i18nBook.isCurrentChinese) {
      return "assets/images/logo_zh_white.png";
    } else if (i18nBook.isCurrentEnglish) {
      return "assets/images/logo_en_white.png";
    } else if (i18nBook.isCurrentRussian) {
      return "assets/images/logo_ru_white.png";
    } else {
      return "assets/images/logo_en_white.png";
    }
  }

  FWidget _buildCardLayer(
    double top,
    double right,
    FWidget cardLayerChild,
  ) {
    return FPositioned(
      top: top,
      right: right,
      child: FCard(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
            _borderRadius,
          ),
        ),
        color: Color.fromARGB(255, 247, 251, 255),
        elevation: 10,
        child: cardLayerChild,
      ),
    );
  }
}

///授权页面Body
class _AuthBody extends FisView<AuthBoardController> implements FWidget {
  const _AuthBody({
    required this.width,
    required this.height,
    this.padding,
  });

  final double width;
  final double height;
  final EdgeInsetsGeometry? padding;

  @override
  FWidget build(BuildContext context) {
    final view = _PageNavigator();
    return FStack(
      children: [
        FContainer(
          width: width,
          height: height,
          padding: padding,
          child: view,
        ),
        _buildQRCodeButton(),
      ],
    );
  }

  FWidget _buildQRCodeButton() {
    if (kIsMobile) {
      return FSizedBox();
    }
    return FObx(() {
      ///非登录页面不显示
      if (controller.state.currentIndex != 0) {
        return FSizedBox();
      }
      return FPositioned(
        top: 0,
        right: 0,
        child: FDiagonalContainer(
          controller.onSwitchQRLogin,
          FTheme.ins.colorScheme.secondary,
          FTheme.ins.colorScheme.primary,
        ),
      );
    });
  }
}

///页面导航
class _PageNavigator extends FisView<AuthBoardController> implements FWidget {
  @override
  FWidget build(BuildContext context) {
    final navNative = FNavigator(
      key: Get.nestedKey(NavIds.AUTH_BOARD),
      initialRoute: RouteNames.Auth.SignIn,
      onGenerateRoute: controller.onGenerateRoute,
    );
    return navNative;
  }
}

///图片背景层
class _ImageBackgroundLayer extends FStatelessWidget {
  @override
  FWidget build(BuildContext context) {
    return FSizedBox.expand(
      child: FImage.asset(
        "assets/images/auth/background.png",
        fit: BoxFit.cover,
      ),
    );
  }
}

///颜色背景层
class _ColorBackgroundLayer extends FStatelessWidget {
  _ColorBackgroundLayer({
    required this.color,
  });

  final Color color;

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      width: double.infinity,
      height: double.infinity,
      color: this.color,
    );
  }
}

///授权页面移动端布局
class _MobileLayout extends FStatelessWidget {
  final FPage businessParent;
  _MobileLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    final double offsetTop = MediaQuery.of(context).padding.top + 28.sp;
    final illustrationWidth = 0.6.sw;
    final illustrationDisplayHeight = illustrationWidth * .85 * .7;
    final panelOffsetTop = illustrationDisplayHeight + offsetTop;
    AuthBoardPage.bodyHeight =
        MediaQuery.of(context).size.height - panelOffsetTop;
    return FScaffold(
      body: FStack(
        children: [
          _ColorBackgroundLayer(
            color: FTheme.ins.colorScheme.primary,
          ),
          _buildIllustration(
            illustrationWidth,
            offsetTop,
          ),
          _buildPanel(
            context,
            illustrationDisplayHeight + offsetTop,
            52,
          ),
        ],
      ),
    );
  }

  FWidget _buildPanel(BuildContext context, double topOffset,
      [double borderRadiusWidth = 50]) {
    final borderRadius = Radius.circular(borderRadiusWidth.sp);
    final size = MediaQuery.of(context).size;
    return FPositioned(
      top: topOffset,
      child: FGestureDetector(
        businessParent: this.businessParent,
        name: 'HideTextInput',
        onTap: () {
          SystemChannels.textInput.invokeMethod('TextInput.hide');
        },
        child: FContainer(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: borderRadius,
              topRight: borderRadius,
            ),
            boxShadow: [
              BoxShadow(
                color: FColorHelper.mixColor(
                  FTheme.ins.colorScheme.primary,
                  Colors.black,
                  70,
                ),
                offset: const Offset(0.0, -6.0), //阴影y轴偏移量
                blurRadius: 20, //阴影模糊程度
                spreadRadius: 0, //阴影扩散程度
              ),
            ],
          ),
          width: size.width,
          height: size.height - topOffset,
          child: _buildPanelColumn(
            context,
            topOffset,
          ),
        ),
      ),
    );
  }

  FWidget _buildPanelColumn(BuildContext context, double topOffset,
      [double borderRadiusWidth = 50]) {
    final size = MediaQuery.of(context).size;
    final paddingTop = borderRadiusWidth.sp * .85;
    final logoHeight = 46.sp;
    double renderedHeight = topOffset + paddingTop + logoHeight;
    return FColumn(
      children: [
        FSizedBox(height: paddingTop),
        FContainer(
          height: logoHeight,
          child: FCenter(
            child: FImage.asset(
              _getLogoPngByLanguage(),
              fit: BoxFit.fitHeight,
            ),
          ),
        ),
        _AuthBody(
          height: size.height - renderedHeight,
          width: size.width,
          padding: EdgeInsets.fromLTRB(
            0.1.sw,
            0,
            0.1.sw,
            18.sp,
          ),
        ),
      ],
    );
  }

  String _getLogoPngByLanguage() {
    if (i18nBook.isCurrentChinese) {
      return "assets/images/logo_blue_zh.png";
    } else if (i18nBook.isCurrentEnglish) {
      return "assets/images/logo_blue_en.png";
    } else if (i18nBook.isCurrentRussian) {
      return "assets/images/logo_blue_ru.png";
    } else {
      return "assets/images/logo_blue_en.png";
    }
  }

  FWidget _buildIllustration(double width, double topOffset) {
    return FPositioned(
      top: topOffset,
      left: 0,
      right: 0,
      child: FCenter(
        child: FContainer(
          width: width,
          alignment: Alignment.center,
          child: FImage.asset(
            "assets/images/auth/illustration.png",
            fit: BoxFit.fitWidth,
          ),
        ),
      ),
    );
  }
}
