/*
 * Author: 黎永顺
 * name: 薪资核算-底部合计行
 * Description:
 * Date: 2023/9/18
 */
import React, { FunctionComponent, useCallback, useEffect, useMemo, useState } from "react";
import { Spin, Table, Typography } from "antd";
import { ColumnType } from "antd/lib/table";
import API from "@/api";

const { Text } = Typography;

interface OwnProps {
  columns: ColumnType<any>[];
  dataSourceUrl: string;
  payload: any;
  sumRow: Partial<{}>;
}

type Props = OwnProps;

const calcFixedTotal: FunctionComponent<Props> = (props) => {
  const [sumRow, setSumRow] = useState<Partial<{}>>({});//薪资核算总计行数据
  const [loading, setLoading] = useState<boolean>(false);
  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 columns = useMemo(() => {
    return !_.isEmpty(props.columns) ? flattenFn(props.columns) : [];
  }, [props.columns]);
  const dataSourceUrl = useCallback((payload) => {
    return API.CalculateService.getAcctResultsum(props.dataSourceUrl, payload);
  }, [props.dataSourceUrl]);
  useEffect(() => {
    if (!_.isEmpty(props.payload) && !props.sumRow) {
      setLoading(true);
      dataSourceUrl(props.payload).then(({ data }) => {
        setLoading(false);
        const { data: result, status } = data;
        if (status) setSumRow(result.sumRow || {});
      });
    } else {
      setSumRow(props.sumRow);
    }
  }, [props.payload, props.sumRow]);
  return (<>
    {
      _.map(columns, (item: any, index) => {
        return <Table.Summary.Cell index={index + 1} key={index + 1} align="center">
          {
            loading ? <Spin spinning={loading} size="small"></Spin> :
              <Text type="danger">{sumRow[item.dataIndex] || "-"}</Text>
          }
        </Table.Summary.Cell>;
      })
    }
  </>);
};

export default calcFixedTotal;
