/*
 * @Title:
 * @Author: hongmye
 * @Date: 2023-01-10 11:18:55
 */
import React, { memo, useEffect } from 'react';
import Iframe from 'react-iframe';
import Empty from '@wisdom-components/empty';
import styles from './index.less';
import Hoc from './HocContainer';
import useFullScreen from './useFullScreen';
const TabWidget = props => {
  const params = Object.assign({}, props.params, {
    fullscreen: !(props.params !== undefined && props.params.fullscreen === 'true'),
  });
  const { linkUrl, fullscreen, bgColor } = params;

  const newLink = linkUrl.replaceAll('@', '#').replaceAll('*', '?').replaceAll('$', '|').replaceAll('!', '&');
  const [ref, isFullscreen, handleFullScreen, handleExit] = useFullScreen(fullscreen);
  const goToPath = (name, data, widgetId) => {
    try {
      const routes = window.globalConfig?.allWidgets || [];
      let info = null;
      // eslint-disable-next-line no-inner-declarations
      function urlSearch(arr) {
        arr.forEach(a => {
          if (a.label) {
            if (a.label === name) {
              info = JSON.parse(JSON.stringify(a));
            }
          }
          if (a.widgets) {
            urlSearch(a.widgets);
          }
        });
      }
      urlSearch(routes);
      if (!info) return info;
      info.url = info.url.substr(0, 1) === '/' ? info.url : `/${info.url}`;
      let url = `/civbase/${info.product}${info.url}`;
      const arr = url.split('|');
      let paramsData = {};
      // eslint-disable-next-line prefer-destructuring
      url = arr[0];
      if (arr[1]) {
        url += encodeURI(`|${arr[1]}`);
        const arrObj = arr[1].split('&');
        arrObj.forEach(item => {
          const temp = item.split('=');
          // eslint-disable-next-line prefer-destructuring
          paramsData[temp[0]] = temp[1];
        });
      }
      paramsData = { ...paramsData, ...data, refresh: true };
      paramsData.widget = widgetId || paramsData.widget;
      console.log(paramsData, url);
      window.history.pushState(paramsData, '', url);
    } catch (error) {
      console.log('🚀 ~ error:', error);
    }
  };
  const onMessage = e => {
    if (e?.data?.name) {
      goToPath(e?.data?.name);
    }
  };
  useEffect(() => {
    window.addEventListener('message', onMessage);
    return () => {
      window.removeEventListener('message', onMessage);
    };
  }, [onMessage]);
  return (
    <div className={styles['tab-iframe']} ref={ref}>
      <div className={styles['oper-wrap']}>
        <div className={styles['oper-btn']}>
          {isFullscreen ? (
            <>
              {/* <div className={styles['btn-fullscreen_container']}>
                <span className={styles['btn-fullscreen_reduce']} onClick={handleExitFullScreen} />
              </div> */}
              <div className={styles['btn-fullscreen_container']} style={{ marginLeft: '8px' }}>
                <span className={styles['btn-fullscreen_exit']} onClick={handleExit} />
              </div>
            </>
          ) : (
            <div className={styles['btn-fullscreen_container']}>
              <span className={styles['btn-fullscreen_full']} onClick={handleFullScreen} />
            </div>
          )}
        </div>
      </div>
      {newLink ? (
        <Iframe
          url={newLink}
          width="100%"
          height="100%"
          display="block"
          position="relative"
          styles={{ border: 'none', background: bgColor ? '#' + bgColor : '' }}
        />
      ) : (
        <Empty description="配置url链接才能显示哦!" />
      )}
    </div>
  );
};

export default memo(Hoc(TabWidget));