import { Typography } from 'antd';
import Link from 'antd/lib/typography/Link';
import _ from 'lodash';
import type { CSSProperties } from 'react';
import { useIntl } from 'umi';
import UserWrap from './userWrap';

const styles: Record<'span', CSSProperties> = {
  span: { color: 'red' },
};

const formatAccount = (text?: string, bracket: 'zh' | 'en' = 'zh') => {
  if (_.isEmpty(text)) return '';
  if (bracket === 'en') {
    return `(${text})`;
  }
  // zh
  return `（${text}）`;
};

export interface UserType {
  id?: number;
  account?: string;
  userName?: string;
  nameZh?: string;
  cnName?: string;
  name?: string;
  state?: number | string;
}

export interface UserLinkProps {
  user?: UserType;
  isDisabled?: boolean;
  showDetail?: boolean;
  userWrapStyle?: CSSProperties;
  bracket?: 'zh' | 'en';
}

const UserLink = (props: UserLinkProps) => {
  const { user, isDisabled, showDetail = true, userWrapStyle, bracket = 'en' } = props;
  const { id: userId, account, userName, nameZh, cnName, name, state } = user || {};

  const { formatMessage } = useIntl();

  const effective = Boolean(account || userName || nameZh || cnName || name);
  if (!effective) return <></>; // 无效用户不渲染

  const vanIdc = document.documentElement.dataset.vanIdc || 'cn';
  // 中文名
  const yxNameZh = nameZh || cnName || name || '';
  // 英文名
  const yxNameEn = formatAccount(account || userName, bracket);

  const ele = (
    <>
      {yxNameZh}
      {yxNameEn}
      {state === 0 && (
        <span style={styles.span}>
          {bracket === 'en' && <>&nbsp;</>}
          {formatMessage({ id: 'base.common.user.state.dimission', defaultMessage: '离职' })}
        </span>
      )}
    </>
  );

  if (vanIdc === 'cn' && showDetail)
    return (
      <UserWrap userId={userId} account={account} style={userWrapStyle}>
        <Typography.Text
          disabled={isDisabled}
          ellipsis={{ tooltip: true }}
          style={{ display: 'inline' }}
        >
          <Link>{ele}</Link>
        </Typography.Text>
      </UserWrap>
    );

  return (
    <Typography.Text
      disabled={isDisabled}
      ellipsis={{ tooltip: true }}
      style={{ display: 'inline' }}
    >
      {ele}
    </Typography.Text>
  );
};

export default UserLink;
