import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { Input, Tooltip } from '@easyv/antd';
import classNames from 'classnames';
import GroupItem from './SpaceItem';
import styles from './GroupMenu.less';
import Sortable from 'react-sortablejs';
import { spacesCut, getSpace, moveSpace, addSpace, deleteSpace, updateSpace } from 'models/space';
import message from 'components/message';

type IProps = ConnectedProps<typeof connector>;

function SpaceMenu({ spaceList, current, setCurrent, getSpace, moveSpace, addSpace, deleteSpace, updateSpace }: IProps) {
  const [inputShow, setInputShow] = useState<boolean>(false);
  const inputRef = useRef<Input>(null);
  const [defaultSpaceInput, setdefaultSpaceInput] = useState<boolean>(false);
  const [menuVisible, setMenuVisible] = useState<boolean>(true);

  const defaultSpace = useMemo(() => {
    return spaceList.find((d) => !d.type);
  }, [spaceList]);

  useEffect(() => {
    getSpace();
  }, []);

  useEffect(() => {
    if (inputShow || defaultSpaceInput) {
      inputRef.current && inputRef.current.focus();
    }
  }, [inputShow, defaultSpaceInput]);

  const handleAddClick = () => {
    setInputShow(true);
    setMenuVisible(true);
  };

  const defaultSpaceInputBlur = (e) => {
    const value = e.target.value.trim();
    if (value && value != defaultSpace.name) {
      updateSpace({
        name: value
      });
    }
    setdefaultSpaceInput(false);
  };
  const handleBlur = (e) => {
    const value = e.target.value.trim();
    if (value) {
      addSpace(value);
    }
    setInputShow(false);
  };

  const handleSelectGroup = (groupId: number) => {
    current != groupId && setCurrent(groupId);
  };
  const updateGroup = (data) => {
    // 修改名字
    const name = data.name.trim();
    name && updateSpace({ name });
  };
  const deleteGroup = (id) => {
    deleteSpace(id);
  };
  // 这个事件不要删除
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  const handleChange = useCallback(() => {}, []);

  return (
    <div className={styles.container}>
      <h3 className={styles.title}>
        <p className={styles.title_left}>
          <i
            className={classNames('icon iconfont icon-sanjiaoxing ' + styles.app_icon_drop)}
            onClick={() => setMenuVisible(!menuVisible)}
            style={{ transform: menuVisible ? 'rotate(90deg)' : 'rotate(0deg)' }}
          />
          <i className="icon iconfont icon-workspace-manage-cion" />
          <span className={styles.app_list}>空间列表</span>
        </p>
        <i className={'icon iconfont icon-btn_addgroup ' + styles.addIcon} onClick={handleAddClick} />
      </h3>

      <div className={styles.menu} style={{ display: menuVisible ? 'block' : 'none' }}>
        {defaultSpace && (
          <div
            className={classNames(styles.menuItem, {
              [styles.active]: current === defaultSpace.id
            })}
            onDoubleClick={() => {
              // 双击
              setdefaultSpaceInput(true);
            }}
            onClick={() => handleSelectGroup(defaultSpace.id)}>
            {defaultSpaceInput ? (
              <Input
                ref={inputRef}
                defaultValue={defaultSpace.name}
                maxLength={20}
                onBlur={defaultSpaceInputBlur}
                onPressEnter={(e: any) => e.target.blur()}
              />
            ) : (
              defaultSpace.name
            )}
          </div>
        )}

        {inputShow && (
          <div className={classNames(styles.menuItem, styles.inputItem)}>
            <Input ref={inputRef} maxLength={20} onBlur={handleBlur} onPressEnter={(e: any) => e.target.blur()} />
          </div>
        )}

        <div
          className={classNames(styles.dropContainer, {
            [styles.isDragging]: false
          })}>
          <Sortable
            tag="div"
            onChange={handleChange}
            options={{
              group: 'nested',
              animation: 150,
              swapThreshold: 0.65,
              direction: 'vertical',
              onEnd: moveSpace,
              scroll: true
            }}>
            {spaceList
              .filter((d) => d.type)
              .map((d, i) => {
                return (
                  <GroupItem
                    key={d.id}
                    id={d.id}
                    index={i}
                    name={d.name}
                    active={current === d.id}
                    isFirst={i === 0}
                    selectGroup={handleSelectGroup}
                    updateGroup={updateGroup}
                    deleteGroup={deleteGroup}
                  />
                );
              })}
          </Sortable>
        </div>
      </div>
    </div>
  );
}

const mapStateToProps = ({ space, user }) => {
  const { list: spaceList, current } = space;
  const { userInfo } = user;

  return {
    spaceList,
    current: current,
    userInfo
  };
};

const mapDispacthToProps = {
  setCurrent: spacesCut,
  getSpace,
  moveSpace,
  addSpace,
  deleteSpace,
  updateSpace
};

const connector = connect(mapStateToProps, mapDispacthToProps);

export default connector(SpaceMenu);
