import React, { memo, useRef, useState } from 'react';
import { connect } from 'react-redux';
import Back from './Back';
import EditableText from 'components/EditableText';
import ExportScreenModal from 'containers/screen-list/components/ExportScreenModal';
import ShareScreenModal from './ShareScreenModal';
import NotificationContainer from './NotificationContainer';
import { authorityConfig } from 'components/ScreenTool';
import SearchModal from './SearchModal';
import ScreenTools from 'components/ScreenTool';
import CommentDelted from './CommentDeleted';
import { updateScreen } from 'models/screens';
import { setScreenState } from 'models/screen-detail';
import { getScreenId, getTopScreenId } from 'utils/screen';
import styles from './index.less';
import classnames from 'classnames';
import { addPanel } from 'models/panel';
import CommponentModule from 'components/ScrreenHeaderModule';
import {
  RecycleLightColored,
  SearchCircleLightColored,
  PreviewLightColored,
  SendLightColored,
  ResourceLightColored,
  LinkLightColored,
  ApplicationLightColored,
  UploadLightColored,
} from '@easyv/react-icons';

import { useProductionInfo } from 'components/easyUse';
import { useAuth } from 'components/easyUse';
import { modules } from 'constants/authority';
import PreviewDropDown from './previewDropdown';
import { Link } from 'react-router-dom';

export const KEYS = {
  COMPONENT: '组件',
  RESOURCE: '资源',
  PANEL: '动态面板',
  REL: '引用面板',
};

function ScreenHeader({
  name,
  shareToken,
  shareInfo,
  share,
  sharePassword,
  editionId,
  constants,
  activatedState,
  centerActivatedState,
  panelId,
  apps = [],
  dispatch,
}) {
  const id = getScreenId();
  const [active, setActive] = useState(false);
  const productionInfo = useProductionInfo();
  const { isRenew = false } = productionInfo;
  const { loading, list: constantsList } = constants;
  const { checkAuth } = useAuth();
  const ref = useRef(null);

  const handleNameUpdate = (name) => {
    dispatch(
      updateScreen({
        id,
        name,
      }),
    );
  };
  const exportState = () => {
    return editionId ? checkAuth('exportTool') || isRenew : true;
  };
  const isHidden = loading && !constantsList?.length;

  const onActivate = (code) => {
    setTimeout(() => {
      dispatch(setScreenState(code === activatedState ? '' : code));
    }, 0);
  };

  const onPanel = (code) => {
    dispatch(addPanel(code?.includes('动态') ? 0 : 1));
  };

  return (
    <header className={styles.container} id="screen-header">
      <Back />
      {panelId ? (
        <div className={classnames(styles.screenName, styles.screntNameOverflow)}>{name}</div>
      ) : (
        <EditableText text={name} className={styles.screenName} onCommit={handleNameUpdate} />
      )}

      {checkAuth(modules.componentAdd) && !isHidden && (
        <CommponentModule
          centerActivatedState={centerActivatedState}
          active={activatedState === KEYS.COMPONENT}
          title={KEYS.COMPONENT}
          onActivate={onActivate}
        />
      )}

      {checkAuth(modules.resource) && (
        <CommponentModule
          active={activatedState === KEYS.RESOURCE}
          centerActivatedState={centerActivatedState}
          title={KEYS.RESOURCE}
          icon={<ResourceLightColored />}
          onActivate={onActivate}></CommponentModule>
      )}

      {checkAuth(modules.componentAdd) && (
        <CommponentModule
          active={activatedState === KEYS.PANEL}
          centerActivatedState={centerActivatedState}
          title={KEYS.PANEL}
          icon={<ApplicationLightColored />}
          onActivate={onPanel}
        />
      )}
      {checkAuth(modules.componentAdd) && (
        <CommponentModule
          centerActivatedState={centerActivatedState}
          active={activatedState === KEYS.REL}
          title={KEYS.REL}
          icon={<LinkLightColored />}
          onActivate={onPanel}
        />
      )}

      <ScreenTools />

      <div className={styles.operate}>
        <span
          className={classnames({
            [styles.lock]: authorityConfig[centerActivatedState]?.includes('回收站'),
          })}>
          <CommentDelted
            setActive={(code) => {
              setActive(code);
            }}>
            <span
              className={classnames([
                styles.item,
                {
                  [styles.active]: active,
                },
              ])}>
              <RecycleLightColored className={styles.icon} />
              <span className={styles.text}>回收站</span>
            </span>
          </CommentDelted>
        </span>

        <span
          className={classnames({
            [styles.lock]: authorityConfig[centerActivatedState]?.includes('搜索'),
          })}>
          <SearchModal>
            <span className={classnames(styles.item)}>
              <SearchCircleLightColored className={styles.icon} />
              <span className={styles.text}>搜索</span>
            </span>
          </SearchModal>
        </span>

        <NotificationContainer lock={authorityConfig[centerActivatedState]?.includes('通知')} />

        {exportState() && !panelId && (
          <ExportScreenModal theme="black" list={[{ screenId: id, screenName: name }]}>
            <span className={styles.item}>
              <UploadLightColored className={styles.icon} />
              <span className={styles.text}>导出</span>
            </span>
          </ExportScreenModal>
        )}

        <span className={styles.item} ref={ref}>
          {panelId ? (
            <Link to={`/panel/${getTopScreenId()}/${panelId}/${id}`} target="_blank" rel="noopener">
              <span className={styles.item}>
                <PreviewLightColored className={styles.icon} />
                <span className={styles.text}>预览</span>
              </span>
            </Link>
          ) : (
            <PreviewDropDown panelId={panelId} parentDom={ref}>
              <Link
                to={panelId ? `/panel/${getTopScreenId()}/${panelId}/${id}` : `/bigscreen/${id}`}
                target="_blank"
                rel="noopener">
                <span className={styles.item}>
                  <PreviewLightColored className={styles.icon} />
                  <span className={styles.text}>预览</span>
                </span>
              </Link>
            </PreviewDropDown>
          )}
        </span>

        {!panelId && !isRenew && (
          <ShareScreenModal
            token={shareToken}
            info={shareInfo}
            theme="black"
            screenId={id}
            share={share}
            password={sharePassword}
            sharedApps={apps}>
            <span className={styles.item}>
              <SendLightColored className={styles.icon} />
              <span className={styles.text}>发布</span>
            </span>
          </ShareScreenModal>
        )}
      </div>
    </header>
  );
}

function mapStateToProps({
  constants,
  createApp,
  materialLib,
  screenDetail,
  screensById,
  panelsById,
  user,
}) {
  const { id } = createApp;
  const { userInfo } = user;
  const { type, edition = {} } = userInfo;
  const screen = screensById[id] || {};
  const { activatedState, centerActivatedState } = screenDetail;
  let { name } = screen;
  const { theFirstColumn } = materialLib;
  const { share, sharePassword, panelId, apps = [], shareToken, shareInfo } = screen;
  const editionId = edition && edition.id;
  if (panelId) {
    const panel = panelsById[panelId];
    if (panel) {
      name = panel.name;
    }
  }
  return {
    name,
    constants,
    share,
    theFirstColumn,
    sharePassword,
    activatedState,
    shareToken,
    shareInfo,
    editionId,
    panelId,
    centerActivatedState,
    apps,
    editionType: window.appConfig.LOCAL ? type : edition.id,
  };
}

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