import 'package:account_center/api/base_model.dart';
import 'package:account_center/page/enterprise/organization_structure/organization_event.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'position_details_state.dart';

class PositionDetailsLogic extends GetxController
    with GetTickerProviderStateMixin {
  final PositionDetailsState state = PositionDetailsState();
  late TabController controller;

  ///组织架构编号 职位
  int departmentNo = 0;

  /// 1 管理员职位
  int? adminPosition;
  bool fromMyDepartment = false;
  List<String> userNos = [];
  List<String> roleNos = [];
  @override
  void onInit() {
    super.onInit();
    controller = TabController(length: 2, vsync: this);
    state.parents = Get.arguments['parents'] ?? [];
    state.title = Get.arguments['isMyDepartment'] == true ? '部门管理' : '组织架构';
    dynamic depart = state.parents.last;
    state.position = depart['departmentName'];
    adminPosition = depart['adminPosition'] ?? 0;
    departmentNo = depart['departmentNo'].toString().toInt();
    fromMyDepartment = Get.arguments['isMyDepartment'] == true;
    state.type = adminPosition == 1 ? '管理员' : '';
  }

  void _requestPositionDetail() {
    fetch(
      Method.get,
      url: HttpApi.getDepartmentInfo,
      onSuccess: (depart) {
        state.position = depart['departmentName'];
        adminPosition = depart['adminPosition'] ?? 0;
        departmentNo = depart['departmentNo'].toString().toInt();
        state.type = adminPosition == 1 ? '管理员' : '';
        update();
      },
      queryParameters: {'departmentNo': departmentNo},
    );
  }

  ///角色列表
  void roleListRequest(int page, int pageSize, success) {
    fetchList(Method.post, url: HttpApi.listDepartmentRoles, onSuccess: (data) {
      roleNos = data.map<String>((e) => e['roleNo']).toList();
      state.noRoleList = data.isEmpty;
      update();
      success(data);
    }, params: {'departmentNo': departmentNo});
  }

  ///人员列表
  void usersListRequest(page, pageSize, success) {
    fetchList(
      Method.post,
      url: HttpApi.listDepartmentUsers,
      onSuccess: (data) {
        userNos = data.map<String>((e) => e['userNo']).toList();
        success(data);
      },
      params: {
        'departmentNo': departmentNo,
        'page': page,
        'pageSize': pageSize, //1员工 2领导
        'userMobile': '',
        'userName': ''
      }..addIf(adminPosition != 1, 'type', 1),
    );
  }

  ///添加角色
  void goToRolePage() {
    Get.toNamed(
      RouteConfig.roleSelectPage,
      arguments: {'forbidNo': roleNos},
    )?.then((value) {
      List<String> list = [];
      for (var item in (value as List<dynamic>)) {
        list.add(item['roleNo']);
      }
      list.addAll(roleNos);
      _addRolesRequest({'departmentNo': departmentNo, 'roleNos': list});
    });
  }

  ///添加角色
  void _addRolesRequest(params) {
    fetch(Method.post, url: HttpApi.positionDetailsAddRoles, onSuccess: (data) {
      controller.index = 1;
      state.roleListController.callRefresh();
    }, params: params);
  }

  ///去添加人员
  void goToStaffPage() {
    Get.toNamed(RouteConfig.staffListSelectPage,
        arguments: {'forbidNo': userNos})?.then((value) {
      List<dynamic> list = [];
      for (var item in (value as List<dynamic>)) {
        list.add({'userName': item['userName'], 'userNo': item['userNo']});
      }
      _addStaffsRequest({'departmentNo': departmentNo, 'users': list});
    });
  }

  ///添加人员
  void _addStaffsRequest(params) {
    fetch(Method.post, url: HttpApi.positionDetailsAddStaffs,
        onSuccess: (data) {
      controller.index = 0;
      state.memberListController.callRefresh();
      OrganizationEvent.refreshData();
    }, params: params);
  }

  ///职位设置
  void goToPositionSettingPage() {
    Get.toNamed(RouteConfig.positionSettingPage, arguments: {
      'departmentNo': departmentNo,
      'departmentName': state.position,
      'adminPosition': adminPosition,
      'isMyDepartment': fromMyDepartment,
      'departmentPno': state.parents[state.parents.length - 2]['departmentNo']
    })?.then((value) {
      OrganizationEvent.refreshData();
      if (value == 'delete') {
        Get.back();
      } else {
        _requestPositionDetail();
      }
    });
  }

  void geToRoleDetails(item) async {
    var result = await Get.toNamed(RouteConfig.roleDetailsPage, arguments: {
      'roleNo': item['roleNo'],
      'from': 'position',
      'showDelete': canShowBottom()
    });
    if (result == 'delete') {
      deleteRow(item);
    }
  }

  void deleteRow(item) {
    fetch(Method.delete, url: HttpApi.deleteDepartmentRole, onSuccess: (data) {
      ToastUtil.showToast('删除成功！');
      state.roleListController.callRefresh();
    }, queryParameters: {
      'roleNo': item['roleNo'],
      'departmentNo': departmentNo
    });
  }

  void removeMember(userNo) {
    fetch(
      Method.post,
      url: HttpApi.deleteUserPosition,
      onSuccess: (data) {
        state.memberListController.callRefresh();
        OrganizationEvent.refreshData();
        ToastUtil.showToast('移除成功！');
      },
      params: {
        'userNo': userNo,
        'departmentNo': departmentNo,
      },
    );
  }

  bool canShowBottom() {
    return !(adminPosition == 1 && fromMyDepartment);
  }
}
