import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/page/enterprise/organization_structure/position_details_page/position_details_logic.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:account_center/widget/tree_node/tree_node.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'position_tree_state.dart';

class PositionTreeLogic extends GetxController {
  final PositionTreeState state = PositionTreeState();
  String? positionNo;
  String? userNo;

  @override
  void onInit() {
    positionNo = Get.arguments['positionNo'];
    userNo = Get.arguments['userNo'];
    super.onInit();
  }

  @override
  void onReady() {
    requestPositionTree();
    super.onReady();
  }

  void requestPositionTree() {
    fetchList(Method.post, url: HttpApi.listPDepartment, params: {
      'departmentNo': positionNo,
      'companyNo': SpUtil.getString(SPKey.companyNo)
    }, onSuccess: (response) {
      state.nodes = formatPositionData(response);
      update();
    }, onError: (code, msg) {});
  }

  List<TreeNode> formatPositionData(List<dynamic>? positions) {
    List<TreeNode> nodes = [];
    positions?.forEach((element) {
      nodes.add(
        TreeNode()
          ..title = element['departmentName']
          ..children = formatPositionData(element['childDepartmentList'])
          ..canCheck = false
          ..canExpand =
              (element['childDepartmentList'] as List<dynamic>).isNotEmpty
          ..expand = true
          ..data = element,
      );
    });
    return nodes;
  }

  void deletePosition() {
    // LoadingUtils.showLoading('');
    ConfirmDialog(
      content: '确定删除此职位！',
      confirm: () {
        fetch(
          Method.post,
          url: HttpApi.deleteUserPosition,
          params: {
            'userNo': userNo.toInt(),
            'departmentNo': positionNo.toInt()
          },
          onSuccess: (response) {
            LoadingUtils.dismiss();
            var fromPosition = Get.isRegistered<PositionDetailsLogic>();
            if (fromPosition) {
              Get.find<PositionDetailsLogic>()
                  .state
                  .memberListController
                  .callRefresh();
            }
            ToastUtil.showToast('删除成功！');
            Get.back(result: {});
          },
          onError: (code, msg) {
            LoadingUtils.dismiss();
            ToastUtil.showToast(msg);
          },
        );
      },
    ).show();
  }
}
