import { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * 权限控制
 *
 * @class HasPermission
 * @extends {Component}
 */
class HasPermission extends Component{
  constructor(props) {
    super(props);
    this.state = {
      isWriteable: false
    };
  }

  componentWillMount() {
    const { permissionCode } = this.props;
    const permissionsMenus = window.localStorage.getItem('permissions');
    let data = [];
    if (permissionsMenus) {
      data = JSON.parse(permissionsMenus);
    }
    if (data && permissionCode) {
      data = data.filter(element => element.permissionType === 'MENU' && element.path === 'biz');
      this.filterPermissionsButton(data, permissionCode);
    } else {
      this.setState({ isWriteable: false });
    }
  }

  getRender = () => {
    const { isWriteable } = this.state;
    if (isWriteable) {
      return this.props.children;
    } else {
      return '';
    }
  }

  filterPermissionsButton = (data, permissionCode) => {
    data.find(
      menu => {
        if (menu.children && menu.children.length > 0) {
          this.filterPermissionsButton(menu.children, permissionCode);
          return false;
        }
        if (menu.permissionType === 'BUTTON' && permissionCode === menu.authCode) {
          this.setState({ isWriteable: true });
          return true;
        }
        return false;
      }
    );
  }

  render() {
    return this.getRender();
  }
}



HasPermission.propTypes = {
  children: PropTypes.node,
  permissionCode: PropTypes.string
};

export default HasPermission;
