import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/widget/my_refresh_list_public.dart';

import 'role_select_state.dart';

class RoleSelectLogic extends GetxController {
  final RoleSelectState state = RoleSelectState();

  /// 搜索关键字
  String? key;

  var controller = MyListController();

  List<dynamic> selectData = [];

  @override
  void onInit() {
    state.forbidNo = Get.arguments['forbidNo'] ?? <String>[];
    var select = Get.arguments['selectData'] ?? <dynamic>[];
    selectData.addAll(select);
    super.onInit();
  }

  void search() {
    controller.callRefresh();
  }

  setKey(String value) {
    key = value;
    controller.callRefresh();
  }

  /// 选择
  check(role, bool checked) {
    role['checked'] = checked;
    if (checked) {
      selectData.add(role);
    } else {
      selectData.removeWhere(
        (element) => element['roleNo'] == role['roleNo'],
      );
    }
    update();
  }

  /// 完成
  finish() {
    Get.back(result: selectData);
  }

  /// 请求数据
  void requestData(int page, int pageSize, Function(List p1) success,
      Function(int p1, String p2) error) {
    fetchList(Method.post, url: HttpApi.pageRole, params: {
      'page': page,
      'pageSize': pageSize,
      'companyNo': SpUtil.getString(SPKey.companyNo),
      'roleName': key,
    }, onSuccess: (response) {
      if (page == 1) {
        state.noData = response.isEmpty;
        update();
      }
      for (var element in response) {
        element['checked'] = selectData.firstWhereOrNull(
              (data) => data['roleNo'] == element['roleNo'],
            ) !=
            null;
      }
      success(response);
    }, onError: (code, msg) {
      error(code, msg);
    });
  }
}
