import 'package:fis_jsonrpc/http_pool.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/components/dialog_confirm.dart';
import 'package:vitalapp/managers/interfaces/account.dart';
import 'package:vitalapp/managers/interfaces/system_setting.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';

import 'state.dart';

class ServerSettingController4Login extends ServerSettingController {
  @override
  Future<void> handleAfterSubmit(bool saved) async {
    if (saved) {
      Get.back();
      PromptBox.toast("保存成功");
    }
  }
}

class ServerSettingController extends FControllerBase {
  final state = ServerSettingState();

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

  @protected
  Future<void> handleAfterSubmit(bool saved) async {
    if (saved) {
      await DialogConfirm.show(
        message: "服务地址已变更，需要重新登录",
        disableCancel: true,
      );
      Get.offAllNamed("/login");
    }
  }

  /// 提交修改
  Future<void> submit() async {
    bool saved = false;

    setBusy("正在保存");
    try {
      final uri = await _buildUri();
      if (uri == null) {
        return;
      }

      Store.app.serverUrl = uri.toString();
      await Store.persistent();
      final result = await Get.find<IAccountManager>().logout();
      if (result) {
        //  更新RPC地址
        rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == 'https');
        rpc.clearCache();

        // 重新加载服务配置
        await Get.find<ISystemSettingManager>().getSettings(true);

        saved = true;
        cancelBusy();
      } else {
        _toastError("保存失败");
      }
    } catch (e) {
      logger.e("ServerSettingController save url error.", e);
      _toastError("保存失败");
    } finally {
      if (!saved) {
        // 给提示一点时间吧
        await Future.delayed(const Duration(milliseconds: 1500));
      }

      handleAfterSubmit(saved);
    }
  }

  Future<Uri?> _buildUri() async {
    RegExp regExp = RegExp(r'\s'); // 匹配空格的正则表达式
    bool hasSpace = regExp.hasMatch(state.host);
    if (hasSpace) {
      _toastError("请输入正确的服务器地址");
      return null;
    }
    final uri = Uri(
      scheme: state.enableSSL ? "https" : "http",
      host: state.host,
      port: state.port,
    );
    final fullAddress = uri.toString();
    if (fullAddress == Store.app.serverUrl) {
      _toastError("服务器地址未发生变更");
      return null;
    }
    final checkResult = await _checkServerValidation(fullAddress);
    if (!checkResult) {
      _toastError("服务器不存在");
      return null;
    }
    return uri;
  }

  void _toastError(String message) {
    cancelBusy();
    PromptBox.toast(message);
  }

  void _load() async {
    final address = Store.app.serverUrl;
    final uri = Uri.parse(address);
    state.enableSSL = uri.scheme.toLowerCase() == "https";
    state.host = uri.host;
    state.port = uri.port;
  }

  /// 检验服务有效性
  Future<bool> _checkServerValidation(String host) async {
    try {
      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;
  }
}
