import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../common/models/server/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

class ServerInfoController extends GetxController {
  ServerInfoController();

  final state = ServerInfoState();

  // host输入
  final TextEditingController hostController = TextEditingController();
  final TextEditingController portController = TextEditingController();
  final TextEditingController urlMappingController = TextEditingController();

  final FocusNode hostNode = FocusNode();
  final FocusNode portNode = FocusNode();
  final FocusNode urlMappingNode = FocusNode();

  final protocolList = ['http', 'https'];

  O2CloudServer? assetsServer;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.protocol = protocolList[0];
    final o2CloudServer = O2ApiManager.instance.o2CloudServer;
    if (o2CloudServer != null) {
      state.protocol = o2CloudServer.httpProtocol ?? protocolList[0];
      hostController.text = o2CloudServer.centerHost ?? '';
      portController.text = '${o2CloudServer.centerPort ?? 80}';
      urlMappingController.text = o2CloudServer.urlMapping ?? '';
    }
    readAssetsServerJson();
    super.onReady();
  }

  void clickType(String protocol) {
    state.protocol = protocol;
  }

  Future<void> readAssetsServerJson() async {
    assetsServer = await O2ApiManager.instance.readAssetsServerJson();
    if (hostController.text != assetsServer?.centerHost ||
        portController.text != '${assetsServer?.centerPort ?? 80}') {
      state.notSameConfig = true;
    }
  }

  Future<void> showAssetsConfig() async {
    final context = Get.context;
    if (context == null) {
      OLogger.e('没有 context！');
      return;
    }
    if (assetsServer == null) {
      return;
    }
    final listView = ListView(children: [
      ListTile(title: Text('${'login_server_assets_config_protocol'.tr}: ${assetsServer?.httpProtocol ?? ''}')),
      ListTile(title: Text('${'login_server_assets_config_host'.tr}: ${assetsServer?.centerHost ?? ''}')),
      ListTile(title: Text('${'login_server_assets_config_port'.tr}: ${assetsServer?.centerPort ?? 90}')),
      ListTile(title: Text('${'login_server_assets_config_urlmapping'.tr}: ${assetsServer?.urlMapping ?? ''}'))
    ]);
    final dialog = await O2UI.showCustomDialog(
        context, 'login_server_assets_config_title'.tr, listView, positiveBtnText: 'login_server_assets_config_reset_btn'.tr);
    if (dialog != null && dialog == O2DialogAction.positive) {
      _writeAssetsConfig2Form();
    }
  }

  void _writeAssetsConfig2Form() {
    if (assetsServer != null) {
      state.protocol = assetsServer?.httpProtocol ?? protocolList[0];
      hostController.text = assetsServer?.centerHost ?? '';
      portController.text = '${assetsServer?.centerPort ?? 80}';
      urlMappingController.text = assetsServer?.urlMapping ?? '';
    }
  }

  void saveServerInfo() {
    final context = Get.context;
    if (context == null) {
      OLogger.e('没有 context！');
      return;
    }
    final host = hostController.text;
    if (host.isEmpty) {
      Loading.toast('login_server_form_label_host_error_msg'.tr);
      return;
    }
    final port = portController.text;
    if (port.isEmpty || !port.isNum) {
      Loading.toast('login_server_form_label_port_error_msg'.tr);
      return;
    }
    String urlJoin = '${state.protocol}://$host:$port/';

    O2UI.showConfirm(
        context, 'login_server_form_submit_confirm_msg'.trArgs([urlJoin]),
        okPressed: () => _saveInfoAndReloadApp());
  }

  Future<void> _saveInfoAndReloadApp() async {
    final host = hostController.text;
    final port = portController.text;
    final urlmapping = urlMappingController.text;
    O2CloudServer cloud = O2CloudServer(
        id: host,
        name: host,
        centerHost: host,
        centerContext: '/x_program_center',
        centerPort: int.tryParse(port),
        httpProtocol: state.protocol,
        urlMapping: urlmapping);
    await O2ApiManager.instance.putO2UnitJson2SP(cloud);
    Get.offAllNamed(O2OARoutes.splash);
  }
}
