import 'package:eitc_erm_dental_flutter/entity/login_info.dart';
import 'package:eitc_erm_dental_flutter/exts.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/http/api_service.dart';
import 'package:eitc_erm_dental_flutter/http/http.dart';
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../global.dart';
import '../../../sp_util.dart';

part 'login_view_model.g.dart';

@riverpod
class Login extends _$Login {
  @override
  String build() {
    return "";
  }

  ///登录
  ///
  /// [mobile] 手机号
  Future<bool> login(String mobile) async {
    try {
      LoginInfo? info = await Http.instance
          .request(ApiService(Http.instance.dio).login(mobile));
      if (info == null || info.token.isNullOrEmpty) {
        logd("登录失败,返回的数据为null或token为空");
        return SynchronousFuture(false);
      }
      await SpUtil.setUserId(info.id!);
      await SpUtil.setUserName(mobile);
      await SpUtil.setToken(info.token!);
      updateToken(info.token!);
    } catch (e) {
      loge("登录异常", error: e);
      return SynchronousFuture(false);
    }
    return SynchronousFuture(true);
  }

  ///登出
  Future<bool> logout() async {
    try {
      String tk = token;
      Http.instance.request(ApiService(Http.instance.dio).logout(tk));
    } catch (e) {
      loge("登出异常", error: e);
    }
    logoutClearData();
    return SynchronousFuture(true);
  }
}
