import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.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/generated/assets.dart';
import 'package:wallpaperx/page/home/home_controller.dart';
import 'package:wallpaperx/page/settings/settings_controller.dart';

class EditUserinfoController extends GetxController {
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  FocusNode usernameFocusNode = FocusNode();
  FocusNode emailFocusNode = FocusNode();
  FocusNode passwordFocusNode = FocusNode();

  bool usernameEmpty = false;
  bool passwordEmpty = false;
  bool emailEmpty = false;

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

  late String title;
  Timer? _timer;

  RxString avatar = Assets.iconPlaceholderAvatar.obs;

  List<String> defaultAvatarList = [
    'assets/avatar/avatar_1.png',
    'assets/avatar/avatar_2.png',
    'assets/avatar/avatar_3.png',
    'assets/avatar/avatar_4.png',
    'assets/avatar/avatar_5.png',
  ];

  @override
  void onInit() {
    super.onInit();
    title = Get.arguments['title'];
    var loginAccount = UPCache.getInstance().get("loginAccount");
    var map = UPCache.getInstance().getJson(loginAccount ?? "");
    if (map != null) {
      final userinfo = UserinfoModel.fromJson(map);
      avatar.value = userinfo.avatar ?? Assets.iconPlaceholderAvatar;
      usernameController.value =
          TextEditingValue(text: userinfo.username ?? "");
      emailController.value = TextEditingValue(text: userinfo.email ?? "");
      passwordController.value =
          TextEditingValue(text: userinfo.password ?? "");
    }
  }

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

  editUserInfo({UserinfoModel? userinfoModel}) {
    String username = usernameController.value.text;
    String password = passwordController.value.text;
    String email = emailController.value.text;
    if (username.isEmpty) {
      toast('Please enter username');
      usernameEmpty = true;
      update(["loginInfo"]);
      return;
    } else {
      update(["loginInfo"]);
      usernameEmpty = false;
    }
    if (email.isEmpty) {
      toast('Please enter email');
      emailEmpty = true;
      update(["loginInfo"]);
      return;
    } else {
      emailEmpty = false;
      update(["loginInfo"]);
    }
    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 loginAccount = UPCache.getInstance().get("loginAccount");
      var userinfo = {
        "avatar": avatar.value,
        "username": username,
        "password": password,
        "email": email,
      };
      if (loginAccount == null) {
        UPCache.getInstance().setData("loginAccount", username);
        UPCache.getInstance().setJson(username, userinfo);
        homeController.userinfo = UserinfoModel.fromJson(userinfo);
        settingsController.update(["userinfo"]);
        Get.back();
        Get.back();
      } else {
        UPCache.getInstance().setData("loginAccount", username);
        UPCache.getInstance().remove(loginAccount);
        UPCache.getInstance().setJson(username, userinfo);
        homeController.userinfo = UserinfoModel.fromJson(userinfo);
        settingsController.update(["userinfo"]);
        Get.back();
      }
    });
  }

  changeAvatar() {
    Get.bottomSheet(
      Container(
        padding: EdgeInsets.all(10.w),
        width: double.infinity,
        height: 300.w,
        child: MasonryGridView.count(
          itemCount: defaultAvatarList.length,
          crossAxisCount: 3,
          mainAxisSpacing: 20.w,
          crossAxisSpacing: 21.w,
          padding: const EdgeInsets.fromLTRB(16, 0, 16, 0).w,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {
                avatar.value = defaultAvatarList[index];
                Get.back();
              },
              child: Container(
                clipBehavior: Clip.hardEdge,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50).r,
                ),
                child: Image.asset(
                  defaultAvatarList[index],
                  width: 100.w,
                ),
              ),
            );
          },
        ),
      ),
      backgroundColor: Colors.white.withOpacity(.1),
    );
  }

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