import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

class SetUserDepartmentLogic extends GetxController {
  List<dynamic> departmentList = [];
  List<String> departmentNos = <String>[];
  List<dynamic> users = [];

  @override
  void onInit() {
    var data = Get.arguments?['data'] ?? <dynamic>[];
    users.addAll(data);
    super.onInit();
  }

  void confirm() {
    fetch(
      Method.post,
      url: HttpApi.updateUserDeptBatch,
      params: {
        'companyNo': SpUtil.getString(SPKey.companyNo),
        'departmentNos': departmentNos,
        'userNos': users.map<String>((e) => e['userNo'].toString()).toList(),
      },
      onSuccess: (response) {
        ToastUtil.showToast('设置成功');
        Get.back(result: {});
      },
    );
  }

  void selectDepartment() {
    Get.toNamed(RouteConfig.departmentSelectPage,
        arguments: {'selectedNos': departmentNos})?.then((value) {
      departmentList.clear();
      departmentList.addAll(value);
      departmentNos = departmentList
          .map<String>((e) => e['departmentNo'].toString())
          .toList();
      update();
      if (departmentNos.isNotEmpty) {
        _requestDepartmentRoleList();
      }
    });
  }

  void _requestDepartmentRoleList() {
    fetchList(
      Method.post,
      url: HttpApi.departmentRoles,
      params: {
        'departmentNos': departmentNos,
      },
      onSuccess: (response) {
        departmentList.clear();
        departmentList.addAll(response);
        update();
      },
      onError: (code, msg) {
        ToastUtil.showToast(msg);
      },
    );
  }
}
