import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/utils/dialog_loading.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'create_department_state.dart';

class CreateDepartmentLogic extends GetxController {
  final CreateDepartmentState state = CreateDepartmentState();
  dynamic parentDept;
  String? departmentNo;
  late String companyNo;
  bool isCreate = true;
  bool onlyShow = false;
  bool isEdit = false;
  dynamic selectedParentDepartment = {};
  List<dynamic> roleList = [];
  List<dynamic> managers = [];
  bool checkName = false;
  @override
  void onInit() {
    if (Get.arguments is Map) {
      var argument = Get.arguments as Map;
      parentDept = argument['parentDept'];
      selectedParentDepartment = parentDept ?? {};
      departmentNo = argument['departmentNo'];
      onlyShow = argument['onlyShow'] ?? false;
      isCreate = departmentNo == null && !onlyShow;
      companyNo = argument['companyNo'].toString();
      if (!isCreate) {
        _requestDepartmentDetail();
      }
    }
    super.onInit();
  }

  void changeRadio(bool? value) {
    state.isManager = value == true;
    update();
  }

  String getRoleNames() {
    return roleList.map((e) => e['roleName']).join(',');
  }

  String departmentManagerNames() {
    return managers.map((e) => e['userName']).join(',');
  }

  void deleteDepartment() {
    ConfirmDialog(
      content: '确定删除该部门吗？',
      confirm: () {
        _requestDeleteDepartment();
      },
    ).show();
  }

  void selectDepartment() {
    Get.toNamed(RouteConfig.departmentSelectPage, arguments: {
      'selectedNos': [
        (selectedParentDepartment['departmentNo'] ?? '').toString()
      ],
      'isSingle': true,
    })?.then((value) {
      if (value != null) {
        selectedParentDepartment = value[0];
        update();
      }
    });
  }

  void selectRoles() {
    Get.toNamed(RouteConfig.roleSelectPage, arguments: {'selectData': roleList})
        ?.then((value) {
      if (value == null) return;
      roleList = value ?? [];
      update();
    });
  }

  void selectDepartmentManager() {
    print(managers.length);
    Get.toNamed(
      RouteConfig.staffListSelectPage,
      arguments: {'listSelected': managers},
    )?.then((data) {
      if (data == null) return;
      managers = data ?? [];
      update();
    });
  }

  void submit() {
    if (state.nameController.text.isEmpty) {
      ToastUtil.showToast('请填写名称');
      checkName = true;
      update();
      return;
    }
    KeyBoardUtils.hideKeyboard();
    LoadingDialog.showLoading();
    if (isCreate) {
      _requestCreateDepartment();
    } else {
      _requestUpdateDepartment();
    }
  }

  void _requestDepartmentDetail() {
    fetch(Method.get, url: HttpApi.departmentDetail, queryParameters: {
      'departmentNo': departmentNo,
    }, onSuccess: (response) {
      state.nameController.text = response['departmentName'];
      managers = response['admins'] ?? [];
      roleList = response['roles'] ?? [];
      update();
    });
  }

  void _requestCreateDepartment() {
    fetch(
      Method.post,
      url: HttpApi.saveDepartment,
      params: <String, dynamic>{
        'companyNo': companyNo,
        'departmentName': state.nameController.text,
        'departmentPno': selectedParentDepartment['departmentNo'] ?? 0,
        'managerUserNos':
            managers.map<String>((e) => e['userNo'].toString()).toList(),
        'roleNos': roleList.map<String>((e) => e['roleNo'].toString()).toList(),
      },
      onSuccess: (response) {
        ToastUtil.showToast('创建成功');
        LoadingDialog.dismissLoading();
        Get.back(result: {
          'changeDepartment': parentDept?['departmentNo'] !=
              selectedParentDepartment['departmentNo']
        });
      },
      onError: (code, msg) {
        LoadingDialog.dismissLoading();
      },
    );
  }

  void _requestUpdateDepartment() {
    fetch(
      Method.post,
      url: HttpApi.updateDepartmentOrPosition,
      params: <String, dynamic>{
        'companyNo': companyNo,
        'departmentName': state.nameController.text,
        'departmentPno': selectedParentDepartment['departmentNo'] ?? 0,
        'departmentNo': departmentNo,
        'managerUserNos':
            managers.map<String>((e) => e['userNo'].toString()).toList(),
        'roleNos': roleList.map<String>((e) => e['roleNo'].toString()).toList(),
      },
      onSuccess: (response) {
        ToastUtil.showToast('编辑成功');
        LoadingDialog.dismissLoading();
        Get.back(result: {
          'changeDepartment': parentDept?['departmentNo'] !=
              selectedParentDepartment['departmentNo']
        });
      },
      onError: (code, msg) {
        LoadingDialog.dismissLoading();
      },
    );
  }

  void _requestDeleteDepartment() {
    LoadingDialog.showLoading();
    fetch(Method.delete,
        url: HttpApi.deleteDepartmentOrPosition,
        queryParameters: {
          'departmentNo': departmentNo,
        }, onSuccess: (response) {
      ToastUtil.showToast('删除成功');
      LoadingDialog.dismissLoading();
      Get.back(result: {'isDelete': true});
    }, onError: (code, msg) {
      LoadingDialog.dismissLoading();
    });
  }
}
