import React, { FC, useEffect, useState } from "react";
import { Table, Tag, Typography } from "antd";
import { exceptStr, paginationFun } from "@/utils/common";
import styles from "@/pages/atdTable/components/index.less";
import { defaultPage, IPage } from "@/common/types";

const { Text } = Typography;
const CommonTable: FC = (props) => {
  const [columns, setColumns] = useState<Array<any>>([]);
  const [sumRow, setSumRow] = useState<Partial<{}>>({});
  const [pageInfo, setPageInfo] = useState<IPage>(defaultPage);
  const [dataSource, setDataSource] = useState<Array<any>>([]);
  const [showSumrow, setShowSumrow] = useState<boolean>(false);
  const [i18n, setI18n] = useState<Partial<{}>>({});

  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, countResult, showSum, pageInfo, i18n } = data;
      const { current: pageNum, pageSize: size, total } = pageInfo;
      setDataSource(dataSource);
      setI18n(i18n);
      setColumns(_.map(columns, item => {
        if (item.dataIndex === "salarySob") {
          return {
            ...item,
            render: (text: string, r: { acctTimes?: number }) => {
              return <div className={styles.customSpan} title={text}>
                <span className={styles.title}>{text}</span>
                <Tag color="#4d7ad8">{`${i18n["第"]}${r?.acctTimes}${i18n["次"]}`}</Tag>
              </div>;
            }
          };
        }
        return { ...item };
      }));
      setShowSumrow(showSum);
      setSumRow(countResult);
      setPageInfo({ pageNum, size, total });
    }
  };
  const sizeChange = (pageobj: IPage) => {
  };
  const onChange = (pageobj: IPage) => {
    setPageInfo({ ...pageInfo, ...pageobj });
    window.parent.postMessage(
      {
        type: "turn",
        payload: { id: "PAGEINFO", params: { ...pageInfo, ...pageobj } }
      },
      "*"
    );
  };
  return <Table
    rowKey="id"
    className={styles.tableWrapper}
    columns={columns}
    dataSource={dataSource}
    bordered
    size="small"
    scroll={{ x: 1200, y: `calc(100vh - 109px)` }}
    pagination={{
      ...paginationFun(pageInfo, sizeChange, onChange, i18n),
      size: "default"
    }}
    summary={() => {
      if (!showSumrow) return;
      let totalColumns: any[] = [];
      _.forEach(columns, it => {
        if (!it.children) {
          totalColumns.push(it);
        } else {
          totalColumns = [...totalColumns, ...it.children];
        }
      });
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            {
              _.map([...totalColumns], (item, index) => {
                if (index === 0) {
                  return <Table.Summary.Cell index={0} key={index} align="center"><Text
                    type="danger">{i18n["总计"]}</Text></Table.Summary.Cell>;
                }
                return <Table.Summary.Cell index={index} key={index}>
                  <Text type="danger">{!_.isNil(sumRow[item.dataIndex]) ? sumRow[item.dataIndex] : "-"}</Text>
                </Table.Summary.Cell>;
              })
            }
          </Table.Summary.Row>
        </Table.Summary>
      );
    }}
  />;
};

export default CommonTable;
