import 'package:base_app/common/common.dart';
import 'package:base_app/common/sp_helper.dart';
import 'package:base_app/data/api/apis.dart';
import 'package:base_app/data/net/dio_util.dart';
import 'package:base_app/data/protocol/base_resp.dart';
import 'package:base_app/data/protocol/user_model.dart';
import 'package:encrypt/encrypt.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/services.dart';
import 'package:pointycastle/asymmetric/api.dart';
/// 与用户相关请求后台仓库
class UserRepository {
  /// 获取公钥接口
  Future<bool> baseConfig() async {
    // 调用登录接口
    BaseRespR<Map<String, dynamic>> baseResp =
        await DioUtil().requestR<Map<String, dynamic>>(
      Method.get,
      AppApi.BASE_CONFIG,
    );
    // 获取失败
    if (baseResp.code != Constant.status_success) {
      return Future.error(baseResp.message);
    }
    //登录成功，将token保存
    if (baseResp.data != null) {
      String publicKey = baseResp.data['publicKey'];
      SpHelper.putObject(BaseConstant.keyPublicKey, publicKey);
      return true;
    } else {
      return false;
    }
  }

  /// 登录并获取用户基本信息
  /// [req] 登录请求对象（username,password）
  Future<UserModel> login(LoginReq req) async {
    // 1. 加密
    String publicKeyStr =
        await rootBundle.loadString('assets/keys/public_key.pem');
    RSAPublicKey publicKey = RSAKeyParser().parse(publicKeyStr);
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    final encrypted = encrypter.encrypt(req.password);
    print(encrypted.base64);
    req.password = encrypted.base64;
    // 2.调用登录接口
    BaseRespR<Map<String, dynamic>> baseResp = await DioUtil()
        .requestR<Map<String, dynamic>>(Method.post, AppApi.USER_LOGIN,
            data: req.toFormData());
    // 登录失败
    if (baseResp.code != Constant.status_success) {
      return Future.error(baseResp.message);
    }
    //登录成功，将token存在cookie
    if (baseResp.data != null) {
      String token = baseResp.data['token'];
      LogUtil.e("token: " + token);
      SpUtil.putString(BaseConstant.keyAppToken, token);
      SpUtil.putString(BaseConstant.keyUserName, req.username);
      DioUtil().setToken(token);
    }
    // 获取用户信息
    baseResp = await DioUtil().requestR<Map<String, dynamic>>(
        Method.get, AppApi.USER_INFO,
        data: null);
    if (baseResp.code != Constant.status_success) {
      return Future.error('获取用户信息失败！请退出重试');
    }
    UserModel model = UserModel.fromJson(baseResp.data);
    SpUtil.putObject(BaseConstant.keyUserModel, model);
    return model;
  }

  // 获取用户信息
  Future<UserModel> getUserInfo() async {
    // 获取用户信息
    BaseRespR<Map<String, dynamic>> baseResp = await DioUtil()
        .requestR<Map<String, dynamic>>(Method.get, AppApi.USER_INFO,
            data: null);
    if (baseResp.code != Constant.status_success) {
      return Future.error('获取用户信息失败！请退出重试');
    }
    UserModel model = UserModel.fromJson(baseResp.data);
    SpUtil.putObject(BaseConstant.keyUserModel, model);
    return model;
  }

  /// 注销
  Future<bool> logout() async {
    // 调用登录接口
    BaseRespR<String> baseResp =
        await DioUtil().requestR<String>(Method.get, AppApi.USER_LOGOUT);
    // 注销失败
    if (baseResp.code != Constant.status_success) {
      return Future.error(baseResp.message);
    } else {
      return true;
    }
  }
}
