/*
 * @Author: 赵伟
 * @Date: 2024-11-29 09:27:19
 * @Description: 用于 BasicInfo 和 BasicTableInfo 组件的子组件
 */

import { Typography } from 'antd';
import React from 'react';
import BasicInfoItemValue from './BasicInfoItemValue';
import { type BasicInfoData, type BasicInfoLink } from './types';

type BasicInfoItemProps = {
  /** 基础信息 */
  data: BasicInfoData;
  /** 标题宽度 */
  labelWidth: number;
  /** 自定义类名前缀 */
  classPrefix: string;
  /** 标题是否显示省略号 */
  labelEllipsis?: boolean;
  /** 标签对齐方式 */
  labelAlign?: 'start' | 'end' | 'justify';
};

function BasicInfoItem({
  data,
  labelWidth,
  classPrefix,
  labelEllipsis = true,
  labelAlign = 'start',
}: BasicInfoItemProps) {
  const { label, value, format, ellipsis } = data;
  const formatValue = format ? format(value) : value;
  const myClassName = `${classPrefix}__item`;
  let valueComponent = undefined;
  if (React.isValidElement(formatValue)) {
    valueComponent = <div className={`${myClassName}__node`}>{formatValue}</div>;
  } else if (Array.isArray(formatValue)) {
    valueComponent = (
      <div className={`${myClassName}__value-container`}>
        {formatValue.map((item: BasicInfoLink) => (
          <BasicInfoItemValue
            key={item.value}
            value={item.value}
            link={item.link}
            url={item.url}
            ellipsis={ellipsis}
            classPrefix={classPrefix}
          />
        ))}
      </div>
    );
  } else if (typeof formatValue === 'object' && formatValue) {
    valueComponent = (
      <BasicInfoItemValue
        value={formatValue.value}
        link={formatValue.link}
        url={formatValue.url}
        ellipsis={ellipsis}
        classPrefix={classPrefix}
      />
    );
  } else {
    valueComponent = (
      <BasicInfoItemValue value={formatValue} ellipsis={ellipsis} classPrefix={classPrefix} />
    );
  }
  return (
    <div className={myClassName} key={label}>
      <div
        className={`${myClassName}__label`}
        style={{ width: labelWidth, textAlign: labelAlign, textAlignLast: labelAlign }}
      >
        <Typography.Text
          ellipsis={labelEllipsis !== false ? { tooltip: label } : false}
          style={{ width: labelAlign === 'justify' ? '100%' : 'auto' }}
        >
          {label}
        </Typography.Text>
      </div>
      {valueComponent}
    </div>
  );
}

export default BasicInfoItem;
