import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';
import 'package:wallpaperx/entity/userinfo_model.dart';
import 'package:wallpaperx/page/home/home_controller.dart';
import 'package:wallpaperx/page/settings/settings_controller.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class LoginController extends GetxController with WidgetsBindingObserver {
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  FocusNode usernameFocusNode = FocusNode();
  FocusNode passwordFocusNode = FocusNode();

  bool usernameEmpty = false;
  bool passwordEmpty = false;

  HomeController homeController = Get.find<HomeController>();
  SettingsController settingsController = Get.find<SettingsController>();

  Timer? _timer;

  @override
  void onClose() {
    super.onClose();
    usernameController.dispose();
    passwordController.dispose();
    usernameFocusNode.dispose();
    passwordFocusNode.dispose();
    _stopTimer();
  }

  login({String? username, String? password}) {
    username = usernameController.value.text;
    password = passwordController.value.text;
    if (username.isEmpty) {
      toast('Please enter username');
      usernameEmpty = true;
      update(["loginInfo"]);
      return;
    } else {
      update(["loginInfo"]);
      usernameEmpty = false;
    }
    if (password.isEmpty) {
      toast('Please enter password');
      passwordEmpty = true;
      update(["loginInfo"]);
      return;
    } else {
      passwordEmpty = false;
      update(["loginInfo"]);
    }
    loading(show: true);
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      dismiss(dismiss: true);
      var map = UPCache.getInstance().getJson(username);
      if (map == null) {
        toast('Account does not exist');
        _stopTimer();
        return;
      }
      if (map["password"] == password) {
        toast('Login success');
        UPCache.getInstance().setData("loginAccount", username);
        homeController.userinfo = UserinfoModel.fromJson(map);
        settingsController.update(["userinfo"]);
        _stopTimer();
        Get.back();
      } else {
        toast('Incorrect password');
        _stopTimer();
      }
    });
  }

  void toUserEdit() {
    Get.toNamed(AppPages.editUserinfo, arguments: {
      'title': 'Register',
    });
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
