import React, { useEffect, useState } from "react";
import { Table } from "antd";
import API from "@/api";
import "../atdTable/components/index.less";

const RankMapTable: React.FC = () => {
    const [cols, setCols] = useState<Array<any>>([]);
    const [dataSource, setDataSource] = useState<Array<any>>([]);
    useEffect(() => {
      getRankInfo();
    }, []);
    useEffect(() => {
      if (!_.isEmpty(dataSource)) {
        setCols(
          _.map(cols, item => {
            const dataIndex = item.dataIndex + "_rowSpan";
            const colsIndex = item.dataIndex.split("_")[1];
            return {
              ...item,
              align: "center",
              className: colsIndex === "1" ? "bg_1_Cols" : colsIndex === "2" ? "bg_2_Cols" : "",
              width: colsIndex === "1" && "60px",
              render: (text: string, _: any) => {
                return {
                  children: <span>{text}</span>,
                  props: {
                    rowSpan: _[dataIndex]
                  }
                };
              }
            };
          })
        );
      }
    }, [dataSource]);

    const changeData = (data: any, field: any) => {
      let count = 0, indexCount = 1;
      const rowSpan = field + "_rowSpan";
      try {
        while (indexCount < data.length) {
          let item = data.slice(count, count + 1)[0];
          if (!item[rowSpan]) {
            item[rowSpan] = 1;
          }
          if (item[field] === data[indexCount][field]) {
            item[rowSpan]++;
            data[indexCount][rowSpan] = 0;
          } else {
            count = indexCount;
          }
          indexCount++;
        }
      } catch {
      }
      return data;
    };
    const getRankInfo = () => {
      API.CalculateService.getRankInfo().then(({ success, data }) => {
        if (success) {
          const { data: dataCopy } = data;
          const { col: columns, data: list } = dataCopy;
          let tmpV: any = [];
          _.forEach(_.reduce(columns, (pre: any, cur: any) => ([...pre, cur["dataIndex"]]), []), item => {
            tmpV = changeData(list, item);
          });
          console.log(columns);
          setCols(columns);
          setDataSource(tmpV);
        }
      });
    };
    return <div style={{ height: "100%", overflowY: "auto" }}>
      <Table
        className="rankMapWrapper"
        columns={cols}
        dataSource={dataSource}
        bordered
        pagination={false}
        size="middle"
      />;
    </div>;
  }
;

export default RankMapTable;
