import 'dart:async';
import 'dart:convert';

import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';

import '../../account_center.dart';
import 'login_state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  @override
  void onInit() {
    Future.delayed(Duration(seconds: 1)).then((value) {
      checkLogic();
    });
    super.onInit();
  }

  void checkLogic() {
    if (getToken()?.isNotEmpty == true) {
      showDialog(
        context: Get.context!,
        builder: (BuildContext context) {
          return CustomAlertDialog();
        },
      );
    }
  }

  // 密码登陆
  void loginByPassword() {
    var phone = state.uNameController.value.text;
    var pwd = state.pwdController.value.text;

    if (phone.isEmpty) {
      ToastUtil.showToast("请输入用户名");
      return;
    }

    if (state.isPwdLogin && pwd.isEmpty) {
      ToastUtil.showToast("请输入密码");
      return;
    }

    // if (phone.length != 11) {
    //   ToastUtil.showToast("用户名不合法");
    //   return;
    // }
    //
    // if (state.isPwdLogin && pwd.length < 6) {
    //   ToastUtil.showToast("密码不能小于6位");
    //   return;
    // }
    if (state.isPwdLogin) {
      KeyBoardUtils.hideKeyboard();
      var content = Utf8Encoder().convert(pwd);
      var digest = md5.convert(content);
      var requestParams = {
        "productCode": AccountCenter.ownerProductCode,
        "pwd": digest.toString(),
        "userMobile": phone
      };
      fetch(Method.post, url: HttpApi.loginPwd, params: requestParams,
          onSuccess: (data) {
        _onLoginSuccess(data);
      });
    }
  }

  void _onLoginSuccess(data) {
    SpUtil.putString(SPKey.token, data['token'])?.then((value) {});
    ToastUtil.showToast("登录成功");
    Get.offAllNamed(
      RouteConfig.accountCenterPage,
      arguments: {'token': data['token']},
    );
  }

  // 验证码登陆
  void loginByCode() {
    var phone = state.uNameController.value.text;
    var code = state.codeController.value.text;
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    if (phone.isEmpty) {
      ToastUtil.showToast("请输入用户名");
      return;
    }

    if (!state.isPwdLogin && code.isEmpty) {
      ToastUtil.showToast("请输入验证码");
      return;
    }

    if (code.length != 6) {
      ToastUtil.showToast("请输入6位验证码");
      return;
    }

    if (phone.length != 11) {
      ToastUtil.showToast("用户名不合法");
      return;
    }

    if (!state.isPwdLogin) {
      // 验证码登录
      fetch(Method.post, url: HttpApi.loginByCode, params: {
        "productCode": AccountCenter.ownerProductCode,
        "captcha": code,
        "userMobile": phone
      }, onSuccess: (data) {
        _onLoginSuccess(data);
      });
    }
  }
}

class CustomAlertDialog extends StatefulWidget {
  @override
  _CustomAlertDialogState createState() => _CustomAlertDialogState();
}

class _CustomAlertDialogState extends State<CustomAlertDialog> {
  int _counter = 2;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // 启动定时器
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_counter > 0) {
          _counter--;
        } else {
          // 到达倒计时结束，关闭弹窗
          Navigator.of(context).pop();
          Get.offAllNamed(
            RouteConfig.accountCenterPage,
            arguments: {'token': getToken()},
          );
        }
      });
    });
  }

  @override
  void dispose() {
    // 销毁定时器
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('提示'),
      content: Text('正在自动登录-- $_counter--'),
      actions: <Widget>[
        TextButton(
          onPressed: () {
            // 关闭弹窗
            Navigator.of(context).pop();
          },
          child: Text('取消'),
        ),
      ],
    );
  }
}
