// 任务优先级定义
export enum JobPriority {
  HIGH = 1,
  MEDIUM_HIGH = 2,
  MEDIUM = 3,
  MEDIUM_LOW = 4,
  LOW = 5,
  LOWEST = 10
}

// 商户权重映射（实际应用中应该从配置或数据库中获取）
const merchantWeights: Record<string, number> = {
  'merchant_1': 1.5,  // 高优先级商户
  'merchant_2': 1.2,  // 中优先级商户
  'merchant_3': 1.0   // 普通商户
};

// 业务类型权重
const businessTypeWeights: Record<string, number> = {
  'TOB': 1.3,  // B2B业务优先级更高
  'TOC': 1.0   // 普通B2C业务
};

// 任务类型到优先级的映射
export const getJobPriority = (jobType: string): JobPriority => {
  const priorityMap: Record<string, JobPriority> = {
    // 高优先级任务
    'ORDER_CREATE': JobPriority.HIGH,
    'BILLING': JobPriority.MEDIUM_HIGH,
    
    // 中等优先级任务
    'AI_OPTIMIZE_PRODUCT': JobPriority.MEDIUM,
    'UPDATE_AD_BUDGET': JobPriority.MEDIUM,
    'RUN_ADS': JobPriority.MEDIUM_HIGH,
    
    // 低优先级任务
    'SYNC_INVENTORY': JobPriority.MEDIUM_LOW,
    'CALCULATE_PROFIT': JobPriority.MEDIUM_LOW,
    'GENERATE_BILL': JobPriority.LOW,
    'STOP_AD': JobPriority.LOW
  };
  
  return priorityMap[jobType] || JobPriority.LOWEST;
};

// 计算综合优先级
export const calculateCompositePriority = (
  jobType: string,
  roi: number,
  merchantId: string,
  businessType: 'TOB' | 'TOC' = 'TOC'
): JobPriority => {
  // 基础优先级
  const basePriority = getJobPriority(jobType);
  
  // 商户权重
  const merchantWeight = merchantWeights[merchantId] || 1.0;
  
  // 业务类型权重
  const businessWeight = businessTypeWeights[businessType];
  
  // ROI调整因子
  let roiFactor = 1.0;
  if (roi > 1.0) {
    roiFactor = 0.7;  // 降低优先级数值，提高实际优先级
  } else if (roi > 0.5) {
    roiFactor = 0.8;
  } else if (roi < 0) {
    roiFactor = 1.2;  // 增加优先级数值，降低实际优先级
  }
  
  // 计算综合优先级
  let compositePriority = basePriority * merchantWeight * businessWeight * roiFactor;
  
  // 确保优先级在合理范围内
  compositePriority = Math.max(JobPriority.HIGH, Math.min(JobPriority.LOWEST, compositePriority));
  
  // 四舍五入到最近的优先级
  const priorities = Object.values(JobPriority).filter(p => typeof p === 'number') as number[];
  priorities.sort((a, b) => a - b);
  
  let closestPriority = priorities[0];
  let minDiff = Math.abs(compositePriority - closestPriority);
  
  for (const p of priorities) {
    const diff = Math.abs(compositePriority - p);
    if (diff < minDiff) {
      minDiff = diff;
      closestPriority = p;
    }
  }
  
  return closestPriority as JobPriority;
};

// 根据ROI调整优先级
export const adjustPriorityByROI = (basePriority: JobPriority, roi: number): JobPriority => {
  // ROI越高，优先级越高
  if (roi > 0.5) {
    return Math.max(JobPriority.HIGH, basePriority - 2);
  } else if (roi > 0.2) {
    return Math.max(JobPriority.MEDIUM, basePriority - 1);
  } else if (roi < 0) {
    return Math.min(JobPriority.LOW, basePriority + 1);
  }
  return basePriority;
};

export default {
  JobPriority,
  getJobPriority,
  adjustPriorityByROI,
  calculateCompositePriority
};

