import { FrontComponent } from '../../const/const';
import { ComponentConfig } from '../../types/type';
import { DataSource } from '/@/api/dataBoard/model';

export interface MapComponentLayout {
  componentType?: FrontComponent;
}

export interface MapComponentValue {
  icon?: string;
  track?: Record<'ts' | 'value', number>[];
  dataSource?: DataSource[];
}

interface Config {
  componentType?: FrontComponent;
}

export const MaphistoryTrackConfig: Config = {
  componentType: FrontComponent.MAP_COMPONENT_TRACK_HISTORY,
};

export const MapRealTrackConfig: Config = {
  componentType: FrontComponent.MAP_COMPONENT_TRACK_REAL,
};

const getTrack = (dataSource: DataSource[], config: Config) => {
  if (dataSource.length >= 2) {
    const trackRecord = dataSource.slice(0, 2);
    if (
      !trackRecord.every((item) => item.componentInfo.value) &&
      config.componentType === FrontComponent.MAP_COMPONENT_TRACK_REAL
    )
      return { track: [], dataSource: [] };

    const track = trackRecord.map((item) => {
      return {
        ts: item.componentInfo.updateTime,
        value: item.componentInfo.value || 0,
      };
    });
    return { track, dataSource };
  }
  return { track: [], dataSource: [] };
};

export const transfromMapComponentConfig: ComponentConfig['transformConfig'] = (
  componentConfig: Config,
  _record,
  dataSourceRecord
) => {
  const { track, dataSource } = getTrack(dataSourceRecord as DataSource[], componentConfig);
  return {
    layout: {
      ...componentConfig,
    } as MapComponentLayout,
    value: {
      track,
      dataSource,
    } as MapComponentValue,
  };
};
