import React, { useEffect, useState } from 'react';
import type { BarConfig } from '@ant-design/plots';
import { Bar } from '@ant-design/plots';
import styles from './index.less';

type MachineProgramExceptionProps = {
  machineProgramExecStatArray: MachineConnectivity.MachineProgramExecStat[];
  conditionKey: string;
  machineProgramExceptionPageTurning: number;
};

type Item = {
  label: string;
  type: string;
  value: number;
};

const convertData = (machineProgramExecStatArray: MachineConnectivity.MachineProgramExecStat[]) => {
  const data: Item[] = [];
  machineProgramExecStatArray.forEach((item) => {
    data.push({
      label: item.program,
      type: '运行时间',
      value: Math.round(item.executionDuration * 10) / 10,
    });
    data.push({
      label: item.program,
      type: '走刀',
      value: Math.round(item.feedDuration * 10) / 10,
    });
  });
  return data;
};

const getAxisMax = (data: { value: number }[]) => {
  let max = 0;
  data.forEach((item) => {
    if (max < item.value) {
      max = item.value;
    }
  });
  return max * 1.15;
};

const MachineProgramException: React.FC<MachineProgramExceptionProps> = ({
  conditionKey,
  machineProgramExecStatArray,
  machineProgramExceptionPageTurning,
}) => {
  const displayCount = 6;

  const [data, setData] = useState<MachineConnectivity.MachineProgramExecStat[]>([]);
  const [displayData, setDisplayData] = useState<MachineConnectivity.MachineProgramExecStat[]>([]);
  const [displayAt, setDisplayAt] = useState(0);
  const [lastConditionKey, setLastConditionKey] = useState('');

  const updateDisplayData = (da: number, sData: MachineConnectivity.MachineProgramExecStat[]) => {
    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(() => {
    setData(machineProgramExecStatArray);
    if (lastConditionKey !== conditionKey) {
      setLastConditionKey(conditionKey);
      setDisplayAt(0);
      updateDisplayData(0, machineProgramExecStatArray);
    }
  }, [conditionKey, lastConditionKey, machineProgramExecStatArray]);

  useEffect(() => {
    const t = setInterval(() => {
      let da = 0;
      if (data.length > displayCount) {
        da = displayAt + displayCount;
        if (da >= data.length) {
          da = 0;
        }
      }
      setDisplayAt(da);
      updateDisplayData(da, data);
    }, machineProgramExceptionPageTurning * 1000);
    return () => {
      clearTimeout(t);
    };
  }, [data, displayAt, machineProgramExceptionPageTurning]);

  const barData = convertData(displayData);
  const axisMax = getAxisMax(barData);
  const config: BarConfig & React.RefAttributes<unknown> = {
    data: barData,
    isGroup: true,
    xField: 'value',
    yField: 'label',
    seriesField: 'type',
    color: ['l(0) 0:#00263a 1:#00d3d7', 'l(0) 0:#18162a 1:#cf474d'],
    xAxis: {
      line: null,
      grid: null,
      title: null,
      label: null,
      max: axisMax,
    },
    yAxis: {
      line: null,
      tickLine: null,
      label: {
        style: {
          fill: '#0ff',
          fontSize: 20,
        },
        autoHide: true,
        autoEllipsis: true,
      },
    },
    legend: {
      layout: 'horizontal',
      position: 'top-right',
      itemName: {
        style: {
          fill: '#0ff',
          fontSize: 20,
        },
      },
      marker: (_name, _index, item) => {
        return {
          ...item,
          style: {
            ...item.style,
            r: 8,
          },
        };
      },
    },
    autoFit: true,
    marginRatio: 0,
    label: {
      position: 'right',
      style: {
        fill: '#0ff',
        fontSize: 20,
      },
      layout: [
        {
          type: 'fixed-overlap',
        },
      ],
    },
    animation: false,
  };

  return (
    <div className={styles.main}>
      <div className={styles.header}>异常运行程序</div>
      <div className={styles.content}>
        <Bar {...config} />
      </div>
    </div>
  );
};

export default MachineProgramException;
