function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useState, useEffect, useMemo } from 'react';
import { Checkbox, Empty, Button } from 'antd';
import { Icon } from '@pisell/materials';
import "./index.less";
// 权限类型的配置映射
var PERMISSION_TYPE_CONFIG = {
  channel: {
    titleKey: 'pisell2.saas.role.channels',
    descriptionKey: 'pisell2.saas.role.control-access-channels',
    prefix: 'channel:'
  },
  pageType: {
    titleKey: 'pisell2.saas.role.page-types',
    descriptionKey: 'pisell2.saas.role.control-access-page-types',
    prefix: 'page:'
  },
  app: {
    titleKey: 'pisell2.saas.role.apps',
    descriptionKey: 'pisell2.saas.role.control-access-apps',
    prefix: 'app:'
  },
  systemManagement: {
    titleKey: 'pisell2.saas.role.system-management',
    descriptionKey: 'pisell2.saas.role.control-system-operations',
    prefix: 'system:'
  }
};
var PermissionManager = function PermissionManager(_ref) {
  var availablePermissions = _ref.availablePermissions,
    currentPermissions = _ref.currentPermissions,
    onChange = _ref.onChange,
    getLocaleText = _ref.getLocaleText,
    getText = _ref.getText,
    updating = _ref.updating;
  // 本地状态管理选中的权限
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    selectedPermissions = _useState2[0],
    setSelectedPermissions = _useState2[1];
  console.log('selectedPermissions', selectedPermissions);
  // 获取所有可用权限类型及其数据
  var permissionTypes = useMemo(function () {
    if (!availablePermissions) return [];
    return Object.keys(availablePermissions).filter(function (key) {
      var _availablePermissions;
      return ((_availablePermissions = availablePermissions[key]) === null || _availablePermissions === void 0 ? void 0 : _availablePermissions.length) > 0;
    }).map(function (key) {
      return {
        type: key,
        items: availablePermissions[key],
        config: PERMISSION_TYPE_CONFIG[key] || {
          titleKey: key,
          descriptionKey: "Control access to ".concat(key),
          prefix: "".concat(key, ":")
        }
      };
    });
  }, [availablePermissions]);

  // 当 currentPermissions 改变时，更新本地状态
  useEffect(function () {
    if (currentPermissions.includes('*')) {
      // 处理 ["*"] 全权限的情况 - 选中所有可用权限
      var allPermissions = permissionTypes.flatMap(function (pt) {
        return pt.items.map(function (item) {
          return item.code;
        });
      });
      setSelectedPermissions(allPermissions);
    } else {
      // 过滤出所有已知类型的权限
      var knownPrefixes = permissionTypes.map(function (pt) {
        return pt.config.prefix;
      });
      var relevantPermissions = currentPermissions.filter(function (p) {
        return knownPrefixes.some(function (prefix) {
          return p.startsWith(prefix);
        }) || p.includes(':');
      });
      setSelectedPermissions(relevantPermissions);
    }
  }, [currentPermissions, permissionTypes]);

  // 判断某个类型是否全选
  var isTypeAllSelected = function isTypeAllSelected(items) {
    return items.length > 0 && items.every(function (item) {
      return selectedPermissions.includes(item.code);
    });
  };

  // 处理某个类型的全选/取消全选
  var handleTypeSelectAll = function handleTypeSelectAll(items, checked) {
    var itemCodes = items.map(function (item) {
      return item.code;
    });
    if (checked) {
      // 添加该类型的所有权限
      var newPermissions = _toConsumableArray(selectedPermissions);
      itemCodes.forEach(function (code) {
        if (!newPermissions.includes(code)) {
          newPermissions.push(code);
        }
      });
      setSelectedPermissions(newPermissions);
    } else {
      // 移除该类型的所有权限
      setSelectedPermissions(selectedPermissions.filter(function (p) {
        return !itemCodes.includes(p);
      }));
    }
  };

  // 处理单个权限勾选
  var handlePermissionChange = function handlePermissionChange(code, checked) {
    if (checked) {
      setSelectedPermissions([].concat(_toConsumableArray(selectedPermissions), [code]));
    } else {
      setSelectedPermissions(selectedPermissions.filter(function (p) {
        return p !== code;
      }));
    }
  };

  // 保存权限
  var handleSave = function handleSave() {
    // 获取所有已知权限前缀
    var knownPrefixes = permissionTypes.map(function (pt) {
      return pt.config.prefix;
    });

    // 保留不在已知类型中的其他权限（如果有的话）
    var otherPermissions = currentPermissions.filter(function (p) {
      return !knownPrefixes.some(function (prefix) {
        return p.startsWith(prefix);
      }) && p !== '*';
    });

    // 合并其他权限和当前选中的权限
    var finalPermissions = [].concat(_toConsumableArray(otherPermissions), _toConsumableArray(selectedPermissions));
    onChange(finalPermissions);
  };
  if (!permissionTypes || permissionTypes.length === 0) {
    return /*#__PURE__*/React.createElement(Empty, {
      description: getText('pisell2.saas.role.no-permissions')
    });
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "permission-manager"
  }, /*#__PURE__*/React.createElement("div", {
    className: "permission-sections-container"
  }, permissionTypes.map(function (_ref2) {
    var type = _ref2.type,
      items = _ref2.items,
      config = _ref2.config;
    var isAllSelected = isTypeAllSelected(items);
    return /*#__PURE__*/React.createElement("div", {
      key: type,
      className: "permission-section"
    }, /*#__PURE__*/React.createElement("div", {
      className: "permission-section-title"
    }, /*#__PURE__*/React.createElement("h4", null, getText(config.titleKey)), /*#__PURE__*/React.createElement("p", null, getText(config.descriptionKey))), /*#__PURE__*/React.createElement("div", {
      className: "permission-section-content"
    }, /*#__PURE__*/React.createElement("div", {
      className: "permission-section-actions"
    }, /*#__PURE__*/React.createElement(Button, {
      size: "small",
      type: "text",
      icon: isAllSelected ? /*#__PURE__*/React.createElement(Icon, {
        type: "pisell2-square"
      }) : /*#__PURE__*/React.createElement(Icon, {
        type: "pisell2-check-square-broken"
      }),
      style: {
        padding: 0,
        fontSize: 12
      },
      onClick: function onClick() {
        return handleTypeSelectAll(items, !isAllSelected);
      }
    }, isAllSelected ? getText('pisell2.saas.role.clear-all') : getText('pisell2.saas.role.select-all'))), /*#__PURE__*/React.createElement("div", {
      className: "permission-items"
    }, items.map(function (item) {
      return /*#__PURE__*/React.createElement("div", {
        key: item.code,
        className: "permission-item"
      }, /*#__PURE__*/React.createElement(Checkbox, {
        checked: selectedPermissions.includes(item.code),
        onChange: function onChange(e) {
          return handlePermissionChange(item.code, e.target.checked);
        }
      }, getLocaleText(item.name)));
    }))));
  })), /*#__PURE__*/React.createElement("div", {
    className: "permission-manager-footer"
  }, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    onClick: handleSave,
    loading: updating
  }, getText('pisell2.saas.role.save'))));
};
export default PermissionManager;