/* eslint-disable global-require */
// 云平台引导页
import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import enterImg from '@/assets/images/demonstration/进入.png';
import { RightOutlined } from '@ant-design/icons';

import { Space, Spin, Progress } from 'antd';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { useIntl } from '@wisdom-utils/components';
import { useDocumentTitle } from '@ant-design/pro-utils';
import { useHistory } from '@wisdom-utils/runtime';
import defaultSetting from '@wisdom-utils/components/lib/AppLayout/layouts/defaultSettings';
import { actionCreators } from '@/containers/App/store';
import LoginAction from '@/pages/user/login/login';
import { defaultApp } from '@/micro';
import usingIcon from '@/assets/bootPage/using-icon.png';
import { appService } from '@/api';
import styles from './index.less';
const industries = [
  { name: '供水', type: '供水', subTitle: 'WATER SUPPLY', color: 'rgb(16,104,239)' },
  { name: '农饮水', type: '农饮水', subTitle: 'RURAL POTABLE WATER', color: 'rgb(4,142,101)' },
  { name: '排水', type: '排水', subTitle: 'DRAINAGE', color: 'rgb(234,117,28)' },
  { name: '水利', type: '水利', subTitle: 'WATER CONSERVANCY', color: 'rgb(0,144,158)' },
  { name: '能源', type: '能源', subTitle: 'ENERGY SOURCES', color: 'rgb(49,139,27)' },
  { name: '高品质水', type: '高品质水', subTitle: 'HIGH QUALITY WATER', color: 'rgb(106,208,218)' },
  // { name: '水资源', type: '水资源', subTitle: 'WATER RESOURCES' },
  { name: '熊猫智能实验室', type: '实验室', subTitle: 'PANDA AI. LAB', color: 'rgb(104,163,242)' },
  { name: '水务大数据', type: '大数据', subTitle: 'WATER BIG DATA', color: 'rgb(85,77,210)' },
  { name: '熊猫新产品', type: '熊猫新产品', subTitle: "PANDA'S NEW PRODUCT", color: 'rgb(12,103,205)' },
  { name: '项目案例', type: '项目案例', subTitle: 'PROJECT CASE', color: 'rgb(107,36,155)' },
];

// let loginAction = null;
const BootPage = props => {
  const dataRef = useRef();
  const process = useRef();
  const { setPattern } = props;
  const [Industries] = useState(props.global.userInfo.Industries);
  const [percentBottom, setPercentBottom] = useState(-40);
  const [percentNum, setPercentNum] = useState(0);
  const [currentType, setCurrentType] = useState('');
  const [loadding, setLoadding] = useState(false);
  const [hasRole, setHasRole] = useState(false);
  const [scale, setScale] = useState(1);
  const [loginAction, setAction] = useState(() => new LoginAction(props));
  const [num] = useState(Industries.filter(item => !!industries.find(d => d.type === item)).length);
  // const history = useHistory();
  useDocumentTitle(
    { title: defaultSetting.title, id: '', pageName: '行业切换' },
    props.global.title || defaultSetting.title,
  );
  useEffect(() => {
    dataRef.current = percentNum;
  }, [percentNum]);
  // eslint-disable-next-line no-shadow
  const handlePage = (event, type, loginAction) => {
    if (loadding) return;
    let count = 1;
    setLoadding(true);
    setPercentBottom(-40 + Math.ceil(Math.random() * 8 * count));
    setPercentNum(Math.ceil(Math.random() * 10));
    setCurrentType(type);
    //
    // event.persist();
    // event.preventDefault();
    process.current = setInterval(() => {
      setTimeout(() => {
        const perBottom = -40 + 8 * count + Math.ceil(Math.random() * 8);
        const perNum = 10 * count + Math.ceil(Math.random() * 10);
        if (perNum >= 80 || dataRef.current >= 80 || count === 10) {
          setLoadding(false);
          return clearInterval(process.current);
        }
        setPercentBottom(perBottom);
        setPercentNum(perNum);
        count += 1;
      }, 0);
    }, 2000);
    // 新增熊猫新产品引导页
    if (type === '熊猫新产品') {
      setTimeout(() => {
        setPercentBottom(40);
        setPercentNum(100);
        clearInterval(process.current);
        setTimeout(() => {
          props.history.push('/cloud/introduction/newproducts');
          // window.history.pushState('', null, `/cloud/introduction/newproducts`);
        }, 500);
      });

      return;
    }

    // setLoadding(true);
    const config = props.global;
    // const loginAction = new LoginAction(props);
    config.uiwidgets = [];
    config.widgets = [];
    config.allWidgets = [];
    props.instance && props.instance.updateConfig(config);
    // props.instance && props.instance.getUserInfoAndConfig('', true, type);
    loginAction && loginAction.getUserInfoAndConfig('', true, type);
  };

  useEffect(() => {
    // eslint-disable-next-line no-use-before-define
    handleResize();
  }, []);
  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(() => {
    window.addEventListener('resize', handleResize);

    const handleToggleIndustry = event => {
      setPercentBottom(38);
      setPercentNum(98);
      setLoadding(false);
      clearInterval(process.current);
      setTimeout(() => {
        props.history.push(`/?client=${props.global.client}`);
      }, 1000);

      // window.share.event.emit('triggerMicro', props.global);
      props.updateCurrentIndex(0);

      defaultApp();
    };
    loginAction.events.on('toggleIndustry', handleToggleIndustry);

    return () => {
      window.removeEventListener('resize', handleResize);
      loginAction.events.removeListener('toggleIndustry', handleToggleIndustry);
    };
  }, [loginAction.events, props, currentType]);

  useEffect(() => {
    window.share.event.on('visible', ret => {
      setTimeout(() => {
        setPercentBottom(40);
        setPercentNum(100);
        setLoadding(false);
        clearInterval(process.current);
        setTimeout(() => {
          window.history.pushState(null, '', ret);
        }, 500);
      }, 500);
    });
  }, []);

  const intl = useIntl();
  const toOMSUsingAnalysis = e => {
    e && e.stopPropagation();
    props.history.push(`/cloud/analysis/using`);
  };

  // const test = `bootPageUl_${props.global && props.global.userInfo && props.global.userInfo.Industries
  //   ? props.global.userInfo.Industries.filter(item => !!industries.find(d => d.type === item)).length
  //   : 0`

  useEffect(() => {
    appService
      .getUserInfo({
        token: props.global.token,
        subOID: 'subOID',
        site: 'cloud',
        ignoreSite: true,
      })
      .then(res => {
        const roles = res?.data?.roles ?? [];
        // eslint-disable-next-line no-underscore-dangle
        const _hasRole = roles && Array.isArray(roles) && roles.filter(r => r.name === '客户运维管理员').length;
        setHasRole(!!_hasRole);
      });
  }, [props.global.token]);

  return (
    <div className={styles.bootPage}>
      <div className={styles.b_top_l}>
        <div className={styles.b_top_l_btn} onClick={() => setPattern(true)}>
          <img src={enterImg} alt="" /> 进入演示模式 <RightOutlined />
        </div>
      </div>
      <div className={styles.bootPageMain}>
        <header className={styles.bootPageHead}>
          {/* eslint-disable-next-line jsx-a11y/alt-text */}
          <img src="https://panda-water.cn/web4/assets/images/bootPage/熊猫图标.png" />
          <div className={styles.bootPageTitle}>
            <span className={styles.bootPageZh}>熊猫智慧水务一体化解决方案</span>
            <span className={styles.bootPageEn}>Panda Smart Water Integration Platform & Solution</span>
          </div>
        </header>
        <section
          className={classNames(styles.bootPageSection, 'animate__fadeInDown', 'animate__animated', 'duration-500ms')}
          // style={{
          //   width: `${scale < 1 ? 1280 : Math.ceil(1280 * scale)}px`,
          // }}
        >
          <ul
            className={classNames(styles.bootPageUl, 'animate__animated')}
            style={{
              transform: `scale(${scale})`,
              left: '300px',
              bottom: '105px',
              opacity: 1,
              width: num === 5 ? 960 : num === 9 || num === 10 ? 1600 : 1280,
            }}
          >
            {industries.map(
              item =>
                props.global &&
                Industries.indexOf(item.type) > -1 && (
                  <li
                    className={styles.bootPageLi}
                    key={item.type}
                    onClick={event => handlePage(event, item.type, loginAction)}
                  >
                    <div className={styles.bootPageList}>
                      <div className={styles.listMain}>
                        <img src={require(`@/assets/bootPage/${item.type}.png`)} alt="" />
                        <span className={styles.bootPageName}>{item.name}</span>
                        <span className={styles.bootPageNameEng}>{item.subTitle}</span>
                      </div>
                    </div>
                    {currentType === item.type && (
                      <div className={styles.bootProgress}>
                        <div className={styles.inner} style={{ bottom: percentBottom }}>
                          <svg
                            className={styles.wave}
                            xmlns="http://www.w3.org/2000/svg"
                            xmlnsXlink="http://www.w3.org/1999/xlink"
                            viewBox="0 24 150 68"
                            preserveAspectRatio="none"
                          >
                            <defs>
                              <path
                                id="gentle-wave"
                                d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"
                              />
                            </defs>
                            <g className={styles.parallax}>
                              <use xlinkHref="#gentle-wave" x="50" y="0" fill={item.color} opacity="0.1" />
                              <use xlinkHref="#gentle-wave" x="50" y="-1" fill={item.color} opacity="0.2" />
                            </g>
                          </svg>
                        </div>
                      </div>
                    )}
                  </li>
                ),
            )}
          </ul>
        </section>
        {/* <Space className={styles.abs}> */}
        {/*  <Spin spinning={loadding} size="large" /> */}
        {/* </Space> */}
      </div>
      {hasRole ? (
        <div className={styles.cloudMonitorBtns}>
          <div className="cloud-using-anaylysis-btn" onClick={toOMSUsingAnalysis}>
            <img src={usingIcon} alt="" title="点击查看平台使用监控" />
            <span>平台使用分析</span>
          </div>
        </div>
      ) : null}
    </div>
  );
};
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));
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(BootPage);