// 农机档案数据存储管理
import { MachineryRecord, MachineryChangeHistory, MachineryTag, MaintenanceRecord } from '../types/machinery';

const MACHINERY_KEY = 'smart_agriculture_machinery';
const HISTORY_KEY = 'smart_agriculture_machinery_history';
const TAGS_KEY = 'smart_agriculture_machinery_tags';
const MAINTENANCE_KEY = 'smart_agriculture_machinery_maintenance';

// 数据迁移：将旧状态值转换为新状态值
function migrateStatusValue(status: string): string {
  const statusMap: Record<string, string> = {
    '运行中': '正常',
    '空闲中': '正常',
    '维修中': '待维护',
    '报废': '已报废',
  };
  return statusMap[status] || status;
}

export const machineryStorage = {
  // 获取所有农机档案
  getAllMachinery(): MachineryRecord[] {
    const data = localStorage.getItem(MACHINERY_KEY);
    if (!data) return [];
    
    const machinery: MachineryRecord[] = JSON.parse(data);
    // 自动迁移旧状态值
    const migrated = machinery.map(m => ({
      ...m,
      status: migrateStatusValue(m.status)
    }));
    
    // 如果有数据被迁移，保存回localStorage
    if (JSON.stringify(machinery) !== JSON.stringify(migrated)) {
      localStorage.setItem(MACHINERY_KEY, JSON.stringify(migrated));
    }
    
    return migrated;
  },

  // 获取单个农机档案
  getMachinery(id: string): MachineryRecord | undefined {
    const all = this.getAllMachinery();
    return all.find(m => m.id === id);
  },

  // 保存农机档案
  saveMachinery(machinery: MachineryRecord): void {
    const all = this.getAllMachinery();
    const index = all.findIndex(m => m.id === machinery.id);
    if (index >= 0) {
      all[index] = machinery;
    } else {
      all.push(machinery);
    }
    localStorage.setItem(MACHINERY_KEY, JSON.stringify(all));
  },

  // 删除农机档案
  deleteMachinery(id: string): void {
    const all = this.getAllMachinery();
    const filtered = all.filter(m => m.id !== id);
    localStorage.setItem(MACHINERY_KEY, JSON.stringify(filtered));
  },

  // 获取变更历史
  getChangeHistory(machineryId: string): MachineryChangeHistory[] {
    const data = localStorage.getItem(HISTORY_KEY);
    const all: MachineryChangeHistory[] = data ? JSON.parse(data) : [];
    return all.filter(h => h.machineryId === machineryId);
  },

  // 保存变更历史
  saveChangeHistory(history: MachineryChangeHistory): void {
    const data = localStorage.getItem(HISTORY_KEY);
    const all: MachineryChangeHistory[] = data ? JSON.parse(data) : [];
    all.push(history);
    localStorage.setItem(HISTORY_KEY, JSON.stringify(all));
  },

  // 获取所有标签
  getAllTags(): MachineryTag[] {
    const data = localStorage.getItem(TAGS_KEY);
    return data ? JSON.parse(data) : [];
  },

  // 保存标签
  saveTag(tag: MachineryTag): void {
    const all = this.getAllTags();
    const index = all.findIndex(t => t.id === tag.id);
    if (index >= 0) {
      all[index] = tag;
    } else {
      all.push(tag);
    }
    localStorage.setItem(TAGS_KEY, JSON.stringify(all));
  },

  // 删除标签
  deleteTag(id: string): void {
    const all = this.getAllTags();
    const filtered = all.filter(t => t.id !== id);
    localStorage.setItem(TAGS_KEY, JSON.stringify(filtered));
  },

  // 根据二维码获取农机
  getMachineryByQRCode(qrCode: string): MachineryRecord | undefined {
    const all = this.getAllMachinery();
    return all.find(m => m.qrCode === qrCode);
  },

  // 获取某个农机的所有维护记录
  getMaintenanceRecords(machineryId: string): MaintenanceRecord[] {
    const data = localStorage.getItem(MAINTENANCE_KEY);
    const all: MaintenanceRecord[] = data ? JSON.parse(data) : [];
    
    // 数据迁移：将旧格式的partsAndMaterials(string[])转换为新格式(MaterialUsage[])
    const migrated = all.map(record => {
      if (record.partsAndMaterials && record.partsAndMaterials.length > 0) {
        // 检查是否是旧格式（string数组）
        const firstItem = record.partsAndMaterials[0];
        if (typeof firstItem === 'string') {
          // 旧格式，转换为新格式
          return {
            ...record,
            partsAndMaterials: (record.partsAndMaterials as any[]).map((id: string) => ({
              materialId: id,
              quantity: 1
            }))
          };
        }
      }
      return record;
    });
    
    // 如果有数据被迁移，保存回localStorage
    if (JSON.stringify(all) !== JSON.stringify(migrated)) {
      localStorage.setItem(MAINTENANCE_KEY, JSON.stringify(migrated));
    }
    
    return migrated.filter(m => m.machineryId === machineryId).sort((a, b) => 
      new Date(b.startTime).getTime() - new Date(a.startTime).getTime()
    );
  },

  // 获取所有维护记录
  getAllMaintenanceRecords(): MaintenanceRecord[] {
    const data = localStorage.getItem(MAINTENANCE_KEY);
    const all: MaintenanceRecord[] = data ? JSON.parse(data) : [];
    
    // 数据迁移：将旧格式的partsAndMaterials(string[])转换为新格式(MaterialUsage[])
    const migrated = all.map(record => {
      if (record.partsAndMaterials && record.partsAndMaterials.length > 0) {
        const firstItem = record.partsAndMaterials[0];
        if (typeof firstItem === 'string') {
          return {
            ...record,
            partsAndMaterials: (record.partsAndMaterials as any[]).map((id: string) => ({
              materialId: id,
              quantity: 1
            }))
          };
        }
      }
      return record;
    });
    
    // 如果有数据被迁移，保存回localStorage
    if (JSON.stringify(all) !== JSON.stringify(migrated)) {
      localStorage.setItem(MAINTENANCE_KEY, JSON.stringify(migrated));
    }
    
    return migrated;
  },

  // 保存维护记录
  saveMaintenanceRecord(record: MaintenanceRecord): void {
    const all = this.getAllMaintenanceRecords();
    const index = all.findIndex(m => m.id === record.id);
    if (index >= 0) {
      all[index] = record;
    } else {
      all.push(record);
    }
    localStorage.setItem(MAINTENANCE_KEY, JSON.stringify(all));
  },

  // 删除维护记录
  deleteMaintenanceRecord(id: string): void {
    const all = this.getAllMaintenanceRecords();
    const filtered = all.filter(m => m.id !== id);
    localStorage.setItem(MAINTENANCE_KEY, JSON.stringify(filtered));
  }
};
