import type { StepType, StepStatus } from '../types';
import { stepOrder } from './constants';

/**
 * 计算生产进度百分比
 */
export function calculateProgress(completed: number, target: number): number {
  if (target === 0) return 0;
  return Math.round((completed / target) * 100);
}

/**
 * 格式化日期显示
 */
export function formatDate(dateString: string | null | undefined): string {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

/**
 * 格式化日期时间显示
 */
export function formatDateTime(dateString: string | null | undefined): string {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('zh-CN');
}

/**
 * 格式化时间（仅时分）
 */
export function formatTime(dateString: string | null | undefined): string {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
}

/**
 * 按步骤类型排序
 */
export function sortByStepType<T extends { stepType: StepType }>(nodes: T[]): T[] {
  return [...nodes].sort((a, b) => {
    const indexA = stepOrder.indexOf(a.stepType);
    const indexB = stepOrder.indexOf(b.stepType);
    return indexA - indexB;
  });
}

/**
 * 查找第一个待确认的节点索引
 */
export function findFirstPendingIndex(nodes: { status: StepStatus }[]): number {
  return nodes.findIndex(n => n.status !== 'completed');
}

/**
 * 生成产品码
 */
export function generateProductCode(name: string, weight: string, colorCode: string): string {
  const nameLetters = name.replace(/[^a-zA-Z]/g, '').toUpperCase();
  const nameCode = nameLetters.slice(0, 2) || 'XX';
  const weightNum = weight.replace(/[^0-9]/g, '') || '0';
  const colorNum = colorCode.replace(/[^0-9]/g, '') || '00';
  return `${nameCode}${weightNum}${colorNum}`;
}

/**
 * 从分享链接中提取参数
 */
export function extractParamsFromLink(link: string): { token: string | null; plan: string | null; type: string | null; shortCode: string | null } {
  const hashMatch = link.match(/#\/import\?(.+)$/);
  if (hashMatch) {
    const queryString = hashMatch[1];
    const params = new URLSearchParams(queryString);
    return {
      token: params.get('token'),
      plan: params.get('plan'),
      type: params.get('type'),
      shortCode: params.get('s')
    };
  }
  try {
    const url = new URL(link, window.location.origin);
    return {
      token: url.searchParams.get('token'),
      plan: url.searchParams.get('plan'),
      type: url.searchParams.get('type'),
      shortCode: url.searchParams.get('s')
    };
  } catch {
    return { token: null, plan: null, type: null, shortCode: null };
  }
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => void>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  return (...args: Parameters<T>) => {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => void>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle = false;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

/**
 * 安全地解析数字
 */
export function safeParseNumber(value: string | number | null | undefined, defaultValue = 0): number {
  if (value === null || value === undefined || value === '') return defaultValue;
  const parsed = typeof value === 'string' ? parseFloat(value) : value;
  return isNaN(parsed) ? defaultValue : parsed;
}

/**
 * 安全地解析整数
 */
export function safeParseInt(value: string | number | null | undefined, defaultValue = 0): number {
  if (value === null || value === undefined || value === '') return defaultValue;
  const parsed = typeof value === 'string' ? parseInt(value, 10) : Math.floor(value);
  return isNaN(parsed) ? defaultValue : parsed;
}

/**
 * 按名称和克重分组产品
 */
export function groupProductsByNameAndWeight<T extends { product_name: string; weight: number }>(
  products: T[]
): Record<string, Record<string, T[]>> {
  const groups: Record<string, Record<string, T[]>> = {};
  products.forEach(product => {
    if (!groups[product.product_name]) {
      groups[product.product_name] = {};
    }
    const weightKey = String(product.weight);
    if (!groups[product.product_name][weightKey]) {
      groups[product.product_name][weightKey] = [];
    }
    groups[product.product_name][weightKey].push(product);
  });
  return groups;
}

/**
 * 计算汇总数据
 */
export function calculateSummary<T extends { raw_fabric_rolls?: number; raw_fabric_meters?: number }>(
  items: T[]
): { totalRolls: number; totalMeters: number } {
  return items.reduce(
    (sum, item) => ({
      totalRolls: sum.totalRolls + (item.raw_fabric_rolls || 0),
      totalMeters: sum.totalMeters + (item.raw_fabric_meters || 0)
    }),
    { totalRolls: 0, totalMeters: 0 }
  );
}
