import React, { ReactNode, useMemo, useEffect, useCallback, ReactText } from 'react';
import qs from 'qs';
import { env, navRedirectDiscope, redirctToLogin } from '@jy-fe/business';
import { ElementType } from '@jy-fe/business/es/authority';
import { unicodeToChar, useDeepEqualIdentifier } from '@jy-fe/utils';
import classnames from 'classnames';
import locale from 'antd/es/locale/zh_CN';
import ConfigProvider from 'antd/es/config-provider';
import Menu from 'antd/es/menu';
import 'antd/es/menu/style/index';
import { SelectInfo } from 'rc-menu/es/interface';
import Tooltip from 'antd/es/tooltip';
import 'antd/es/tooltip/style/index';
import message from 'antd/es/message';
import 'antd/es/message/style/index';
import {
  XuiQilinThemeLayoutInfoDataType,
  XuiQilinThemeLayoutProps,
} from './xui-qinlin-theme-layout.d';
import XuiRoleMenu from '../xui-role-menu';

const XuiQilinThemeLayout: React.FC<XuiQilinThemeLayoutProps> = ({
  systemType,
  ownModule,
  Link,
  history,
  children,
  initialState,
  ignoreMainPageRedirctPath,
  horizontalSelectedUrl,
  onSelectedHorizontalMenuCallback,
  openedKeys,
  selectedKeys,
  onSelectedSubMenu,
  onSelectedMenuItem,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  positionVisible,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onPositionVisible,
  roleDataDiscope,
  effectCallback,
}) => {
  /** 获取当前路由地址 */
  const token = localStorage.getItem('token');
  const { pathname } = location;
  const className = 'xui-ant__qinlin-theme-layout';
  const headerClassName = 'xui-ant__qinlin-theme-layout--header';
  const bodyClassName = 'xui-ant__qinlin-theme-layout--body';
  /**
   * 以下为权限部分
   */
  /** 解析浏览器?后的参数对 */
  const urlParams = useMemo(() => qs.parse(location.search, { ignoreQueryPrefix: true }), []);

  const { code } = urlParams;

  if (code) {
    delete urlParams.code;
    const searchStr = qs.stringify(urlParams, { addQueryPrefix: true });
    history.replace(`${location.pathname}${searchStr}`);
  }

  /** 无首页重定向地址 */
  if (token && location.pathname === '/' && ignoreMainPageRedirctPath) {
    history.replace(ignoreMainPageRedirctPath);
  }

  const {
    roleData = [],
    redirectPathMap = {},
    verticalNav = [],
    access = [],
    aidMap = {},
    highlightIdMap = {},
  } = initialState || {};

  const accessEqual = useDeepEqualIdentifier(access);
  const aidMapEqual = useDeepEqualIdentifier(aidMap);

  /** 重定向判断 */
  navRedirectDiscope(systemType, redirectPathMap, pathname, redirectPath => {
    history.replace(redirectPath);
  });

  /** 退出登录 */
  const logout = useCallback(() => {
    localStorage.removeItem('token');
    message.success('退出成功');
    location.href = env.ssoLogoutHREF;
  }, []);

  /** 点击横向滚动条后的调用 */
  const selectedHorizontalMenuCallback = useCallback(
    (currentPathname: string, currentRedirectPath: string) => {
      onSelectedHorizontalMenuCallback(currentPathname);
      history.push(currentRedirectPath);
    },
    [history, onSelectedHorizontalMenuCallback],
  );

  /** 获取横向导航栏选中块的相关属性 */
  const selectedHorizontalMenuItem = useCallback(
    (item: any) => {
      if (item.mstyle === '/') {
        selectedHorizontalMenuCallback('/', '/');
      } else {
        navRedirectDiscope(systemType, redirectPathMap, item.mstyle, redirectPath => {
          selectedHorizontalMenuCallback(item.mstyle, redirectPath);
        });
      }
    },
    [systemType, redirectPathMap, selectedHorizontalMenuCallback],
  );

  /** 生成横向导航栏 */
  const HorizontalMenu = useMemo(() => {
    const menus = roleData.map((element: ElementType) => {
      if (element.newTabType === 1) {
        return (
          <a key={element.id || ''} target='__blank' href={element.lowerLevelUrl}>
            <div className={`${headerClassName}--menu--item`}>{element.mlabel}</div>
          </a>
        );
      }
      if (ownModule.includes(element.mstyle || '')) {
        return (
          <div
            key={element.id || ''}
            className={classnames({
              [`${headerClassName}--menu--item`]: true,
              [`${headerClassName}--menu--itemActive`]: horizontalSelectedUrl === element.mstyle,
            })}
            onClick={() => selectedHorizontalMenuItem(element)}
          >
            {element.mlabel}
          </div>
        );
      }
      return (
        <a key={element.id || ''} href={element.lowerLevelUrl}>
          <div className={`${headerClassName}--menu--item`}>{element.mlabel}</div>
        </a>
      );
    });
    const ShowMenuItemArray = menus.slice(0, 8);
    let HideMenuItemArray: JSX.Element[] = [];
    if (menus.length > 8) {
      HideMenuItemArray = menus.slice(8);
    }
    return {
      ShowMenuItemArray,
      HideMenuItemArray,
    };
  }, [ownModule, horizontalSelectedUrl, roleData, selectedHorizontalMenuItem]);

  /** 判断纵向导航栏跳转 */
  const checkVerticalMenu = useCallback(
    (data: any) => {
      if (data.newTabType === 1) {
        return (
          <a rel='noopener noreferrer' target='_blank' href={data.allMenuStyle}>
            {data.mlabel}
          </a>
        );
      }
      if (data.urlType === systemType) {
        return <Link to={data.mstyle}>{data.mlabel}</Link>;
      }
      return <a href={`${data.domainName}${data.mstyle}`}>{data.mlabel}</a>;
    },
    [Link, systemType],
  );

  /** 生成纵向导航栏 */
  const VerticalMenu = useMemo(() => {
    const verticalMenuArray: ReactNode[] = [];
    if (horizontalSelectedUrl !== '/') {
      verticalNav.forEach((element: any) => {
        if (element.pmystyle === horizontalSelectedUrl) {
          if (element.children && element.children.length > 0) {
            verticalMenuArray.push(
              <Menu.SubMenu
                key={element.id}
                title={
                  <div className={`${bodyClassName}--verticalMenu--subMenu`}>
                    <span className='iconbpo'>{unicodeToChar(element.micon || '')}</span>
                    <div>{element.mlabel}</div>
                  </div>
                }
              >
                {element.children.map((child: any) => {
                  return <Menu.Item key={child.id}>{checkVerticalMenu(child)}</Menu.Item>;
                })}
              </Menu.SubMenu>,
            );
          } else {
            verticalMenuArray.push(
              <Menu.Item key={element.id}>
                <div className={`${bodyClassName}--verticalMenu--subMenu`}>
                  <span className='iconbpo'>{unicodeToChar(element.micon || '')}</span>
                  <div>{checkVerticalMenu(element)}</div>
                </div>
              </Menu.Item>,
            );
          }
        }
      });
    }
    return verticalMenuArray;
  }, [horizontalSelectedUrl, verticalNav, checkVerticalMenu]);

  /** 用户信息 */
  const info = useMemo<XuiQilinThemeLayoutInfoDataType>(() => {
    let currentInfo = {} as XuiQilinThemeLayoutInfoDataType;
    const infoStr = localStorage.getItem('info');
    if (infoStr) {
      currentInfo = JSON.parse(infoStr);
    }
    return currentInfo;
  }, []);

  /** 用户名 */
  const userName = useMemo<string>(() => {
    if (info.userInfo && info.userInfo.realName) {
      const {
        userInfo: { realName },
      } = info;
      return realName;
    }
    return '';
  }, [info]);

  /** 当前公司logo */
  const companyLogo = useMemo(() => {
    if (info.tenancyInfo && info.tenancyInfo.tenancyLogo) {
      const {
        tenancyInfo: { tenancyLogo },
      } = info;
      return tenancyLogo;
    }
    return '';
  }, [info]);

  /** 当前公司名称 */
  const companyName = useMemo(() => {
    if (info.tenancyInfo && info.tenancyInfo.tenancyName) {
      const {
        tenancyInfo: { tenancyName },
      } = info;
      return tenancyName;
    }
    return '';
  }, [info]);

  const roleMenuData = useMemo(() => {
    const { postRoleResList = [] } = info;
    return postRoleResList;
  }, [info]);

  const changeParams = useMemo(() => {
    const {
      tenancyInfo: { tenancyId },
    } = info;
    return {
      tenancyId,
    };
  }, [info]);

  /** 公司/部门/职位 信息 */
  const positionInfo = useMemo<{ positionIds: string[]; positionNames: string[] }>(() => {
    const { tenancies, rootOrgId, orgId, postId } = info;
    const positionIds = [rootOrgId, orgId, postId];
    const positionNames = [] as string[];
    tenancies?.forEach(tenancy => {
      if (tenancy.tenancyId === rootOrgId) {
        positionNames.push(tenancy.tenancyName);
        tenancy.tenancyDetps?.forEach(dept => {
          if (dept.deptId === orgId) {
            positionNames?.push(dept.deptKey);
            dept.postList?.forEach(post => {
              if (post.postId === postId) {
                positionNames.push(post.postTitle);
              }
            });
          }
        });
      }
    });

    return { positionIds, positionNames };
  }, [info]);

  const onRoleMenuChange = useCallback(
    (params: { postId?: ReactText; roleId: ReactText; orgId?: ReactText }) => {
      redirctToLogin({
        // admType,
        redirect_url: location.origin,
        ...params,
        ...changeParams,
      });
    },
    [changeParams],
  );

  useEffect(() => {
    const hKey = `/${pathname.split('/')[1]}`;
    /** 锁定横向导航栏高亮 */
    onSelectedHorizontalMenuCallback(hKey);
    // /** 锁定纵向导航栏高亮 */
    let highlightIdMapKey = '';
    for (let i = 0; i < access.length; i++) {
      const accessValue = access[i];
      if (pathname.includes(accessValue)) {
        highlightIdMapKey = accessValue;
        break;
      }
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const highlightIds = highlightIdMap[highlightIdMapKey];
    if (highlightIds) {
      onSelectedSubMenu(highlightIds);
      onSelectedMenuItem([highlightIds[highlightIds.length - 1]]);
    }
  }, [
    pathname,
    accessEqual,
    highlightIdMap,
    onSelectedSubMenu,
    onSelectedMenuItem,
    onSelectedHorizontalMenuCallback,
  ]);

  useEffect(() => {
    roleDataDiscope({
      roleId: info.roleId,
      aidMap,
      userName,
      ...positionInfo,
    });
  }, [userName, roleDataDiscope, info.roleId, aidMapEqual, positionInfo]);

  useEffect(() => {
    effectCallback();
  }, [effectCallback]);

  return (
    <ConfigProvider locale={locale}>
      <div className={className}>
        <div className={headerClassName}>
          <div className={`${headerClassName}--company`}>
            <div>
              <img alt={'logo'} src={companyLogo} />
              {companyName && companyName.length > 11 ? (
                <Tooltip title={companyName}>
                  <div className={`${headerClassName}--company--name`}>{companyName}</div>
                </Tooltip>
              ) : (
                companyName
              )}
            </div>
            <XuiRoleMenu
              className={`${headerClassName}--popover`}
              onChange={onRoleMenuChange}
              dataSource={roleMenuData}
              visible={positionVisible}
              onVisibleChange={onPositionVisible}
              trigger='click'
            >
              <span
                className={classnames({
                  iconbpo: true,
                  [`${headerClassName}--company--arrow`]: true,
                  [`${headerClassName}--company--arrowClicked`]: positionVisible,
                })}
              >
                &#xe668;
              </span>
            </XuiRoleMenu>
          </div>

          <div className={`${headerClassName}--menu`}>
            {HorizontalMenu.ShowMenuItemArray}
            {HorizontalMenu.HideMenuItemArray.length > 0 && (
              <div
                className={classnames(
                  `${headerClassName}--admin`,
                  `${headerClassName}--adminInMenu`,
                )}
              >
                更多
                <span className='iconbpo'>&#xe668;</span>
                <div className='xui-ant__qinlin-theme-layout--menuBlock'>
                  <div className='menu'>{HorizontalMenu.HideMenuItemArray}</div>
                </div>
              </div>
            )}
          </div>
          <div className={`${headerClassName}--down`}>
            <a className={'iconbpo'} href={`${env.qlHREF}/download/downloadList`}>
              &#xe6c9;
            </a>
          </div>
          <div className={`${headerClassName}--knowledge`}>
            <a
              href={`${env.knowledgeHREF}/home/Pubindex.html`}
              rel={'noopener noreferrer'}
              target={'_blank'}
            >
              {'知识库'}
            </a>
          </div>
          <div className={`${headerClassName}--admin`}>
            {userName}
            <span className={'iconbpo'}>&#xe668;</span>
            <div className='xui-ant__qinlin-theme-layout--menuBlock'>
              <div className='menu'>
                <a href={`${env.qlHREF}/person/personsetting`}>
                  <div className='menu--item'>
                    <span className={'iconbpo'}>&#xe682;</span>
                    {'个人设置'}
                  </div>
                </a>
                <div className={classnames('menu--item', 'menu--system')} onClick={logout}>
                  <span className={'iconbpo'}>&#xe680;</span>
                  {'退出系统'}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className={bodyClassName}>
          <div className={`${bodyClassName}--verticalMenu`}>
            <Menu
              mode={'inline'}
              openKeys={openedKeys}
              selectedKeys={selectedKeys}
              theme={'dark'}
              onOpenChange={onSelectedSubMenu}
              onSelect={(e: SelectInfo) => onSelectedMenuItem(e.selectedKeys || [])}
            >
              {VerticalMenu}
            </Menu>
          </div>
          <div className={`${bodyClassName}--content`}>
            <div className={`${bodyClassName}--content--mainBody`}>
              <ConfigProvider locale={locale}>{children}</ConfigProvider>
            </div>
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
};

export default XuiQilinThemeLayout;
