import React, { FunctionComponent, useCallback, useEffect, useMemo, useState } from "react";
import { Table, Typography } from "antd";
import moment from "moment";
import styles from "@/pages/atdTable/components/index.less";
import { ColumnType } from "antd/lib/table";
import API from "@/api";

const { Text } = Typography;

interface OwnProps {
  location: any;
}

type Props = OwnProps;

const index: FunctionComponent<Props> = (props) => {
  const { location: { query } } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [report, setReport] = useState<any>({ columns: [], dataSource: [], sumRow: {} });

  useEffect(() => {
    setLoading(true);
    dataSourceUrl({ ...query, isPrintf: true }).then(({ success, data }) => {
      setLoading(false);
      if (success) {
        const { data: result } = data;
        setReport({
          columns: traverse(result?.column), dataSource: result?.data?.list, sumRow: result?.sumRow
        });
      }
    });
  }, []);
  useEffect(() => {
    if (!_.isEmpty(report?.columns)) {
      window.document.body.innerHTML =
        window.document.getElementById("print")!.innerHTML;
      const styleTag = document.createElement("style");
      styleTag.type = "text/css";
      styleTag.innerHTML = `
        .ant-table {
          td, th, .ant-table-title, .ant-table-footer, table {
            border-color: #333 !important;
          }
        }
      `;
      window.document.head.appendChild(styleTag);
      window.print();
      // window.location.reload();
    }
    return () => {
    };
  }, [report?.columns]);


  const dataSourceUrl = useCallback((payload) => {
    return API.CalculateService.getAcctresult(payload);
  }, []);

  const traverse: any = (arr: any[]) => {
    return _.map(arr, item => {
      if (!_.isEmpty(item.children)) {
        return { dataIndex: item.column, title: item.text, children: traverse(item.children), align: "center" };
      } else {
        return { dataIndex: item.column, title: item.text, align: "center" };
      }
    });
  };
  const flattenFn = (source: ColumnType<any>[]) => {
    let res: ColumnType<any>[] = [];
    source.forEach((el: any) => {
      _.isEmpty(el.children) && res.push(el);
      el.children && res.push(...flattenFn(el.children));
    });
    return res;
  };
  const rowSelection = {
    columnWidth: 50, columnTitle: "序号",
    renderCell: (value: boolean, record: any, index: number) => (<span>{index + 1}</span>)
  };
  const columns = useMemo(() => {
    return !_.isEmpty(report.columns) ? flattenFn(report.columns) : [];
  }, [report.columns]);
  return (
    <div className={styles.resizeTable} id="print">
      <Table
        dataSource={report.dataSource} columns={report.columns} pagination={false}
        size="small" bordered className={styles.tableWrapper} rowSelection={rowSelection}
        title={() => <div
          style={{ display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12 }}>
          {`${moment(query?.startDate).format("YYYY")}年${moment(query?.startDate).format("M")}月份工资清单`}
        </div>}
        footer={() => <div style={{ display: "flex", alignItems: "center", padding: "0 40px" }}>
          <div style={{ flex: "1", fontSize: 12 }}>制表：</div>
          <div style={{ flex: "1", fontSize: 12 }}>审批：</div>
          <div style={{ flex: "1", fontSize: 12 }}>批准：</div>
        </div>}
        summary={() => (
          <Table.Summary>
            <Table.Summary.Row>
              <Table.Summary.Cell index={0} align="center"><Text>小计</Text></Table.Summary.Cell>
              {
                !_.isEmpty(report?.sumRow) &&
                _.map(columns, (item: any, index) => {
                  return <Table.Summary.Cell index={index + 1} key={index + 1} align="center">
                    <Text>{report?.sumRow[item.dataIndex] || ""}</Text>
                  </Table.Summary.Cell>;
                })
              }
            </Table.Summary.Row>
          </Table.Summary>
        )}
      />
    </div>
  );
};

export default index;
