part of login;

enum LoginType { code, password }

class LoginController extends GetxController {
  // 0：密码登录  1：验证码登录
  late int loginType = 0;
  // 2、密码登录
  // 账号
  final TextEditingController phoneInput = TextEditingController();
  // 密码
  final TextEditingController passwordInput = TextEditingController();
  // 验证码
  final TextEditingController codeInput = TextEditingController();
  // 显示密码
  final ValueNotifier<bool> showPassword = ValueNotifier(false);
  // 定时器
  late Timer _timer;
  // 按钮是否可用
  bool _enable = false;
  bool get enable => _enable;

  // 倒计时60秒
  int _countDown = 60;
  int get countDown => _countDown;
  bool _isCounting = false;
  bool get isCounting => _isCounting;
  // 同意协议
  bool _agree = false;
  bool get agree => _agree;

  @override
  void onInit() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // 定时器回调
    });

    /// 测试账号
    if (kDebugMode) {
      phoneInput.text = '13811534871';
      passwordInput.text = 'wpf123456*';
      // phoneInput.text = '18810760819';
      // passwordInput.text = '1234567m';
      // phoneInput.text = '17311837355';
      // passwordInput.text = '12345678';
    }
    super.onInit();
  }

  @override
  void onClose() {
    phoneInput.dispose();
    passwordInput.dispose();
    showPassword.dispose();
    codeInput.dispose();
    _timer.cancel();
    _isCounting = false;
    super.onClose();
  }

  void onShowPassword() => showPassword.value = !showPassword.value;

  /// 同意与否
  void setAgree() {
    _agree = !_agree;
    update();
  }

  /// 开启定时器
  void start() {
    _isCounting = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countDown > 1) {
        _countDown--;
      } else {
        stop();
      }
      update();
    });
  }

  /// 停止计时器
  void stop() {
    if (_timer != null) {
      _timer.cancel();
      _isCounting = false;
    }
    _countDown = 60;
  }

  /// 是否可点击
  void setCanClick() {
    if (loginType == 0) {
      if (ValidatorTool.isValidPhoneNumber(phoneInput.text) &&
          ValidatorTool.isValidPassword(passwordInput.text)) {
        _enable = true;
      } else {
        _enable = false;
      }
    } else {
      if (ValidatorTool.isValidPhoneNumber(phoneInput.text) &&
          ValidatorTool.isValidCode(codeInput.text)) {
        _enable = true;
      } else {
        _enable = false;
      }
    }

    update();
  }

  /// 跟新登录类型
  void updateLoginType(int value) {
    stop();
    loginType = value;
    update();
  }

  /// 显示用户协议弹框
  Future<bool> _showAgreementDialog(BuildContext context) async {
    await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0.w),
          ),
          contentPadding: EdgeInsets.zero,
          title: Center(
            child: Padding(
              padding: EdgeInsets.only(top: 24.w),
              child: Text(
                '用户协议及隐私协议',
                style: TextStyle(
                  fontSize: 16.w,
                  fontWeight: Fonts.medium,
                  color: Colours.c3,
                ),
              ),
            ),
          ),
          content: Wrap(
            children: [
              Container(
                margin: EdgeInsets.only(top: 20.w, bottom: 29.w),
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Center(
                  child: Text(
                    '已阅读并同意《用户协议》、《隐私政策》',
                    style: TextStyle(
                      fontSize: 14.w,
                      color: Colours.c6,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
              Container(
                height: 1.w,
                width: double.infinity,
                color: Colours.cLine,
              ),
            ],
          ),
          actionsPadding: EdgeInsets.zero,
          actions: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    width: 105.w,
                    height: 39.5.w,
                    color: Colours.cFF,
                    alignment: Alignment.center,
                    child: Text(
                      '不同意',
                      style: TextStyle(
                        fontSize: 15.w,
                        fontWeight: Fonts.medium,
                        color: Colours.c6,
                      ),
                    ),
                  ),
                ),
                Container(
                  height: 39.5.w,
                  width: 1,
                  color: Colours.cLine,
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                    setAgree();
                  },
                  child: Container(
                    width: 105.w,
                    height: 39.5.w,
                    color: Colours.cFF,
                    alignment: Alignment.center,
                    child: Text(
                      '同意',
                      style: TextStyle(
                        fontSize: 15.w,
                        fontWeight: Fonts.boldSemi,
                        color: Colours.cAB1941,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
    return agree;
  }

  /// 登录
  void onLogin(BuildContext context) async {
    Tools.unfocus();
    if (!agree) {
      await _showAgreementDialog(context);
      if (!agree) return;
    }

    String type = '1';
    if (loginType == 1) {
      type = '2';
    }
    final result = await AccountAPI.login(
        phone: phoneInput.text,
        password:
            EncryptUtil.encodeMd5(EncryptUtil.encodeMd5(passwordInput.text)),
        code: codeInput.text,
        type: type);

    if ((result.token ?? '').isEmpty) return;

    // 存储用户信息
    await Future.wait([UserStore.to.login(result)]);
    // await Future.wait([
    //    UserStore.to.setToken(result.token!),
    //    UserStore.to.setAccessToken(result.accessToken!),
    //
    // ]);
    //
    // await Future.wait([
    //   UserStore.to.setInfo(result),
    //   UserStore.to.profile(),
    // ]);

    if (context.mounted) {
      // context.goNamed(Routes.main);
      Future.delayed(const Duration(milliseconds: 10)).then((value) {
        context.pop();
      });
    } else {
      context.goNamed(Routes.main);
    }
  }

  /// 发送验证码
  void sendCode() async {
    if (!agree) {
      await _showAgreementDialog(Get.context!);
      if (!agree) return;
    }
    final result =
        await AccountAPI.sendCode(phone: phoneInput.text, type: 'login');
    if (result) {
      Toast.show('发送成功');
      start();
    } else {
      Toast.show('发送失败');
    }
  }
}
