import React, { memo, useCallback, useRef } from 'react';
import { Link } from 'react-router-dom';
import classNames from 'classnames';
import EditableText from '../../../components/EditableText';
import MoveSpace from '../../../components/MoveSpace';
import DragSourceContainer from './DragSourceContainer';
import SynchronizationModal from './SynchronizationModal';
import ShareScreenModal from '../../screen-edit/components/ScreenHeader/ShareScreenModal';
import lazyWithPreload from '../../../lazyWithPreload';
import { connect } from 'react-redux';
import dragImg from '../../../../images/icon_moveguide.png';
import styles from './ScreenItem.less';
import { Dropdown, Menu } from '@easyv/antd';
import { ScreenItem } from 'models/screen.types';
import { EllipsisOutlined, PartitionOutlined } from '@ant-design/icons';
import EasyvTooltip from 'components/EasyvTooltip';
import Space from 'components/Space';
import EasyvButton from 'components/EasyvButton';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { useProductionInfo } from 'components/easyUse';
import FileCard from 'components/FileCard';
import ExportScreenModal from './ExportScreenModal';
import { useHistory } from 'react-router-dom';
import { useAuth } from 'components/easyUse';
import EasyvScreenLock from 'components/EasyvScreenLock';
import message from 'components/message';
import { modules } from 'constants/authority';

const ScreenEdit = lazyWithPreload(() => import('../../screen-edit'));

interface IProps {
  screenId: number;
  screenName: string;
  thumb: null | string | number;
  share: string;
  password?: string;
  shareToken?: string;
  shareInfo?: {
    title: string;
    description: string;
    thumb: string;
  };
  apps: number[];
  isMultiExport: boolean;
  isSelected: boolean;
  screenCopyable: boolean;
  deleteScreen: Function;
  updateScreen: Function;
  copyScreen: Function;
  onDragStart: Function;
  onDragEnd: Function;
  onSelected: Function;
  onUnselected: Function;
  isOverScreen: boolean;
}

function ScreenItem({
  screenId,
  screenName,
  thumb,
  share,
  password,
  shareToken,
  shareInfo,
  apps,
  isMultiExport,
  isSelected,
  screenCopyable,
  deleteScreen,
  updateScreen,
  copyScreen,
  onDragStart,
  onDragEnd,
  onSelected,
  onUnselected,
  isOverScreen,
}: IProps) {
  const productionInfo = useProductionInfo();
  const { isAdmin, isRenew } = productionInfo;
  const deleteItem = () => deleteScreen(screenId);
  const updateName = (name) => updateScreen({ id: screenId, name });
  const copyItem = () => copyScreen(screenId);
  const dragStart = () => onDragStart(screenId);
  const dragEnd = () => onDragEnd(screenId);
  const deletRef = useConfirmRef();
  const screentRef: any = useRef(null);
  const clickScreen = isSelected ? () => onUnselected(screenId) : () => onSelected(screenId);
  const { checkAuth } = useAuth();
  const history = useHistory();

  const overScreen = (e) => {
    if (isOverScreen) {
      message.error('您的应用数已超出上限，请删除部分应用后再试');
      e.preventDefault();
    }
  };

  const linkNodeView = useCallback(() => {
    history.push(`/node/view/${screenId}`);
  }, [screenId]);

  const menu = (
    <Menu>
      <Menu.Item key="4">
        <span className={styles.iconStyle} onClick={linkNodeView}>
          <PartitionOutlined
            style={{ width: '14px', height: '14px', lineHeight: '14px', marginRight: 4 }}
            title="节点管理"
          />
          节点管理
        </span>
      </Menu.Item>
      {checkAuth(modules.space) && isAdmin && (
        <Menu.Item key="0">
          {isOverScreen ? (
            <span onClick={overScreen} className={styles.iconStyle}>
              <i
                className="icon iconfont icon-yirukongjian"
                style={{ width: '14px', height: '14px', lineHeight: '14px' }}
                title="移入空间"
              />
              移入空间
            </span>
          ) : (
            <MoveSpace screenId={screenId}>
              <span className={styles.iconStyle}>
                <i
                  className="icon iconfont icon-yirukongjian"
                  style={{ width: '14px', height: '14px', lineHeight: '14px' }}
                  title="移入空间"
                />
                移入空间
              </span>
            </MoveSpace>
          )}
        </Menu.Item>
      )}
      <Menu.Item key="1" onClick={copyItem}>
        {screenCopyable ? (
          <span className={styles.iconStyle}>
            <i
              className={'icon iconfont icon-fuzhi1'}
              style={{ width: '14px', height: '14px', lineHeight: '14px' }}
              title="复制"
            />
            复制
          </span>
        ) : null}
      </Menu.Item>
      <Menu.Item key="3" onClick={() => deletRef.current?.show()}>
        <span className={styles.iconStyle}>
          <i
            className="icon iconfont icon-btn_delete"
            style={{ width: '14px', height: '14px', lineHeight: '14px' }}
            title="删除"
          />
          删除
        </span>
      </Menu.Item>
    </Menu>
  );

  return (
    <>
      <FileCard
        hoverRenderNode={
          !isMultiExport && (
            <div className={styles.hoverWrapper}>
              <Space size={16}>
                <DragSourceContainer
                  id={screenId}
                  className={styles.drag}
                  dragPreviewImg={dragImg}
                  onDragStart={dragStart}
                  onDragEnd={dragEnd}>
                  <EasyvTooltip title="移动">
                    <i className="icon iconfont icon-btn_move" id={`${screenId}`} />
                  </EasyvTooltip>
                </DragSourceContainer>

                {checkAuth('screenExport') ? (
                  <ExportScreenModal theme="black" list={[{ screenId, screenName }]}>
                    <EasyvTooltip title="导出">
                      <i className="icon iconfont icon-daochu" />
                    </EasyvTooltip>
                  </ExportScreenModal>
                ) : null}

                {checkAuth('screenSynchronization') && (
                  <SynchronizationModal screenId={screenId}>
                    <EasyvTooltip title="同步">
                      <i className="icon iconfont icon-wenjiantongbu" />
                    </EasyvTooltip>
                  </SynchronizationModal>
                )}

                {!isRenew &&
                  checkAuth('screenPublish') &&
                  (isOverScreen ? (
                    <EasyvTooltip title="发布">
                      <i onClick={overScreen} className="icon iconfont icon-btn_publishhomepage" />
                    </EasyvTooltip>
                  ) : (
                    <ShareScreenModal
                      screenName={screenName}
                      screenId={screenId}
                      token={shareToken}
                      info={shareInfo}
                      share={share}
                      theme="black"
                      password={password}
                      sharedApps={apps}>
                      <EasyvTooltip title="发布">
                        <i className="icon iconfont icon-btn_publishhomepage" />
                      </EasyvTooltip>
                    </ShareScreenModal>
                  ))}

                {checkAuth('screenShort') && (
                  <div onClick={copyItem}>
                    {screenCopyable ? (
                      <EasyvTooltip title="复制">
                        <i className="icon iconfont icon-fuzhi1" />
                      </EasyvTooltip>
                    ) : null}
                  </div>
                )}

                {checkAuth('screenShort') && (
                  <div onClick={() => deletRef.current?.show()}>
                    <EasyvTooltip title="删除">
                      <i className="icon iconfont icon-btn_delete" />
                    </EasyvTooltip>
                  </div>
                )}

                {!checkAuth('screenShort') && (
                  <Dropdown
                    getPopupContainer={() => screentRef.current}
                    overlayClassName={styles.ellipsisWrapper}
                    overlay={menu}>
                    <EllipsisOutlined style={{ fontWeight: 500 }} />
                  </Dropdown>
                )}
              </Space>
              <div ref={screentRef} style={{ margin: '12px 0' }}>
                <Space size={12}>
                  <Link to={`/bigscreen/${screenId}`} target="_blank" rel="noopener">
                    <EasyvButton theme="default">预览</EasyvButton>
                  </Link>
                  <EasyvScreenLock screenId={screenId} to={`/create/${screenId}`}>
                    <EasyvButton theme="primary">编辑</EasyvButton>
                  </EasyvScreenLock>
                </Space>
              </div>
            </div>
          )
        }
        appPreviewImgUrl={thumb}
        onMouseEnter={() => ScreenEdit.preload()}
        onClick={clickScreen}
        appName={screenName}
        isSelected={isSelected}
        isMultiExport={isMultiExport}
        renderFooter={
          <div className={styles.footerWrapper}>
            <div
              className={classNames(styles.exportMask, {
                [styles.IsMultiExport]: isMultiExport,
              })}
              onClick={clickScreen}>
              {isSelected ? (
                <span
                  className={classNames(styles.exportMaskSelectIcon, {
                    [styles.exportMaskSelected]: isSelected,
                  })}>
                  <i className={classNames('icon', 'iconfont', 'icon-icon_sucess')} />
                </span>
              ) : (
                <i
                  style={{
                    width: '16px',
                    height: '16px',
                    borderRadius: '50%',
                    border: '1px solid rgba(255,255,255,0.6)',
                    display: 'inline-block',
                  }}
                />
              )}
            </div>
            <EditableText
              text={screenName}
              isMultiExport={isMultiExport}
              className={styles.screenName}
              onCommit={updateName}
              suffix={
                <div className={styles.box}>
                  {isMultiExport ? (
                    <i></i>
                  ) : (
                    <i className={classNames('icon iconfont icon-bianji ' + styles.editIcon)} />
                  )}
                  {share || apps.length > 0 ? (
                    <span className={styles.screenStatus}>
                      <i className={styles.screenStatusStatusIcon} />
                      已发布
                    </span>
                  ) : (
                    <span className={styles.screenStatus}>
                      <i
                        className={styles.screenStatusStatusIcon}
                        style={{ background: '#B4B7C1' }}
                      />
                      未发布
                    </span>
                  )}
                </div>
              }
            />
          </div>
        }
      />
      {/* 删除选择层 */}
      <EasyvModal.Confirm
        content={
          <p>
            删除<span style={{ color: '#fff' }}>{screenName}</span>应用3天内，可在【回收站】恢复
          </p>
        }
        closable={false}
        title="删除应用"
        ref={deletRef}
        onOk={() => {
          deleteItem();
          deletRef.current?.close();
        }}
      />
    </>
  );
}
function mapStateToProps({ screens, space }) {
  const isOverScreen = screens.list.filter((d) => !d.deletedAt).length > space?.active?.size;

  return {
    isMultiExport: screens.isMultiExport,
    isOverScreen: isOverScreen,
  };
}

export default connect(mapStateToProps)(memo(ScreenItem));
