/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { Input, Progress } from '@easyv/antd';
import classNames from 'classnames';
import Sortable from 'react-sortablejs';
import GroupItem from './GroupItem';
import UngroupItem from './UngroupItem';
import { spacesCut } from 'models/space';
import { selectGroup, getGroups, addGroup, deleteGroup, updateGroup, moveScreenToGroup, moveGroup } from 'models/group';
import { getScreens, clearScreenList } from 'models/screens';
import TrashMenu from './TrashMenu';
import { useHistory } from 'react-router-dom';
import trim from 'lodash/trim';
import { RootState } from 'models';
import styles from './GroupMenu.less';
import message from 'components/message';
import EasyvTooltip from 'components/EasyvTooltip';
import { QuestionCircleOutlined } from '@ant-design/icons';
import EasyvModal, { useActionModalRef } from 'components/EasyvModal';
import { useAuth } from 'components/easyUse';

type IProps = ConnectedProps<typeof connector>;

function GroupMenu({
  groups,
  screens,
  current,
  isDragging,
  spaceActive = {
    size: 0
  },
  isOverScreen,
  getGroups,
  selectGroup,
  addGroup,
  updateGroup,
  deleteGroup,
  moveScreenToGroup,
  moveGroup,
  getScreens,
  clearScreenList
}: IProps) {
  const [inputShow, setInputShow] = useState(false);
  const inputRef = useRef<Input>(null);
  const history = useHistory();
  const [menuVisible, setMenuVisible] = useState<boolean>(true);
  const modalRef = useActionModalRef();
  const { checkAuth } = useAuth();

  useEffect(() => {
    getGroups();
  }, [current]);

  useEffect(() => {
    getScreens();
    return () => {
      clearScreenList();
    };
  }, [clearScreenList, getScreens]);

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

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

  useEffect(() => {
    // 组件卸载后，重置分组选中
    return () => {
      if (/\/screens\/trash/.test(window.location.pathname)) {
        selectGroup(0);
      }
    };
  }, [current, window.location.pathname]);

  const handleBlur = (e) => {
    const value = trim(e.target.value);
    // Easyv5.0需求
    if (value.length > 50) {
      message.error('分组名不能超过50个字符');
      return;
    }
    if (value) {
      addGroup(value);
    }
    setInputShow(false);
  };

  const ungroupedCount = screens.filter((d) => !d.groupId && d.groupId !== 0).length;

  const handleChange = useCallback(() => {
    //
  }, []);

  const screenPercent = typeof spaceActive?.size == 'number' ? Math.round((screens.length / spaceActive?.size) * 100) : 0;

  const handleSelectGroup = (groupId: number) => {
    history.push('/');
    selectGroup(groupId);
  };

  const isScreenList = window.location.pathname === `${BASENAME || '/'}` || window.location.pathname === BASENAME + '/';

  const handleOk = () => {
    window.open(window.appConfig.HOME_URL + '/order/additional', '_self');
    modalRef.current?.close();
  };

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

      <div>
        <div className={styles.menu} style={{ display: menuVisible ? 'block' : 'none' }}>
          <div
            className={classNames(styles.menuItem, {
              [styles.active]: isScreenList && current === 0
            })}
            onClick={() => handleSelectGroup(0)}>
            <p>全部应用</p>
            <p>{screens.length}</p>
          </div>
          {inputShow && (
            <div className={classNames(styles.menuItem, styles.inputItem)}>
              <Input ref={inputRef} onBlur={handleBlur} onPressEnter={(e: any) => e.target.blur()} />
            </div>
          )}

          <div
            className={classNames(styles.dropContainer, {
              [styles.isDragging]: isDragging
            })}>
            <Sortable
              tag="div"
              className={styles.dropContainerChild}
              onChange={handleChange}
              options={{
                group: 'nested',
                animation: 150,
                swapThreshold: 0.65,
                direction: 'vertical',
                onEnd: moveGroup,
                scroll: true
              }}>
              {groups.map((d, i) => {
                const groupedCount = screens.filter((v) => v.groupId === d.id).length;
                return (
                  <GroupItem
                    key={d.id}
                    id={d.id}
                    index={i}
                    name={d.name}
                    active={isScreenList && current === d.id}
                    isFirst={i === 0}
                    groupedCount={groupedCount}
                    moveScreenToGroup={moveScreenToGroup}
                    // moveGroup={moveGroup}
                    selectGroup={handleSelectGroup}
                    updateGroup={updateGroup}
                    deleteGroup={deleteGroup}
                  />
                );
              })}
            </Sortable>
            {/* 未分组 */}
            <UngroupItem
              active={isScreenList && current === -1}
              groupedCount={ungroupedCount}
              moveScreenToGroup={moveScreenToGroup}
              selectGroup={handleSelectGroup}
            />
          </div>
        </div>
        <TrashMenu />
      </div>
      {!window.appConfig.LOCAL && (
        <div className={styles.appNum}>
          <div className={styles.appNumHeader}>
            <p className={styles.appNumText}>
              <span>应用数</span>
              {checkAuth('additional') && (
                <EasyvTooltip
                  placement="top"
                  title={
                    <p style={{ lineHeight: '25px' }}>
                      扩大空间应用数
                      <span
                        style={{ textDecorationLine: 'underline', color: '#3A89FE', marginLeft: '8px', cursor: 'pointer' }}
                        onClick={() => {
                          modalRef.current?.show();
                        }}>
                        去扩容
                      </span>
                    </p>
                  }>
                  <QuestionCircleOutlined className="whiteHover" style={{ marginLeft: '5px', cursor: 'pointer' }} />
                </EasyvTooltip>
              )}
            </p>
            {/* TODO应用数超额 */}
            <p>
              <span className={styles.currentNum} style={isOverScreen ? { color: '#EB515A' } : undefined}>
                {screens.length || 0}
              </span>

              <span className={styles.totalNum} style={{ color: '#b4b7c1', fontSize: '12px' }}>
                /{spaceActive?.size || 0}
              </span>
            </p>
          </div>
          <Progress percent={screenPercent} showInfo={false} status={screenPercent > 90 ? 'exception' : 'normal'} trailColor="#3D4154" />
          <EasyvModal.ActionModal
            maskClosable={false}
            okText="立即购买"
            ref={modalRef}
            title="扩容空间应用数"
            onCancel={() => {
              modalRef.current?.close();
            }}
            onOk={handleOk}
            content={
              <div className={styles.content}>
                <p className={styles.coTitle}>应用数量增购包</p>
                <div className={styles.price}>
                  <p className={styles.money}>3000</p>
                  <p className={styles.unit}>
                    元/套 <span style={{ textDecoration: 'line-through', color: 'rgba(180, 183, 193, 0.6)' }}>¥4000</span>
                  </p>
                  <p className={styles.btn}>限时优惠</p>
                </div>
                <p style={{ lineHeight: '24px' }}>
                  售卖规则：<span style={{ color: '#fff' }}>10个应用数/套</span>
                  <br />
                  使用说明：购买此增购包可永久增加主账号10个应用数量；用户账号到期后只需续费原账号即可使用，无需额外支付增购包费用
                </p>
              </div>
            }
          />
        </div>
      )}
    </div>
  );
}

const mapStateToProps = ({ groups, screens, space }: RootState) => {
  const { list: groupList, current } = groups;
  const { list: screenList, dragScreenId } = screens;
  const { active: spaceActive } = space;
  const isOverScreen = screenList.filter((d) => !d.deletedAt).length > (spaceActive?.size || 0);

  return {
    groups: groupList,
    screens: screenList.filter((d) => !d.deletedAt),
    current,
    isDragging: !!dragScreenId,
    spaceActive,
    isOverScreen: isOverScreen
  };
};

const mapDispacthToProps = {
  selectGroup,
  getGroups,
  addGroup,
  deleteGroup,
  updateGroup,
  moveScreenToGroup,
  moveGroup,
  getScreens,
  clearScreenList,
  spacesCut
};

const connector = connect(mapStateToProps, mapDispacthToProps);

export default connector(GroupMenu);
