// 变更历史示例数据
import { MachineryChangeHistory } from '../types/machinery';
import { machineryStorage } from './machineryStorage';

/**
 * 初始化变更历史示例数据
 * 为每台农机创建真实的变更记录
 */
export function initializeChangeHistoryMockData() {
  // 检查是否已有变更历史数据
  const allMachinery = machineryStorage.getAllMachinery();
  if (allMachinery.length === 0) {
    console.log('⚠️ 没有农机数据，无法创建变更历史示例');
    return;
  }

  // 检查是否已有变更历史
  const existingHistory = allMachinery.reduce((count, m) => {
    return count + machineryStorage.getChangeHistory(m.id).length;
  }, 0);

  if (existingHistory > 0) {
    console.log('ℹ️ 已存在变更历史数据，跳过初始化');
    return;
  }

  const now = new Date();
  const changes: MachineryChangeHistory[] = [];

  // ==================== 农机1：约翰迪尔拖拉机变更历史 ====================
  if (allMachinery[0]) {
    const machinery1Id = allMachinery[0].id;

    // 1. 设备状态变更
    changes.push({
      id: `change-${Date.now()}-001`,
      machineryId: machinery1Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '正常',
      newValue: '待维护',
      operator: '张三',
      operatedAt: new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000).toISOString(), // 3天前
    });

    // 2. 当前位置变更
    changes.push({
      id: `change-${Date.now()}-002`,
      machineryId: machinery1Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '1号地块',
      newValue: '3号地块',
      operator: '李四',
      operatedAt: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000).toISOString(), // 5天前
    });

    // 3. 操作人员变更
    changes.push({
      id: `change-${Date.now()}-003`,
      machineryId: machinery1Id,
      fieldName: 'operator',
      fieldLabel: '操作人员',
      oldValue: '张三',
      newValue: '王五',
      operator: '系统管理员',
      operatedAt: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 7天前
    });

    // 4. 保险信息更新
    changes.push({
      id: `change-${Date.now()}-004`,
      machineryId: machinery1Id,
      fieldName: 'insuranceEndDate',
      fieldLabel: '保险结束日期',
      oldValue: '2025-03-31',
      newValue: '2026-03-31',
      operator: '财务部-刘会计',
      operatedAt: new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10天前
    });

    // 5. 购机价格调整
    changes.push({
      id: `change-${Date.now()}-005`,
      machineryId: machinery1Id,
      fieldName: 'purchasePrice',
      fieldLabel: '购机价格',
      oldValue: 350000,
      newValue: 345000,
      operator: '财务部-刘会计',
      operatedAt: new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000).toISOString(), // 15天前
    });

    // 6. 备注更新
    changes.push({
      id: `change-${Date.now()}-006`,
      machineryId: machinery1Id,
      fieldName: 'remarks',
      fieldLabel: '备注',
      oldValue: '主力耕作设备，状态良好',
      newValue: '主力耕作设备，状态良好，已完成季度保养',
      operator: '张三',
      operatedAt: new Date(now.getTime() - 20 * 24 * 60 * 60 * 1000).toISOString(), // 20天前
    });

    // 7. 设备状态恢复正常
    changes.push({
      id: `change-${Date.now()}-007`,
      machineryId: machinery1Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '待维护',
      newValue: '正常',
      operator: '维修班-李师傅',
      operatedAt: new Date(now.getTime() - 1 * 24 * 60 * 60 * 1000).toISOString(), // 1天前
    });
  }

  // ==================== 农机2：收割机变更历史 ====================
  if (allMachinery[1]) {
    const machinery2Id = allMachinery[1].id;

    // 1. 设备名称规范化
    changes.push({
      id: `change-${Date.now()}-008`,
      machineryId: machinery2Id,
      fieldName: 'name',
      fieldLabel: '设备名称',
      oldValue: '久保田收割机',
      newValue: '久保田PRO988Q收割机',
      operator: '资产管理员',
      operatedAt: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天前
    });

    // 2. 作业前位置更新
    changes.push({
      id: `change-${Date.now()}-009`,
      machineryId: machinery2Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '机库A区',
      newValue: '东片收割区',
      operator: '李四',
      operatedAt: new Date(now.getTime() - 25 * 24 * 60 * 60 * 1000).toISOString(), // 25天前
    });

    // 3. 作业后位置更新
    changes.push({
      id: `change-${Date.now()}-010`,
      machineryId: machinery2Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '东片收割区',
      newValue: '机库A区',
      operator: '李四',
      operatedAt: new Date(now.getTime() - 20 * 24 * 60 * 60 * 1000).toISOString(), // 20天前
    });

    // 4. 设备状态因故障变更
    changes.push({
      id: `change-${Date.now()}-011`,
      machineryId: machinery2Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '正常',
      newValue: '待维护',
      operator: '李四',
      operatedAt: new Date(now.getTime() - 18 * 24 * 60 * 60 * 1000).toISOString(), // 18天前
    });

    // 5. 维修完成，状态恢复
    changes.push({
      id: `change-${Date.now()}-012`,
      machineryId: machinery2Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '待维护',
      newValue: '正常',
      operator: '维修班-赵师傅',
      operatedAt: new Date(now.getTime() - 16 * 24 * 60 * 60 * 1000).toISOString(), // 16天前
    });

    // 6. 标签更新
    changes.push({
      id: `change-${Date.now()}-013`,
      machineryId: machinery2Id,
      fieldName: 'tags',
      fieldLabel: '标签',
      oldValue: ['tag-2', 'tag-3'],
      newValue: ['tag-1', 'tag-2', 'tag-3'],
      operator: '系统管理员',
      operatedAt: new Date(now.getTime() - 12 * 24 * 60 * 60 * 1000).toISOString(), // 12天前
    });
  }

  // ==================== 农机3：播种机变更历史 ====================
  if (allMachinery[2]) {
    const machinery3Id = allMachinery[2].id;

    // 1. 操作人员调整
    changes.push({
      id: `change-${Date.now()}-014`,
      machineryId: machinery3Id,
      fieldName: 'operator',
      fieldLabel: '操作人员',
      oldValue: '王五',
      newValue: '赵六',
      operator: '系统管理员',
      operatedAt: new Date(now.getTime() - 40 * 24 * 60 * 60 * 1000).toISOString(), // 40天前
    });

    // 2. 播种前检修
    changes.push({
      id: `change-${Date.now()}-015`,
      machineryId: machinery3Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '正常',
      newValue: '待维护',
      operator: '赵六',
      operatedAt: new Date(now.getTime() - 35 * 24 * 60 * 60 * 1000).toISOString(), // 35天前
    });

    // 3. 检修完成
    changes.push({
      id: `change-${Date.now()}-016`,
      machineryId: machinery3Id,
      fieldName: 'status',
      fieldLabel: '设备状态',
      oldValue: '待维护',
      newValue: '正常',
      operator: '维修班-孙师傅',
      operatedAt: new Date(now.getTime() - 33 * 24 * 60 * 60 * 1000).toISOString(), // 33天前
    });

    // 4. 作业地点变更
    changes.push({
      id: `change-${Date.now()}-017`,
      machineryId: machinery3Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '机库B区',
      newValue: '西片播种区',
      operator: '赵六',
      operatedAt: new Date(now.getTime() - 28 * 24 * 60 * 60 * 1000).toISOString(), // 28天前
    });

    // 5. 作业完成归库
    changes.push({
      id: `change-${Date.now()}-018`,
      machineryId: machinery3Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '西片播种区',
      newValue: '机库B区',
      operator: '赵六',
      operatedAt: new Date(now.getTime() - 22 * 24 * 60 * 60 * 1000).toISOString(), // 22天前
    });

    // 6. 保险金额调整
    changes.push({
      id: `change-${Date.now()}-019`,
      machineryId: machinery3Id,
      fieldName: 'insuranceAmount',
      fieldLabel: '保险金额',
      oldValue: 150000,
      newValue: 160000,
      operator: '财务部-刘会计',
      operatedAt: new Date(now.getTime() - 8 * 24 * 60 * 60 * 1000).toISOString(), // 8天前
    });
  }

  // ==================== 农机4：植保无人机变更历史 ====================
  if (allMachinery[3]) {
    const machinery4Id = allMachinery[3].id;

    // 1. 电池更换记录
    changes.push({
      id: `change-${Date.now()}-020`,
      machineryId: machinery4Id,
      fieldName: 'remarks',
      fieldLabel: '备注',
      oldValue: '最新款植保无人机，智能化程度高',
      newValue: '最新款植保无人机，智能化程度高，电池已更换',
      operator: '无人机操作员-周七',
      operatedAt: new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000).toISOString(), // 6天前
    });

    // 2. 作业区域变更
    changes.push({
      id: `change-${Date.now()}-021`,
      machineryId: machinery4Id,
      fieldName: 'currentLocation',
      fieldLabel: '当前位置',
      oldValue: '设备间',
      newValue: '北片植保区',
      operator: '周七',
      operatedAt: new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000).toISOString(), // 4天前
    });

    // 3. 标签添加
    changes.push({
      id: `change-${Date.now()}-022`,
      machineryId: machinery4Id,
      fieldName: 'tags',
      fieldLabel: '标签',
      oldValue: ['tag-1', 'tag-2', 'tag-3'],
      newValue: ['tag-1', 'tag-2', 'tag-3', 'tag-4'],
      operator: '系统管理员',
      operatedAt: new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000).toISOString(), // 2天前
    });
  }

  // ==================== 农机5：拖拉机变更历史 ====================
  if (allMachinery[4]) {
    const machinery5Id = allMachinery[4].id;

    // 1. 供应商信息更正
    changes.push({
      id: `change-${Date.now()}-023`,
      machineryId: machinery5Id,
      fieldName: 'supplier',
      fieldLabel: '供应商',
      oldValue: '农机经销商',
      newValue: '雷沃重工授权经销商',
      operator: '采购部-吴采购',
      operatedAt: new Date(now.getTime() - 50 * 24 * 60 * 60 * 1000).toISOString(), // 50天前
    });

    // 2. 部门调整
    changes.push({
      id: `change-${Date.now()}-024`,
      machineryId: machinery5Id,
      fieldName: 'department',
      fieldLabel: '所属部门',
      oldValue: '第三生产队',
      newValue: '第一生产队',
      operator: '人事部-郑主管',
      operatedAt: new Date(now.getTime() - 45 * 24 * 60 * 60 * 1000).toISOString(), // 45天前
    });

    // 3. 年检完成
    changes.push({
      id: `change-${Date.now()}-025`,
      machineryId: machinery5Id,
      fieldName: 'remarks',
      fieldLabel: '备注',
      oldValue: '可靠耐用，适合大田作业',
      newValue: '可靠耐用，适合大田作业，已完成年检',
      operator: '安全员-冯安全',
      operatedAt: new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString(), // 14天前
    });
  }

  // 保存所有变更记录
  changes.forEach(change => {
    machineryStorage.saveChangeHistory(change);
  });

  console.log(`✅ 已初始化 ${changes.length} 条变更历史示例数据`);
}

/**
 * 清除所有变更历史（仅用于测试）
 */
export function clearChangeHistory() {
  localStorage.removeItem('smart_agriculture_machinery_history');
  console.log('🗑️ 已清除所有变更历史');
}

/**
 * 获取变更历史统计信息
 */
export function getChangeHistoryStatistics() {
  const allMachinery = machineryStorage.getAllMachinery();
  
  let totalChanges = 0;
  const changesByMachinery: Record<string, number> = {};
  const changesByField: Record<string, number> = {};
  const changesByOperator: Record<string, number> = {};

  allMachinery.forEach(machinery => {
    const changes = machineryStorage.getChangeHistory(machinery.id);
    totalChanges += changes.length;
    changesByMachinery[machinery.name] = changes.length;

    changes.forEach(change => {
      // 按字段统计
      changesByField[change.fieldLabel] = (changesByField[change.fieldLabel] || 0) + 1;
      
      // 按操作人统计
      changesByOperator[change.operator] = (changesByOperator[change.operator] || 0) + 1;
    });
  });

  return {
    totalChanges,
    totalMachinery: allMachinery.length,
    changesByMachinery,
    changesByField,
    changesByOperator,
    avgChangesPerMachinery: allMachinery.length > 0 ? totalChanges / allMachinery.length : 0,
  };
}
