import type {
  AlertEvent,
  DataSourceRecord,
  FieldOption,
  HistoryRecord,
  Protocol,
  TrackPoint,
  VehicleRecord,
  VehicleSourceSnapshot,
  VehicleStatus
} from './types';

export const protocolMeta: Record<Protocol, { label: string; short: string; color: 'blue' | 'green' | 'orange' }> = {
  GB32960: { label: 'GB/T 32960', short: '32960', color: 'blue' },
  JT808: { label: 'JT/T 808', short: '808', color: 'green' },
  YUTONG_MQTT: { label: '宇通 MQTT', short: 'MQTT', color: 'orange' }
};

export const statusLabel: Record<VehicleStatus, string> = {
  online: '在线',
  warning: '关注',
  offline: '离线'
};

export const sourceHealthLabel = {
  healthy: '健康',
  warning: '波动',
  down: '中断'
} as const;

export const dataSources: DataSourceRecord[] = [
  {
    id: 'src-hyundai',
    name: '现代 HTWO 平台',
    protocol: 'GB32960',
    endpoint: '47.99.166.38:32960',
    platformAccount: 'Hyundai',
    health: 'warning',
    vehicleCount: 184,
    onlineCount: 41,
    latencyP95Ms: 312,
    lastFrameAt: '2026-07-08 12:05:33',
    owner: '数智中心'
  },
  {
    id: 'src-yuejin',
    name: '跃进 32960 平台',
    protocol: 'GB32960',
    endpoint: '115.29.187.205:32960',
    platformAccount: 'YueJin',
    health: 'healthy',
    vehicleCount: 96,
    onlineCount: 83,
    latencyP95Ms: 188,
    lastFrameAt: '2026-07-08 12:06:08',
    owner: '接入组'
  },
  {
    id: 'src-g7s',
    name: 'G7s 转发',
    protocol: 'JT808',
    endpoint: '115.29.187.205:808',
    platformAccount: 'g7gps',
    health: 'healthy',
    vehicleCount: 312,
    onlineCount: 229,
    latencyP95Ms: 246,
    lastFrameAt: '2026-07-08 12:06:11',
    owner: '接入组'
  },
  {
    id: 'src-ga',
    name: '广安车联',
    protocol: 'JT808',
    endpoint: '115.231.168.135:43625',
    platformAccount: 'phone-binding',
    health: 'healthy',
    vehicleCount: 128,
    onlineCount: 107,
    latencyP95Ms: 271,
    lastFrameAt: '2026-07-08 12:05:59',
    owner: '运营'
  },
  {
    id: 'src-yutong',
    name: '宇通 MQTT',
    protocol: 'YUTONG_MQTT',
    endpoint: '/ytforward/shln/3',
    platformAccount: 'yutong-forward',
    health: 'warning',
    vehicleCount: 58,
    onlineCount: 50,
    latencyP95Ms: 438,
    lastFrameAt: '2026-07-08 12:04:48',
    owner: '接入组'
  }
];

function source(
  id: string,
  status: VehicleStatus,
  latencyMs: number,
  lastSeen: string,
  fieldCount: number,
  overrides: Partial<VehicleSourceSnapshot> = {}
): VehicleSourceSnapshot {
  const sourceRecord = dataSources.find((item) => item.id === id);
  if (!sourceRecord) {
    throw new Error(`Unknown source ${id}`);
  }
  return {
    id,
    protocol: sourceRecord.protocol,
    sourceName: sourceRecord.name,
    endpoint: sourceRecord.endpoint,
    platformAccount: sourceRecord.platformAccount,
    status,
    latencyMs,
    lastSeen,
    fieldCount,
    ...overrides
  };
}

export const vehicles: VehicleRecord[] = [
  {
    id: 'veh-001',
    plate: '粤AG18312',
    vin: 'LB9A32A22P0LS1230',
    phone: '13307795425',
    oem: 'G7s',
    status: 'online',
    city: '上海',
    address: '上海市奉贤区海湾镇海兴路',
    longitude: 121.075044,
    latitude: 30.590921,
    mapX: 58,
    mapY: 44,
    heading: 126,
    soc: 78.4,
    hydrogenKg: 12.23,
    primarySourceId: 'src-hyundai',
    sources: [
      source('src-hyundai', 'online', 226, '12 秒前', 86, {
        totalMileageKm: 119925,
        todayMileageKm: 86.4,
        speedKph: 42
      }),
      source('src-g7s', 'online', 241, '19 秒前', 34, {
        totalMileageKm: 119924.7,
        todayMileageKm: 86.1,
        speedKph: 41
      })
    ],
    flatFields: {
      GB32960: {
        'gb32960.vehicle.speed_kph': 42,
        'gb32960.vehicle.total_mileage_km': 119925,
        'gb32960.vehicle.soc_pct': 78.4,
        'gb32960.vehicle.dc_voltage_v': 556.1,
        'gb32960.vendor.fc_stack.stack_1.avg_cell_voltage_v': 0.79,
        'gb32960.vendor.fc_stack.stack_1.hydrogen_inlet_pressure_kpa': 130,
        'gb32960.vendor.fc_auxiliary.stack_1.air_compressor_power_kw': 0.8
      },
      JT808: {
        'jt808.location.speed_kph': 41,
        'jt808.location.total_mileage_km': 119924.7,
        'jt808.location.latitude': 30.590901,
        'jt808.location.longitude': 121.075011,
        'jt808.location.alarm_flag': 0
      },
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-002',
    plate: '粤AFF7936',
    vin: 'LB9A32A22P0LS1261',
    phone: '13426091261',
    oem: '广安车联',
    status: 'online',
    city: '杭州',
    address: '杭州市萧山区机场高速',
    longitude: 120.435311,
    latitude: 30.227898,
    mapX: 43,
    mapY: 53,
    heading: 84,
    hydrogenKg: 9.4,
    primarySourceId: 'src-ga',
    sources: [
      source('src-ga', 'online', 209, '21 秒前', 31, {
        totalMileageKm: 48798.9,
        todayMileageKm: 54.1,
        speedKph: 27
      })
    ],
    flatFields: {
      GB32960: {},
      JT808: {
        'jt808.location.speed_kph': 27,
        'jt808.location.total_mileage_km': 48798.9,
        'jt808.location.direction_deg': 84,
        'jt808.additional.total_mileage_km': 48798.9,
        'jt808.additional.fuel_level_pct': 61
      },
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-003',
    plate: '粤AG15568',
    vin: 'LB9A32A23P0LS1222',
    oem: '宇通',
    status: 'warning',
    city: '郑州',
    address: '郑州市管城回族区经开第八大街',
    longitude: 113.746221,
    latitude: 34.716884,
    mapX: 69,
    mapY: 34,
    heading: 0,
    soc: 65.1,
    hydrogenKg: 8.7,
    primarySourceId: 'src-yutong',
    sources: [
      source('src-yutong', 'warning', 524, '4 分钟前', 24, {
        totalMileageKm: 88310,
        todayMileageKm: 19.8,
        speedKph: 0
      })
    ],
    flatFields: {
      GB32960: {},
      JT808: {},
      YUTONG_MQTT: {
        'mqtt.vehicle.total_mileage_m': 88310000,
        'mqtt.vehicle.speed_kph': 0,
        'mqtt.vehicle.soc_pct': 65.1,
        'mqtt.vehicle.left_hydrogen_kg': 8.7,
        'mqtt.fuel_cell.voltage_v': 318,
        'mqtt.fuel_cell.current_a': 54.9,
        'mqtt.fuel_cell.air_in_pressure_kpa': 18
      }
    }
  },
  {
    id: 'veh-004',
    plate: '粤AG18285',
    vin: 'LB9A32A23P0LS1236',
    phone: '13426091236',
    oem: '现代四川',
    status: 'offline',
    city: '成都',
    address: '成都市龙泉驿区车城大道',
    longitude: 104.269552,
    latitude: 30.574117,
    mapX: 31,
    mapY: 37,
    heading: 0,
    soc: 41.2,
    hydrogenKg: 5.1,
    primarySourceId: 'src-hyundai',
    sources: [
      source('src-hyundai', 'offline', 0, '38 分钟前', 77, {
        totalMileageKm: 72104,
        todayMileageKm: 0,
        speedKph: 0
      })
    ],
    flatFields: {
      GB32960: {
        'gb32960.vehicle.total_mileage_km': 72104,
        'gb32960.vehicle.soc_pct': 41.2,
        'gb32960.vehicle.status': 'offline'
      },
      JT808: {},
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-005',
    plate: '粤AFN0065',
    vin: 'LB9A32A23P0LS1270',
    phone: '13307791270',
    oem: '广安车联',
    status: 'online',
    city: '广安',
    address: '广安市前锋区物流大道',
    longitude: 106.884219,
    latitude: 30.504891,
    mapX: 51,
    mapY: 68,
    heading: 213,
    hydrogenKg: 11.9,
    primarySourceId: 'src-ga',
    sources: [
      source('src-ga', 'online', 218, '31 秒前', 33, {
        totalMileageKm: 65177.2,
        todayMileageKm: 102.6,
        speedKph: 63
      })
    ],
    flatFields: {
      GB32960: {},
      JT808: {
        'jt808.location.speed_kph': 63,
        'jt808.location.total_mileage_km': 65177.2,
        'jt808.location.direction_deg': 213,
        'jt808.additional.total_mileage_km': 65177.2
      },
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-006',
    plate: '粤AG39007',
    vin: 'LB9A32A25P0LS1223',
    oem: '跃进',
    status: 'online',
    city: '上海',
    address: '上海市浦东新区申江路',
    longitude: 121.6431,
    latitude: 31.2249,
    mapX: 73,
    mapY: 57,
    heading: 36,
    soc: 82,
    hydrogenKg: 13.6,
    primarySourceId: 'src-yuejin',
    sources: [
      source('src-yuejin', 'online', 164, '8 秒前', 92, {
        totalMileageKm: 90441.5,
        todayMileageKm: 73.2,
        speedKph: 51
      })
    ],
    flatFields: {
      GB32960: {
        'gb32960.vehicle.speed_kph': 51,
        'gb32960.vehicle.total_mileage_km': 90441.5,
        'gb32960.vehicle.soc_pct': 82,
        'gb32960.vendor.fc_stack.stack_1.stack_water_outlet_temp_c': 63
      },
      JT808: {},
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-007',
    plate: '粤AFQ8013',
    vin: 'LB9A32A25P0LS1254',
    oem: 'G7s',
    phone: '13307791254',
    status: 'warning',
    city: '苏州',
    address: '苏州市吴江区同津大道',
    longitude: 120.6415,
    latitude: 31.1608,
    mapX: 63,
    mapY: 61,
    heading: 175,
    hydrogenKg: 7.3,
    primarySourceId: 'src-g7s',
    sources: [
      source('src-g7s', 'warning', 612, '6 分钟前', 34, {
        totalMileageKm: 40031.8,
        todayMileageKm: 12.4,
        speedKph: 18
      })
    ],
    flatFields: {
      GB32960: {},
      JT808: {
        'jt808.location.speed_kph': 18,
        'jt808.location.total_mileage_km': 40031.8,
        'jt808.location.direction_deg': 175,
        'jt808.quality.delay_ms': 612
      },
      YUTONG_MQTT: {}
    }
  },
  {
    id: 'veh-008',
    plate: '粤AG37790',
    vin: 'LB9A32A26P0LS1232',
    oem: '宇通',
    status: 'online',
    city: '上海',
    address: '上海市金山区亭卫公路',
    longitude: 121.3309,
    latitude: 30.7478,
    mapX: 47,
    mapY: 72,
    heading: 302,
    soc: 74.6,
    hydrogenKg: 10.5,
    primarySourceId: 'src-yutong',
    sources: [
      source('src-yutong', 'online', 352, '44 秒前', 22, {
        totalMileageKm: 119925,
        todayMileageKm: 41.6,
        speedKph: 29
      }),
      source('src-yuejin', 'online', 191, '37 秒前', 84, {
        totalMileageKm: 119924.9,
        todayMileageKm: 41.4,
        speedKph: 30
      })
    ],
    flatFields: {
      GB32960: {
        'gb32960.vehicle.speed_kph': 30,
        'gb32960.vehicle.total_mileage_km': 119924.9,
        'gb32960.vehicle.soc_pct': 74.6
      },
      JT808: {},
      YUTONG_MQTT: {
        'mqtt.vehicle.total_mileage_m': 119925000,
        'mqtt.vehicle.speed_kph': 29,
        'mqtt.vehicle.soc_pct': 74.6,
        'mqtt.vehicle.left_hydrogen_kg': 10.5
      }
    }
  }
];

export const trackPoints: TrackPoint[] = [
  { id: 'trk-1', vehicleId: 'veh-001', time: '08:12', state: 'running', address: '奉贤区海湾镇', longitude: 121.0192, latitude: 30.5803, speedKph: 36, mileageKm: 119842.1, note: '早高峰开始运行' },
  { id: 'trk-2', vehicleId: 'veh-001', time: '09:48', state: 'running', address: '金山区亭卫公路', longitude: 121.2451, latitude: 30.7359, speedKph: 58, mileageKm: 119887.4, note: '高速路段速度稳定' },
  { id: 'trk-3', vehicleId: 'veh-001', time: '10:26', state: 'alert', address: '浦东新区申江路', longitude: 121.6145, latitude: 31.2012, speedKph: 0, mileageKm: 119901.2, note: '出现 92 秒数据断链' },
  { id: 'trk-4', vehicleId: 'veh-001', time: '11:36', state: 'stop', address: '奉贤区海兴路', longitude: 121.075044, latitude: 30.590921, speedKph: 0, mileageKm: 119925, note: '车辆停靠，今日里程闭合' },
  { id: 'trk-5', vehicleId: 'veh-005', time: '07:52', state: 'running', address: '前锋区物流大道', longitude: 106.8951, latitude: 30.5002, speedKph: 44, mileageKm: 65074.6, note: 'JT808 位置上报正常' },
  { id: 'trk-6', vehicleId: 'veh-005', time: '10:18', state: 'running', address: '沪蓉高速广安段', longitude: 106.7289, latitude: 30.4567, speedKph: 63, mileageKm: 65177.2, note: '总里程来自 0x01 附加信息' }
];

export const alertEvents: AlertEvent[] = [
  {
    id: 'alt-1',
    vehicleId: 'veh-001',
    level: 'P1',
    type: '断链',
    title: 'GB32960 心跳延迟',
    detail: '现代 HTWO 平台 3 台车超过 90 秒未上报，已触发断链预警。',
    sourceId: 'src-hyundai',
    time: '2026-07-08 11:58:21',
    status: 'open'
  },
  {
    id: 'alt-2',
    vehicleId: 'veh-007',
    level: 'P2',
    type: '里程跳变',
    title: 'JT808 总里程回退',
    detail: 'G7s 来源出现 1 条总里程小幅回退，统计服务已跳过异常区间。',
    sourceId: 'src-g7s',
    time: '2026-07-08 11:41:06',
    status: 'processing'
  },
  {
    id: 'alt-3',
    vehicleId: 'veh-003',
    level: 'P2',
    type: '字段缺失',
    title: 'MQTT 字段缺失',
    detail: '宇通 MQTT 本次只上报经纬度，实时快照使用上一帧补全业务字段。',
    sourceId: 'src-yutong',
    time: '2026-07-08 10:36:44',
    status: 'open'
  },
  {
    id: 'alt-4',
    vehicleId: 'veh-004',
    level: 'P1',
    type: '定位异常',
    title: '车辆长时间离线',
    detail: '现代四川来源 38 分钟无实时数据，当前位置仅作为最后有效位置展示。',
    sourceId: 'src-hyundai',
    time: '2026-07-08 10:14:09',
    status: 'open'
  }
];

export const historyRecords: HistoryRecord[] = [
  {
    id: 'raw-gb-20260708-000923',
    vehicleId: 'veh-001',
    protocol: 'GB32960',
    frameType: '实时信息上报 0x02',
    receiveTime: '2026-07-08 12:05:33.226',
    deviceTime: '2026-07-08 12:05:32',
    sourceName: '现代 HTWO 平台',
    latencyMs: 226,
    fieldCount: 86,
    exportable: true
  },
  {
    id: 'raw-808-20260708-002841',
    vehicleId: 'veh-001',
    protocol: 'JT808',
    frameType: '位置信息汇报 0x0200',
    receiveTime: '2026-07-08 12:05:34.118',
    deviceTime: '2026-07-08 12:05:33',
    sourceName: 'G7s 转发',
    latencyMs: 241,
    fieldCount: 34,
    exportable: true
  },
  {
    id: 'raw-mqtt-20260708-000114',
    vehicleId: 'veh-003',
    protocol: 'YUTONG_MQTT',
    frameType: '遥测转发 code=0F80',
    receiveTime: '2026-07-08 12:04:48.524',
    deviceTime: '2026-07-08 12:04:47',
    sourceName: '宇通 MQTT',
    latencyMs: 524,
    fieldCount: 24,
    exportable: true
  },
  {
    id: 'raw-gb-20260708-000927',
    vehicleId: 'veh-006',
    protocol: 'GB32960',
    frameType: '补发信息上报 0x03',
    receiveTime: '2026-07-08 12:06:08.164',
    deviceTime: '2026-07-08 12:05:58',
    sourceName: '跃进 32960 平台',
    latencyMs: 164,
    fieldCount: 92,
    exportable: true
  },
  {
    id: 'raw-808-20260708-002846',
    vehicleId: 'veh-005',
    protocol: 'JT808',
    frameType: '位置信息汇报 0x0200',
    receiveTime: '2026-07-08 12:05:59.218',
    deviceTime: '2026-07-08 12:05:58',
    sourceName: '广安车联',
    latencyMs: 218,
    fieldCount: 33,
    exportable: true
  }
];

export const fieldOptions: FieldOption[] = [
  { key: 'speed_kph', label: '车速', protocol: 'ALL' },
  { key: 'total_mileage_km', label: '总里程', protocol: 'ALL' },
  { key: 'soc_pct', label: 'SOC', protocol: 'GB32960' },
  { key: 'left_hydrogen_kg', label: '剩余氢量', protocol: 'YUTONG_MQTT' },
  { key: 'direction_deg', label: '方向角', protocol: 'JT808' },
  { key: 'lat_lon', label: '经纬度', protocol: 'ALL' },
  { key: 'fc_stack', label: '燃料电池堆', protocol: 'GB32960' },
  { key: 'quality_delay', label: '链路延迟', protocol: 'ALL' }
];

export function getVehiclePrimarySource(vehicle: VehicleRecord) {
  return vehicle.sources.find((item) => item.id === vehicle.primarySourceId) ?? vehicle.sources[0];
}

export function getVehicleProtocols(vehicle: VehicleRecord) {
  return vehicle.sources.map((item) => item.protocol);
}
