import React from 'react';
import type { ColumnConfig } from '@ant-design/plots';
import { Column } from '@ant-design/plots';
import styles from './index.less';

type MachineStatusProps = {
  staticMachineStatus?: MachineConnectivity.StaticMachineStatus;
  conditionKey: string;
};

type NameMappingItem = {
  field: string;
  name: string;
};

const nameMapping: NameMappingItem[] = [
  {
    field: 'production',
    name: '生产',
  },
  {
    field: 'manual_input',
    name: '人工操作',
  },
  {
    field: 'wait',
    name: '等待',
  },
  {
    field: 'ready',
    name: '准备',
  },
  {
    field: 'setup',
    name: '设置',
  },
  {
    field: 'alarm',
    name: '报警',
  },
  {
    field: 'shut_down',
    name: '停机',
  },
  {
    field: 'feedDuration',
    name: '走刀',
  },
];

const convertData = (staticMachineStatus?: MachineConnectivity.StaticMachineStatus) => {
  const data: { field: string; type: string; value: number }[] = [];
  nameMapping.forEach((m) => {
    const val =
      staticMachineStatus && staticMachineStatus[m.field] ? staticMachineStatus[m.field] : 0;
    data.push({
      field: m.field,
      type: m.name,
      value: Math.round(val * 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.1;
};

const MachineStatus: React.FC<MachineStatusProps> = ({ staticMachineStatus }) => {
  const data = convertData(staticMachineStatus);
  const axisMax = getAxisMax(data);
  const config: ColumnConfig & React.RefAttributes<unknown> = {
    data: data,
    xField: 'type',
    yField: 'value',
    xAxis: {
      line: null,
      tickLine: null,
      label: {
        style: {
          fill: '#0ff',
          fontSize: 20,
        },
        autoHide: true,
        autoEllipsis: true,
      },
    },
    yAxis: {
      line: null,
      grid: null,
      title: null,
      label: null,
      max: axisMax,
    },
    columnWidthRatio: 0.4,
    label: {
      position: 'top',
      style: {
        fill: '#0ff',
        fontSize: 20,
      },
      layout: [
        {
          type: 'fixed-overlap',
        },
      ],
    },
    color: ({ type }) => {
      switch (type) {
        case '报警':
          return 'l(90) 0:#ce474c 1:#19162a';
        case '走刀':
          return 'l(90) 0:#cc9c08 1:#1b2222';
        default:
          return 'l(90) 0:#00d3d7 1:#00263a';
      }
    },
  };

  return (
    <div className={styles.main}>
      <div className={styles.header}>机床状态</div>
      <div className={styles.content}>
        <Column {...config} />
      </div>
    </div>
  );
};

export default MachineStatus;
