import './index.less';
import { NodeGroup } from 'react-move';
import { interpolate, interpolateTransformSvg } from 'd3-interpolate';
import type { GaoYaProcessStandardDailyData } from '../../services/api';
import { useCallback, useEffect, useState } from 'react';
import type { Setting } from '../SettingForm';

type TableProps = {
  data: GaoYaProcessStandardDailyData['processDayDataList'];
  setting: Setting;
};

const CountTable: React.FC<TableProps> = ({ data, setting }) => {
  const rowHight = 50;
  const displayCount = 8;
  const [displayData, setDisplayData] = useState<
    GaoYaProcessStandardDailyData['processDayDataList']
  >([]);
  const [displayAt, setDisplayAt] = useState(0);
  const [pause, setPause] = useState(false);
  const [scollOnce, setScollOnce] = useState(false);
  const [groupData, setGroupData] = useState({});
  const updateDisplayData = (da: number, sData) => {
    let endAt1 = da + displayCount;
    let endAt2 = 0;
    if (endAt1 > sData.length) {
      endAt2 = endAt1 - sData.length;
      endAt1 = sData.length;
    }
    const ret = sData.slice(da, endAt1);
    if (sData.length > displayCount) {
      sData.slice(0, endAt2).forEach((i) => ret.push(i));
    }
    setDisplayData(ret);
  };
  useEffect(() => {
    if (!data.length) return;
    // 获取表头
    const cols = data.reduce((pre, cur) => {
      cur.gaoYaProcessDataStepList.map((v) => {
        if (pre.includes(v.qiFangNo)) {
          return;
        }
        pre.push(v.qiFangNo);
      });

      return pre;
    }, []);

    // 补齐数据
    data.map((item) => {
      item.gaoYaProcessDataStepList = cols.map((c, i) => {
        const r = item.gaoYaProcessDataStepList.find((v) => v.qiFangNo === c);
        return r
          ? { ...r }
          : {
              qiFangNo: c,
              id: parseInt(Math.random() * 10000) * i,
              planNumber: 0,
              actNumber: 0,
            };
      });
    });

    // 计算横合计
    const r = data.map((item, index) => {
      item.rowSum = item.gaoYaProcessDataStepList.reduce((pre, cur) => {
        return pre + cur.actNumber;
      }, 0);
      return item;
    });
    const g = {};
    // 计算竖合计
    r.map((item) => {
      item.gaoYaProcessDataStepList.map((v) => {
        if (g[v.qiFangNo]) {
          g[v.qiFangNo].planNumber += v.planNumber;
          g[v.qiFangNo].actNumber += v.actNumber;
        } else {
          g[v.qiFangNo] = {
            planNumber: v.planNumber,
            actNumber: v.actNumber,
          };
        }
      });
    });

    setGroupData(g);
    setDisplayData(r);
    console.log(r, '----====');
  }, [data]);

  const scoll = useCallback(() => {
    if (pause) {
      return;
    }
    let da = 0;
    if (data.length > displayCount) {
      da = displayAt + 1;
      if (da >= data.length) {
        da = 0;
      }
    }

    setDisplayAt(da);
    updateDisplayData(da, data);
  }, [data, displayAt, pause]);

  useEffect(() => {
    const t = setInterval(() => {
      scoll();
    }, setting.rowMovingTime * 1000);
    return () => {
      clearTimeout(t);
    };
  }, [setting.rowMovingTime, scoll]);

  return (
    <>
      <div className="main">
        <div className="table-header">
          <div className="fiexd-column" style={{ width: '140px' }}>
            <div className="table-cell">类别</div>
          </div>
          <div className="generate-column">
            {displayData[0]?.gaoYaProcessDataStepList.map((item) => (
              <div className="table-cell" key={item.id}>
                <div className="column-name">{item.qiFangNo}</div>
                <div style={{ display: 'flex', flex: 1 }}>
                  <div className="real-num">实际</div>
                  <div className="plan-num">计划</div>
                </div>
              </div>
            ))}
          </div>
          <div className="fiexd-column" style={{ width: '140px' }}>
            <div className="table-cell">当日合计</div>
          </div>
        </div>

        <div className="table-body">
          <NodeGroup
            data={displayData}
            keyAccessor={(d) => d.id}
            start={(d, i) => {
              return { y: i * rowHight, opacity: 0 };
            }}
            enter={() => {
              return { opacity: [1], timing: { duration: 1000 } };
            }}
            update={(d, i) => {
              return { y: [i * rowHight], opacity: [1], timing: { duration: 1000 } };
            }}
            leave={() => {
              return { y: [-rowHight], opacity: [0], timing: { duration: 1000 } };
            }}
            interpolation={(begValue, endValue, attr) => {
              if (attr === 'transform') {
                return interpolateTransformSvg(begValue, endValue);
              }
              return interpolate(begValue, endValue);
            }}
          >
            {(nodes) => (
              <>
                <div
                  onMouseEnter={() => setPause(true)}
                  onMouseLeave={() => {
                    setPause(false);
                    setScollOnce(true);
                  }}
                  style={{
                    height:
                      displayData.length * 50 >= 400 ? '400px' : displayData.length * 50 + 'px',
                    position: 'relative',
                    overflow: 'hidden',
                  }}
                >
                  {nodes.map((node) => (
                    <div
                      className="row-container"
                      key={node.key}
                      style={{
                        position: 'absolute',
                        left: 0,
                        top: 0,
                        width: '100%',
                        transform: `translate(0px, ${node.state.y}px)`,
                        opacity: node.state.opacity,
                      }}
                    >
                      <div className="flex-column" style={{ width: '140px' }}>
                        <div className="table-b-cell" style={{ display: 'block' }}>
                          {node.data.type}
                        </div>
                      </div>
                      <div className="generate-column">
                        {node.data.gaoYaProcessDataStepList.map((item) => {
                          return (
                            <div className="table-b-cell" key={item.id}>
                              <div className="item-cell">{item.actNumber}</div>
                              <div className="item-cell">{item.planNumber}</div>
                            </div>
                          );
                        })}
                      </div>
                      <div className="flex-column" style={{ width: '140px' }}>
                        <div className="table-b-cell">{node.data.rowSum}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </NodeGroup>
          <div className="row-container">
            <div className="flex-column" style={{ width: '140px' }}>
              <div className="table-b-cell" style={{ display: 'block' }}>
                当日合计
              </div>
            </div>
            <div className="generate-column">
              {displayData[0]?.gaoYaProcessDataStepList.map((item) => (
                <div className="table-b-cell" key={item.qiFangNo}>
                  <div className="item-cell">{groupData[item.qiFangNo].actNumber}</div>
                  <div className="item-cell">{groupData[item.qiFangNo].planNumber}</div>
                </div>
              ))}
            </div>
            <div className="flex-column" style={{ width: '140px' }}>
              <div className="table-b-cell">{displayData.reduce((p, c) => p + c.rowSum, 0)}</div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default CountTable;
