/**
 * 故障码库 - 基于农机厂商提供的标准故障码
 * 包含诊断规则、预测模型和解决方案知识库
 */

// 故障码定义
export interface FaultCode {
  code: string;
  name: string;
  category: FaultCategory;
  level: 'info' | 'warning' | 'error' | 'critical';
  description: string;
  
  // 诊断规则
  diagnosticRules: DiagnosticRule[];
  
  // 预测条件
  predictionConditions?: PredictionCondition[];
  
  // 解决方案
  solutions: Solution[];
  
  // 关联知识库
  knowledgeBaseIds: string[];
  
  // 厂商信息
  manufacturer?: string;
  applicableModels?: string[];
}

export type FaultCategory = 
  | '发动机系统'
  | '传动系统'
  | '液压系统'
  | '电气系统'
  | '冷却系统'
  | '燃油系统'
  | '排放系统'
  | '作业装置'
  | '其他';

// 诊断规则
export interface DiagnosticRule {
  condition: string; // 触发条件描述
  sensorKeys: string[]; // 关联的传感器参数
  threshold?: {
    min?: number;
    max?: number;
    duration?: number; // 持续时间（秒）
  };
  diagnosis: string; // 诊断结果
  confidence: number; // 置信度 0-1
}

// 预测条件（用于潜在故障预测）
export interface PredictionCondition {
  type: 'usage' | 'sensor' | 'pattern'; // 预测类型
  description: string;
  indicators: {
    key: string; // 指标键值
    threshold: number;
    unit?: string;
  }[];
  warningMessage: string;
  recommendedAction: string;
}

// 解决方案
export interface Solution {
  step: number;
  action: string;
  priority: 'high' | 'medium' | 'low';
  estimatedTime?: string; // 预计耗时
  requiredTools?: string[]; // 所需工具
  requiredParts?: string[]; // 所需零件
  safetyWarning?: string; // 安全提示
}

/**
 * 故障码库数据
 */
export const FAULT_CODE_LIBRARY: FaultCode[] = [
  // ========== 发动机系统 ==========
  {
    code: 'P0301',
    name: '第1缸失火',
    category: '发动机系统',
    level: 'error',
    description: '发动机第1缸检测到失火现象',
    diagnosticRules: [
      {
        condition: '第1缸点火信号异常',
        sensorKeys: ['cylinder1_misfire_count'],
        threshold: { min: 3, duration: 10 },
        diagnosis: '火花塞老化或点火线圈故障',
        confidence: 0.85,
      },
      {
        condition: '燃油喷射异常',
        sensorKeys: ['fuel_pressure', 'injector1_status'],
        diagnosis: '喷油嘴堵塞或燃油压力不足',
        confidence: 0.75,
      },
    ],
    predictionConditions: [
      {
        type: 'usage',
        description: '火花塞使用寿命预警',
        indicators: [
          { key: 'spark_plug_1_hours', threshold: 500, unit: '小时' },
        ],
        warningMessage: '火花塞使用寿命已达90%，建议更换',
        recommendedAction: '计划在下次保养时更换火花塞',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '检查第1缸火花塞状态，观察是否有烧蚀、积碳',
        priority: 'high',
        estimatedTime: '10分钟',
        requiredTools: ['火花塞扳手', '间隙规'],
      },
      {
        step: 2,
        action: '检查点火线圈输出，测量电阻值',
        priority: 'high',
        estimatedTime: '15分钟',
        requiredTools: ['万用表'],
      },
      {
        step: 3,
        action: '检查燃油喷射系统，清洗或更换喷油嘴',
        priority: 'medium',
        estimatedTime: '30分钟',
        requiredTools: ['喷油嘴清洗设备'],
        requiredParts: ['喷油嘴（如需更换）'],
      },
    ],
    knowledgeBaseIds: ['KB001', 'KB015'],
  },
  
  {
    code: 'P0171',
    name: '系统过稀',
    category: '燃油系统',
    level: 'warning',
    description: '燃油系统混合气过稀',
    diagnosticRules: [
      {
        condition: '空燃比传感器检测混合气过稀',
        sensorKeys: ['o2_sensor_voltage', 'fuel_trim'],
        diagnosis: '空气滤清器堵塞或进气系统漏气',
        confidence: 0.80,
      },
      {
        condition: '燃油压力低于标准值',
        sensorKeys: ['fuel_pressure'],
        threshold: { max: 250 }, // kPa
        diagnosis: '燃油泵压力不足或燃油滤清器堵塞',
        confidence: 0.85,
      },
    ],
    predictionConditions: [
      {
        type: 'usage',
        description: '空气滤清器使用时间预警',
        indicators: [
          { key: 'air_filter_hours', threshold: 500, unit: '小时' },
        ],
        warningMessage: '空气滤清器使用超过500小时，可能影响进气效率',
        recommendedAction: '检查并更换空气滤清器',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '检查并更换空气滤清器',
        priority: 'high',
        estimatedTime: '10分钟',
        requiredParts: ['空气滤清器'],
      },
      {
        step: 2,
        action: '检查燃油泵工作压力',
        priority: 'high',
        estimatedTime: '20分钟',
        requiredTools: ['燃油压力表'],
      },
      {
        step: 3,
        action: '检查进气系统是否有漏气',
        priority: 'medium',
        estimatedTime: '30分钟',
        requiredTools: ['烟雾机'],
      },
    ],
    knowledgeBaseIds: ['KB002', 'KB018'],
  },

  {
    code: 'C0040',
    name: '发动机温度过高',
    category: '冷却系统',
    level: 'critical',
    description: '发动机冷却液温度超过安全阈值',
    diagnosticRules: [
      {
        condition: '冷却液温度超过105℃',
        sensorKeys: ['coolant_temp'],
        threshold: { min: 105 },
        diagnosis: '冷却系统故障，需立即停机',
        confidence: 0.95,
      },
      {
        condition: '温度持续上升且风扇未启动',
        sensorKeys: ['coolant_temp', 'fan_status'],
        diagnosis: '散热风扇故障',
        confidence: 0.90,
      },
    ],
    predictionConditions: [
      {
        type: 'sensor',
        description: '冷却液温度趋势预警',
        indicators: [
          { key: 'coolant_temp_trend', threshold: 2, unit: '℃/分钟' },
        ],
        warningMessage: '冷却液温度上升过快，可能即将过热',
        recommendedAction: '减轻负荷，检查冷却系统',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '立即停机，等待冷却',
        priority: 'high',
        estimatedTime: '30分钟',
        safetyWarning: '⚠️ 严禁在高温时打开水箱盖，避免烫伤！',
      },
      {
        step: 2,
        action: '检查冷却液液位，必要时补充',
        priority: 'high',
        estimatedTime: '10分钟',
        requiredParts: ['冷却液'],
        safetyWarning: '确保发动机已完全冷却',
      },
      {
        step: 3,
        action: '检查水泵工作状态',
        priority: 'high',
        estimatedTime: '20分钟',
      },
      {
        step: 4,
        action: '检查散热器是否堵塞',
        priority: 'medium',
        estimatedTime: '15分钟',
      },
    ],
    knowledgeBaseIds: ['KB003', 'KB025'],
  },

  // ========== 预测性故障 ==========
  {
    code: 'W1001',
    name: '发动机积碳预警',
    category: '发动机系统',
    level: 'warning',
    description: '根据运行模式和燃油消耗分析，预测发动机可能存在积碳',
    diagnosticRules: [
      {
        condition: '长时间低转速运行',
        sensorKeys: ['engine_rpm', 'low_rpm_duration'],
        threshold: { max: 1200, duration: 7200 }, // 低于1200转持续2小时
        diagnosis: '长期低转速运行容易产生积碳',
        confidence: 0.70,
      },
      {
        condition: '燃油消耗率异常升高',
        sensorKeys: ['fuel_consumption_rate'],
        diagnosis: '燃烧效率下降，可能积碳严重',
        confidence: 0.75,
      },
    ],
    predictionConditions: [
      {
        type: 'pattern',
        description: '发动机积碳风险评估',
        indicators: [
          { key: 'low_rpm_hours_ratio', threshold: 0.6, unit: '占比' },
          { key: 'fuel_efficiency_drop', threshold: 15, unit: '%' },
        ],
        warningMessage: '发动机存在积碳风险，建议进行清洗保养',
        recommendedAction: '安排发动机清洗维护，使用积碳清洗剂',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '使用发动机积碳清洗剂',
        priority: 'medium',
        estimatedTime: '1小时',
        requiredParts: ['积碳清洗剂'],
      },
      {
        step: 2,
        action: '适当提高发动机转速运行30分钟',
        priority: 'medium',
        estimatedTime: '30分钟',
      },
      {
        step: 3,
        action: '检查火花塞积碳情况，必要时更换',
        priority: 'low',
        estimatedTime: '20分钟',
      },
    ],
    knowledgeBaseIds: ['KB030', 'KB031'],
  },

  {
    code: 'W1002',
    name: '皮带磨损预警',
    category: '传动系统',
    level: 'warning',
    description: '根据使用时间和振动数据，预测传动皮带可能需要更换',
    diagnosticRules: [
      {
        condition: '皮带使用时间接近更换周期',
        sensorKeys: ['belt_usage_hours'],
        threshold: { min: 1800 }, // 1800小时
        diagnosis: '皮带接近使用寿命',
        confidence: 0.80,
      },
      {
        condition: '振动传感器检测异常',
        sensorKeys: ['vibration_level'],
        threshold: { min: 0.5 },
        diagnosis: '皮带松弛或磨损导致振动增大',
        confidence: 0.75,
      },
    ],
    predictionConditions: [
      {
        type: 'usage',
        description: '皮带寿命预测',
        indicators: [
          { key: 'belt_usage_hours', threshold: 1800, unit: '小时' },
          { key: 'belt_tension_drop', threshold: 20, unit: '%' },
        ],
        warningMessage: '皮带磨损严重，建议及时更换避免断裂',
        recommendedAction: '准备备用皮带，计划更换时间',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '检查皮带张紧度',
        priority: 'high',
        estimatedTime: '10分钟',
        requiredTools: ['张紧度测量仪'],
      },
      {
        step: 2,
        action: '检查皮带表面磨损、裂纹',
        priority: 'high',
        estimatedTime: '10分钟',
      },
      {
        step: 3,
        action: '更换传动皮带',
        priority: 'high',
        estimatedTime: '45分钟',
        requiredParts: ['传动皮带'],
        requiredTools: ['扳手组', '张紧工具'],
      },
    ],
    knowledgeBaseIds: ['KB040', 'KB041'],
  },

  {
    code: 'W1003',
    name: '液压油变质预警',
    category: '液压系统',
    level: 'warning',
    description: '根据液压油使用时间和温度数据，预测液压油可能需要更换',
    diagnosticRules: [
      {
        condition: '液压油使用时间超过标准',
        sensorKeys: ['hydraulic_oil_hours'],
        threshold: { min: 500 },
        diagnosis: '液压油接近更换周期',
        confidence: 0.85,
      },
      {
        condition: '液压油温度频繁过高',
        sensorKeys: ['hydraulic_oil_temp', 'over_temp_count'],
        threshold: { min: 80, duration: 3600 },
        diagnosis: '高温加速液压油老化',
        confidence: 0.80,
      },
    ],
    predictionConditions: [
      {
        type: 'sensor',
        description: '液压油质量评估',
        indicators: [
          { key: 'hydraulic_oil_hours', threshold: 500, unit: '小时' },
          { key: 'over_temp_hours', threshold: 50, unit: '小时' },
        ],
        warningMessage: '液压油性能下降，建议更换以保护液压系统',
        recommendedAction: '安排液压油更换和系统清洗',
      },
    ],
    solutions: [
      {
        step: 1,
        action: '抽取液压油样本，检查颜色和杂质',
        priority: 'medium',
        estimatedTime: '10分钟',
      },
      {
        step: 2,
        action: '更换液压油和滤芯',
        priority: 'high',
        estimatedTime: '2小时',
        requiredParts: ['液压油', '液压滤芯'],
        requiredTools: ['油桶', '扳手'],
      },
      {
        step: 3,
        action: '清洗液压油箱',
        priority: 'medium',
        estimatedTime: '1小时',
      },
    ],
    knowledgeBaseIds: ['KB050', 'KB051'],
  },

  // ========== 电气系统 ==========
  {
    code: 'U0100',
    name: 'CAN通信故障',
    category: '电气系统',
    level: 'error',
    description: 'CAN总线通信中断或数据异常',
    diagnosticRules: [
      {
        condition: 'CAN总线无数据',
        sensorKeys: ['can_bus_status'],
        diagnosis: '总线连接故障或控制器故障',
        confidence: 0.90,
      },
    ],
    solutions: [
      {
        step: 1,
        action: '检查CAN总线插头连接',
        priority: 'high',
        estimatedTime: '15分钟',
      },
      {
        step: 2,
        action: '使用诊断仪检测总线电压',
        priority: 'high',
        estimatedTime: '20分钟',
        requiredTools: ['CAN总线诊断仪'],
      },
    ],
    knowledgeBaseIds: ['KB060'],
  },
];

/**
 * 解决方案知识库
 */
export interface KnowledgeBaseArticle {
  id: string;
  title: string;
  category: string;
  tags: string[];
  content: string;
  diagrams?: string[]; // 图片URL
  videos?: string[]; // 视频URL
  relatedFaultCodes: string[];
  difficulty: 'easy' | 'medium' | 'hard';
  estimatedTime: string;
  author: string;
  createdAt: string;
  updatedAt: string;
  viewCount: number;
  helpfulCount: number;
}

export const KNOWLEDGE_BASE: KnowledgeBaseArticle[] = [
  {
    id: 'KB001',
    title: '火花塞检查与更换指南',
    category: '发动机维修',
    tags: ['火花塞', '发动机', '失火', '点火系统'],
    content: `
# 火花塞检查与更换指南

## 检查步骤
1. 拆下火花塞
2. 观察电极磨损情况
3. 检查间隙（标准：0.8-0.9mm）
4. 查看颜色（正常为灰白色）

## 更换标准
- 电极磨损严重
- 绝缘体开裂
- 积碳严重无法清理
- 使用超过500小时

## 注意事项
⚠️ 更换时注意扭矩规格
⚠️ 使用正确型号的火花塞
    `,
    relatedFaultCodes: ['P0301', 'P0302', 'P0303', 'P0304'],
    difficulty: 'easy',
    estimatedTime: '30分钟',
    author: '技术团队',
    createdAt: '2024-01-01',
    updatedAt: '2024-10-01',
    viewCount: 1250,
    helpfulCount: 980,
  },
  {
    id: 'KB003',
    title: '发动机过热故障排查流程',
    category: '冷却系统',
    tags: ['过热', '冷却系统', '水温', '散热器'],
    content: `
# 发动机过热故障排查流程

## 紧急处理
1. 立即停机，避免拉缸
2. 等待完全冷却（至少30分钟）
3. 检查冷却液液位

## 常见原因
- 冷却液不足
- 水泵故障
- 节温器卡死
- 散热器堵塞
- 风扇不转

## 排查顺序
1. 检查液位（最简单）
2. 检查风扇（观察即可）
3. 检查水泵皮带
4. 检查散热器
5. 检查节温器

## 预防措施
✅ 定期检查冷却液
✅ 清洗散热器
✅ 检查风扇工作
    `,
    relatedFaultCodes: ['C0040'],
    difficulty: 'medium',
    estimatedTime: '1-2小时',
    author: '技术团队',
    createdAt: '2024-01-15',
    updatedAt: '2024-09-20',
    viewCount: 2100,
    helpfulCount: 1850,
  },
  {
    id: 'KB030',
    title: '发动机积碳清理与预防',
    category: '发动机维护',
    tags: ['积碳', '清洗', '保养', '燃烧室'],
    content: `
# 发动机积碳清理与预���

## 积碳产生原因
- 长期低速运行
- 燃油质量差
- 进气系统污染
- 火花塞老化

## 清理方法
### 1. 化学清洗
使用专用积碳清洗剂，从进气道注入

### 2. 拆解清洗
拆卸火花塞，刮除积碳

### 3. 核桃砂清洗
专业设备清洗进气道

## 预防措施
✅ 定期高转速运行
✅ 使用优质燃油
✅ 定期更换空滤
✅ 添加燃油添加剂
    `,
    relatedFaultCodes: ['W1001'],
    difficulty: 'medium',
    estimatedTime: '2-3小时',
    author: '资深技师',
    createdAt: '2024-03-10',
    updatedAt: '2024-10-05',
    viewCount: 1580,
    helpfulCount: 1320,
  },
];

/**
 * 根据故障码查找
 */
export function getFaultCodeInfo(code: string): FaultCode | undefined {
  return FAULT_CODE_LIBRARY.find(f => f.code === code);
}

/**
 * 根据分类查找故障码
 */
export function getFaultCodesByCategory(category: FaultCategory): FaultCode[] {
  return FAULT_CODE_LIBRARY.filter(f => f.category === category);
}

/**
 * 根据故障码查找知识库文章
 */
export function getKnowledgeBaseArticles(faultCode: string): KnowledgeBaseArticle[] {
  return KNOWLEDGE_BASE.filter(kb => kb.relatedFaultCodes.includes(faultCode));
}

/**
 * 分析传感器数据，预测潜在故障
 */
export function predictPotentialFaults(sensorData: Record<string, any>): {
  faultCode: string;
  confidence: number;
  message: string;
  action: string;
}[] {
  const predictions: any[] = [];
  
  FAULT_CODE_LIBRARY.forEach(fault => {
    if (!fault.predictionConditions) return;
    
    fault.predictionConditions.forEach(condition => {
      const allIndicatorsMet = condition.indicators.every(indicator => {
        const value = sensorData[indicator.key];
        return value !== undefined && value >= indicator.threshold;
      });
      
      if (allIndicatorsMet) {
        predictions.push({
          faultCode: fault.code,
          confidence: 0.75,
          message: condition.warningMessage,
          action: condition.recommendedAction,
        });
      }
    });
  });
  
  return predictions;
}
