/* eslint-disable global-require */
// 集成登录引导页
import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import { notification } from 'antd';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { useDocumentTitle } from '@ant-design/pro-utils';
import defaultSetting from '@wisdom-utils/components/lib/AppLayout/layouts/defaultSettings';
import { actionCreators } from '@/containers/App/store';
import { store } from '@wisdom-utils/utils';
import LoginAction from '@/pages/user/login/login';
import Cookies from 'js-cookie';
import { defaultApp } from '@/micro';
import { appService } from '@/api';
import { SERVICE_INTERFACE_SUCCESS_CODE } from '@/constants';
import styles from './index.less';

const Integration = props => {
  const dataRef = useRef();
  const [percentBottom, setPercentBottom] = useState(-40);
  const [currentType, setCurrentType] = useState('');
  const [scale, setScale] = useState(1);
  const [loginAction, setAction] = useState(() => new LoginAction(props));
  const [num, setNum] = useState(0);
  const [dataList, setDataList] = useState([]);
  const [client, setClient] = useState('');


  //子站跳转
  const handlePage = (item, loginAction) => {
    let count = 1;
    setPercentBottom(-40 + Math.ceil(Math.random() * 8 * count));

    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) {
          return clearInterval(process.current);
        }
        setPercentBottom(perBottom);
        count += 1;
      }, 0);
    }, 3000);

    if (item.subType == '外链') {
      if (item.paramValue == 'ticket') {
        //获取临时token
        appService.getTicketByToken({ token: window.globalConfig?.token }).then(res => {
          if (res.code === 0) {
            let url = item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramName + '=' + res.data;
            window.open(url, "_blank");
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        });
      } else {
        let url = item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramName + '=' + window.globalConfig?.token;
        window.open(url, "_blank");
      }
    } else {
      if (window.qiankunIsCache) {
        store.set('event:dropCache');
      }

      let cli = item.url?.indexOf('client=') >= 0 ? item.url.split('client=')[1] : '';

      Cookies.set('client', cli, {
        expires: 86400000 / (24 * 60 * 60 * 1000),
        path: '/',
      });
      sessionStorage.setItem('client', cli);
      const currentProduct = `__global__recent_productIndex__micro_${window.location.hostname}_${window.globalConfig?.client ?? 'city'}`;
      sessionStorage.removeItem(currentProduct);
      const currentProductNew = `__global__recent_productIndex__micro_${window.location.hostname}_${cli || 'city'}`;
      sessionStorage.setItem(currentProductNew, 0);

      setClient(cli);
      setCurrentType(item.name);

      const config = props.global;
      config.uiwidgets = [];
      config.widgets = [];
      config.allWidgets = [];
      window.qiankunStarted = false;
      if (cli) {
        config.client = cli;
      }

      // props.instance && props.instance.updateConfig(config);
      loginAction && loginAction.getUserInfoAndConfig('', true, item.type);
    }
  };

  useEffect(() => {
    const handleToggleIndustry = event => {
      setPercentBottom(38);
      clearInterval(process.current);
      props.history.push(`/?client=${client ? client : props.global.client}`);

      props.updateCurrentIndex(0);

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

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


  //获取集成站点数据
  useEffect(() => {
    appService
      .GetIntegrationConfig({
        type: '集成登录',
        userId: window.globalConfig.userInfo?.OID ?? null,
        isEnable: true,
      })
      .then(res => {
        const { code, data } = res;
        if (code !== SERVICE_INTERFACE_SUCCESS_CODE) {
          notification.error({ message: '提示', duration: 3, description: '集成站点配置错误' });
          return;
        } else {
          setNum(data.length);
          setDataList(data);
          const config = props.global;
          config.isIntegration = data.length;
          props.updateConfig && props.updateConfig(config);
          if (data.length == 1) {
            handlePage(data[0], loginAction)
          }
        }
      })
      .catch(err => {
        notification.error({ message: '提示', duration: 3, description: '集成站点配置错误' });
      });
  }, [props.global.token]);

  return (
    <div className={styles.bootPage}>
      <div className={styles.bootPageMain}>
        <header className={styles.bootPageHead}>
          {
            props.global.logo
              ? <img role="logo" src={props.global && props.global.transformDevAssetsBaseURL && props.global.transformDevAssetsBaseURL(props.global.logo)} />
              : <img src={require(window.globalConfig.logo ? window.globalConfig.logo : `@/assets/bootPage/熊猫图标.png`)} />
          }
          <div className={styles.bootPageTitle}>
            <span className={styles.bootPageZh}>{window.globalConfig?.title ?? '熊猫智慧水务一体化解决方案'}</span>
            <span className={styles.bootPageEn}>{window.globalConfig.title ? window.globalConfig.subtitle : 'Panda Smart Water Integration Platform & Solution'}</span>
          </div>
        </header>
        <section className={classNames(styles.bootPageSection, 'animate__fadeInDown', 'animate__animated', 'duration-500ms')} >
          <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, }} >
            {dataList.length > 1 ? dataList.map(item => (
              <li className={styles.bootPageLi} key={item.name} onClick={event => handlePage(item, loginAction)} >
                <div className={styles.bootPageList}>
                  <div className={styles.listMain}>
                    {/* <img src={require(`@/assets/bootPage/供水.png`)} alt="" /> */}
                    <img src={window.location.origin + '/' + (item.icon ? item.icon : 'center/images/科技风/二供.png')} alt="" />
                    <span className={styles.bootPageName}>{item.name}</span>
                  </div>
                </div>
                {currentType === item.name && (
                  <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={'rgb(16,104,239)'} opacity="0.1" />
                          <use xlinkHref="#gentle-wave" x="50" y="-1" fill={'rgb(16,104,239)'} opacity="0.2" />
                        </g>
                      </svg>
                    </div>
                  </div>
                )}
              </li>
            )) : ''}
          </ul>
        </section>
      </div>
    </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,
)(Integration);