// @ts-ignore
import React, { useEffect, useState } from 'react';
import Empty from '@wisdom-components/empty';
import { Table } from 'antd';
import BasicTable from '../index';
import request from 'umi-request';

const Demo = () => {
  const [columns, setColumns] = useState([]);
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = (params = {}) => {
    request(`${baseUrl}/AcrossTable/GetEquipmentDataReport`, {
      method: 'get',
      params: {},
    }).then(function (response) {
      const data = response.data;
      let column = data.map((item, index) => {
        return {
          title: `${item.DName + item.DType}(${item.Unit})`,
          dataIndex: `name${index}`,
          key: `name${index}`,
          width: 300,
        };
      });
      column.unshift({
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        fixed: true,
        width: 200,
        resize: true,
        maxWidth: 250,
        minWidth: 100,
      });
      let dataSource = data[0].NameDate.map((item, index) => ({ key: index, time: item.Time }));
      data.forEach((item, index) => {
        item.NameDate.forEach((child) => {
          dataSource.forEach((v) => {
            if (child.Time === v.time) v[`name${index}`] = child.Value;
          });
        });
      });
      setColumns(column);
      setDataSource(dataSource);
    });
  };

  const Summary = (currentData) => (
    <Table.Summary.Row>
      {columns.map((item, index) => {
        let sum = 0;
        currentData.reduce((prev, next) => {
          sum += next[item.key];
        }, 0);
        return (
          <Table.Summary.Cell key={index} index={index}>
            {index === 0 ? '总计' : sum}
          </Table.Summary.Cell>
        );
      })}
    </Table.Summary.Row>
  );

  // @ts-ignore
  return (
    <div style={{ height: '400px' }}>
      {!!dataSource.length && (
        <BasicTable
          dataSource={dataSource}
          columns={columns}
          bordered
          summary={Summary}
          pagination={false}
        />
      )}
      {!dataSource.length && <Empty description={'暂无数据'} />}
    </div>
  );
};

export default Demo;

const baseUrl = 'https://www.fastmock.site/mock/162c15dca15c4dba9ba51e0a0b76929b/api';
