import {commonApi} from '@tuya/tuya-panel-api'
import { IGetDpResultByHourResponse, IGetDpResultByMonthResponse } from '@tuya/tuya-panel-api/lib/common/interface'

export interface PagingResult<T> {
  data: T
  hasNext: boolean
  currentOffset: number
}

export interface DpReportSataResData {
  dps: DpReportSataData[]
  hasNext: boolean
  total: number
}

export interface DpReportSataData {
  timeStamp: number
  dpId: number
  timeStr: string
  value: string
}

export async function getDpReportSataData(
  deviceId: string,
  dpIds: string[],
  offset: number,
  limit: number,
  sortType?: 'ASC' | 'DESC',
): Promise<DpReportSataResData | undefined> {
  const params = {
    devId: deviceId,
    dpIds: dpIds.join(','),
    offset: offset,
    limit: limit,
    sortType: sortType || 'DESC',
  }
  const maxRetries = 3; // 设置重试次数的最大值
  let retry = 0;

  while (retry <= maxRetries) {
    try {
      const res = await commonApi.statApi.getDpReportLog(params);
      return res;
    } catch (err) {
      retry++;
      if (retry > maxRetries) {
        return undefined;
      }
    }
  }
}

export interface DpResultByMonthResData {
  years: object;
  thisDay: string;
  sum: string;
}

export async function getDpResultByMonth(
  devId: string,
  dpId: string,
  type: 'sum' | 'minux' | 'mac',
): Promise<IGetDpResultByMonthResponse | undefined> {
  const params = {
    devId,
    dpId,
    type,
  }
  const maxRetries = 3; // 设置重试次数的最大值
  let retry = 0;

  while (retry <= maxRetries) {
    try {
      const res = await commonApi.statApi.getDpResultByMonth(params);
      return res;
    } catch (err) {
      retry++;
      if (retry > maxRetries) {
        return undefined;
      }
    }
  }
}

export interface DpResultByDataWithSpecifiedResData {
  result: object;
  min: string;
}

export async function getDataWithSpecified(
  devId: string,
  dpId: string,
  startDay: string,
  endDay: string,
  type: 'sum' | 'minux' | 'avg',
): Promise<DpResultByDataWithSpecifiedResData | undefined> {
  const params = {
    devId,
    dpId,
    startDay,
    endDay,
    type,
  }
  const maxRetries = 3; // 设置重试次数的最大值
  let retry = 0;

  while (retry <= maxRetries) {
    try {
      const res = await commonApi.statApi.getDataWithSpecified(params);
      return res;
    } catch (err) {
      retry++;
      if (retry > maxRetries) {
        return undefined;
      }
    }
  }
}

export async function getDpResultByHour(
  devId: string,
  dpId: string,
  date: string,
  type: 'sum' | 'minux' | 'avg',
): Promise<IGetDpResultByHourResponse | undefined> {
  const params = {
    devId,
    dpId,
    date,
    type,
  }
  const maxRetries = 3; // 设置重试次数的最大值
  let retry = 0;

  while (retry <= maxRetries) {
    try {
      const res = await commonApi.statApi.getDpResultByHour(params);
      return res;
    } catch (err) {
      retry++;
      if (retry > maxRetries) {
        return undefined;
      }
    }
  }
}