import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/services/modules/config_language.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/pages/user/user_device/controllers/org_device_controller.dart';
import 'package:flyinsono/pages/user/user_device/controllers/user_device_controller.dart';
import 'package:flyinsono/pages/user/user_device/state.dart';
import 'package:flyinsono/pages/user/user_device/widgets/select_user_member.dart';
import 'package:flyinsono/pages/user/user_device/widgets/share_terminal_mobile.dart';
export 'package:fis_lib_business_components/index.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'entrtys/device_info.dart';

class DeviceController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  ///设备短码控制器
  final shortCodeController = TextEditingController();

  ///设备类型控制器
  final deviceTypeController = TextEditingController();

  ///设备型号控制器
  final deviceModelController = TextEditingController();

  ///组织设备控制器
  late final OrgDeviceController orgDeviceController;

  ///用户设备控制器
  late final UserDeviceController userDeviceController;

  final textEditingController = TextEditingController();

  final state = UserDeviceState();

  ///设备列表滚动条Controller
  final terminalController = ScrollController();

  ///名称编辑框Controller
  final nameEditingController = TextEditingController();

  ///手机添加设备时用的控制器
  final deviceNameEditingController = TextEditingController();

  ///设备唯一码Controller
  final deviceCodeController = TextEditingController();

  ///搜索框Controller
  final searchController = TextEditingController();

  ///搜索框FocusNode
  final searchFocusNode = FocusNode();

  ///语言服务
  final languageService = Get.find<LanguageService>();

  /// 【服务器状态】分享用户列表
  List<ShareDeviceUserDTO> shareUsers = [];

  bool _isFocus = false;
  int _totalCount = 0;

  final orgNameController = TextEditingController();

  DeviceController() {
    orgDeviceController = OrgDeviceController(this);
    userDeviceController = UserDeviceController(this);
  }

  ///添加设备
  void addTerminalDevice() {
    orgDeviceController.addTerminalDevice();
  }

  /// 绑定设备信息（添加设备）
  Future<void> bindDevice(FInteractiveContainer businessParent) async {
    await userDeviceController.bindDevice(businessParent);
  }

  /// 点击设备卡片
  void changeCard(int index, DeviceExtendInfoDTO terminal) {
    state.selectTerminalCardIndex = index;
    state.selectedTerminal = terminal;
    getShareDeviceUsers(terminal.deviceCode ?? '');
    deviceCodeController.text = terminal.shortCode ?? '';
    nameEditingController.text = terminal.description ?? '';
    if (kIsMobile) {
      deviceNameEditingController.text = terminal.description ?? '';
    }
    findDeviceDiagnosisModulesAsync();
  }

  /// 关闭绑定设备弹窗
  Future<void> closeBindDevice() async {
    Get.back();
    state.deviceInfo = DeviceInfo();
    shortCodeController.text = '';
    state.isCanShare = true;
    await getOrganizationByCode();
  }

  /// 移除关联用户
  Future<void> deleteShareDeviceToUserAsync(
      FInteractiveContainer businessParent) async {
    userDeviceController.deleteShareDeviceToUserAsync(businessParent);
  }

  /// 获取AI应用列表
  Future<void> findDeviceDiagnosisModulesAsync() async {
    try {
      final deviceCode = state.selectedTerminal.deviceCode ?? '';
      if (deviceCode.isEmpty) {
        return;
      }
      var result = await rpc.device.findDeviceDiagnosisModulesAsync(
        FindDeviceDiagnosisModulesRequest(
          token: Store.user.token,
          deviceCode: state.selectedTerminal.deviceCode,
        ),
      );
      state.diagnosisModule = result;
    } catch (e) {
      logger.e("findDeviceDiagnosisModulesAsync ex", e);
    }
  }

  ///筛选超声机
  Future<void> findTerminalByParameters() async {
    await orgDeviceController.findTerminalByParameters();
  }

  ///打开筛选超声机页面
  void findTerminals() {
    orgDeviceController.findTerminals();
  }

  /// 通过deviceCode来获取设备信息 自动回填
  Future<void> getDeviceInfo(String value, {bool isFromParam = false}) async {
    await orgDeviceController.getDeviceInfo(value, isFromParam: isFromParam);
    state.refreshDeviceInfo();
  }

  /// 获取该机构下面所有部门
  void getOrganization() async {
    userDeviceController.getOrganization();
  }

  /// 获取当前机构的所在医院
  Future getOrganizationByCode() async {
    await userDeviceController.getOrganizationByCode();
  }

  /// 获取选择的关联的用户
  void getSelectedIdxs(List selectIndexList) {
    orgDeviceController.getSelectedIdxs(selectIndexList);
  }

  /// 获取分享设备用户集合
  Future getShareDeviceUsers(String deviceCode) async {
    await orgDeviceController.getShareDeviceUsers(deviceCode);
  }

  /// 根据语言包翻译
  String getValues(String code) {
    var value = languageService.findLanguageValueByCode('ai', code);
    return value;
  }

  /// 初始化数据
  Future<void> initData({bool isNewDatas = false}) async {
    try {
      busy = true;
      PageCollection<DeviceExtendInfoDTO> result;
      GetPersonDeviceRequest request = GetPersonDeviceRequest(
        token: Store.user.token,
        pageIndex: isNewDatas ? state.pageIndex : 1,
        pageSize: 20,
        keyWord: state.queryString,
        organizationCodes: state.selectedOrganizationLocated,
      );

      /// 机构管理员查询
      if (state.isOrgDevice) {
        result = await rpc.device.getOrganizationDeviceListAsync(request);
      } else {
        /// 非机构管理员查询
        result = await rpc.device.getPersonDeviceListAsync(request);
      }
      var resultPage = result.pageData ?? [];
      _totalCount = result.dataCount;
      resultPage.forEach((element) {
        var languageConfigs = element.languageConfigs ?? [];
        var deviceType = element.deviceType ?? '';
        var languageCode = i18nBook.locale.toCodeString('-');
        var currentDevice = languageConfigs
            .firstWhereOrNull((element) => element.language == languageCode);
        if (currentDevice != null) {
          deviceType = currentDevice.value ?? '';
        }
        element.deviceType = deviceType;
        if (element.isEmergencyDevice) {
          state.selectedECDevice = element.deviceCode ?? '';
        }
      });
      if (isNewDatas) {
        state.terminals.addAll(resultPage);
      } else {
        state.terminals = resultPage;
      }

      if (state.terminals.length > 0) {
        state.selectedTerminal = state.terminals[0];
        getShareDeviceUsers(state.terminals[0].deviceCode ?? "");
        nameEditingController.text = state.selectedTerminal.description ?? "";
        deviceCodeController.text = state.selectedTerminal.shortCode!;
      }
      if (state.isOrgDevice) {
        findDeviceDiagnosisModulesAsync();
      }
      busy = false;
      await orgDeviceController.getOrganizationByUserAndDevicesAsync();

      await getOrganizationByCode();
    } catch (e) {
      busy = false;
      logger.e("init terminal datas error:", e);
    }
  }

  ///初始化监听
  void initListener() {
    searchFocusNode.addListener(() {
      print("focus:${searchFocusNode.hasFocus}");
      if (searchFocusNode.hasFocus) {
        _isFocus = true;
      } else {
        Future.delayed(Duration(microseconds: 200), () => _isFocus = false);
      }
    });
    terminalController.addListener(() {
      // 如果滑动到底部
      if (terminalController.position.pixels ==
              terminalController.position.maxScrollExtent &&
          state.terminals.length < _totalCount) {
        state.pageIndex++;
        initData(isNewDatas: true);
      }
    });
  }

  ///在线直播
  void liveClick() {}

  ///修改设备诊断状态
  Future<void> modifyDeviceDiagnosisModuleStateAsync(
      bool isEnabled, String diagnosisModule) async {
    await userDeviceController.modifyDeviceDiagnosisModuleStateAsync(
        isEnabled, diagnosisModule);
  }

  @override
  Future<void> onEnterPressed() async {
    if (kIsMobile) return;
    if (_isFocus) {
      await searchTerminal();
    }
  }

  @override
  void onInit() {
    initListener();
    super.onInit();
  }

  ///树形结构点击事件
  bool onNodeTap(String v) {
    return orgDeviceController.onNodeTap(v);
  }

  @override
  void onReady() {
    super.onReady();
    Future.delayed(Duration(milliseconds: 300), () {
      initData();
    });
    userDeviceController.initDeviceType();
    getOrganization();
  }

  /// 手机端关联用户
  void openConnectionUser(DeviceExtendInfoDTO deviceExtendInfoDTO) async {
    await getShareDeviceUsers(
      deviceExtendInfoDTO.deviceCode!,
    );
    state.selectedTerminal = deviceExtendInfoDTO;
    Get.to(
      () => SelectDeviceUserMember(),
    );
  }

  /// 手机端移除设备
  void openDeleteDevice(DeviceExtendInfoDTO deviceExtendInfoDTO,
      FInteractiveContainer businessParent) async {
    await getShareDeviceUsers(
      deviceExtendInfoDTO.deviceCode!,
    );
    state.selectedTerminal = deviceExtendInfoDTO;
    await removeOrgTerminal(businessParent);
  }

  /// 手机端分享设备
  void openShareUser(DeviceExtendInfoDTO deviceExtendInfoDTO) async {
    await getShareDeviceUsers(
      deviceExtendInfoDTO.deviceCode!,
    );
    state.selectedTerminal = deviceExtendInfoDTO;
    Get.to(
      () => ShareTerminalMobile(),
    );
  }

  /// 刷新
  Future<void> refersh() async {
    busy = true;
    state.queryString = '';
    searchController.text = '';
    state.pageIndex = 1;
    await initData();
    state.selectTerminalCardIndex = 0;
    busy = false;
  }

  ///移除组织超声机
  Future<void> removeOrgTerminal(FInteractiveContainer businessParent) async {
    await orgDeviceController.removeTerminal(businessParent);
  }

  ///个人设备移除
  Future<void> removePersonDevice() async {
    userDeviceController.removePersonDevice();
  }

  ///移除超声机
  Future<void> removeTerminal(FInteractiveContainer businessParent) async {
    await orgDeviceController.removeTerminal(businessParent);
  }

  /// 重设设备名称input框的值
  void resetDeviceName() {
    nameEditingController.text = state.selectedTerminal.description ?? "";
  }

  ///搜索超声机
  Future<void> searchTerminal() async {
    await initData();
  }

  ///选中时同步设备信息
  void setDevice() {
    userDeviceController.setDevice();
  }

  /// 分享设备
  Future<void> shareTerminal() async {
    orgDeviceController.shareTerminal();
  }

  /// 手机端分享设备的提交
  Future<void> submitMobileUsers() async {
    await userDeviceController.submitMobileUsers();
  }

  ///分享设备提交
  Future<void> submitUsers() async {
    await userDeviceController.submitUsers();
  }

  ///修改设备信息
  void updateTerminal() {
    orgDeviceController.updateTerminal();
  }

  ///更新超声机信息
  Future<void> updateTerminalInfo() async {
    await userDeviceController.updateTerminalInfo();
  }
}
