import { setUserAuthority } from "@/services/kratos/user";
import { jsonInBlacklist } from "@/services/kratos/jwt";
import {
  LogoutOutlined,
  SettingOutlined,
  SwapOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { history, useModel } from "@umijs/max";
import type { MenuProps } from "antd";
import { message, Spin } from "antd";
import { createStyles } from "antd-style";
import React from "react";
import { flushSync } from "react-dom";
import HeaderDropdown from "../HeaderDropdown";

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel("@@initialState");
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: "flex",
      height: "48px",
      marginLeft: "auto",
      overflow: "hidden",
      alignItems: "center",
      padding: "0 8px",
      cursor: "pointer",
      borderRadius: token.borderRadius,
      "&:hover": {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({
  menu,
  children,
}) => {
  const { styles } = useStyles();
  const { initialState, setInitialState } = useModel("@@initialState");

  /**
   * 退出登录
   */
  const loginOut = async () => {
    const res = await jsonInBlacklist();
    if (res.code !== 0) {
      return;
    }
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    const searchParams = new URLSearchParams({
      redirect: pathname + search,
    });
    const redirect = urlParams.get("redirect");
    if (window.location.pathname !== "/user/login" && !redirect) {
      history.replace({
        pathname: "/user/login",
        search: searchParams.toString(),
      });
    }
  };

  /**
   * 切换角色
   */
  const changeUserAuth = async (authorityId: string) => {
    try {
      const res = await setUserAuthority({ 
        uuid: initialState?.currentUser?.uuid || '',
        authorityId 
      });
      if (res.code === 0) {
        message.success('角色切换成功');
        // 标记需要关闭所有标签页并跳转首页
        window.sessionStorage.setItem('needCloseAll', 'true');
        window.sessionStorage.setItem('needToHome', 'true');
        window.location.reload();
      }
    } catch (error) {
      message.error('角色切换失败');
    }
  };

  const onMenuClick: MenuProps["onClick"] = (event) => {
    const { key } = event;
    if (key === "logout") {
      flushSync(() => {
        setInitialState((s) => ({ ...s, currentUser: undefined }));
      });
      loginOut();
      return;
    }
    if (key === "person") {
      history.push("/person");
      return;
    }
    if (key.startsWith("switch_")) {
      const authorityId = key.replace("switch_", "");
      changeUserAuth(authorityId);
      return;
    }
    history.push(`/account/${key}`);
  };

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  // 构建菜单项
  const menuItems: MenuProps['items'] = [];

  // 当前角色显示
  if (currentUser.authority) {
    menuItems.push({
      key: "current_role",
      label: (
        <span style={{ fontWeight: 'bold' }}>
          当前角色：{currentUser.authority.authorityName}
        </span>
      ),
      disabled: true,
    });
  }

  // 切换角色选项
  if (currentUser.authorities && currentUser.authorities.length > 1) {
    const otherAuthorities = currentUser.authorities.filter(
      (auth: any) => auth.authorityId !== currentUser.authority?.authorityId
    );
    if (otherAuthorities.length > 0) {
      menuItems.push({ type: "divider" as const });
      otherAuthorities.forEach((auth: any) => {
        menuItems.push({
          key: `switch_${auth.authorityId}`,
          icon: <SwapOutlined />,
          label: `切换为：${auth.authorityName}`,
        });
      });
    }
  }

  // 分隔线
  menuItems.push({ type: "divider" as const });

  // 个人信息
  menuItems.push({
    key: "person",
    icon: <UserOutlined />,
    label: "个人信息",
  });

  // 个人设置（可选）
  if (menu) {
    menuItems.push({
      key: "settings",
      icon: <SettingOutlined />,
      label: "个人设置",
    });
  }

  // 分隔线
  menuItems.push({ type: "divider" as const });

  // 退出登录
  menuItems.push({
    key: "logout",
    icon: <LogoutOutlined />,
    label: "退出登录",
  });

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {children}
    </HeaderDropdown>
  );
};
