import 'dart:convert';

import 'package:dio/dio.dart' as dio_package;
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/apis/api.dart';
import 'package:sk_base_mobile/store/dict.store.dart';
import 'package:sk_base_mobile/util/logger_util.dart';
import 'package:sk_base_mobile/widgets/tap_to_dismiss_keyboard.dart';
import 'package:sk_base_mobile/models/auth.dart';
import 'package:sk_base_mobile/models/user_info.model.dart';
import 'package:sk_base_mobile/services/service.dart';
import '../constants/constants.dart';
import '../util/util.dart';

class AuthStore extends GetxService {
  static AuthStore get to => Get.find();
  final userInfo = UserInfoModel().obs;

  Future<AuthStore> init() async {
    try {
      String? preUserInfo =
          StorageService.to.getString(CacheKeys.userInfo, isWithUser: false);
      String? token =
          StorageService.to.getString(CacheKeys.token, isWithUser: false);

      if (token != null) {
        if (preUserInfo != null) {
          await getMyProfile();
          LoggerUtil().info('[Store-Auth] userId: ${userInfo.value.id}');
        }
      }
    } catch (e) {
      LoggerUtil().info(
        '[Store-Auth]Init failed, please try again.$e',
      );
    }
    return this;
  }

  Future<void> deleteAccount() async {
    await LoadingUtil.to.show(status: 'Deleting...');
    try {
      final response = await Api.deleteAccount();
      if (response.data != null) {
        await SnackBarUtil().success('Delete account succeed.');
        await logout();
      }
    } catch (e) {
      await SnackBarUtil().error('Delete account faield. Please try again.');
    } finally {
      await LoadingUtil.to.dismiss();
    }
  }

  Future<void> logout({bool force = false}) async {
    await StorageService.to.remove(CacheKeys.token, isWithUser: false);
    await StorageService.to.remove(CacheKeys.userInfo, isWithUser: false);
    LoggerUtil().info('[Store-Auth] Logout succeed.');
    // 如果当前已经在login界面 不需要跳转
    // 判断是否Get已经注册
    if (Get.currentRoute != RouteConfig.login) {
      Get.offAllNamed(RouteConfig.login);
    }
    // 不用getx跳转登录页
  }

  Future<void> login(
      {required String username, required String password}) async {
    dio_package.Response response;
    // if (type == LoginEnum.fastLogin &&
    //     StorageService.to.getString(CacheKeys.deviceUUID, isWithUser: false) ==
    //         null) {
    //   SnackBarUtil().error('Need DeviceUUID. Please restart app.');
    //   return;
    // }

    await LoadingUtil.to.show();
    TapToDismissKeyboard.dismissOf(context: Get.context!);
    try {
      await Future.delayed(const Duration(seconds: 1));
      response = await Api.login(username, password);
      if (response.data != null) {
        final auth = Auth.fromJson(response.data['data']);

        if (auth.token != null) {
          await StorageService.to
              .setString(CacheKeys.token, auth.token!, isWithUser: false);
        }
        await getMyProfile();
        await getCommonInfo();
        Get.offNamed(RouteConfig.home);
      }
    } catch (e) {
      await SnackBarUtil().error('账号密码错误');
      LoggerUtil().error(e);
    } finally {
      LoadingUtil.to.dismiss();
    }
  }

  Future<void> updateUserInfoState(UserInfoModel newInfo) async {
    userInfo(newInfo);
    await StorageService.to
        .setString(CacheKeys.userInfo, jsonEncode(newInfo), isWithUser: false);
  }

  Future<void> getMyProfile() async {
    try {
      final response = await Api.getMyProfile();
      if (response.data != null) {
        UserInfoModel userInfo = UserInfoModel.fromJson(response.data);
        await updateUserInfoState(userInfo);
      }
    } catch (e) {
      SnackBarUtil().error('$e');
    } finally {}
  }

  Future<void> saveUserInfo(Map<String, dynamic> data) async {
    LoadingUtil.to.show(status: 'Saving...');
    try {
      final res = await Api.saveUserInfo(data);
      if (res.data != null) {
        await getMyProfile();
        SnackBarUtil().success('Save successfully.');
      }
    } catch (e) {
      SnackBarUtil().error('$e');
    } finally {
      LoadingUtil.to.dismiss();
    }
  }

  Future<void> getCommonInfo() async {
    await AppInfoService.to.getAppConfig();
    await Future.wait([
      DictService.to.getDictTypes()

      /// 依赖业务信息
      // Get.putAsync<BlockStore>(() => BlockStore().init()),
    ]);
  }
}
