import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/style/index.dart';
import '../../common/utils/index.dart';
import '../../common/widgets/index.dart';
import '../../environment_config.dart';
import 'index.dart';

class LoginPage extends GetView<LoginController> {
  const LoginPage({Key? key}) : super(key: key);

  // 头部 logo和名称
  Widget _buildLogo(BuildContext context) {
    return Container(
      width: 110,
      margin: const EdgeInsets.only(top: 84), // 顶部系统栏 44px
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 84,
            width: 84,
            margin: const EdgeInsets.symmetric(horizontal: 15),
            child: Stack(
              alignment: Alignment.center,
              children: [
                Positioned(
                  left: 0,
                  top: 0,
                  right: 0,
                  child: Container(
                    height: 84,
                    decoration: BoxDecoration(
                      color: Theme.of(context).scaffoldBackgroundColor,
                      boxShadow: const [Shadows.primaryShadow],
                      borderRadius: const BorderRadius.all(
                          Radius.circular(42)), // 父容器的50%
                    ),
                    child: Container(),
                  ),
                ),
                Positioned(
                  top: 4,
                  child: ClipOval(
                      child: ProgramCenterService.to.loginAvatarImageView()),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: GestureDetector(
                onLongPress: () => controller.openConfig(),
                child: Text(
                  'appName'.tr,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.secondary,
                    fontFamily: "Montserrat",
                    fontWeight: FontWeight.w600,
                    fontSize: 24,
                    height: 1,
                  ),
                )),
          ),
        ],
      ),
    );
  }

  // 底部copyright
  Widget _buildBottom() {
    return Obx(() => Container(
          margin: const EdgeInsets.only(bottom: 10),
          child: Align(
            alignment: Alignment.center,
            child: Text(
                'copy_right'.trArgs(['appName'.tr, controller.state.year])),
          ),
        ));
  }

  // 表单
  Widget _buildInputForm(BuildContext context) {
    return Obx(() => Container(
          width: 295,
          margin: const EdgeInsets.only(top: 49),
          child: Column(children: [
            // 账号输入框
            TextField(
              maxLines: 1,
              autofocus: true,
              style: Theme.of(context).textTheme.bodyMedium,
              keyboardType: TextInputType.text,
              textInputAction: TextInputAction.next,
              controller: controller.userNameController,
              onEditingComplete: () {
                if (controller.state.isPasswordLogin) {
                  FocusScope.of(context).requestFocus(controller.passwordNode);
                } else {
                  FocusScope.of(context).requestFocus(controller.codeNode);
                }
              },
              decoration: InputDecoration(
                labelText: 'login_form_user_name'.tr,
                prefixIcon: Icon(Icons.person,
                    color: Theme.of(context).colorScheme.secondary),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            // 密码或短信验证码 输入框
            controller.state.isPasswordLogin
                ? _passwordModeTextFormField(context)
                : _codeModeTextFormField(context),
            const SizedBox(
              height: 16,
            ),
            // 登录按钮
            SizedBox(
              width: double.infinity,
              height: 42,
              child: O2ElevatedButton(
                () {
                  controller.login();
                },
                Text('login'.tr),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Row(
              children: [
                //切换登录模式
                Expanded(
                  child: Visibility(
                      visible: controller.state.isShowChangeLoginModeButton,
                      child: TextButton(
                          onPressed: () => controller.changeLoginMode(),
                          child: Text(
                              controller.state.isPasswordLogin
                                  ? 'login_form_change_login_mode_code'.tr
                                  : 'login_form_change_login_mode_password'.tr,
                              style: Theme.of(context).textTheme.bodySmall))),
                ),
                Expanded(
                    child: EnvironmentConfig.isDirectConnectMode()
                        ? Visibility(
                            visible: controller.state.registerEnable,
                            child: TextButton(
                                onPressed: () => controller.gotoRegister(),
                                child: Text('login_to_register'.tr,
                                    style:
                                        Theme.of(context).textTheme.bodySmall)))
                        : TextButton(
                            onPressed: () => controller.rebind(),
                            child: Text('login_form_rebind'.tr,
                                style: Theme.of(context).textTheme.bodySmall)))
              ],
            ),
            const SizedBox(
              height: 16,
            ),
            Visibility(
                visible: controller.state.isVisibleAgree,
                child: Row(
                  children: [
                    Obx(() => Checkbox(
                          value: controller.state.isAgree,
                          onChanged: (value) => controller.changeAgree(value),
                        )),
                    Expanded(
                        flex: 1,
                        child: RichText(
                          maxLines: 2,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                          text: TextSpan(
                              text: 'privacy_policy_bind_content_part1'.tr,
                              style: Theme.of(context).textTheme.bodySmall,
                              children: [
                                TextSpan(
                                    text: 'user_agreement_book_mark'.tr,
                                    style: TextStyle(
                                        color: Theme.of(context)
                                            .colorScheme
                                            .primary,
                                        fontSize: 12),
                                    recognizer: TapGestureRecognizer()
                                      ..onTap =
                                          () => controller.openUserAgreement()),
                                TextSpan(
                                  text:
                                      'privacy_policy_dialog_content_part2'.tr,
                                  style: Theme.of(context).textTheme.bodySmall,
                                ),
                                TextSpan(
                                    text: 'privacy_policy_book_mark'.tr,
                                    style: TextStyle(
                                        color: Theme.of(context)
                                            .colorScheme
                                            .primary,
                                        fontSize: 12),
                                    recognizer: TapGestureRecognizer()
                                      ..onTap =
                                          () => controller.openPrivacyPolicy()),
                              ]),
                        ))
                  ],
                ))
          ]),
        ));
  }

  ///
  /// 密码登录
  ///
  Widget _passwordModeTextFormField(BuildContext context) {
    return Obx(() {
      if (controller.state.isCaptcha) {
        return Column(
          children: [
            TextField(
              maxLines: 1,
              obscureText: true,
              style: Theme.of(context).textTheme.bodyMedium,
              focusNode: controller.passwordNode,
              controller: controller.passwordController,
              textInputAction: TextInputAction.next,
              onEditingComplete: () {
                FocusScope.of(context).requestFocus(controller.captchaNode);
              },
              decoration: InputDecoration(
                labelText: 'login_form_user_password'.tr,
                prefixIcon: Icon(Icons.lock,
                    color: Theme.of(context).colorScheme.secondary),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: TextField(
                      maxLines: 1,
                      style: Theme.of(context).textTheme.bodyMedium,
                      keyboardType: TextInputType.number,
                      focusNode: controller.captchaNode,
                      controller: controller.captchaController,
                      textInputAction: TextInputAction.done,
                      decoration: InputDecoration(
                        labelText: 'login_form_user_code'.tr,
                        prefixIcon: Icon(Icons.lock,
                            color: Theme.of(context).colorScheme.secondary),
                      ),
                    )),
                controller.state.captchaBase64String.isEmpty
                    ? TextButton(
                        onPressed: () {
                          controller.getCaptchaImageData();
                        },
                        child: const Text('点击刷新'))
                    : InkWell(
                        onTap: () {
                          controller.getCaptchaImageData();
                        },
                        child: Image.memory(
                          controller.parseCaptchaImg(),
                          width: 100,
                          height: 50,
                          fit: BoxFit.cover,
                        ),
                      )
              ],
            )
          ],
        );
      } else {
        return TextField(
          maxLines: 1,
          obscureText: true,
          style: Theme.of(context).textTheme.bodyMedium,
          focusNode: controller.passwordNode,
          controller: controller.passwordController,
          textInputAction: TextInputAction.done,
          decoration: InputDecoration(
            labelText: 'login_form_user_password'.tr,
            prefixIcon: Icon(Icons.lock,
                color: Theme.of(context).colorScheme.secondary),
          ),
        );
      }
    });
  }

  ///
  /// 短信验证码登录
  ///
  Widget _codeModeTextFormField(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: TextField(
            maxLines: 1,
            obscureText: true,
            style: Theme.of(context).textTheme.bodyMedium,
            keyboardType: TextInputType.text,
            controller: controller.codeController,
            focusNode: controller.codeNode,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              labelText: 'login_form_user_code'.tr,
              prefixIcon: Icon(Icons.lock,
                  color: Theme.of(context).colorScheme.secondary),
            ),
          ),
        ),
        Expanded(
            flex: 1,
            child: CountDownButton(() {
              return controller.onCheckMobile();
            }, () {
              OLogger.d('发送短信。。。。');
              controller.sendSmsCode();
            }))
      ],
    );
  }

  /// 双因素认证第二步
  Widget _buildTwoFactorAuthForm(BuildContext context) {
    return Obx(() => Container(
        width: 295,
        margin: const EdgeInsets.only(top: 49),
        child: Column(children: [
          TextField(
            maxLines: 1,
            obscureText: true,
            style: Theme.of(context).textTheme.bodyMedium,
            keyboardType: TextInputType.text,
            controller: controller.twoFactorCodeController,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              labelText: 'login_form_user_code'.tr,
              prefixIcon: Icon(Icons.lock,
                  color: Theme.of(context).colorScheme.secondary),
            ),
          ),
          const SizedBox(
            height: 16,
          ),
          // 登录按钮
          SizedBox(
            width: double.infinity,
            height: 42,
            child: O2ElevatedButton(
              () {
                controller.loginTwofactorStepTwo();
              },
              Text('two_factor_login'.tr),
            ),
          ),
          const SizedBox(
            height: 16,
          ),
          TextButton(
              onPressed: () => controller.twoFactorBackLogin(),
              child: Text('two_factor_back'.tr,
                  style: Theme.of(context).textTheme.bodySmall))
        ])));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginController>(
      builder: (_) {
        return Scaffold(
          // resizeToAvoidBottomInset: false,
          body: PageScrollContentWidget(
            contentWidget: Column(
              children: <Widget>[
                _buildLogo(context),
                Obx(() => controller.state.twoFactorLogin
                    ? _buildTwoFactorAuthForm(context)
                    : _buildInputForm(context)),
                const Spacer(),
                _buildBottom(),
              ],
            ),
          ),
        );
      },
    );
  }
}
