import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/page/enterprise/role_management/role_management_logic.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'role_details_state.dart';

class RoleDetailsLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final RoleDetailsState state = RoleDetailsState();

  String roleNo = '';

  bool get fromUserDetail => state.from.isNotEmpty;

  bool showDelete = true;

  late TabController controller;

  List<dynamic> userList = [];

  List<dynamic> departmentList = [];

  @override
  void onInit() {
    super.onInit();
    controller = TabController(length: 3, vsync: this);
    roleNo = Get.arguments['roleNo'] ?? '';
    state.from = Get.arguments['from'] ?? 'roleManager';
    showDelete = Get.arguments['showDelete'] ?? true;
    _refreshListData();
  }

  void _refreshListData() {
    _roleDetailsRequest();
    _requestDepartList();
    _requestUserList();
  }

  ///获取用户详情接口
  void _roleDetailsRequest() {
    fetch(Method.get,
        url: HttpApi.roleDetails,
        queryParameters: {"roleNo": roleNo}, onSuccess: (data) {
      if (data != null) {
        state.listPro = data['productInfo'] ?? [];
        state.data = data;
        update();
      }
    });
  }

  void _requestUserList() {
    fetch(Method.post,
        url: HttpApi.pageRoleUsersList,
        params: {"roleNo": roleNo}, onSuccess: (data) {
      userList = data['records'];
      update();
    });
  }

  void _requestDepartList() {
    fetch(Method.post,
        url: HttpApi.pageRoleDepartmentsList,
        params: {"roleNo": roleNo}, onSuccess: (data) {
      departmentList = data['records'];
      update();
    });
  }

  ///删除用户角色
  void deleteUserRoleRequest() {
    ConfirmDialog(
      content: '确定移除此角色？',
      confirm: () {
        Get.back(result: 'delete');
      },
    ).show();
  }

  ///角色设置
  void goToRoleSettingPage() {
    Get.toNamed(RouteConfig.roleSettingPage, arguments: state.data)
        ?.then((value) {
      if (value is String) {
        ///删除后回到列表页
        if (value == deleteRole) {
          Get.back(result: value);
        } else {
          _roleDetailsRequest();
        }
      } else {
        _roleDetailsRequest();
      }
    });
  }

  ///跳转新增产品
  void goToAddProductPage() {
    Get.toNamed(RouteConfig.productListPage,
            arguments:
                state.listPro.map<String>((e) => e['productCode']).toList())
        ?.then((value) {
      if (value != null) {
        _newRoleProductRequest(value['entity'], value['menuList']);
        update();
      }
    });
  }

  ///新增产品
  void _newRoleProductRequest(entity, menuList) {
    fetch(Method.post, url: HttpApi.roleNewProduct, onSuccess: (data) {
      ToastUtil.showToast('新增成功');
      _roleDetailsRequest();
    }, params: {
      'productCode': entity['productCode'],
      'roleNo': roleNo,
      'companyNo': state.data['companyNo'],
      'menuList': menuList,
    });
  }

  ///去重
  void removeRepeat(entity, menuList) {
    if (state.listPro.isEmpty) {
      state.listPro.add({
        'productCode': entity['productCode'],
        'productTypeMsg': entity['productTypeMsg'],
        'productName': entity['productName'],
        'roleNo': roleNo,
        'menuList': menuList
      });
      return;
    }
    for (var element in state.listPro) {
      if (element['productCode'] != entity['productCode']) {
        state.listPro.add({
          'productCode': entity['productCode'],
          'productTypeMsg': entity['productTypeMsg'],
          'productName': entity['productName'],
          'menuList': menuList
        });
        break;
      }
    }
  }

  List<dynamic> getSelectMenus(menus) {
    var list = [];
    if (menus is List) {
      for (var element in menus) {
        list.add({'menuNo': element['menuNo']});
        list.addAll(getSelectMenus(element['childMenuList']));
      }
    }
    return list;
  }

  ///条目点击事件
  void gotoProductPermissionPage(entity) {
    Get.toNamed(
      RouteConfig.productDetailsPermissionPage,
      arguments: {
        'menuList': getSelectMenus(entity['menuVoList']),
        'entity': entity,
        'from': state.from,
      }..addIf(state.from == 'position' || state.data?['roleStrategy'] == 1,
          'onlyShow', true),
    )?.then((value) {
      if (value == null) return;
      if (value?['type'] == 'delete') {
        _deleteProduct(value['entity']);
      } else {
        _updateProductMenuRequest(value['entity'], value['menuList']);
      }
    });
  }

  ///更新角色产品权限
  void _updateProductMenuRequest(entity, menuList) {
    fetch(Method.post, url: HttpApi.roleUpdateProductMenu, onSuccess: (data) {
      _roleDetailsRequest();
      ToastUtil.showToast('编辑成功');
    }, params: {
      'roleNo': roleNo,
      'productCode': entity['productCode'] ?? '',
      'menuList': menuList ?? [],
    });
  }

  ///删除产品
  void _deleteProduct(entity) {
    fetch(Method.delete, url: HttpApi.deleteRoleProduct, onSuccess: (data) {
      ToastUtil.showToast('删除成功');
      _roleDetailsRequest();
    }, queryParameters: {
      'roleNo': roleNo,
      'productCode': entity['productCode'] ?? '',
    });
  }

  void addDepartment() {
    Get.toNamed(RouteConfig.departmentSelectPage, arguments: {
      'forbidNos': departmentList
          .map<String>((e) => e['departmentNo'].toString())
          .toList()
    })?.then((value) {
      if (value == null) return;
      _requestAddDepartment(value);
    });
  }

  void addUser() {
    Get.toNamed(
      RouteConfig.staffListSelectPage,
      arguments: {
        'forbidNo': userList.map((e) => e['userNo']?.toString() ?? '').toList()
      },
    )?.then((data) {
      if (data != null) {
        _requestAddUser(data);
      }
    });
  }

  void _requestAddUser(List<dynamic> users) {
    if (users.isEmpty) return;
    LoadingUtils.showLoading(text: '');
    fetch(Method.post,
        url: HttpApi.saveRoleUsers,
        onSuccess: (data) {
          _requestUserList();
          LoadingUtils.dismiss();
          ToastUtil.showToast('添加成功');
        },
        params: {
          'companyNo': SpUtil.getString(SPKey.companyNo),
          'roleNo': roleNo,
          'userNos': users.map((e) => e['userNo']?.toString() ?? '').toList(),
        },
        onError: (error, code) {
          LoadingUtils.dismiss();
        });
  }

  void _requestAddDepartment(List<dynamic> departs) {
    LoadingUtils.showLoading(text: '');
    fetch(Method.post,
        url: HttpApi.saveRoleDepartments,
        onSuccess: (data) {
          _requestDepartList();
          LoadingUtils.dismiss();
          ToastUtil.showToast('添加成功');
        },
        params: {
          'companyNo': SpUtil.getString(SPKey.companyNo),
          'roleNo': roleNo,
          'departmentNos':
              departs.map((e) => e['departmentNo']?.toString() ?? '').toList(),
        },
        onError: (error, code) {
          LoadingUtils.dismiss();
        });
  }

  void deletePerson(staff) {
    ConfirmDialog(
        content: '确定移除该成员',
        confirm: () {
          LoadingUtils.showLoading(text: '');
          fetch(Method.post, url: HttpApi.deleteRoleUsers, params: {
            'roleNo': roleNo,
            'userNos': [staff?['userNo']]
          }, onSuccess: (response) {
            _requestUserList();
            LoadingUtils.dismiss();
            ToastUtil.showToast('移除成功');
          }, onError: (code, message) {
            LoadingUtils.dismiss();
          });
        }).show();
  }

  void deleteDepart(element) {
    ConfirmDialog(
        content: '确定移除该部门',
        confirm: () {
          LoadingUtils.showLoading(text: '');
          fetch(Method.post, url: HttpApi.deleteRoleDepartments, params: {
            'roleNo': roleNo,
            'departmentNos': [element?['departmentNo']]
          }, onSuccess: (response) {
            _requestDepartList();
            LoadingUtils.dismiss();
            ToastUtil.showToast('移除成功');
          }, onError: (code, message) {
            LoadingUtils.dismiss();
          });
        }).show();
  }
}
