import type { NdmRecordCheck, RecordInfo, RecordItem } from '@/apis';
import dayjs from 'dayjs';
import destr from 'destr';
import { groupBy } from 'es-toolkit';

export type NvrRecordDiag = {
  gbCode: string;
  channelName: string;
  recordDuration: RecordItem;
  lostChunks: RecordItem[];
};

// 解析出丢失的录像时间段
export const transformRecordChecks = (rawRecordChecks: NdmRecordCheck[]): NvrRecordDiag[] => {
  // 解析diagInfo
  const parsedRecordChecks = rawRecordChecks.map((recordCheck) => ({
    ...recordCheck,
    diagInfo: destr<RecordInfo>(recordCheck.diagInfo),
  }));
  // 按国标码分组
  const recordChecksByGbCode = groupBy(parsedRecordChecks, (recordCheck) => recordCheck.gbCode);
  // 提取分组后的国标码和录像诊断记录
  const channelGbCodes = Object.keys(recordChecksByGbCode);
  const recordChecksList = Object.values(recordChecksByGbCode);
  // 初始化每个通道的录像诊断数据结构
  const recordDiags = channelGbCodes.map((gbCode, index) => ({
    gbCode,
    channelName: recordChecksList.at(index)?.at(-1)?.name ?? '',
    records: [] as RecordItem[],
    lostChunks: [] as RecordItem[],
  }));
  // 写入同一gbCode的录像片段
  recordChecksList.forEach((recordChecks, index) => {
    recordChecks.forEach((recordCheck) => {
      recordDiags.at(index)?.records.push(...recordCheck.diagInfo.recordList);
    });
  });
  // 过滤掉没有录像记录的通道
  const filteredRecordDiags = recordDiags.filter((recordDiag) => recordDiag.records.length > 0);
  // 计算每个通道丢失的录像时间片段
  filteredRecordDiags.forEach((recordDiag) => {
    recordDiag.records.forEach((record, index, records) => {
      const nextRecordItem = records.at(index + 1);
      if (!!nextRecordItem) {
        // 如果下一段录像的开始时间不等于当前录像的结束时间，则判定为丢失
        const nextStartTime = nextRecordItem.startTime;
        const currEndTime = record.endTime;
        if (nextStartTime !== currEndTime) {
          recordDiag.lostChunks.push({
            startTime: currEndTime,
            endTime: nextStartTime,
          });
        }
      }
    });
  });
  return recordDiags.map((recordDiag) => {
    const firstRecord = recordDiag.records.at(0);
    const startTime = firstRecord ? dayjs(firstRecord.startTime).format('YYYY-MM-DD HH:mm:ss') : '';
    const lastRecord = recordDiag.records.at(-1);
    const endTime = lastRecord ? dayjs(lastRecord.endTime).format('YYYY-MM-DD HH:mm:ss') : '';
    return {
      gbCode: recordDiag.gbCode,
      channelName: recordDiag.channelName,
      recordDuration: { startTime, endTime },
      lostChunks: recordDiag.lostChunks,
    };
  });
};
