//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { IScreenItem } from './../models/video.datatype';
import { IPlayerOption, IVideoShotGroup } from '../models/video.datatype';
import { traduction } from '@/utils/language';
import { queryTask } from '@/services/video-service';
import { downloadFileWithResponse } from '@/utils/common-service';
import { downloadData } from '@/services/video-service';

export const videoShotGroup = [
  {
    url: '',
    label: traduction('VIDEO_RECORDING_LOCAL'),
    detail: traduction('VIDEO_DOWNLOAD_PLAYER'),
    value: '0',
    playId: 'localId',
    videoType: 'LocalVideo',
    active: false,
    playerMenu: {
      id: 'playerMenuId',
      disable: false,
      options: getOption('localId'),
    },
  },
  {
    url: '',
    label: traduction('VIDEO_RECORDING_CPU_ERROR'),
    detail: traduction('NO_CPU_VIDEO_ERROR'),
    value: '0',
    downloadId: 'cpuErrorId',
    videoType: 'CaterrorVideo',
    refreshID: 'cpuRefreshId',
    playId: 'cpuVideoId',
    active: false,
    playerMenu: {
      id: 'playerMenuId',
      disable: false,
      options: getOption('cpuVideoId'),
    },
  },
  {
    url: '',
    label: traduction('VIDEO_RECORDING_SHUTDOWN'),
    detail: traduction('NO_SHUTDOWN_VIDEO_ERROR'),
    value: '0',
    downloadId: 'downOffId',
    videoType: 'PoweroffVideo',
    playId: 'offVideoId',
    active: false,
    playerMenu: {
      id: 'playerMenuId',
      disable: false,
      options: getOption('offVideoId'),
    },
  },
  {
    url: '',
    label: traduction('VIDEO_RECORDING_RESTART'),
    detail: traduction('NO_RESTARTS_VIDEO_ERROR'),
    value: '0',
    downloadId: 'restDownId',
    videoType: 'OsresetVideo',
    refreshID: 'restRefreshId',
    playId: 'restVideoId',
    active: false,
    playerMenu: {
      id: 'playerMenuId',
      disable: false,
      options: getOption('restVideoId'),
    },
  },
] as IVideoShotGroup[];

export const screenArray = [
  {
    status: false,
    id: 'img0',
    date: '',
    img: '',
  },
  {
    status: false,
    id: 'img1',
    date: '',
    img: '',
  },
  {
    status: false,
    id: 'img2',
    date: '',
    img: '',
  },
] as IScreenItem[];

function getOption(playId: string) {
  const options = [
    {
      id: 0,
      label: traduction('HTML5_VIDEO_PLAYER'),
      active: false,
      playId: playId,
    },
  ] as IPlayerOption[];
  return options;
}

// 下载文件步骤二 查询创建文件目录进度  Completed 为完成
export function taskService(url: string, item: any) {
  queryTask(url)
    .then((res: any) => {
      const taskData = res.data;
      if (taskData.prepare_progress === 100 && taskData.state === 'Completed') {
        // 下载
        restDownloadFile(item);
      } else if (taskData.prepare_progress <= 100) {
        setTimeout(() => {
          taskService(url, item);
        }, 3000);
      }
    })
    .catch(() => {
      item.down = false;
    });
}

export function restDownloadFile(item: any) {
  if (item.downloadId === 'cpuErrorId') {
    item.fileName = 'video_caterror.rep';
  } else if (item.downloadId === 'downOffId') {
    item.fileName = 'video_poweroff.rep';
  } else {
    item.fileName = 'video_osreset.rep';
  }
  downloadData(item.fileName)
    .then((res: any) => {
      const fileName = res.headers['content-disposition'].split('=')[1];
      downloadFileWithResponse(res.data, fileName);
      item.down = false;
    })
    .catch(() => {
      item.down = false;
    });
}

export function downloadPlayer(event: any, playId: string, vShotGroup: IVideoShotGroup[]): any {
  for (const key of vShotGroup) {
    if (key.playId === playId) {
      if (key.value === '0') {
        return;
      }
      key.active = true;
    } else {
      key.active = false;
    }
    event.stopPropagation();
    event.preventDefault();
  }
}

export function getFileSize(fileSize: number) {
  let result = '';
  let size = '';
  if (fileSize < 1024) {
    size = String(fileSize);
    result = `（${size} Byte）`;
  }
  if (fileSize >= 1024 && fileSize < 1024 * 1024) {
    size = (fileSize / 1024).toFixed(3);
    result = `（${size} KB）`;
  }

  if (fileSize >= 1024 * 1024) {
    size = (fileSize / (1024 * 1024)).toFixed(3);
    result = `（${size} MB）`;
  }
  return result;
}

export function getRandomFileName(fileName: string) {
  return `${Date.now()}_${fileName}`;
}

export function imgSort(arr: object[]) {
  if (arr.length === 0) {
    return arr;
  }
  const tmpArr: any = [];
  arr.forEach((item, idx) => {
    tmpArr.push({
      key: idx + 1,
      value: item,
    });
  });
  tmpArr.sort((a: any, b: any) => {
    const newLast = new Date(b.value.replace(/-/g, '/'));
    const newBefore = new Date(a.value.replace(/-/g, '/'));
    return (newLast as any) - (newBefore as any);
  });
  return tmpArr;
}
