import React from 'react'

// 提取中文名称的最后两个字符
export function getChineseChars(name: string): string {
  const chineseChars = name.match(/[\u4e00-\u9fa5]/g);
  if (chineseChars && chineseChars.length > 0) {
    return chineseChars.slice(-2).join('');
  }
  return name.charAt(name.length - 1).toUpperCase();
}

// 根据名称生成背景色（类似钉钉的配色方案）
export function getBackgroundColor(name: string): string {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8',
    '#F7DC6F', '#BB8FCE', '#85C1E2', '#F8B739', '#52BE80',
    '#EC7063', '#5DADE2', '#58D68D', '#F4D03F', '#AF7AC5',
    '#85C1E9', '#F1948A', '#82E0AA', '#F7DC6F', '#AED6F1'
  ];
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
}

// 根据联系人ID获取默认头像
export function getDefaultAvatar(contactId: number, contactName?: string): React.ReactNode {
  // 特殊处理：系统通知和群聊
  if (contactName?.includes('系统') || contactName?.includes('通知')) {
    return (
      <div style={{
        width: '100%',
        height: '100%',
        borderRadius: '4px',
        backgroundColor: '#909399',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#fff',
        fontSize: '40%',
        fontWeight: '500',
        lineHeight: '1',
        whiteSpace: 'nowrap'
      }}>
        系
      </div>
    );
  }
  
  if (contactName?.includes('群')) {
    return (
      <div style={{
        width: '100%',
        height: '100%',
        borderRadius: '4px',
        backgroundColor: '#409EFF',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#fff',
        fontSize: '40%',
        fontWeight: '500',
        lineHeight: '1',
        whiteSpace: 'nowrap'
      }}>
        群
      </div>
    );
  }

  // 普通联系人：使用中文名称
  const displayName = contactName || `用户${contactId}`;
  const chars = getChineseChars(displayName);
  const bgColor = getBackgroundColor(displayName);

  return (
    <div style={{
      width: '100%',
      height: '100%',
      borderRadius: '4px',
      backgroundColor: bgColor,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      color: '#fff',
      fontSize: '40%',
      fontWeight: '500',
      userSelect: 'none',
      lineHeight: '1',
      whiteSpace: 'nowrap'
    }}>
      {chars}
    </div>
  );
}
