import dayjs, { Dayjs } from 'dayjs';
import { uid } from 'uid';
import NP from 'number-precision';

import { TimeRangeItem } from './types';

export const createDefaultTime = (): TimeRangeItem => {
  return { id: uid(), value: [dayjs(), dayjs().add(1, 'hour')] as [Dayjs, Dayjs] };
};

export enum FrequencyEnum {
  second = 1,
  miniute = 60,
  hour = 3600,
}

export const frequencyOptions = [
  { label: '秒', value: FrequencyEnum.second },
  { label: '分钟', value: FrequencyEnum.miniute },
  { label: '小时', value: FrequencyEnum.hour },
];

export interface DetectionJSON {
  detectionNum: number;
  detectionUnit: FrequencyEnum;
}
/** 根据后端返回的时间(单位是秒)，拆分成单位和数值 */
export const getDetectionJSON = (time: number | undefined | null): DetectionJSON => {
  if (time && time > 0) {
    for (let i = frequencyOptions.length - 1; i >= 0; i--) {
      const unit = frequencyOptions[i].value;
      if (time >= unit) {
        return { detectionNum: NP.divide(time, unit), detectionUnit: unit };
      }
    }
  }
  return { detectionNum: 5, detectionUnit: FrequencyEnum.miniute };
};

export const getDetectionTimeJSON = (time?: string): TimeRangeItem[] | null => {
  if (!time) return null;
  const timeArr = time.split(';');
  const nowStr = dayjs().format('YYYY-MM-DD');
  const timeStrArr = timeArr
    .map((x) => {
      const [startDate, endDate] = x.split('-');
      return [dayjs(`${nowStr} ${startDate}`), dayjs(`${nowStr} ${endDate}`)] as [Dayjs, Dayjs];
    })
    .map((x) => {
      return { id: uid(), value: x };
    });
  return timeStrArr;
};
