import 'package:account_center/api/base_model.dart';
import 'package:account_center/page/enterprise/role_management/role_details_page/role_details_entity.dart';
import 'package:account_center/page/enterprise/role_management/role_management_logic.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'role_setting_state.dart';

class RoleSettingLogic extends GetxController {
  final RoleSettingState state = RoleSettingState();

  @override
  void onInit() {
    super.onInit();
    var data = Get.arguments;
    if (data != null) {
      var entity = RoleDetailsEntity.fromJson(data);
      state.entity = entity;
      state.controllerName.text = entity.roleName ?? '';
      state.controllerDescribe.text = entity.roleDescribe ?? '';
      state.radioIndex = entity.roleStrategy ?? 0;
      state.switchState = state.entity?.status == 10;
    }
  }

  ///删除角色
  void deleteRoleRequest() {
    fetch(
      Method.delete,
      url: HttpApi.deleteRole,
      onSuccess: (data) {
        Get.back(result: deleteRole);
        ToastUtil.showToast('移除成功');
      },
      queryParameters: {
        'roleNo': state.entity?.roleNo,
      },
    );
  }

  ///更新角色
  void updateRoleRequest() {
    KeyBoardUtils.hideKeyboard();
    fetch(
      Method.post,
      url: HttpApi.updateRole,
      onSuccess: (data) {
        Get.back(result: updateRole);
        ToastUtil.showToast('编辑成功');
      },
      params: {
        'roleNo': state.entity?.roleNo,
        'roleDescribe': state.controllerDescribe.text,
        'roleName': state.controllerName.text,
        'roleStrategy': state.radioIndex,
      },
    );
  }

  ///角色策略变化
  void radioChange(int? value) {
    //0-无策略,1-管理员,2-默认菜单
    state.radioIndex = value ?? 0;
    update();
  }

  ///角色启用状态
  void _roleSwitchRequest() {
    fetch(Method.get, url: HttpApi.roleSwitch, queryParameters: {
      "roleNo": state.entity?.roleNo ?? '',
      "status": state.switchStateValue,
    }, onSuccess: (data) {
      update();
    });
  }

  ///状态启用开关
  void switchChange(bool value) {
    state.switchState = value;
    state.switchState
        ? state.switchStateValue = 10
        : state.switchStateValue = 20;
    _roleSwitchRequest();
  }

  void back() {
    Get.back();
  }
}
