import React, { useCallback, useEffect, useMemo } from "react";
import styles from "./index.module.scss";
import { Table } from "antd";
import ImageLazy from "../ImageLazy";

type Props = {
  yHeight: number; //设置表格的高度
  list: any; //表格数据
  columnsTemp: any[][]; //表格展示
  total?: number; //总数
  pageNum?: number;
  pageSize?: number;
  pagingInfo?: any | boolean;
  onChange?: (pageNum: number, pageSize: number) => void;
  lastBtn?: any;
  classKey?: string; //一个组件多次使用的时候要传递，分别设置style
};

function MyTable({
  yHeight,
  list,
  columnsTemp,
  total,
  pageNum = 1,
  pageSize = 10,
  pagingInfo = {
    showQuickJumper: true,
    position: ["bottomCenter"],
    showSizeChanger: true,
  },
  onChange,
  lastBtn = [],
  classKey = "",
}: Props) {
  useEffect(() => {
    const dom = document.querySelector(
      `.MyTable${classKey} .ant-table-body`
    ) as HTMLDivElement;

    if (dom) dom.style.height = yHeight + "px";
  }, [classKey, yHeight]);

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      if (onChange) {
        onChange(pageNum, pageSize);
      }
    },
    [onChange]
  );

  const dataChangeFu = useCallback(
    (v: any) => {
      const nullTxt = "（空）";

      /**
       * index:序号
       * txt:正常数据
       * img:图片
       * txtChange:判断显示不同字段
       * text:文字比较多的情况
       */

      const obj = {
        index: (_: any, __: any, index: number) =>
          index + 1 + (pageNum - 1) * pageSize,
        txt: (item: any) => item[v[2]] || nullTxt,
        img: (item: any) => (
          <div className="tableImgAuto">
            <ImageLazy width={60} height={60} src={item.thumb} />
          </div>
        ),
        txtChange: (item: any) =>
          Reflect.get(v[3], item[v[2]]) || v[4] || nullTxt,
        text: (item: any) =>
          item[v[2]] ? (
            item[v[2]].length >= v[3] ? (
              <span style={{ cursor: "pointer" }} title={item[v[2]]}>
                {item[v[2]].substring(0, v[3]) + "..."}
              </span>
            ) : (
              item[v[2]]
            )
          ) : (
            nullTxt
          ),
      };

      return Reflect.get(obj, v[0]);
    },
    [pageNum, pageSize]
  );

  const columns = useMemo(() => {
    const arr: any = columnsTemp.map((v: any) => ({
      title: v[1],
      render: dataChangeFu(v),
    }));

    return arr;
  }, [columnsTemp, dataChangeFu]);

  return (
    <Table
      className={`${styles.MyTable} MyTable${classKey}`}
      scroll={{ y: yHeight }}
      dataSource={list}
      columns={[...columns, ...lastBtn]}
      rowKey="id"
      pagination={
        pagingInfo
          ? {
              ...pagingInfo,
              current: pageNum,
              pageSize: pageSize,
              total: total,
              onChange: paginationChange(),
            }
          : false
      }
    />
  );
}

const MemoMyTable = React.memo(MyTable);

export default MemoMyTable;
