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

import { TimeRangeItem, TimePeriodItem } from './types';
import { CameraAlgoItem } from '@/api/camera/camera-preview';

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

export const createDefaultTime = (): TimePeriodItem => {
  return {
    id: uid(),
    startDay: null,
    endDay: null,
    timeRangeList: [{ id: uid(), startTime: '', endTime: '' }],
  };
};

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;
};

export const getMetaValues = (extra: string | undefined | null) => {
  if (!extra) return [];
  const extraObj = JSON.parse(extra);
  const params = extraObj?.inferParams;
  if (!params || (params && params.length == 0)) return [];
  const metaObjs = params[0]?.metaObjs;
  if (!metaObjs || (metaObjs && metaObjs.length == 0)) return [];
  const metaArr = metaObjs.map((item: any) => {
    const val = {
      id: uid(),
      label: item.label,
      confidence: item.confidence * 100,
      'min-width': item['min-width'],
      'min-height': item['min-height'],
    } as any;
    item.nextObjs.forEach((next) => {
      val[`${next.label}.confidence`] = next.confidence * 100;
      val[next.label + '.' + 'min-width'] = next['min-width'];
      val[next.label + '.' + 'min-height'] = next['min-height'];
    });
    return val;
  });

  return metaArr;
};

export const getDetectionTime = (time: string | undefined | null) => {
  if (!time) return [];
  const timeList = JSON.parse(time);
  if (!timeList || (timeList && timeList.length === 0)) {
    return [];
  }
  return timeList;
};

export const getInferCode = (extra: string | undefined | null) => {
  if (!extra) return '';
  const extraObj = JSON.parse(extra);
  return extraObj?.inferCode || '';
};

export const getExtraCommonInfo = (detail: CameraAlgoItem | undefined | null) => {
  if (!detail) return {};
  let extraValue = getCommonInfo(detail.extra);
  if (isEqual(extraValue, {})) {
    extraValue = getCommonInfo(detail.algoInfo?.extra);
  }
  return extraValue;
};

interface CommonInfo {
  regionJudge?: number;
  judge?: number;
  timeWindow?: number;
}

const getCommonInfo = (extra: string | undefined | null): CommonInfo => {
  if (!extra) return {};
  const extraObj = JSON.parse(extra);
  const params = extraObj?.inferParams;
  if (!params || (params && params.length == 0)) return {};
  const regionJudge = params[0]?.regionJudge;
  const judge = params[0]?.judge;
  const timeWindow = params[0]?.timeWindow;
  const ret = {} as CommonInfo;
  if (regionJudge || regionJudge == 0) {
    ret.regionJudge = regionJudge;
  }
  if (judge || judge == 0) {
    ret.judge = judge;
  }
  if (timeWindow || timeWindow == 0) {
    ret.timeWindow = timeWindow;
  }
  return ret;
};

export const getTimeCompletion = (time: TimePeriodItem) => {
  if (!time.startDay || !time.endDay) {
    return false;
  }
  time.timeRangeList.forEach((item) => {
    if (!item.startTime || !item.endTime) {
      return false;
    }
  });
  return true;
};
