import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/product_menu_control.dart';
import 'package:account_center/common/sp/sp_util.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 'product_details_permission_state.dart';

class ProductDetailsPermissionLogic extends GetxController {
  final ProductDetailsPermissionState state = ProductDetailsPermissionState();
  List<dynamic> menuList = [];

  @override
  void onInit() {
    super.onInit();

    ///产品数据
    state.entity = Get.arguments['entity'];
    menuList = Get.arguments['menuList'] ?? [];
    state.onlyShow = Get.arguments['onlyShow'] ?? false;
    state.showDelete = !state.onlyShow &&
        Get.arguments['from'] == 'roleManager' &&
        hasMenuPermission('btn_remove_role_product');
  }

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

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

  void _requestMenuData() {
    fetchList(
      Method.get,
      url: HttpApi.listMenusByProduct,
      queryParameters: {
        'productCode': state.entity['productCode'] ?? '',
        'companyNo': getCompanyNo()
      },
      onSuccess: (response) {
        state.listData = TreeNode.formatNodes(
          response,
          'childrenList',
          formatData,
        );
        update();
      },
      onError: (code, msg) {
        ToastUtil.showToast(msg);
      },
    );
  }

  TreeNode formatData(element) => TreeNode()
    ..canExpand = element['menuType'] != 3
    ..isChecked = state.onlyShow ? false : _getChecked(element)
    ..data = element
    ..title = element['menuName'] ?? ''
    ..canCheck = state.onlyShow ? false : true;

  bool? _getChecked(element) {
    dynamic contains = menuList
        .firstWhereOrNull((menu) => element['menuNo'] == menu['menuNo']);
    if (contains == null) {
      return false;
    } else {
      if (contains['halfStatus'] == 0) {
        return null;
      } else {
        return true;
      }
    }
  }

  List<dynamic> _selectData(List<TreeNode> nodes) {
    List<dynamic> result = [];
    for (var node in nodes) {
      if (node.isChecked == false) continue;
      Map map = {};
      map['menuCode'] = node.data['menuCode'];
      map['menuNo'] = node.data['menuNo'];
      result.add(map);
      result.addAll(_selectData(node.children));
    }
    return result;
  }

  /// 确定
  void confirm() {
    Get.back(result: {
      'menuList': _selectData(state.listData),
      'entity': state.entity
    });
  }

  /// 删除角色
  void deleteRole() {
    Get.dialog(
        ConfirmDialog(
          content: '确定删除此产品？',
          confirm: () {
            Get.back(result: {
              'type': 'delete',
              'entity': state.entity,
            });
          },
        ),
        useSafeArea: true);
  }
}
