import React, { FC, useEffect, useState } from "react";
import { Table } from "antd";
import { PaginationData } from "rc-pagination";
import { exceptStr, paginationAction } from "@/utils/common";
import { renderCols } from "@/pages/unitTable/renderColsOpts";
import styles from "./index.less";

const UnitTable: FC = (props) => {
  const [unitTableType, setUnitTableType] = useState<string>("");
  const [columns, setColumns] = useState<Array<any>>([]);
  const [dataSource, setDataSource] = useState<Array<any>>([]);
  const [pageInfo, setPageInfo] = useState<Partial<PaginationData>>({});
  const [i18n, setI18n] = useState<any>({});
  const [permission, setPermission] = useState<boolean>(false);
  const [scrollHeight, setScrollHeight] = useState<number | undefined>(undefined);

  useEffect(() => {
    window.parent.postMessage({ type: "init" }, "*");
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);
  const receiveMessageFromIndex = (event: any) => {
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { columns, dataSource, pageInfo, scrollHeight, i18n, showOperateBtn, unitTableType } = data;
      setI18n(i18n);
      setScrollHeight(scrollHeight);
      setUnitTableType(unitTableType);
      setColumns(columns);
      setDataSource(dataSource);
      setPageInfo(pageInfo);
      setPermission(showOperateBtn);
    }
  };
  const onChange = (current: number, pageSize: number) => {
    setPageInfo((prevState) => {
      const { pageSize: size } = prevState;
      window.parent.postMessage(
        {
          type: "turn",
          payload: { id: "PAGEINFO", params: { ...pageInfo, current: size === pageSize ? current : 1, pageSize } }
        },
        "*"
      );
      return { ...pageInfo, current: size === pageSize ? current : 1, pageSize };
    });
  };
  return <Table rowKey="id" className={styles.multi_fun_table} dataSource={dataSource} size="middle"
                columns={renderCols(columns, unitTableType, i18n, permission)}
                scroll={{ x: 1200, y: `calc(100vh - ${scrollHeight || 109}px)` }}
                pagination={!_.isNil(pageInfo) ? {
                  ...paginationAction(pageInfo, i18n, onChange),
                  size: "default"
                } : false}
  />;
};

export default UnitTable;
