import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { withRouter, RouteComponentProps } from 'react-router-dom';
import message from 'components/message';
import ImportScreensModal from './ImportScreensModal';
import lazyWidthPreload from '../../../lazyWithPreload';
import {
  getScreens,
  searchScreen,
  selectAllScreen,
  openMultiExport,
  closeMultiExport,
  cancelSelectedCurrentGroupScreen,
  ScreensState,
  deleteScreen,
  updateScreensSortType,
} from 'models/screens';
import { getGroups } from 'models/group';
import styles from './ScreenOperate.less';
import EasyvButton from 'components/EasyvButton';
import { GroupState } from 'models/group.types';
import { UserState } from 'models/user.types';
import { SpaceState } from 'models/space.types';
import EasyVExportScreensModal, {
  useEasyVExportScreensModal,
} from 'components/exportAppModal/exportScreensModal';
import { ScreenItem } from 'models/screen.types';
import EasyvSearchHeader from 'components/EasyvSearchHeader';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { useProductionInfo } from 'components/easyUse';
import { useAuth } from 'components/easyUse';

const ScreenTemplate = lazyWidthPreload(() => import('../../screen-template'));

interface IProps extends RouteComponentProps {
  searchScreen: (name) => void;
  closeMultiExport: () => void;
  openMultiExport: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
  selectAllScreen: (scrrens: number[]) => void;
  getScreens: () => void;
  // eslint-disable-next-line @typescript-eslint/ban-types
  getGroups: Function;
  maxScreenCount: number;
  editionId: string | undefined | null;
  total: number;
  search: string;
  currentGroupId: number | 'trash';
  isMultiExport: boolean;
  selectedScreensInfo: Pick<ScreenItem, 'screenId' | 'screenName'>[];
  currentAllScreenIds: number[];
  screenAddable: boolean;
  isImportExpired: boolean;
  filterScreenLength: number;
  cancelSelectedCurrentGroupScreen: (scrrens: number[]) => void;
  currentGroupName: string;
  trashedScreenLength: number;
  deleteScreen: (id: number | number[]) => void;
  updateScreensSortType: (e) => void;
  isAccountOwner?: boolean;
  userInfo?: any; // TODO: 增加user类型
}

const ScreenOperate = (props: IProps) => {
  const {
    search,
    currentGroupId,
    isMultiExport,
    selectedScreensInfo,
    currentAllScreenIds,
    maxScreenCount,
    total,
    screenAddable,
    isImportExpired,
    filterScreenLength,
    currentGroupName,
    userInfo,
    deleteScreen,
    updateScreensSortType,
  } = props;
  const [isSelectAll, setIsSelectAll] = useState<boolean>(false); //是否全部选中
  const { checkAuth } = useAuth();
  const productionInfo = useProductionInfo();
  const { isRenew } = productionInfo;

  const exportRef = useEasyVExportScreensModal();

  const deleteScreenRef = useConfirmRef();

  useEffect(() => {
    // 当前分组的所有大屏是否都在选中的大屏列表中，如果在返回false，否则返回true，页面显示全选
    setIsSelectAll(
      currentAllScreenIds
        .map((item) => selectedScreensInfo.filter((info) => info.screenId === item).length > 0)
        .includes(false),
    );
  }, [selectedScreensInfo, currentAllScreenIds]);

  const container = useRef<HTMLDivElement | null>(null);

  const onChange = (e) => {
    const value = e.target.value && e.target.value.trim();
    props.searchScreen(value);
  };

  const checkUserInfo = () => {
    checkMaxScreen(() => {
      props.history.push('/template');
    });
  };

  const checkMaxScreen = (onSuccess, onError?: () => void) => {
    const { maxScreenCount, total } = props;
    if (total < maxScreenCount) {
      onSuccess && onSuccess();
    } else {
      message.error('您的应用数已超出上限，请删除部分应用后再试');
      onError && onError();
    }
  };
  const onImportComplete = () => {
    props.getScreens();
    props.getGroups();
  };

  const onSelectSortTypeChange = (e) => {
    // 可视化应用更新
    if (e === 'byUpdatedAt') {
      //按修改时间排序
      updateScreensSortType('byUpdatedAt');
      return;
    }
    //按创建时间排序
    updateScreensSortType('byCreatedAt');
  };

  return (
    <div
      ref={container}
      className={classNames(styles.container, {
        [styles.isMultiExport]: isMultiExport,
      })}>
      <div className={styles.btn_wrapper}>
        {!isMultiExport ? (
          screenAddable ? (
            <EasyvButton
              theme="primary"
              style={{ display: 'flex', alignItems: 'center' }}
              onClick={checkUserInfo}
              onMouseEnter={() => ScreenTemplate.preload()}>
              <i
                className="icon iconfont icon-constant-custom"
                style={{ position: 'relative', top: '1px' }}
              />
              新建应用
            </EasyvButton>
          ) : (
            <div></div>
          )
        ) : (
          <p className={styles.selectedText}>
            <span>已选择</span>
            <span className={styles.text}>&thinsp;&thinsp;{selectedScreensInfo.length}</span>
            <span>个应用</span>
          </p>
        )}
        <div className={styles.patchAction}>
          {isMultiExport ? (
            <>
              <EasyvButton
                theme="default"
                id="select-all"
                onClick={() => {
                  const allButton: any = document.querySelector('button[id=select-all]');
                  allButton.blur();
                  // 全选累加，取消累减
                  const list = isSelectAll
                    ? selectedScreensInfo.map((item) => item.screenId).concat(currentAllScreenIds)
                    : selectedScreensInfo
                        .filter((item) => !currentAllScreenIds.includes(item.screenId))
                        .map((item) => item.screenId);
                  if (isSelectAll) {
                    props.selectAllScreen([...new Set(list)]);
                    return;
                  }
                  props.cancelSelectedCurrentGroupScreen(list);
                }}>
                {isSelectAll ? '全选' : '取消全选'}
              </EasyvButton>
              <EasyvButton
                disabled={!selectedScreensInfo.length}
                onClick={() => deleteScreenRef.current?.show()}
                theme="danger"
                style={{ marginLeft: '24px' }}>
                删除
              </EasyvButton>
              {checkAuth('screenAllExport') && (
                <EasyvButton
                  disabled={!selectedScreensInfo.length}
                  onClick={() => exportRef.current?.show()}
                  theme="primary"
                  style={{ marginLeft: '8px' }}>
                  导出
                </EasyvButton>
              )}

              <EasyvButton
                theme="default"
                style={{ marginLeft: '8px' }}
                onClick={() => {
                  props.closeMultiExport();
                }}>
                取消操作
              </EasyvButton>
            </>
          ) : (
            checkAuth('screenAllOperate') && (
              <EasyvButton
                disabled={filterScreenLength === 0}
                theme="default"
                onClick={(e) => {
                  const list = selectedScreensInfo
                    .filter((item) => !currentAllScreenIds.includes(item.screenId))
                    .map((item) => item.screenId);
                  props.cancelSelectedCurrentGroupScreen(list);
                  props.openMultiExport(e);
                }}>
                批量管理
              </EasyvButton>
            )
          )}
          {!isImportExpired && !isMultiExport && checkAuth('screenImport') && (
            <ImportScreensModal
              onComplete={onImportComplete}
              groupId={currentGroupId}
              disabled={total >= maxScreenCount}
              checkAuth={checkAuth}>
              <EasyvButton style={{ marginLeft: 8 }} theme="default">
                应用导入
              </EasyvButton>
            </ImportScreensModal>
          )}
        </div>
      </div>
      <div className={styles.search_wrapper}>
        <EasyvSearchHeader
          isNoTrashedScreen={true}
          onSearchChange={(e) => onChange(e)}
          filterScreenLength={filterScreenLength}
          isMultiExport={isMultiExport}
          search={search}
          onSelectSortTypeChange={onSelectSortTypeChange}
          currentAllScreenLength={currentAllScreenIds.length}
          currentGroupName={currentGroupName}
        />
      </div>

      <EasyvModal.Confirm
        ref={deleteScreenRef}
        onOk={async () => {
          await deleteScreen(selectedScreensInfo.map((item) => item.screenId));
          deleteScreenRef.current?.close();
          props.closeMultiExport();
        }}
        content={<p>批量删除应用后3天内，可在【回收站】恢复</p>}
        title={'批量删除应用'}
      />
      <EasyVExportScreensModal
        content={'确认批量导出应用吗?'}
        list={selectedScreensInfo}
        onComplete={props.closeMultiExport}
        ref={exportRef}
      />
    </div>
  );
};

function mapStateToProps({
  screens,
  groups,
  user,
  space,
}: {
  screens: ScreensState;
  groups: GroupState;
  user: UserState;
  space: SpaceState;
}) {
  // eslint-disable-next-line prefer-const
  let { search, list: screenList, isMultiExport, selectedScreens } = screens;
  const trashedScreenLength = screenList.filter((d) => d.deletedAt).length || 0; //回收站当前数量
  screenList = screenList.filter((d) => !d.deletedAt);

  const { current, list = [] } = groups;
  const selectedScreensInfo = screenList
    .filter((d) => selectedScreens.includes(d.screenId))
    .map((d) => ({ screenName: d.screenName, screenId: d.screenId }));
  let allScreens: ScreenItem[] = [];
  if (current === 0) {
    allScreens = screenList;
  } else if (current === -1) {
    allScreens = screenList.filter((d) => d.groupId == null);
  } else {
    allScreens = screenList.filter((d) => d.groupId == current);
  }

  const resultScreens = allScreens.filter((d) =>
    d.screenName.toLowerCase().includes(search.toLowerCase()),
  );

  return {
    search,
    maxScreenCount: space.active?.size || 0,
    editionId: user.userInfo?.edition?.id,
    total: screenList.length,
    isMultiExport,
    selectedScreensInfo,
    currentAllScreenIds: allScreens.map((d) => d.screenId),
    currentGroupId: current, // -1未分组,0全部应用分组,trash回收站
    screenAddable: !(window.appConfig.LOCAL && user.userInfo.type === 'education'),
    isImportExpired: user.userInfo.isImportExpired,
    filterScreenLength: resultScreens.length,
    trashedScreenLength,
    currentGroupName: [-1, 0, 'trash'].includes(current)
      ? { '-1': '未分组', '0': '全部应用', trash: '回收站' }[current]
      : list.filter((item) => item.id === current)[0].name || '暂无分组信息',
    userInfo: user.userInfo,
  };
}

const mapDispatchToProps = {
  searchScreen,
  openMultiExport,
  closeMultiExport,
  selectAllScreen,
  getScreens,
  getGroups,
  cancelSelectedCurrentGroupScreen,
  deleteScreen,
  updateScreensSortType,
};

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ScreenOperate));
