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

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

  useEffect(() => {
    window.parent.postMessage({ type: "init" }, "*");
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);
  const receiveMessageFromIndex = async (event: any) => {
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { columns, dataSource, pageInfo, sumpayload } = data;
      const { current: pageNum, pageSize: size, total } = pageInfo;
      setDataSource(dataSource);
      setColumns(columns);
      setPageInfo({ pageNum, size, total });
      const confCode: any = await API.CalculateService.getSysconfcode({ code: "OPEN_ACCT_RESULT_SUM" });
      setShowSumrow(confCode.data.status && confCode.data.data === "1");
      if (confCode.data.status && confCode.data.data === "1") {
        const sumRowlist: any = await API.CalculateService.salaryBillSendSum(sumpayload);
        if (sumRowlist.data.status) {
          if (!_.isEmpty(sumRowlist.data.data.sumRow)) {
            const tmpVSumRow= _.reduce(_.keys(sumRowlist.data.data.sumRow), (pre, cur) => (_.assign(pre, { [`${cur}_salaryItem`]: sumRowlist.data.data.sumRow[cur] })), {})
            setSumRow(tmpVSumRow);
          } else {
            setSumRow({ [new Date().getTime()]: new Date().getTime() });
          }
        }
        if (sumRowlist.data.status && _.isNil(sumRowlist.data.data.sumRow)) {
          setSumRow({ [new Date().getTime()]: new Date().getTime() });
        }
      }
    }
  };
  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}
    size="small"
    pagination={{
      ...paginationFun(pageInfo, sizeChange, onChange),
      size: "default"
    }}
    scroll={{ x: 1200, y: "calc(100vh - 193px)" }}
    summary={() => {
      if (_.isEmpty(columns) || !showSumrow) return;
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            {
              _.isEmpty(sumRow) ? <Spin tip="加载中"/> :
                _.map(columns, (item, index) => {
                  if (index === 0) {
                    return <Table.Summary.Cell index={0} key={index}><Text
                      type="danger">总计</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 PreviewTable;
