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

const { Text } = Typography;
export type extraType = {
  selectedKey: string;
  selectedRowKeys: string[] | number[];
  permission: boolean;
  scrollHeight: number;
  rowKey: string;
  showTotalCell: boolean
}
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 [sumRow, setSumRow] = useState<Partial<{}>>({});//总计行数据
  const [i18n, setI18n] = useState<any>({});
  const [extraParams, setExtraParams] = useState<Partial<extraType>>({});//额外参数

  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: permission, unitTableType = "welfareRecord",
        selectedRowKeys: rowKeys = [], selectedKey, rowKey, showTotalCell = false, sumDataSource = {}
      } = data;
      setI18n(i18n);
      setColumns(columns);
      setDataSource(dataSource);
      setPageInfo(pageInfo);
      setUnitTableType(unitTableType);
      setSumRow(sumDataSource);
      setExtraParams({
        selectedKey, scrollHeight, permission, rowKey, showTotalCell,
        selectedRowKeys: [extraParams.selectedRowKeys, ...rowKeys]
      });
    }
  };
  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 };
    });
  };
  const rowSelection = {
    columnWidth: 60, selectedRowKeys: extraParams.selectedRowKeys,
    preserveSelectedRowKeys: true,
    onChange: (selectedRowKeys: React.Key[]) => {
      // @ts-ignore
      setExtraParams({ ...extraParams, selectedRowKeys: selectedRowKeys });
      window.parent.postMessage(
        { type: "turn", payload: { id: "CHECKBOX", params: { selectedRowKeys } } }, "*"
      );
    }
  };
  return <Table rowKey={extraParams.rowKey || "id"} className={styles.multi_fun_table} dataSource={dataSource}
                size="middle" columns={renderCols(columns, unitTableType, i18n, extraParams)}
                scroll={{ x: 1200, y: `calc(100vh - ${extraParams?.scrollHeight || 109}px)` }}
                bordered={_.some(columns, k => k.children)}
                rowSelection={!_.isNil(extraParams?.selectedRowKeys) ? rowSelection : undefined}
                pagination={!_.isNil(pageInfo) ? {
                  ...paginationAction(pageInfo, i18n, onChange),
                  size: "default"
                } : false}
                summary={() => (
                  !extraParams.showTotalCell ? <></> :
                    <Table.Summary fixed={true}>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={0} align="center"><Text
                          type="danger">{i18n["总计"]}</Text></Table.Summary.Cell>
                        <CaclFixedTotal columns={!_.isNil(extraParams?.selectedRowKeys) ? columns : columns.slice(1)}
                                        dataSourceUrl="" payload={{}} sumRow={sumRow}/>
                      </Table.Summary.Row>
                    </Table.Summary>
                )}
  />;
};

export default UnitTable;
