/*
 * @Author: 赵伟
 * @Date: 2024-06-26 10:05:52
 * @Description: 列表自定义 render
 */

import { formatDate } from '@/utils/date';
import { Tooltip } from 'antd';
import dayjs from 'dayjs';

type TableCellFormatter = (value?: any | null) => string | undefined | null;

// 字符串转换函数
export const stringFormatter: TableCellFormatter = (value?: any | null) => {
  return value;
};

// 日期转换函数
export const dateFormatter: TableCellFormatter = (value?: any | null) => {
  if (value === undefined || value === null || value === '') {
    return null;
  }
  if (!dayjs(value).isValid()) {
    return null;
  }
  return formatDate(value);
};

// 数组转换函数
export function arrayFormatter(property?: string) {
  return (value?: any | null): ReturnType<TableCellFormatter> => {
    if (
      value === undefined ||
      value === null ||
      Array.isArray(value) === false ||
      value.length === 0
    ) {
      return null;
    }

    let list = value;
    if (property && typeof value[0] === 'object') {
      list = value.map((item) => item[property]);
    }
    return list.join(',');
  };
}

function tableCellRender(ellipsis: boolean = false, format: TableCellFormatter = stringFormatter) {
  return (value?: any | null) => {
    const text = format(value);
    if (ellipsis && text) {
      return (
        <Tooltip title={text} placement="topLeft" overlayStyle={{ maxWidth: '400px' }}>
          {renderCell(text)}
        </Tooltip>
      );
    } else {
      return renderCell(text);
    }
  };
}

function renderCell(text?: any | null) {
  return <span>{text ?? '--'}</span>;
}

export default tableCellRender;
