import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:vitalapp/architecture/utils/common_util.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/logger/logger.dart';

import 'interfaces/account.dart';

class AccountManager implements IAccountManager {
  @override
  Future<int> login(String account, String password, bool isAutoLogin) async {
    int code = 0;
    try {
      final symmetryEncryptPassword =
          password.isEmpty ? '' : FEncryptHelper.symmetryEncrypt(password);
      final result = await rpc.login.commonLoginAsync(
        CommonLoginRequest(
          anyAccount: account,
          password: symmetryEncryptPassword,
          loginSource: LoginSource.Android,
        ),
      );

      await Store.user
          .handleLogin(account, result.token!, password, isAutoLogin);
    } catch (e) {
      if (e is JsonRpcException) {
        final loginExCode = e.data.code;
        code = loginExCode;
      } else {
        code = -1;
      }
    }
    return code;
  }

  @override
  Future<bool> logout() async {
    await Store.user.handleLogOut();
    try {
      await rpc.login.loginOutAsync(
        TokenRequest(token: Store.user.token),
      );
    } catch (e) {
      logger.e("AccountManager call logout error", e);
    }
    CommonUtil.idCardRecognition.release();
    return true;
  }

  @override
  Future<UserDTO?> getUserDetailAsync() async {
    try {
      return await rpc.user.getUserDetailAsync(
        GetUserRequest(
          token: Store.user.token,
          code: Store.user.userCode,
        ),
      );
    } catch (e) {
      return null;
    }
  }

  @override
  Future<bool> updateUserAsync(UserDTO dto) async {
    try {
      var request = UpdateUserRequest(
        token: Store.user.token,
        code: dto.code,
        realName: dto.realName,
        phone: dto.phone,
        headImageToken: dto.headImageToken,
      );
      var result = await rpc.user.updateUserAsync(request);
      if (result) {
        await Store.user.updateUserInfo(dto);
      }
      return result;
    } catch (e) {}
    return false;
  }

  @override
  Future<String> getUserPasswordDetailAsync() async {
    try {
      var result = await rpc.userPassword.getUserPasswordDetailAsync(
          GetUserPasswordRequest(
              token: Store.user.token, code: Store.user.userCode));
      return result.secretPassword ?? '';
    } catch (e) {}
    return '';
  }

  @override
  Future<bool> updateUserPasswordAsync(String secretPassword) async {
    try {
      var result = await rpc.userPassword.updateUserPasswordAsync(
          UpdateUserPasswordRequest(
              token: Store.user.token,
              code: Store.user.userCode,
              secretPassword: secretPassword));
      return result;
    } catch (e) {}
    return false;
  }

  @override
  Future<List<UserFeatureDTO>?> getMenuPermission() async {
    try {
      var result = await rpc.user.getMenuPermissionAsync(
        GetMenuPermissionRequest(
          token: Store.user.token,
          appType: ApplicationTypeEnum.App,
        ),
      );
      for (var element in result) {
        print(element.toJson());
      }
      return result;
    } catch (e) {
      logger.e("AccountManager call getMenuPermission error", e);
    }
    return null;
  }

  @override
  Future<List<UserFeatureDTO>?> getOperationPermission() async {
    try {
      var request = GetOperationPermissionRequest(
        token: Store.user.token,
        appType: ApplicationTypeEnum.App,
      );
      var result = await rpc.user.getOperationPermissionAsync(request);
      // var json = jsonEncode(request);
      // print(jsonEncode(request.toJson()));
      for (var element in result) {
        print(element.toJson());
        logger.i('新增权限${element.toJson()}');
      }
      return result;
    } catch (e) {
      logger.e("AccountManager call getMenuPermission error", e);
    }
    return null;
  }
}
