/*
 * @Author: XianKaiQun
 * @LastEditors  : WuWei
 * @Date: 2020-10-28 15:22:00
 * @LastEditTime : 2023-11-17 10:27:45
 */

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:mobx/mobx.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
part 'auth.g.dart';

///用户全局状态管理
class AuthGlobalStore = _AuthGlobalStore with _$AuthGlobalStore;

abstract class _AuthGlobalStore with Store {
  ///员工信息
  @observable
  EmployeesInfoModel? info;

  @action
  _setinfo(EmployeesInfoModel? value) => info = value;

  ///已登录后存在的id
  dynamic get _userId => WisStorageUtil.get(key: 'storage-user-id');
  dynamic get dialogContext => WisStorageUtil.get(key: 'dialog-context');

  ///发起登录
  @action
  Future<bool> login({
    required String entCode,
    required String account,
    required String password,
  }) async {
    final res = await AuthApi.postLogin(entCode, {
      'account': account,
      'password': password,
    });
    final id = res.data?.id;
    final success = id != null;
    if (!success) return false;
    WToastUtil.show('登录成功！');

    await WisStorageUtil.set(key: 'storage-user-id', data: id);
    await WisStorageUtil.set(key: 'storage-user-entCode', data: entCode);

    for (var item in _loginListeners) item();
    return true;
  }

  @action
  Future logout() async {
    await AuthApi.getLogout();
    await WisStorageUtil.remove(key: 'storage-cookie');
    await WisStorageUtil.remove(key: 'storage-user-id');
    final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();
    await communityGlobalStore.removeCommunity();
    for (var item in _logoutListeners) item();

    WNavUtil.instance!.pushNamedAndRemoveUntil('login', (r) => false);
  }

  ///请求获取用户信息
  @action
  Future<bool> getInfo() async {
    if (_userId == null) return false;
    final res = await EmployeeApi.getEmployeeInfo(_userId);
    final success = res.data?.id != null;
    if (!success) return false;
    _setinfo(res.data);
    return true;
  }

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

  ///添加登录监听
  void addLoginListener(void Function() listener) {
    if (_loginListeners.indexOf(listener) == -1) {
      _loginListeners.add(listener);
    }
  }

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

  ///添加登录监听
  void addLogoutListener(void Function() listener) {
    if (_logoutListeners.indexOf(listener) == -1) {
      _logoutListeners.add(listener);
    }
  }

  ///取消登录监听
  void removeLogoutListener(Function() listener) =>
      _logoutListeners.remove(listener);
}
