import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Store } from 'amos-tool';
import { Connect as UIConnect, Animate } from 'amos-framework';
import SysConsts from 'amos-processor/lib/config/consts';
import Header from './../common/header';
import { header3dConf, triggerMenuChange, is3dView, getAddress } from './headerConf';
import { getPermissionsMenus } from '../../services/securityService';
import { eventTopics } from './../../view/tileView/consts';

const lsTool = Store.lsTool;

@UIConnect.eventConnect
class Root3DView extends Component {

  constructor(props) {
    super(props);
    this.state = {
      menus: [],
      is3DPage: false
    };
    this.address = getAddress();
  }

  componentDidMount() {
    this.initMenus();
    this.props.subscribe(eventTopics.plan_start, (topic, data) => {
      this.setState({
        planStarted: data.planStarted
      });
    });
  }

  initMenus = () => {
    let role = lsTool.read('selectedRole');
    getPermissionsMenus(role).then((menus = []) => {
      let userMenus = [];
      menus.forEach(element => {
        if (element.permissionType === 'MENU' && element.path === 'main') {
          userMenus = element.children;
        }
      });
      if (!userMenus || userMenus.length < 1) {
        return;
      }
      const lsTool = Store.lsTool;
      lsTool.write(SysConsts.permissions, JSON.stringify(menus));
      let view3dMenus = [...userMenus];
      view3dMenus = this.filterMenusButton(view3dMenus);
      this.setState({
        menus: view3dMenus
      });
    });
  }

  handleMenuClick = (item) => {
    const { permissionCode } = item;
    if (!is3dView(permissionCode)){
      triggerMenuChange(permissionCode);
    }
  }

  filterMenusButton = (menus) => {
    return menus.filter(
      menu => {
        if (menu.children && menu.permissionType === 'SUBMENU') {
          menu.children = this.filterMenusButton(menu.children);
          return true;
        }
        if (!menu.children && menu.permissionType === 'SUBMENU') {
          return true;
        }
        if (!menu.children || menu.permissionType === 'BUTTON') {
          return false;
        }
      }
    );
  }

  render() {
    const { menus, planStarted } = this.state;
    const { children } = this.props;
    // debugger;
    return (
      <div className="root-3dview">
        <div className="view-port">
          <Animate key="animate-sidecontrol" transitionName="zoom-comb-up" showProp="visible" transitionAppear>
            {!planStarted ? <Header {...header3dConf} address={this.address} menus={menus} onMenuItemClick={this.handleMenuClick} /> : null}
          </Animate>
          <div className="content-body">{children}</div>
        </div>
      </div>
    );
  }
}

Root3DView.propTypes = {
  children: PropTypes.node,
  subscribe: PropTypes.func
};

export default Root3DView;
