/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
/* eslint-disable no-underscore-dangle, no-confusing-arrow */
import ProLayout from '@ant-design/pro-layout';
import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'umi';
import { connect } from 'dva';
import { Icon as LegacyIcon } from '@ant-design/compatible';
import { Result, Button, Layout, Menu } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { getAuthorityFromRouter, getUrlSearchParams, getToken } from '@/utils/utils';

import logo from '../assets/logo.png';
import style from './BasicLayout.less';

const { Sider } = Layout;
const { SubMenu } = Menu;

const noMatch = (
  <Result
    status="403"
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        {window.__POWERED_BY_QIANKUN__ ? (
          <a href={`${window.origin}/access/login`}>Go Login</a>
        ) : (
          <Link to="/user/login">Go Login</Link>
        )}
      </Button>
    }
  />
);

const BasicLayout = props => {
  const {
    dispatch,
    children,
    settings,
    menuData = [],
    location = {
      pathname: '/',
    },
  } = props;

  const [siderCollapsed, setSiderCollapsed] = useState(false);

  // const audioRef = useRef()

  useEffect(() => {
    try {
      const token = getToken();
    } catch (e) {
      console.log(e);
    }

    if (dispatch) {
      dispatch({
        type: 'settings/getSetting',
      });
      dispatch({
        type: 'menu/getMenuData',
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = payload => {
    console.log('payload :>> ', payload);
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
    setSiderCollapsed(payload);
  }; // get children authority

  // 跳转到首页
  const toIndex = () => {
    props.history.push('/');
  };

  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/');
  const _menu = param =>
    param.map(v =>
      v.children && v.children.length ? (
        <SubMenu
          key={v.path}
          title={
            <span>
              <LegacyIcon type={v.icon} />
              <span>{v.name}</span>
            </span>
          }
        >
          {_menu(v.children)}
        </SubMenu>
      ) : (
        <Menu.Item key={v.path}>
          <Link to={v.path}>
            <LegacyIcon type={v.icon} />
            <span className="nav-text">{v.name}</span>
          </Link>
        </Menu.Item>
      ),
    );

  // 乾坤嵌套进入系统
  const qianKunLayout = () => (
    <div id="micro">
      <Layout className={style.layout}>
        <Sider
          collapsible
          collapsed={siderCollapsed}
          onCollapse={() => setSiderCollapsed(!siderCollapsed)}
        >
          <Menu theme="dark" mode="inline" defaultSelectedKeys={[location.pathname]}>
            {_menu(menuData)}
          </Menu>
        </Sider>
        <Layout style={{ zIndex: 1 }}>
          <Authorized noMatch={noMatch}>{children}</Authorized>
        </Layout>
      </Layout>
    </div>
  );

  // 商家端直接进入系统
  const merchantLayout = () => (
    <ProLayout
      logo={logo}
      onCollapse={handleMenuCollapse}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      // eslint-disable-next-line consistent-return
      breadcrumbRender={(routers = []) => {
        if (routers.length) {
          return [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            ...routers,
          ];
        }
      }}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      menuDataRender={() => menuData}
      rightContentRender={rightProps => <RightContent {...rightProps} />}
      pageTitleRender={() => ''}
      menuHeaderRender={() => (
        <div className={style['custom-title-box']} onClick={toIndex}>
          {!siderCollapsed && <div className={style['custom-title-box-title']}>商户管理系统</div>}
        </div>
      )}
      {...props}
      {...settings}
    >
      <Authorized authority={authorized.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );

  // tob后管嵌套进入系统
  const tobLayout = () => (
    <Layout className={style.tobLayout}>
      <Authorized noMatch={noMatch}>{children}</Authorized>
    </Layout>
  );

  // 是否从消费地图后管跳转过来
  const searchPrams = getUrlSearchParams();
  const isTob = searchPrams.source === 'tob';

  if (window.__POWERED_BY_QIANKUN__) {
    return qianKunLayout();
  }
  if (isTob && searchPrams.token) {
    console.log('window.parent :>> ', window.parent);
    window.wp = window.parent;
    return tobLayout();
  }
  return merchantLayout();
};
export default connect(({ global, settings, menu }) => ({
  collapsed: global.collapsed,
  settings,
  menuData: menu.menuData,
}))(BasicLayout);
