/*
 * @Author: XianKaiQun
 * @Date: 2020-03-31 18:07:48
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-16 10:03:39
 * @Descripttion: 全局变量
 */
import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/auth.dart';
import 'package:app_package/src/api/employee.dart';
import 'package:flutter/widgets.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

///登录用户相关的全局变量
class GlobalUserStore with ChangeNotifier {
  final BuildContext context;
  GlobalUserStore(this.context);
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  ///可以通过这个简化获取store流程
  static GlobalUserStore of(BuildContext context, {bool listen = true}) {
    return Provider.of<GlobalUserStore>(context, listen: listen);
  }

  ///已登录后存在的id
  get _id => WisStorageUtil.get(key: 'storage-user-id');
  EmployeesInfoModel? get userInfo => _userInfo;

  ///登录用户信息
  EmployeesInfoModel? _userInfo;

  ///登录
  Future<bool> login(String entCode, Map<String, dynamic> data) async {
    var res = await AuthApi.postLogin(entCode, data);
    var success = res.data?.id != null;
    if (success) {
      await WisStorageUtil.set(key: 'storage-user-id', data: res.data!.id);
      return true;
    } else {
      return false;
    }
  }

  ///请求获取用户信息
  Future<bool> getInfo() async {
    if (_id == null) {
      return false;
    }
    var res = await EmployeeApi.getEmployeeInfo(_id);
    if (res.data?.id == null) {
      return false;
    } else {
      _userInfo = res.data;
      notifyListeners();
      for (var item in _loginListeners) {
        item();
      }
      return true;
    }
  }

  ///退出登录
  Future logOut() async {
    await AuthApi.getLogout();
    await WisStorageUtil.remove(key: 'storage-cookie');
    await WisStorageUtil.remove(key: 'storage-user-id');
    await communityGlobalStore.removeCommunity();
    for (var item in _logOutListeners) {
      item();
    }
    WNavUtil.instance!.pushNamedAndRemoveUntil(
      'login',
      (r) => false,
    );
  }

  List<Function()> _loginListeners = [];
  List<Function()> _logOutListeners = [];

  ///添加登录监听
  void addLoginListener(Function() listener) {
    _loginListeners.add(listener);
  }

  ///取消登录监听
  void removeLoginListener(Function() listener) {
    _loginListeners.remove(listener);
  }

  ///添加登录监听
  void addLogOutListener(Function() listener) {
    _logOutListeners.add(listener);
  }

  ///取消登录监听
  void removeOutListener(Function() listener) {
    _logOutListeners.remove(listener);
  }
}
