import 'package:account_center/api/base_model.dart';
import 'package:account_center/page/staff_manager/member_manage_event.dart';
import 'package:account_center/page/staff_manager/model/department_and_position_vos.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import '../../../routes/route_config.dart';

class StaffDetailLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  late TabController controller;

  String? userNo;
  dynamic companyNo;

  /// 从职位详情进入
  bool fromPositionDetail = false;

  dynamic detail = {};

  List<dynamic> departmentList = [];

  List<dynamic> roleList = [];

  List<dynamic> positionList = [];

  @override
  void onInit() {
    controller = TabController(length: 2, vsync: this);
    var arguments = Get.arguments as Map;
    userNo = arguments['userNo'];
    companyNo = arguments['companyNo'];
    fromPositionDetail = arguments['isFromPosition'] ?? false;
    super.onInit();
  }

  @override
  void onReady() {
    requestDetail();
    // requestRoleList();
    super.onReady();
  }

  void enableUser() {
    LoadingUtils.showLoading(text: '');
    fetch(
      Method.put,
      url: HttpApi.updateStaffStatus,
      queryParameters: {
        'companyNo': companyNo,
        'userNo': userNo.toInt(),
        'status': detail['status'] == 20 ? 10 : 20
      },
      onSuccess: (response) {
        ToastUtil.showToast(detail['status'] == 20 ? '启用成功' : '禁用成功');
        requestDetail();
        LoadingUtils.dismiss();
      },
      onError: (code, msg) {
        LoadingUtils.dismiss();
      },
    );
  }

  /// 获取详情
  void requestDetail() {
    fetch(Method.get,
        url: HttpApi.getEmpDetailGroupByRolesWithType,
        queryParameters: {
          'companyNo': companyNo,
          'userNo': userNo,
        }, onSuccess: (response) {
      detail = response;
      roleList = response['roles'] ?? [];
      positionList = response['positions'] ?? [];
      departmentList = response['deptAndRoles'] ?? [];
      LoadingUtils.dismiss();
      update();
    }, onError: (code, msg) {
      ToastUtil.showToast(msg);
      LoadingUtils.dismiss();
    });
  }

  void back() {
    Get.back();
  }

  void editPeople() {
    Get.toNamed(RouteConfig.editPeoplePage, arguments: {
      'userNo': userNo,
      'companyNo': companyNo,
    })?.then((value) {
      requestDetail();
    });
  }

  /// 局部刷新key
  final int keyRoleList = 0, keyPositionList = 1;

  Future<void> addPosition() async {}

  void requestAddPosition(List<String> ids) {
    fetch(Method.post, url: HttpApi.saveUserPosition, params: {
      'departmentNos': ids,
      'companyNo': companyNo.toString().toInt(),
      'userNo': userNo.toInt(),
    }, onSuccess: (response) {
      requestDetail();
    }, onError: (code, msg) {
      LoadingUtils.dismiss();
      ToastUtil.showToast(msg);
    });
  }

  /// 角色列表
  void requestRoleList() {}

  void remove() {
    ConfirmDialog(
      content: '确定要将该人员离职吗？',
      confirm: () {
        fetch(
          Method.delete,
          url: HttpApi.deleteStaff,
          queryParameters: {
            'companyNo': companyNo,
            'userNo': userNo,
          },
          onSuccess: (response) {
            ToastUtil.showToast('离职成功');
            Get.back();
            MemberManageEvent.refreshData();
          },
          onError: (code, msg) {},
        );
      },
    ).show();
  }

  /// 有信息
  bool hasBaseMessage() {
    return true;
  }

  void toPositionDetail(DepartmentAndPositionVos? position) {
    Get.toNamed(RouteConfig.positionTreePage, arguments: {
      'positionNo': position?.positionNo ?? 0,
      'userNo': userNo
    })?.then((value) {
      if (value != null) {
        requestDetail();
      }
    });
  }

  Future<void> toRoleDetail(role) async {
    var result = await Get.toNamed(RouteConfig.roleDetailsPage, arguments: {
      'roleNo': role['roleNo'],
      'from': 'user',
    });
    if (result == 'delete') {
      fetch(Method.delete, url: HttpApi.deleteUserRole, onSuccess: (data) {
        ToastUtil.showToast('删除成功！');
        requestRoleList();
      }, queryParameters: {'roleNo': role['roleNo'], 'userNo': userNo});
    }
  }

  void removeFromPosition() {
    ConfirmDialog(
      content: '确定删除此人员！',
      confirm: () {
        Get.back(result: 'delete');
      },
    );
  }
}
