import { Tooltip } from '@tingwu/design';
import React, { memo, useCallback, useMemo } from 'react';
import { AvatarListData, AvatarListProps } from './index.type';
import { AvatarListComp } from './styled';

const avatarCoverWidth = 5; // 头像覆盖宽度

// 头像展示列表区域
const AvatarList: React.FC<AvatarListProps> = memo(
  ({
    data, // 需要展示的发言人的id数组
    maxShowNumber = 2, // 最大展示数量
    emitIcon = 'https://img.alicdn.com/imgextra/i1/O1CN01pcjP4i1wVrr4UpLRf_!!6000000006314-2-tps-100-100.png', // 默认省略头像
  }) => {
    // 格式化要展示的列表
    const formatData = useMemo(() => {
      return data?.slice(0, data.length > maxShowNumber ? 1 : maxShowNumber);
    }, [data, maxShowNumber]);

    // 展示省略头像
    const showEmit = useMemo(() => {
      return (data || []).length > maxShowNumber;
    }, [data, maxShowNumber]);

    // 计算宽度
    const computerWidth = useMemo(() => {
      const avatarNum = (formatData?.length || 0) + Number(showEmit); // 展示的头像数量
      return 20 * avatarNum - avatarCoverWidth * (avatarNum - 1);
    }, [formatData, showEmit, avatarCoverWidth]);

    // 渲染省略头像
    const renderEmitAvatar = useMemo(() => {
      return <img className="AvatarList_Emit" src={emitIcon as string} />;
    }, [emitIcon]);

    // 渲染头像
    const renderAvatar = useCallback(
      ({ avatar, avatarName }: AvatarListData, index: number, arr: any) => {
        return (
          <Tooltip key={`AvatarList_${avatarName}_${index}`} title={avatarName}>
            <div
              className="AvatarList__Avatar"
              style={{
                zIndex: arr.length - index,
                left: `${index * -avatarCoverWidth}px`,
              }}
            >
              {avatar}
            </div>
          </Tooltip>
        );
      },
      [avatarCoverWidth],
    );

    // 渲染头像组
    const renderAvatarList = useMemo(() => {
      return (formatData || []).map(renderAvatar);
    }, [formatData, renderAvatar]);

    return (
      <AvatarListComp style={{ width: `${computerWidth}px` }}>
        {renderAvatarList}
        {showEmit && renderEmitAvatar}
      </AvatarListComp>
    );
  },
);

export default AvatarList;
