import React, { memo, useCallback, useContext } from 'react';
import styles from './index.less';
import EditableText from 'components/EditableText';
import SearchModal from './SearchModal';
import ExportScreenModal from '../../../screen-list/components/ExportScreenModal';
import ShareScreenModal from 'containers/screen-edit/components/ScreenHeader/ShareScreenModal';
import NotificationContainer from 'containers/screen-edit/components/ScreenHeader/NotificationContainer';
import { useProductionInfo } from 'components/easyUse';
import CommponentModule from 'components/ScrreenHeaderModule';
import Back from 'containers/screen-edit/components/ScreenHeader/Back';
import { NodesContext } from '../../Context/index';
import { updateScreen } from 'models/screens';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { findNode } from 'utils/nodes';
import { Type } from '@/utils/nodes.types';
import { useTitle } from 'components/easyUse';
import { eventTracking } from '@/models/event-tracking';
import { HideIrrelevant } from '@/utils/eventTracking/nodes.type';
import {
  updateLayerNodeEages,
  MenuActionState,
  updateMenuState,
  setCurrentNode,
} from 'models/node';
import { Link } from 'react-router-dom';
import {
  SearchCircleLightColored,
  MainLightColored,
  PreviewLightColored,
  SendLightColored,
  UploadLightColored,
} from '@easyv/react-icons';
import EasyvTooltip from '@/components/EasyvTooltip';

export enum KEYS {
  HIDE = '隐藏不相关',
  CLEAR = '清除',
}

function Header({
  editionId,
  nodeCurrents,
  nodeScale,
  shareToken,
  id,
  share,
  apps,
  sharePassword,
  screen,
  dispatch,
  node,
  shareInfo,
  name,
}) {
  const productionInfo = useProductionInfo();
  const { activatedState, setActivatedState, canvas, clearCurrentNode } = useContext(NodesContext);
  useTitle(`${screen.name} - 节点编辑`);
  const { isRenew = false } = productionInfo;

  const handleNameUpdate = (name) => {
    dispatch(
      updateScreen({
        name,
        id: screen.id,
      }),
    );
  };
  const exportState = () => {
    return editionId ? editionId === 'saas_vip' || isRenew : true;
  };

  const onHide = useCallback(
    async (code) => {
      const state = code === activatedState ? '' : code;
      setActivatedState(state);
      let nodeSelect = {
        nodes: [],
        edges: [],
      };
      if (state && Object.keys(node).length) {
        // 选中
        const nodesUp = nodeCurrents.reduce((all, id) => {
          const nodeUp = findNode({ id, nodeData: node, type: Type.UP });
          return all.concat(nodeUp);
        }, []);
        const nodesDown = nodeCurrents.reduce((all, id) => {
          const nodeDown = findNode({ id, nodeData: node, type: Type.DOWN });
          return all.concat(nodeDown);
        }, []);
        nodeSelect = {
          nodes: Array.from(
            new Set(
              nodesDown
                .map((d) => d.nodes)
                .concat(nodesUp.map((d) => d.nodes))
                .flat(2),
            ),
          ),
          edges: Array.from(
            new Set(
              nodesDown
                .map((d) => d.edges)
                .concat(nodesUp.map((d) => d.edges))
                .flat(2),
            ),
          ),
        };
      }
      dispatch(updateLayerNodeEages(nodeSelect));
      dispatch(updateMenuState(MenuActionState.NONE));
      // 埋点
      dispatch(
        eventTracking<HideIrrelevant>({
          id: `${screen.id}-hideIrrelevant`,
          type: 'hideIrrelevant',
          screenName: screen.name,
          screenId: screen.id,
          num: 1,
        }),
      );
    },
    [nodeCurrents, activatedState],
  );

  const onClear = () => {
    // clear
    setActivatedState('');
  };

  return (
    <div className={styles.header}>
      <div className={styles.name}>
        <Back />
        <EditableText
          text={screen.name}
          className={styles.screenName}
          onCommit={handleNameUpdate}
        />
      </div>
      <div className={styles.centerBox}>
        <div className={styles.operate}>
          {/* TODO 暂时屏蔽 */}
          {/* <span className={styles.item}>
            <CommponentModule active={activatedState === KEYS.CLEAR} title={KEYS.CLEAR} icon={<ClearLightColored />} onActivate={onClear} />
          </span> */}
          <EasyvTooltip title="隐藏与选中节点不相关的节点">
            <span
              id="node-asjkndajnbasd-hide"
              className={classNames(styles.item, {
                [styles.hide]: !nodeCurrents.length,
              })}>
              <CommponentModule
                active={activatedState === KEYS.HIDE}
                title={KEYS.HIDE}
                icon={<MainLightColored />}
                onActivate={onHide}
              />
            </span>
          </EasyvTooltip>
        </div>
      </div>
      <div className={styles.rightBox}>
        <div className={styles.operate}>
          <SearchModal
            node={node}
            nodeScale={nodeScale}
            canvas={canvas}
            clearCurrentNode={clearCurrentNode}
            setCurrentNode={(id) => {
              dispatch(setCurrentNode(id));
            }}>
            <span className={styles.item}>
              <SearchCircleLightColored className={styles.icon} />
              <span className={styles.text}>搜索</span>
            </span>
          </SearchModal>
          <NotificationContainer />

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

          <span>
            <Link to={`/bigscreen/${id}`} target="_blank" className={styles.item} rel="noopener">
              <PreviewLightColored className={styles.icon} />
              <span className={styles.text}>预览</span>
            </Link>
          </span>
          {!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>
      </div>
    </div>
  );
}

function mapStateToProps({
  constants,
  createApp,
  materialLib,
  screenDetail,
  screensById,
  user,
  node,
}) {
  const { id, nodeScale } = createApp;
  const { userInfo } = user;
  const { type, edition = {} } = userInfo;
  const screen = screensById[id] || {};
  const { activatedState } = screenDetail;
  const { name } = screen;
  const { theFirstColumn } = materialLib;
  const { share, sharePassword, apps = [], shareToken, shareInfo } = screen;

  return {
    name,
    constants,
    share,
    nodeScale,
    theFirstColumn,
    id,
    sharePassword,
    activatedState,
    shareToken,
    shareInfo,
    nodeCurrents: node.currents,
    nodeState: node.nodeState,
    apps,
    editionType: window.appConfig.LOCAL ? type : edition.id,
  };
}
export default connect(mapStateToProps)(memo(Header));
