/* eslint-disable prettier/prettier */

import React, { useEffect, useState, useCallback, useRef } from 'react';
import classNames from 'classnames';
import { connect } from 'react-redux';
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 { notification, Tooltip, message } from 'antd';
import homeIcon from '@/assets/bootPage/集成登录.png';
import { appService } from '@/api';
import axios from 'axios';
import { defaultApp } from '@/micro';
import { useHistory } from '@wisdom-utils/runtime';
import LoadPage from '@/components/LoadPage';
import { getUserInfo, getWebSiteConfig } from '@/api/service/base';
import { goToPath, searchUrl } from '@/utils/utils';
import styles from './index.less';
const tipStyleMap = {
  左下: {
    justifyContent: 'flex-start',
  },
  // 中下:{},
  右下: {
    justifyContent: 'flex-end',
  },
};
const IntegratedSwitch = props => {
  const integratedConfig = props.integratedConfig?.toObject
    ? props.integratedConfig.toObject()
    : props.integratedConfig || {};
  const timer = useRef(null);
  const timer3 = useRef(null);
  const progressRef = useRef(0);
  const history = useHistory();
  const [loginAction, setAction] = useState(() => new LoginAction(props));
  const [dataList, setDataList] = useState([]);
  const [client, setClient] = useState('');
  const clientRef = useRef(props.global.client);
  const clientInfo = useRef({}); // 跳转子站信息

  const [jumpLoading, setJumpLoading] = useState(false);
  const [progressValue, setProgressValue] = useState(0);
  const jumpProgressEnd = () => {
    setProgressValue(100);
    timer.current && clearInterval(timer.current);
    timer.current = null;
  };
  const jumpProgressStart = () => {
    if (timer.current) {
      clearInterval(timer.current);
      timer.current = null;
    }
    progressRef.current = 0;
    setProgressValue(0);
    timer.current = setInterval(() => {
      if (progressRef.current < 97.5) {
        progressRef.current += 2.5;
        setProgressValue(progressRef.current);
      } else {
        setProgressValue(99);
        timer.current && clearInterval(timer.current);
        timer.current = null;
      }
    }, 100);
  };
  // 定时消除 loading
  const startTiming = (time = 2) => {
    if (timer3.current) {
      clearInterval(timer3.current);
      timer3.current = null;
    }
    timer3.current = setTimeout(() => {
      setJumpLoading(false);
      timer.current && clearInterval(timer.current);
      timer.current = null;
    }, time * 1000);
  };
  const handError = err => {
    if (err) {
      message.error(err);
    }

    setJumpLoading(false);
    jumpProgressEnd();
  };
  useEffect(() => {
    // if (!window?.globalConfig?.userInfo?.OID || (!(window?.globalConfig?.isIntegration > 1) && window?.globalConfig?.Industry !== '集成登录')) return setDataList([]);
    if (!window?.globalConfig?.userInfo?.OID || !(window?.globalConfig?.isIntegration >= 1)) return setDataList([]);
    let list = localStorage.getItem('integrationData'); //
    list = list ? JSON.parse(list) : [];
    if (Array.isArray(list) && list?.length) {
      setDataList(list || []);
    } else {
      appService
        .GetIntegrationConfig({
          type: '集成登录',
          userId: window?.globalConfig?.userInfo?.OID ?? null,
          isEnable: true,
          client:
            localStorage.getItem('integrationClient') ||
            sessionStorage.getItem('client') ||
            props?.global?.client ||
            '',
        })
        .then(res => {
          let arr = res?.data || [];
          arr = arr.map(item => {
            if (item.subType === '内链' && !item.client && item.url) {
              item.client = item.url?.indexOf('client=') >= 0 ? item.url.split('client=')[1] : '';
            }
            return item;
          });
          setDataList(arr);
        })
        .catch(err => {
          setDataList([]);
        });
    }
  }, []);

  // 子站跳转
  // eslint-disable-next-line no-shadow
  const handlePage = useCallback((item, loginAction) => {
    if (window.clientInfo) {
      window.clientInfo = null;
    }

    if (item.subType === '外链') {
      setJumpLoading(true);
      jumpProgressStart();
      startTiming(5);
      // 营收
      if (item.paramValue === 'ticket') {
        // 获取临时token
        appService.getTicketByToken({ token: window.globalConfig?.token }).then(res => {
          if (res.code === 0) {
            const url = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramValue}=${res.data}`;
            if (item?.openOpt === '当前页打开') {
              history.push('/thirdParty', { linkUrl: url });
            } else {
              window.open(url, '_blank');
            }
          } else {
            setJumpLoading(false);
            jumpProgressEnd();
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        });
      } else {
        const url = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramName}=${
          window.globalConfig?.token
        }`;
        if (item?.openOpt === '当前页打开') {
          history.push('/thirdParty', { linkUrl: url });
        } else {
          window.open(url, '_blank');
        }
      }
    } else if (item.subType === '内链') {
      const { pathname } = window.location;
      const cli = item.client;
      if (item.client === props.global.client && pathname.indexOf('/civbase/thirdParty') === -1) {
        if (item.url) {
          goToPath(item.url);
          return;
        }
      }
      const token = props.global?.token || Cookies.get('token');
      getWebSiteConfig({
        identity: token,
        client: cli,
      }).then(res => {
        if (!res?.data?.[0]?.widgets?.length) {
          message.error({
            duration: 3,
            content: '您没有该板块权限,请联系管理员',
          });

          return;
        }
        setJumpLoading(true);
        jumpProgressStart();
        startTiming(5);
        if (window.qiankunIsCache) {
          store.set('event:dropCache');
        }

        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);
        clientRef.current = cli;
        window.clientInfo = item;
        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);
      });
    } else {
      setJumpLoading(true);
      jumpProgressStart();
      startTiming(5);
      let { url } = item;
      if (url?.indexOf('{userId}') >= 0) {
        url = url.replace('{userId}', window.globalConfig?.userInfo?.OID);
      }
      axios({
        url,
        method: 'get',
        dataType: 'json',
      }).then(res => {
        if (res?.data?.code === 0) {
          if (item?.openOpt === '当前页打开') {
            history.push('/thirdParty', { linkUrl: res.data?.data });
          } else {
            window.open(res.data?.data, '_blank');
          }
        } else {
          setJumpLoading(false);
          jumpProgressEnd();
        }
      });
    }
  });

  useEffect(() => {
    const handleToggleIndustry = event => {
      setJumpLoading(false);
      jumpProgressEnd();
      let url = '';
      const { pathname } = window.location;
      if (window.clientInfo?.url && window.clientInfo.subType === '内链') {
        if (pathname.indexOf('/civbase/thirdParty') === -1) {
          // 上一个也是站内跳转,则可直接用 BasicLayout 里的跳转
          return;
        }
        // 上个子站不是站外链接,可直接用跳转
        url = searchUrl(window.clientInfo.url);
      }
      history.push(`/?client=${clientRef.current || props.global.client || ''}`);
      props.updateCurrentIndex(0);
      defaultApp(url);
    };
    const handleError = () => {
      setJumpLoading(false);
      jumpProgressEnd();
    };
    loginAction.events.on('toggleIndustry', handleToggleIndustry);
    loginAction.events.on('loginError', handleError);
    return () => {
      loginAction.events.removeListener('toggleIndustry', handleToggleIndustry);
      loginAction && loginAction.events && loginAction.events.removeListener('loginError', handleError);
    };
  }, [loginAction.events, props]);

  return dataList.length > 1 && integratedConfig?.isShowTip !== '不显示' ? (
    <div
      className={styles.switchPage}
      style={{
        ...tipStyleMap[(integratedConfig?.tipAlign)],
      }}
    >
      {jumpLoading ? (
        <div className={styles.integrationJumpLoad} key="jumpLoading">
          <div style={{ width: '285px' }}>
            <LoadPage percent={progressValue / 100} text="页面加载中~" />
          </div>
        </div>
      ) : null}
      <ul className={classNames(styles.switchPageCase, styles.switchPageSmall)}>
        <li
          className={styles.switchPageLi}
          onClick={() => {
            const integrationClient = localStorage.getItem('integrationClient');
            sessionStorage.setItem('client', integrationClient);
            localStorage.removeItem('integrationClient');
            history.push('/industry');
          }}
        >
          <div className={styles.switchPageList}>
            <Tooltip placement="top" title="主页">
              <img src={homeIcon} alt="" />
            </Tooltip>
          </div>
        </li>
        {dataList.map(item => (
          <li className={styles.switchPageLi} key={item.name} onClick={event => handlePage(item, loginAction)}>
            <div className={styles.switchPageList}>
              <Tooltip placement="top" title={item.name}>
                <img
                  src={`${window.location.origin}/${item.icon ? item.icon : 'center/images/科技风/二供.png'}`}
                  alt=""
                />
              </Tooltip>
            </div>
          </li>
        ))}
      </ul>
    </div>
  ) : null;
};

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  instance: state.getIn(['global', 'instance']),
  client: state.getIn(['global', 'client']),
  integratedConfig: state.getIn(['global', 'integratedConfig']),
});
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,
)(IntegratedSwitch);