import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { DATE_FORMATS, DateFormatType } from '../types';

/**
 * 统一的日期格式化函数
 */
export const formatDate = (
  date: Date | string, 
  formatType: DateFormatType = 'DISPLAY_WITH_TIME'
): string => {
  try {
    if (!date) return '';
    
    const dateObj = typeof date === 'string' ? parseDate(date) : date;
    if (!dateObj || isNaN(dateObj.getTime())) {
      return '';
    }
    
    return format(dateObj, DATE_FORMATS[formatType], { locale: zhCN });
  } catch (error) {
    console.error('日期格式化失败:', error, { date, formatType });
    return '';
  }
};

/**
 * 解析日期字符串
 */
export const parseDate = (dateStr: string): Date | null => {
  try {
    if (!dateStr || dateStr.includes('未找到') || dateStr.includes('时效值为0')) {
      return null;
    }
    
    // 移除所有星期信息
    let cleanStr = dateStr
      .replace(/\s*星期[一二三四五六日天]\s*/g, ' ')
      .replace(/\s*周[一二三四五六日天]\s*/g, ' ')
      .replace(/\s+/g, ' ')
      .trim();
    
    // 处理可能的格式问题
    cleanStr = cleanStr.replace(/(\d{4}-\d{2}-\d{2})(\d{2}:\d{2})/, '$1 $2');
    
    let date = new Date(cleanStr);
    if (!isNaN(date.getTime())) {
      return date;
    }
    
    // 尝试其他格式解析...
    return null;
  } catch (error) {
    console.error('日期解析失败:', error, dateStr);
    return null;
  }
};

/**
 * 根据JSON规则调整开始日期
 */
export const adjustStartDateByJsonRule = (
  date: Date, 
  ruleJson: string
): { adjustedDate: Date; description?: string } => {
  if (!ruleJson || ruleJson.trim() === '') {
    return { adjustedDate: date };
  }
  
  try {
    const rules = JSON.parse(ruleJson);
    const dayOfWeek = date.getDay();
    const dayKey = dayOfWeek === 0 ? '7' : dayOfWeek.toString();
    
    const rule = rules[dayKey];
    if (!rule) {
      return { adjustedDate: date };
    }
    
    const adjustedDate = new Date(date);
    let description = rule.description || '';
    
    switch (rule.action) {
      case 'delayInSameWeek':
        // 实现延迟逻辑
        break;
      // 其他规则...
    }
    
    return { adjustedDate, description };
  } catch (error) {
    console.error('日期规则解析失败:', error);
    return { adjustedDate: date };
  }
};