/**
 * 充电桩大盘 - 时间工具模块
 */

import { state } from './state.js';

/**
 * 统一时间格式化
 * @param {number} seconds - 秒数
 * @returns {{text: string, detailed: string}}
 */
export function formatDuration(seconds) {
  if (seconds <= 0) return { text: '刚刚', detailed: '刚刚' };

  const mins = Math.floor(seconds / 60);
  if (mins < 1) return { text: '刚刚', detailed: '刚刚' };
  if (mins < 60) return { text: `${mins} 分钟`, detailed: `${mins} 分钟` };

  const hrs = Math.floor(mins / 60);
  const remainMins = mins % 60;

  if (hrs < 24) {
    if (remainMins === 0) {
      return { text: `${hrs} 小时`, detailed: `${hrs} 小时` };
    }
    return { text: `${hrs} 小时`, detailed: `${hrs} 小时 ${remainMins} 分钟` };
  }

  const days = Math.floor(hrs / 24);
  return { text: `${days} 天`, detailed: `${days} 天` };
}

/**
 * 从缓存计算持续时长（用于公牛桩等不返回时长的 API）
 * @param {object} connector - 充电桩数据
 * @param {object} cache - 状态缓存对象
 * @returns {number} 持续时长（秒）
 */
function getDurationFromCache(connector, cache) {
  const key = connector.connector_id || connector.connector_name;
  const timestamp = cache[key];
  if (!timestamp) return 0;
  return Math.floor((Date.now() - timestamp) / 1000);
}

/**
 * 获取空闲时间显示
 */
export function getIdleTime(connector) {
  let idleSeconds = connector.idle_seconds || 0;
  // 如果 API 没返回时长，尝试从缓存计算
  if (idleSeconds <= 0) {
    idleSeconds = getDurationFromCache(connector, state.freeCache);
  }
  if (idleSeconds <= 0) return { seconds: 0, text: '空闲中' };
  const formatted = formatDuration(idleSeconds);
  return { seconds: idleSeconds, text: `空闲 ${formatted.text}` };
}

/**
 * 获取充电时间显示
 */
export function getChargingTime(connector) {
  let chargingSeconds = connector.charging_seconds || 0;
  // 如果 API 没返回时长，尝试从缓存计算
  if (chargingSeconds <= 0) {
    chargingSeconds = getDurationFromCache(connector, state.chargingCache);
  }
  if (chargingSeconds <= 0) return { seconds: 0, text: '充电中' };
  const formatted = formatDuration(chargingSeconds);
  return { seconds: chargingSeconds, text: `已充 ${formatted.text}` };
}

/**
 * 获取占位时间显示
 */
export function getOccupiedTime(connector) {
  let occupiedSeconds = connector.occupied_seconds || 0;
  // 如果 API 没返回时长，尝试从缓存计算
  if (occupiedSeconds <= 0) {
    occupiedSeconds = getDurationFromCache(connector, state.occupiedCache);
  }
  if (occupiedSeconds <= 0) return { seconds: 0, text: '占位中' };
  const formatted = formatDuration(occupiedSeconds);
  return { seconds: occupiedSeconds, text: `占位 ${formatted.text}` };
}

/**
 * 格式化剩余充电时间
 */
export function formatRemainingTime(minutes) {
  if (minutes === null || minutes === undefined) return null;
  if (minutes <= 0) return '即将充满';

  const hrs = Math.floor(minutes / 60);
  const mins = minutes % 60;

  if (hrs > 0 && mins > 0) {
    return `剩余 ${hrs} 小时 ${mins} 分钟`;
  } else if (hrs > 0) {
    return `剩余 ${hrs} 小时`;
  }
  return `剩余 ${mins} 分钟`;
}
