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

import { Link } from '@umijs/max';
import { Typography } from 'antd';
import React from 'react';
import { type BasicInfoData, type BasicInfoLink } from './types';

type BasicInfoItemProps = {
  data: BasicInfoData;
  labelWidth: number;
  classPrefix: string;
};

export function BasicInfoItem({ data, labelWidth, classPrefix }: BasicInfoItemProps) {
  const { label, value, format, ellipsis } = data;
  const formatValue = format ? format(value) : value;
  const myClassName = `${classPrefix}__item`;
  let valueComponent = undefined;
  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 (React.isValidElement(formatValue)) {
    // 这个判断必须在下面的判断之前
    valueComponent = (
      <BasicInfoItemValue value={formatValue} ellipsis={ellipsis} classPrefix={classPrefix} />
    );
  } 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 }}>
        {label}
      </div>
      {valueComponent}
    </div>
  );
}

type BasicInfoItemValueProps = {
  ellipsis?: boolean;
  classPrefix: string;
  value: string | React.ReactNode;
  link?: string;
  url?: string;
};

export function BasicInfoItemValue({
  value,
  link,
  url,
  ellipsis,
  classPrefix,
}: BasicInfoItemValueProps) {
  const myClassName = `${classPrefix}__item__value`;
  let component = undefined;
  if (url && value) {
    component = (
      <a className={`${myClassName}__link`} href={url} target="_blank" rel="noopener noreferrer">
        {value}
      </a>
    );
  } else if (link && value) {
    component = (
      <Link to={link} className={`${myClassName}__link`}>
        {value}
      </Link>
    );
  } else if (React.isValidElement(value)) {
    return value;
  } else {
    component = <span className={`${myClassName}__text`}>{value ?? '--'}</span>;
  }

  return (
    <div className={myClassName}>
      <Typography.Text
        ellipsis={ellipsis ? { tooltip: value } : false}
        style={{ fontSize: 'inherit' }}
      >
        {component}
      </Typography.Text>
    </div>
  );
}
