import 'package:fis_jsonrpc/http_pool.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'state.dart';

class LoginGatewayController extends FControllerBase {
  final state = LoginGatewayState();

  void onSubmit() async {
    try {
      RegExp regExp = RegExp(r'\s'); // 匹配空格的正则表达式
      bool hasSpace = regExp.hasMatch(state.gateway);
      if (hasSpace) {
        PromptBox.toast("请输入正确的服务器地址");
        return;
      }
      var checkResult = await _checkServerValidation();
      if (!checkResult) {
        PromptBox.toast("服务器不存在");
        return;
      }
      final uri = Uri.parse(state.gateway);
      final fullAddress = uri.toString();
      Store.app.serverUrl = fullAddress;
      await Store.persistent();
      _setRpc(uri);
      PromptBox.toast("保存成功");
    } catch (e) {
      PromptBox.toast("保存失败");
    }
  }

  @override
  void onInit() {
    _load();

    super.onInit();
  }

  _setRpc(Uri uri) {
    rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == 'https');
    rpc.clearCache();
  }

  void _load() async {
    final address = Store.app.serverUrl;
    final uri = Uri.parse(address);
    _setRpc(uri);
    state.gateway = rpc.currentHostAddress;
  }

  @override
  void onReady() {
    //
    super.onReady();
  }

  @override
  void onClose() {
    _doDispose();
    super.onClose();
  }

  void _doDispose() {}

  /// 检验服务有效性
  Future<bool> _checkServerValidation() async {
    try {
      final host = state.gateway;

      var response = await jrpcHttpPool.getClient(
        host,
        timeout: 3000,
        headers: {'content-type': "text/plain"},
      ).post(
        '/IVitalLoginService',
        data:
            '{"jsonrpc":"2.0","method":"CommonLoginAsync","params":["AnyAccount": "abc123","AnyCode": "","Platform": 1,"LoginSource": 1,"Password": "fb6414d24e3c347d46032b0496f1c4e4"],"id":1}',
      );
      if (response.data != null) {
        print(response.data);
        return true;
      }
    } catch (e) {
      print("Http unknown error:${e}");
    }
    return false;
  }
}
