import React, { useMemo } from 'react';
import style from './index.less';
import { Dropdown } from '@easyv/antd';
import { DownOutlined } from '@easyv/react-icons';
import { useHistory } from 'react-router-dom';
import { connect } from 'react-redux';
import { getSpace, setCurrent, addSpace } from 'models/space';
import { selectGroup } from 'models/group';
import { useProductionInfo } from 'components/easyUse';
type Iprops = {
  spaceList: any[];
  current: number;
  selectGroup: (x: number) => void;
  setCurrent: (current: number) => void;
  addSpace: (name: string) => void;
};

function EasyvSpace({ spaceList, current, selectGroup, setCurrent }: Iprops): React.ReactElement {
  const productionInfo = useProductionInfo();
  const { isAdmin, isRoot, isLocal } = productionInfo;
  const selectSpace = async (id: number) => {
    await setCurrent(id);
    await selectGroup(0);
  };

  const history = useHistory();

  const active = useMemo(() => {
    return spaceList.find((d) => d.id === current);
  }, [spaceList, current]);

  const content = (
    <div className={style.content}>
      <div className={style.spaceList}>
        {spaceList.map((e) => {
          return (
            <p
              onClick={() => {
                selectSpace(e.id);
              }}
              className={e.id === current ? style.active : ''}
              key={e.id}>
              {e.name}
            </p>
          );
        })}
      </div>

      {isRoot || isAdmin ? (
        <div
          className={style.addSpace}
          onClick={() => {
            const url = BASENAME + '/space';
            const result = window.open(url, 'space', '');
            !result && history.push('/space');
          }}>
          <span>管理空间</span>
        </div>
      ) : null}
    </div>
  );
  const DropdownNode = (
    <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
      <span className={style.spaceName}>{active?.name || '默认工作空间'}</span>
      <DownOutlined className={style.down} />
    </div>
  );

  return (
    <div className={style.space}>
      <Dropdown placement="bottomLeft" overlayClassName={style.popover} overlay={content} trigger={['click']}>
        {DropdownNode}
      </Dropdown>
    </div>
  );
}
function mapStateToProps({ space }) {
  return {
    spaceList: space.list,
    current: space.current
  };
}

export default connect(mapStateToProps, {
  getSpace,
  setCurrent,
  addSpace,
  selectGroup
})(EasyvSpace);
