import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { useTitle } from 'components/easyUse';
import Loading from 'components/Loading';
import ScreenHeader from './components/ScreenHeader';
import ScreenLayers from './components/ScreenLayers';
import ScreenPreview from './components/ScreenPreview';
import ScreenConfig from './components/ScreenConfig';
import EasyvRefresh from 'components/EasyvRefresh';
import { getUserInfo } from 'models/user';
import { getFonts } from 'models/font';
import { getConstants } from 'models/constant';
import { getThemes } from 'models/theme';
import { getSources } from 'models/source';
import { getFilters } from 'models/filter';
import { setScreenDataState } from 'models/screen-edit';
import { getConstants as getTenantConstants } from 'models/tenant-constant';
import {
  getScreenData,
  resetSelect,
  clearScreen,
  redirectScreen,
  selectLayerWithScrollIntoView,
} from 'models/create-app';
import { getScreenId, getTopScreenId } from 'utils/screen';
import ScreenEditProvider from './components/ScreenEditProvider';
import { useLocation } from 'react-router-dom';
import {  isNodePage, isEditPage } from 'utils/utils';
import { ConfigProvider } from '@easyv/react-gui';
import { getTransferinfo } from 'models/transfer';
import { getScreen } from 'models/screen';
import styles from './index.less';
import { getDataContainers } from 'models/data-container';
import NodeView from 'containers/nodes-edit/index';
import { screenEditModel, updateScreentEditModel, screenStateType } from 'models/screen-edit';
import { getScreens } from 'models/screens';
import EasyvScreenLock from 'components/EasyvScreenLock';
import {EditScreen} from '@/utils/eventTracking/component.type';
import { eventTracking } from '@/models/event-tracking';

function ScreenEdit({
  match,
  history,
  loading,
  screenName,
  modalEdit,
  dispatch,
  screen,
  screenState,
}) {
  useTitle(screenName);

  const topScreenId = getTopScreenId();
  const [restartLoading, setRestartLoading] = useState(false);
  const location = useLocation();
  const _isNodePage = isNodePage();

  

  useEffect(() => {
    const { id, name } = screen;
    /**
     * 编辑大屏埋点
     * 类型、大屏名称、大屏ID、编辑次数、租户id
     * type、screenName、screenId、screenEditNum、tenantId
     */
    id && dispatch(eventTracking<EditScreen>({
      id: `${id}-edit`,
      type: 'editScreen',
      screenName: name,
      screenId: id,
      screenEditNum: 1,
    }))
  }, [screen?.id]);

  // 加载数据
  useEffect(() => {
    dispatch(setScreenDataState(0)); // 初始化
    const controller = window.AbortController && new AbortController();
    const signal = controller && controller.signal;

    (async () => {
      const userInfo = await dispatch(getUserInfo());
      if (userInfo) {
        const id = +match.params.screenId;
        dispatch(getFilters(id));
        dispatch(getDataContainers(id));
        const result = await dispatch(getScreenData(id, signal));
        if (result) {
          const stateId = +match.params.stateId;
          dispatch(getConstants()); // 组件列表

          await dispatch(setScreenDataState(1)); // 标记一轮结束
          dispatch(getSources());
          dispatch(getFonts());

          window.appConfig.LOCAL && dispatch(getTransferinfo());

          await dispatch(redirectScreen(stateId ? stateId : id)); // 动态面板状态
          dispatch(getThemes());
          dispatch(getTenantConstants()); // 我的组件
          dispatch(getScreens()); // 拉取所有大屏
          await dispatch(getScreen(id, signal)); // 数据补齐第二轮
        }
        dispatch(setScreenDataState(2)); // 最后一轮结束
      }
    })();

    return () => {
      controller && controller.abort();
      dispatch(updateScreentEditModel(screenEditModel.CANVAS)); // 重置
      dispatch(clearScreen());
      dispatch(setScreenDataState(0)); // 初始化
    };
  }, [dispatch]);

  const watchPageState = () => {
    const type = isEditPage() ? screenEditModel.CANVAS : isNodePage() ? screenEditModel.NODES : '';
    type && dispatch(updateScreentEditModel(type));
  };

  // 路由监听
  useEffect(() => {
    watchPageState();
    const unlisten = history.listen((location) => {
      const id = getScreenId(location.pathname);
      if (id) {
        dispatch(redirectScreen(id));

        watchPageState();
        if (id === topScreenId) {
          dispatch(getFilters(id));
          dispatch(getDataContainers(id));
        }
      }
      if (!_isNodePage) {
        const preSelectLayer = sessionStorage.getItem('pre_select_layer');
        dispatch(preSelectLayer ? selectLayerWithScrollIntoView(preSelectLayer) : resetSelect());
        sessionStorage.removeItem('pre_select_layer');
      }
    });
    return () => {
      unlisten();
    };
  }, []);

  return _isNodePage ? (
    screenState === screenStateType.lastRound ? (
      <NodeView />
    ) : (
      <div className={styles.container}>
        <Loading />
      </div>
    )
  ) : (
    <ConfigProvider>
      {/* 超时提示刷新 */}
      <EasyvRefresh />
      <ScreenEditProvider>
        <div className={styles.container}>
          {(loading || restartLoading) && <Loading />}
          {!modalEdit && <ScreenHeader />}
          <section className={styles.content} style={modalEdit ? { height: '100vh' } : {}}>
            {!modalEdit && <ScreenLayers />}
            <ScreenPreview />
            <ScreenConfig />
          </section>
        </div>
      </ScreenEditProvider>
      <EasyvScreenLock />
    </ConfigProvider>
  );
}

function mapStateToProps({ createApp, screensById, screenEdit }) {
  const { id, loading, modalEdit } = createApp;
  const screen = screensById[id] || {};
  const { screenState } = screenEdit;
  return {
    loading,
    screenName: screen.name,
    modalEdit,
    screen,
    screenState,
  };
}

export default connect(mapStateToProps)(ScreenEdit);
