import React from 'react';
import PropTypes from 'prop-types';
import { Menu, Breadcrumb, Icon } from 'antd';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { fullPath } from '../../utils/helper';
import styles from './header.less';

const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;

class HeaderPane extends React.Component {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'main/fetchUser' });
    dispatch({ type: 'main/fetchDomain' });
    dispatch({ type: 'main/fetchDomains' });
  }
  render() {
    const { dispatch, user, domain, domainList, routes, params } = this.props;
    const userTitle = (
      <span>
        <Icon type="user" />
        { user }
      </span>
    );
    const domainTitle = (
      <span>
        <Icon type="home" />
        { domain }
      </span>
    );
    const onClick = ({ keyPath }) => {
      if (keyPath[1] === 'user' && keyPath[0] === 'logout') {
        dispatch({ type: 'main/logout' });
      } else if (keyPath[1] === 'domain') {
        dispatch({ type: 'main/switchDomain', payload: keyPath[0] });
      }
    };
    const breadsProps = {
      className: styles.breads,
      routes,
      params,
      itemRender(route, _params, _routes, paths) {
        if (!paths || !paths.length) {
          return null;
        }
        if (paths.length === 1) {
          return <Icon type="home" />;
        }
        const bread = route.name ? route.name : route.path;
        return <Link to={fullPath(`/${paths.join('/')}`)}>{ bread }</Link>;
      },
    };
    const menuProps = {
      className: styles.menu,
      mode: 'horizontal',
      theme: 'light',
      selectable: false,
      onClick,
    };
    return (
      <div className={styles.board}>
        <Breadcrumb {...breadsProps} />
        <Menu {...menuProps}>
          <SubMenu title={userTitle} key="user" >
            <MenuItem key="logout">
              <span>
                <Icon type="logout" />
                登出
              </span>
            </MenuItem>
          </SubMenu>
          <SubMenu title={domainTitle} key="domain">
            {
              domainList.map(dm => (
                <MenuItem key={dm.path}>
                  { dm.name }
                </MenuItem>
              ))
            }
          </SubMenu>
        </Menu>
      </div>
    );
  }
}

HeaderPane.propTypes = {
  dispatch: PropTypes.func,
  user: PropTypes.string,
  domain: PropTypes.string,
  domainList: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number,
    name: PropTypes.string,
  })),
};

const mapStateToProps = ({ main }) => {
  return {
    user: main.user,
    domain: main.domain,
    domainList: main.domainList,
  };
};

export default connect(mapStateToProps)(HeaderPane);