import React, { useEffect, useState } from "react";
import { Table } from "antd"
import Tooltip from "./Tooltip"
import { moneyHandle } from "../../utils"
import { isNil } from 'lodash';

const TableBox = ({ backToPrePage, pagination, columns, rowKey, dataSource, total, onChange, loading, ...parameter }: any) => {
  const showTotal = (total: any) => `共 ${total} 条`;
  const [Col, setCol] = useState(columns)

  useEffect(() => {
    if (dataSource?.length <= 0 && pagination?.current > 1) {
      backToPrePage && backToPrePage(pagination?.current - 1)
    }
  }, [dataSource])

  useEffect(() => {
    columns?.forEach((item: any) => {
      const newItem = item;
      if (newItem?.styleType === 'money') {
        newItem.align = newItem.align || 'right';
        newItem.render = (text: any) => {
          let t = text
          if (isNil(text)) {
            t = newItem?.emptyText
            if (isNil(newItem?.emptyText)) {
              t = '-'
            }
          }
          return newItem?.ellipsis ? <Tooltip
            title={t}
          >
            {t === '-' ? '-' : moneyHandle(t || 0, '¥')}
          </Tooltip> : moneyHandle(t || 0, '¥')
        };
      }

      if (newItem.ellipsis && !newItem.render) {
        newItem.render = (text: any) => {
          let t = text
          if (isNil(text)) {
            t = newItem?.emptyText
            if (isNil(newItem?.emptyText)) {
              t = '-'
            }
          }
          return (
            <div
              style={{
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
              }}
            >
              <Tooltip title={t}>
                {t}
              </Tooltip>
            </div>
          );
        };
      }

      if (!newItem.render) {
        newItem.render = (text: any) => {
          let t = text
          if (isNil(text)) {
            t = newItem?.emptyText
            if (isNil(newItem?.emptyText)) {
              t = '-'
            }
          }
          return (
            <>{t}</>
          );
        };
      }
    });
    setCol(columns)
  }, [columns]);

  return <Table
    columns={Col}
    rowKey={rowKey}
    dataSource={dataSource}
    onChange={onChange}
    loading={loading}
    pagination={pagination ? {
      showQuickJumper: true,
      total,
      showSizeChanger: true,
      showTotal: showTotal,
      ...pagination,
    } : false}
    {...parameter}
  />
}

export default TableBox