/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import socketIOClient from 'socket.io-client';
import sailsIOClient from 'sails.io.js';
import Loading from 'components/Loading';
import Title from 'components/Title';
import ScreenContainer from './ScreenContainer';
import { useSizeByDomId } from 'components/easyUse';
import { appActions, interactionActions } from './models';
import { emitEvent } from 'models/interaction';
import { getFonts } from 'models/font';
import styles from './index.less';
import { PasswordCheck } from './PasswordCheck';
import { useTitle } from 'components/easyUse';

// checkMode:login|code
// 默认都是code模式 需要输入控制码
// 如果是login模式 则不需要控制码 接口会验证用户cookie
const isLoginMode = /checkMode=login/.test(location.search);
// 尝试从url里取控制码
const controlCodeMatch = (location.search.match(/controlCode=(\w+)/) || [])[1];

function InteractionDetail({
  match,
  loading,
  name,
  config,
  pages,
  activePage,
  pageAnimation,
  getApp,
  getFonts,
  emitEvent,
  jumpPage,
  renderCheck
}) {
  const { width: windowWidth = 0, height: windowHeight } = useSizeByDomId();
  const { params } = match;
  const { appId } = params;

  const [controlCode, setControlCode] = useState(controlCodeMatch);
  useTitle('终端控制器');

  const io = useMemo(() => {
    if (renderCheck) {
      return;
    }
    const result = sailsIOClient(socketIOClient);
    result.sails.reconnection = true;
    result.sails.url = '/';

    result.socket.on('connect', () => {
      result.socket.get('/api/v3/remote/mobile/enter', {
        id: appId,
        controlCode,
        mobileId: appId
      });
    });

    result.socket.on('message', (data) => {
      emitEvent(data);
    });

    return result;
  }, [renderCheck]);

  useEffect(() => {
    // 如果已经发布，则判断当前终端控制码是否正确，正确则直接进入终端界面,否则进入输入控制码的界面
    getApp(appId, isLoginMode ? {} : { byControlCode: controlCode });
    getFonts();
  }, [controlCode, appId]);

  const { width } = config;
  const scale = windowWidth / width;

  const handleEmitEvent = ({ payload }) => {
    payload = {
      ...payload,
      _from: {
        ...payload._from,
        mobileId: Number(appId)
      }
    };

    if (payload.page) {
      jumpPage(payload);
    } else if (!payload.screen) {
      emitEvent(payload);
    } else {
      if (io) {
        if (payload?.animation?.delay > 0) {
          setTimeout(() => {
            io.socket.get('/api/v3/remote/broadcast', {
              data: payload,
              controlCode,
              mobileId: appId
            });
          }, payload.animation.delay);
        } else {
          io.socket.get('/api/v3/remote/broadcast', {
            data: payload,
            controlCode,
            mobileId: appId
          });
        }
      }
    }
  };

  if (renderCheck === 2) {
    return null;
  }

  // 如果没有发布或者控制码错误
  if (renderCheck === 1) return <PasswordCheck appId={appId} onLogin={(v) => setControlCode(v)} />;

  return (
    <div className={styles.container}>
      <Title title={name} />
      {pages
        .concat()
        .reverse()
        .map((d) => {
          return (
            <ScreenContainer
              key={d.id}
              id={d.id}
              active={activePage === d.uniqueTag}
              emitEvent={handleEmitEvent}
              scale={scale}
              animation={pageAnimation}
              containerHeight={windowHeight}
            />
          );
        })}

      {loading && <Loading />}
    </div>
  );
}

function mapStateToProps({ interactionDetail }) {
  const { loading, name, config, pages, activePage, pageAnimation, renderCheck } = interactionDetail;
  return {
    loading,
    name,
    pages,
    config,
    activePage,
    pageAnimation,
    renderCheck
  };
}

const mapDispatchToProps = {
  getApp: appActions.getApp,
  jumpPage: interactionActions.jumpPage,
  getFonts,
  emitEvent
};

export default connect(mapStateToProps, mapDispatchToProps)(InteractionDetail);
