import type { Station } from '@/apis';
import type { NvrRecordDiag } from './record-check';
import { downloadByData, formatDuration } from '@/utils';
import dayjs from 'dayjs';

export const exportRecordDiagCsv = (recordDiags: NvrRecordDiag[], stationName: Station['name']) => {
  const csvHeader = '通道名称,开始时间,结束时间,持续时长\n';
  const csvRows = recordDiags
    .map((channel) => {
      if (channel.lostChunks.length === 0) {
        return `${channel.channelName},,,`;
      }
      return channel.lostChunks
        .map((loss) => {
          const duration = formatDuration(loss.startTime, loss.endTime);
          const startTime = dayjs(loss.startTime).format('YYYY-MM-DD HH:mm:ss');
          const endTime = dayjs(loss.endTime).format('YYYY-MM-DD HH:mm:ss');
          return `${channel.channelName},${startTime},${endTime},${duration}`;
        })
        .join('\n');
    })
    .join('\n');
  const csvContent = csvHeader.concat(csvRows);
  const time = dayjs().format('YYYY-MM-DD_HH-mm-ss');
  downloadByData(csvContent, `${stationName}_录像缺失记录_${time}.csv`, 'text/csv;charset=utf-8', '\ufeff');
};
