/* eslint-disable indent */
/* eslint-disable global-require */
// 云平台引导页
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from '@/containers/App/store';
import Cookies from 'js-cookie';
import _ from 'lodash';
import { useHistory, useAliveController } from '@wisdom-utils/runtime';
import classNames from 'classnames';
import styles from './index.less';
import bgImage from './images/背景.png';
import iconImage from './images/图层 12@2x.png';
import leftTiltle from './images/组 11@2x.png';
import rightTiltle from './images/组 11@2x(1).png';
import SecurityLayout from '../SecurityLayout';
import { defaultApp, findMenuPath } from '../../micro';

const HomePage = props => {
  const { clear } = useAliveController();
  const history = useHistory();
  const { global: globalConfig } = props || {};
  const { transitionPage = {}, title } = globalConfig;
  const { title: name = '', content: industries = [], background = null, icon } = transitionPage;
  const [scale, setScale] = useState(1);
  const handleResize = () => {
    const width = document.documentElement.clientWidth;
    const height = document.documentElement.clientHeight;
    // eslint-disable-next-line no-shadow
    const scale = width / 1920;
    setScale(scale);
  };
  useEffect(() => {
    const tk = Cookies.get('token') || props.global.token;
    const isLogin = tk !== null && tk !== 'undefined' && tk !== void 0;
    let client = props?.global?.client || sessionStorage.getItem('client') || null;
    client = client !== 'undefined' && !_.isNull(client) && !_.isUndefined(client) ? client : 'city';
    // eslint-disable-next-line no-prototype-builtins
    let generateType = props.global && props.global.hasOwnProperty('get') ? props.global.get('generateType') : null;
    generateType =
      !_.isNull(generateType) && !_.isUndefined(generateType) && generateType !== 'undefined'
        ? `&generateType=${generateType}`
        : '';
    if (!isLogin) {
      history.push(`/user/login?client=${client}${generateType}`, { reload: true });
      clear();
      props.logout();
    }
  }, [clear, history, props, props.global]);
  useEffect(() => {
    handleResize();
  }, []);
  useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  const handlePage = (target, index) => {
    const { allWidgets, client } = props.global;
    const url = findMenuPath([allWidgets[index]]);
    target.updateCurrentIndex && target.updateCurrentIndex(index);
    target.history.push(`/?client=${client}`);
    window.share.event.emit('triggerMicro', target.global);

    defaultApp(url);
  };
  return (
    <SecurityLayout loading {...props}>
      <div className={styles.transitionPage} style={{ backgroundImage: `url(${background || bgImage})` }}>
        <div className={styles.transitionPageContainer}>
          <section
            className={classNames(styles.bootPageSection, 'animate__fadeInDown', 'animate__animated', 'duration-500ms')}
            style={{
              height: '22%',
            }}
          >
            <ul
              className={classNames(styles.bootPageUl, 'animate__animated')}
              style={{
                transform: `scale(${scale})`,
                left: '300px',
                bottom: '105px',
                opacity: 1,
                width: 'auto',
                flexDirection: 'column',
              }}
            >
              <div className={styles.title}>
                <img src={icon || iconImage} alt="" />
                <span>{title}</span>
              </div>
              <div className={styles.sub}>
                <img src={leftTiltle} alt="" />
                <span>{name}</span>
                <img src={rightTiltle} alt="" />
              </div>
            </ul>
          </section>
        </div>
        <div className={styles.transitionPageContainer}>
          <section
            className={classNames(styles.bootPageSection, 'animate__fadeInDown', 'animate__animated', 'duration-500ms')}
            style={{
              marginTop: '8%',
            }}
          >
            <ul
              className={classNames(styles.bootPageUl, 'animate__animated')}
              style={{
                transform: `scale(${scale})`,
                left: '300px',
                bottom: '105px',
                opacity: 1,
                width:
                  industries.length === 4
                    ? 1400
                    : industries.length === 5
                    ? 960
                    : industries.length === 6
                    ? 1045
                    : 1280,
                height: industries.length > 4 ? 640 : '',
              }}
            >
              {industries && industries.length < 5
                ? industries.map((item, index) => (
                    <div
                      className={styles.container}
                      onClick={() => handlePage(props, index)}
                      key={`${item.name}-${index}`}
                    >
                      <div className={styles.imageContainer} style={{ backgroundImage: `url(${item.image})` }}>
                        <img src={item.icon} alt="" className={styles.icon} />
                      </div>
                      <div className={styles.textContainer}>
                        <span className={styles.textName}>{item.name}</span>
                        <span className={styles.text}>{item.subTitle}</span>
                      </div>
                    </div>
                  ))
                : industries.map((item, index) => (
                    <div
                      className={styles.multiContainer}
                      onClick={() => handlePage(props, index)}
                      key={`${item.name}-${index}`}
                    >
                      <div className={styles.textContainer} style={{ backgroundImage: `url(${item.image})` }}>
                        <span className={styles.textName}>{item.name}</span>
                        <span className={styles.text}>{item.subTitle}</span>
                      </div>
                    </div>
                  ))}
            </ul>
          </section>
        </div>
      </div>
    </SecurityLayout>
  );
};
const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  instance: state.getIn(['global', 'instance']),
});
const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  createContext(data) {
    dispatch(actionCreators.createContext(data));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
  logout() {
    dispatch(actionCreators.logout());
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(HomePage);