import React, { Component, useEffect, useState } from 'react';
import { Popconfirm, message, Dropdown, Button, Select } from 'antd';
import { userMenuIcon } from './constData';
import {
  HomeOutlined,
  UserOutlined,
  CaretDownOutlined,
} from '@ant-design/icons';
import { Spin, Menu, Avatar } from 'antd';
import HeaderDropdown from './HeaderDropdown';
import Axios from '../util/axios';
import getStore, { getUserName } from '../util/userInfo';
import { getLoginUrl } from '../util/permessionUtils';
import './index.less';
import cn from 'classnames';
import userLogo1 from '../../assets/userLogo1.png';

// stash存在则为一体化，否则为轻量级
const ModuleUser = ({
  stash = '',
  isBigDataFoundationPlatform = false,
  PZCS = false,
  xiangtan = false,
}) => {
  const [tenantList, setTenantList] = useState([]);
  const [haveAppSystemPermission, setHaveAppSystemPermission] = useState(false);
  const [getSystemPermission, setGetSystemPermission] = useState(false);
  useEffect(() => {
    localStorage.setItem('stash', stash);
    if (['integration', 'LNRD', 'HBJK'].includes(stash)) {
      getTenantList();
      allSystemList();
      getMenuList();
    }
  }, []);
  const handleClickmenu = (url) => {
    window.location.href = url;
  };
  const handleClickSysManage = () => {
    if (['LNRD', 'HBJK'].includes(stash)) {
      Axios('get', '/admin-api/system/auth/homePage', '', {})
        .then((res) => {
          if (res.data.code === 0) {
            window.location.href = `/admin-ui${res.data.data.path}`;
          } else {
            message.warning(res.data.msg || '获取系统管理页面路由信息失败');
          }
        })
        .catch((e) => console.log('e', e));
    } else if (stash === 'integration') {
      Axios('get', '/admin-api/system/auth/systemPage', '', {})
        .then((res) => {
          if (res.data.code === 0) {
            window.location.href = `/admin-ui${res.data.data.path}`;
          } else {
            message.warning(res.data.msg || '获取系统管理页面路由信息失败');
          }
        })
        .catch((e) => console.log('e', e));
    } else {
      const menuList = getStore({ name: 'menu' });
      const sysManagePath = menuList?.find((item) => item.name === '权限管理')
        .children[0].path;
      window.location.href =
        stash === 'GZW'
          ? '/data-platform/#' + sysManagePath
          : '/#' + sysManagePath;
    }
  };
  const {
    PersonalCenterSrc,
    MessageCenterSrc,
    SystemManageSrc,
    LogoutSrc,
    AppSystemSrc,
  } = userMenuIcon;

  const isHaveSystemManagementPermission = ['LNRD', 'HBJK'].includes(stash)
    ? true
    : stash === 'integration'
    ? getSystemPermission
    : getStore({ name: 'isHaveSystemManagementPermission' });
  const DEFAULT_LOGOUT_URL = ['integration', 'LNRD', 'HBJK'].includes(stash)
    ? '/admin-ui/login'
    : stash === 'GZW'
    ? '/data-platform/#/login'
    : '/#/login';

  // 跳转服务门户
  const jumpToExterHome = () => {
    window.open('/admin-ui/data-share-portal/homePage', '_blank');
  };

  const curTenantId = ['integration', 'LNRD', 'HBJK'].includes(stash)
    ? getStore({ name: 'tenantId' }) && parseInt(getStore({ name: 'tenantId' }))
    : '';
  const curTenantName = ['integration', 'LNRD', 'HBJK'].includes(stash)
    ? getStore({ name: 'tenantName' })
    : '';

  const getTenantList = () => {
    Axios('get', '/admin-api/system/user/getUserTenant', '', {})
      .then((res) => {
        if (res.data.code === 0) {
          let tenantLists =
            res.data.data &&
            res.data.data.map((item) => {
              return {
                id: item.id,
                value: item.id,
                label: item.name,
              };
            });
          setTenantList(tenantLists || []);
        }
      })
      .catch((e) => console.log('e', e));
  };
  const allSystemList = () => {
    Axios(
      'get',
      '/admin-api/system/user/get-user-menu-List?menuName=数据平台',
      '',
      {},
    )
      .then((res) => {
        if (res.data.code === 0) {
          let menuGet =
            res.data.data &&
            res.data.data[0]?.routes?.map((item) => {
              return {
                ...item,
                path:
                  item.path.indexOf('/') !== -1 ? item.path : '/' + item.path,
              };
            });
          let haveAppSystem_Permission =
            menuGet?.some((item) => item.name === '数据源管理') || false;
          setHaveAppSystemPermission(haveAppSystem_Permission);
        }
      })
      .catch((e) => console.log('e', e));
  };

  const hasSystemManageMenu = (menuList) => {
    for (const item of menuList) {
      if (item.name === '系统管理') {
        return true;
      }
      if (item.children && item.children.length > 0) {
        if (hasSystemManageMenu(item.children)) {
          return true;
        }
      }
    }
    return false;
  };

  const getMenuList = () => {
    Axios('get', '/admin-api/system/auth/list-menus', '')
      .then((res) => {
        if (res.data.code === 0) {
          const hasPermission = hasSystemManageMenu(res.data.data);
          setGetSystemPermission(hasPermission);
        }
      })
      .catch((e) => console.log('e', e));
  };

  // 退出登录
  const logout = () => {
    const logoutUrl = ['integration', 'LNRD', 'HBJK'].includes(stash)
      ? '/admin-api/system/auth/logout'
      : stash === 'GZW'
      ? '/data-platform/auth/token/logout'
      : '/auth/token/logout';
    const logouType = ['integration', 'LNRD', 'HBJK'].includes(stash)
      ? 'post'
      : 'delete';
    Axios(logouType, logoutUrl, '', {})
      .then(() => {
        console.log('退出登录接口调用成功');
        localStorage.clear();
        sessionStorage.clear();
        if (['integration', 'LNRD', 'HBJK'].includes(stash)) {
          getLoginUrl()
            .then((res) => {
              if (res?.data?.data?.loginoutUrl) {
                console.log('Login URL found:', res.data.data.loginoutUrl);
                window.location.href = res.data.data.loginoutUrl;
              } else {
                console.log(
                  'No login URL found, redirect to default login page.',
                );
                window.location.href = '/admin-ui/login';
              }
            })
            .catch((e) => {
              console.log('GetLoginUrl error: ', e);
              window.location.href = '/admin-ui/login';
            });
        } else {
          window.location.href = DEFAULT_LOGOUT_URL;
        }
      })
      .catch((error) => {
        console.error('Error while logging out, error:', error);
        message.error('服务器错误，请稍后重试');
      });
  };

  // 切换租户改缓存、调接口、刷界面
  const handleChangeTenant = (e) => {
    let token = getStore({ name: 'access_token' });
    Axios('post', `/admin-api/system/auth/setRedisTokenOfTenant`, '', {
      data: { token, tenantId: e },
    })
      .then((res) => {
        if (res.data.code === 0) {
          console.log('接口调用成功');
          window.localStorage.setItem('curTenantId', e);
          window.localStorage.setItem(
            'curTenantName',
            tenantList.find((item) => item.id === e)?.label,
          );
          window.location.reload();
        } else {
          message.warning(res.data.msg || '租户切换失败');
        }
      })
      .catch((e) => console.log('e', e));
  };

  const menu = (
    <Menu className="menu" selectedKeys={[]}>
      {!xiangtan && (
        <Menu.Item
          key="personalCenter"
          onClick={() =>
            handleClickmenu(
              isBigDataFoundationPlatform
                ? '/admin-ui/user/profile'
                : ['integration', 'LNRD', 'HBJK'].includes(stash)
                ? '/admin-ui/data-share-portal/personal/info'
                : stash === 'GZW'
                ? '/data-platform/#/info/index'
                : '/#/info/index',
            )
          }
        >
          <img
            src={PersonalCenterSrc}
            alt=""
            style={{ marginRight: '10px', marginTop: '-3px' }}
          />
          <span>
            {['integration', 'LNRD', 'HBJK'].includes(stash)
              ? '用户中心'
              : '个人中心'}
          </span>
        </Menu.Item>
      )}
      {!xiangtan && isHaveSystemManagementPermission && (
        <Menu.Item key="systemManage" onClick={handleClickSysManage}>
          <img
            src={SystemManageSrc}
            alt=""
            style={{ marginRight: '10px', marginTop: '-3px' }}
          />
          <span>系统管理</span>
        </Menu.Item>
      )}
      {!xiangtan && haveAppSystemPermission && (
        <Menu.Item
          key="appSystem"
          onClick={() =>
            handleClickmenu(
              PZCS
                ? '/dataadmin/#/appManager/index'
                : '/dataadmin/#/appSystem/index',
            )
          }
        >
          <img
            src={AppSystemSrc}
            alt=""
            style={{ marginRight: '10px', marginTop: '-3px' }}
          />
          <span>数据源管理</span>
        </Menu.Item>
      )}
      <Menu.Item key="logout" onClick={() => logout()}>
        <img
          src={LogoutSrc}
          alt=""
          style={{ width: '15px', height: '15px', marginRight: '10px' }}
        />
        <span>退出登录</span>
      </Menu.Item>
    </Menu>
  );

  return (
    <div
      className={cn(
        stash !== 'LNRD' ? 'right_size' : 'right_size_LNRD',
        'right',
      )}
    >
      {['integration', 'LNRD', 'HBJK'].includes(stash) && [
        !isBigDataFoundationPlatform && !PZCS && (
          <Button
            type="link"
            onClick={jumpToExterHome}
            className={cn(
              stash === 'LNRD'
                ? 'fwmh_color_LNRD'
                : stash === 'HBJK'
                ? 'fwmh_color_HBJK'
                : null,
            )}
          >
            共享门户
          </Button>
        ),
        !PZCS && (
          <Select
            defaultValue={curTenantId}
            className={
              stash === 'LNRD'
                ? 'right-select_LNRD'
                : stash === 'HBJK'
                ? 'right-select_HBJK'
                : 'right-select'
            }
            style={{
              width: 150,
              border: 'none',
            }}
            onChange={handleChangeTenant}
            options={tenantList}
          />
        ),
      ]}
      {getUserName() ? (
        <HeaderDropdown overlay={menu}>
          <span style={{ display: 'inline-block', marginLeft: '12px' }}>
            {stash === 'HBJK' ? (
              <Avatar  size={30} style={{fontSize:'16px!important'}} src={userLogo1}/>
            ) : (
              <Avatar  size={30} style={{fontSize:'16px!important'}} icon={<UserOutlined />} />
            )}
            <span
              style={{
                marginLeft: '10px',
                verticalAlign: '-2px',
                fontSize: '14px',
                fontWeight: '400',
                // color: stash !== 'LNRD'? null: '#FFFFFF'
                color: ['LNRD', 'HBJK'].includes(stash) ? '#FFFFFF' : null,
              }}
            >
              {getUserName()}
            </span>
            <CaretDownOutlined
              style={{
                marginLeft: '10px',
                fontSize: '8px',
                color: ['LNRD', 'HBJK'].includes(stash) ? '#FFFFFF' : '#333333',
              }}
            />
          </span>
        </HeaderDropdown>
      ) : (
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
            lineHeight: '57px',
            textAlign: 'center',
          }}
        />
      )}
    </div>
  );
};

export default ModuleUser;
