/*
 * Copyright (C) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  IjkMediaPlayer, VideoCodecMode, OnPreparedListener, OnVideoSizeChangedListener,
  OnErrorListener, OnCompletionListener, OnSeekCompleteListener, OnInfoListener, LogUtils
} from '@ohos/ijkplayer';
import { BusinessError } from '@ohos.base';
import { PlayStatus } from '../common/PlayStatus';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import { IjkplayerMapManager } from './IjkplayerMapManager';

@Entry
@Component
struct IjkVideoDynamicResolutionPage {
  private videoUrl: string = '';
  @State playStatus: PlayStatus = PlayStatus.INIT;
  @State curIndex: number = 0;
  @State isVideoFileExists: boolean = false;
  @State currentWidth: number = 0;
  @State currentHeight: number = 0;
  @State resolutionHistoryText: string = '';
  @State resolutionChanged: boolean = false;
  @State videoAspectRatio: number = 1;
  @State videoWidth: string = '100%';
  @State errorMsg: string = '';
  @State mContext: object | undefined = undefined;
  @State codecMode: VideoCodecMode = VideoCodecMode.BUFFER;
  @State progressValue: number = 0;
  @State currentTime: string = '00:00';
  @State totalTime: string = '00:00';
  @State slideEnable: boolean = false;
  @State loadingVisible: Visibility = Visibility.None;
  @State replayVisible: Visibility = Visibility.None;
  @State recordProgressVisible: Visibility = Visibility.None;

  private readonly PROGRESS_MAX_VALUE: number = 100;
  private readonly decodePixelToVp: number = 0.14;
  private readonly scaledWidthMaxVp: number = 400;
  private readonly videoSizeApplyDelayMs: number = 48;
  private recordSaveFilePath: string = '';
  private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  private videoUrls: string[] = [
    '/Sample-8bit-resolution.mp4',
    '/Sample-8bit-resolution_480-2k.mp4',
    '/Sample-10bit-resolution-hevc_480-2k.mp4',
    '/Sample-10bit-resolution-hevc_1080-480.mp4',
  ];
  private recordSessionActive: boolean = false;
  private last: number = 0;
  private xcomponentId: string = '';
  private changeHighlightTimer: number = 0;
  private videoSizeApplyTimer: number = 0;
  private updateProgressTimer: number = 0;
  private isSeekTo: boolean = false;
  private mDestroyPage: boolean = false;

  aboutToAppear() {
    this.xcomponentId = 'xcomponentId_' + IjkplayerMapManager.generateId();
    this.videoUrl = this.getHostResourceDir() + this.videoUrls[this.curIndex];
    this.updateVideoFileExists();
  }

  async aboutToDisappear() {
    this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
    await this.stopRecord(false);
    IjkplayerMapManager.getInstance().destroyStatusMap.set(this.xcomponentId, true);
    this.mDestroyPage = true;
    if (this.playStatus !== PlayStatus.INIT) {
      this.stop(true);
    }
    this.clearResolutionTimers();
    this.stopProgressTask();
  }

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Auto, justifyContent: FlexAlign.Start }) {
      this.TitleBar()
      Divider().vertical(false).strokeWidth('20px').color(Color.White).lineCap(LineCapStyle.Round)
      this.VideoArea()
      Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
        Text(this.videoUrls[this.curIndex].substring(1))
          .fontSize('50px').fontColor(Color.Black).margin({ left: '15px', right: '15px' })
      }
      this.ProgressRow()
      this.PlaybackControls()
      this.RecordControls()
      this.ResolutionPanel()
    }.width('100%').height('100%')
  }

  @Builder
  TitleBar() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text($r('app.string.dynamic_resolution_player'))
        .fontSize('30px').fontColor(Color.White).margin('10px').fontWeight(FontWeight.Bold)
    }.height('100px').width('100%').backgroundColor(Color.Black)
  }

  @Builder
  VideoArea() {
    Stack({ alignContent: Alignment.Center }) {
      Column() {
        XComponent({ id: this.xcomponentId, type: XComponentType.SURFACE, libraryname: 'ijkplayer_napi' })
          .onLoad((event?: object) => { if (event) { this.mContext = event; } })
          .width(this.getXComponentWidth()).aspectRatio(this.videoAspectRatio).id(this.xcomponentId)
      }.width(this.getXComponentWidth()).aspectRatio(this.videoAspectRatio)

      Image($r('app.media.icon_replay')).objectFit(ImageFit.Auto).width('120px').height('120px')
        .visibility(this.replayVisible).border({ width: 0 }).borderStyle(BorderStyle.Dashed)
        .onClick(() => { this.startPlayOrResume(); })
      Image($r('app.media.icon_load')).objectFit(ImageFit.Auto).width('120px').height('120px')
        .visibility(this.loadingVisible).border({ width: 0 }).borderStyle(BorderStyle.Dashed)
    }.width('100%').backgroundColor('#000000').clip(true)
  }

  @Builder
  ProgressRow() {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
      Text(this.currentTime).width('100px').fontSize('20px').margin('20px')
      Slider({
        value: this.progressValue, min: 0, max: this.PROGRESS_MAX_VALUE, step: 1, style: SliderStyle.OutSet
      })
        .width('600px').blockColor(Color.Blue).trackColor(Color.Gray).selectedColor(Color.Blue)
        .showSteps(true).showTips(true).enabled(this.slideEnable)
        .onChange((value: number, mode: SliderChangeMode) => {
          if (mode === SliderChangeMode.End) {
            this.isSeekTo = true;
            this.mDestroyPage = false;
            this.setOverlay(Visibility.Visible, Visibility.None);
            const seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
            this.mIjkMediaPlayer.seekTo(seekValue + '');
            this.setProgress();
            this.isSeekTo = false;
          }
        })
      Text(this.totalTime).width('100px').fontSize('20px').margin('10px')
      Text('surface mode:').fontSize('25px').margin({ left: 10 })
      Toggle({ type: ToggleType.Switch, isOn: this.codecMode === VideoCodecMode.SURFACE })
        .selectedColor('#007DFF').switchPointColor('#FFFFFF')
        .onChange((isOn: boolean) => {
          this.codecMode = isOn ? VideoCodecMode.SURFACE : VideoCodecMode.BUFFER;
        })
    }
  }

  @Builder
  PlaybackControls() {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
      this.ActionButton($r('app.string.Play'), () => { this.startPlayOrResume(); })
      this.ActionButton($r('app.string.Pause'), () => { this.pause(); })
      this.ActionButton('stop', () => { this.stop(true); })
      this.ActionButton($r('app.string.Switch'), () => { void this.playNext(); })
    }
  }

  @Builder
  RecordControls() {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
      Button($r('app.string.startRecord')).visibility(this.recordButtonVisibility())
        .onClick(() => { this.startRecord(); }).width('400px').height('80px').margin('15px')
      Progress({ value: 0, total: 100, type: ProgressType.Ring })
        .width(50).color(Color.Blue).style({ strokeWidth: 10, status: ProgressStatus.LOADING })
        .visibility(this.recordProgressVisible)
      Button($r('app.string.stopRecord')).visibility(this.recordButtonVisibility())
        .onClick(() => { this.stopRecord(true); }).width('400px').height('80px').margin('15px')
    }
  }

  @Builder
  ResolutionPanel() {
    Column() {
      Text('分辨率状态').fontSize('38px').fontWeight(FontWeight.Medium).fontColor(Color.Black).margin({ bottom: 10 })
      Row() {
        Text('当前分辨率: ').fontSize('36px').fontColor(Color.Black)
        Text(this.currentWidth > 0 ? `${this.currentWidth} × ${this.currentHeight}` : '等待播放...')
          .fontSize('36px').fontWeight(FontWeight.Bold)
          .fontColor(this.resolutionChanged ? '#FF4500' : '#333333')
      }.width('100%').justifyContent(FlexAlign.Start).padding(12).borderRadius(8)
        .backgroundColor(this.resolutionChanged ? '#FFF0E0' : '#F5F5F5')

      Text('样片各段约 16:9(如 854×480~2560×1440)。按解码宽度映射视口(vp),Surface/BUFFER 便于对比分辨率切换。')
        .fontSize('22px').fontColor('#888888').margin({ top: 8 }).width('100%')

      if (this.resolutionHistoryText.length > 0) {
        Text('变化记录:').fontSize('28px').fontColor('#666666').margin({ top: 12 })
        Text(this.resolutionHistoryText).fontSize('26px').fontColor('#888888').margin({ top: 4 }).width('100%')
      }
      if (this.errorMsg.length > 0) {
        Text(this.errorMsg).fontSize('28px').fontColor('#FF0000').margin({ top: 12 })
      }
    }.width('100%').padding({ left: '15px', right: '15px', top: 8 })
  }

  @Builder
  ActionButton(label: ResourceStr | string, action: () => void) {
    Button(label).onClick(action).width('400px').height('80px').margin('15px')
  }

  private recordButtonVisibility(): Visibility {
    return this.recordProgressVisible === Visibility.Visible ? Visibility.None : Visibility.Visible;
  }

  private getHostResourceDir(): string {
    return this.getUIContext().getHostContext()?.resourceDir ?? '';
  }

  private isPageAlive(): boolean {
    return !this.mDestroyPage &&
      !IjkplayerMapManager.getInstance().destroyStatusMap.get(this.xcomponentId);
  }

  private runIfAlive(action: () => void): void {
    if (this.isPageAlive()) {
      action();
    }
  }

  private logCatchError(context: string, e: object): void {
    const err = e as BusinessError;
    LogUtils.getInstance()
      .error(`${context}. Cause:${err?.code ?? 'unknown'}, message:${err?.message ?? String(e)}`);
  }

  private showToast(message: ResourceStr | string, duration?: number): void {
    if (duration !== undefined) {
      this.getUIContext().getPromptAction().showToast({ message, duration });
    } else {
      this.getUIContext().getPromptAction().showToast({ message });
    }
  }

  private clearTimer(timerId: number): number {
    if (timerId) {
      clearTimeout(timerId);
    }
    return 0;
  }

  private clearResolutionTimers(): void {
    this.changeHighlightTimer = this.clearTimer(this.changeHighlightTimer);
    this.videoSizeApplyTimer = this.clearTimer(this.videoSizeApplyTimer);
  }

  private setOverlay(loading: Visibility, replay: Visibility): void {
    this.loadingVisible = loading;
    this.replayVisible = replay;
  }

  private applyVideoSizeLayout(width: number, height: number): void {
    const aspectRatio = width / height;
    if (aspectRatio < 1) {
      this.videoWidth = (width / height) * 100 + '%';
    } else {
      this.videoWidth = '100%';
    }
    this.videoAspectRatio = aspectRatio;
  }

  private configurePlayerOptions(): void {
    const player = IjkMediaPlayer.OPT_CATEGORY_PLAYER;
    const format = IjkMediaPlayer.OPT_CATEGORY_FORMAT;
    this.mIjkMediaPlayer.setOption(player, 'enable-accurate-seek', '1');
    this.mIjkMediaPlayer.setOption(player, 'max-buffer-size', '102400');
    this.mIjkMediaPlayer.setOption(player, 'min-frames', '100');
    this.mIjkMediaPlayer.setOption(player, 'start-on-prepared', '1');
    this.mIjkMediaPlayer.setOption(player, 'packet-buffering', '1');
    if (this.codecMode === VideoCodecMode.BUFFER) {
      this.mIjkMediaPlayer.setOption(player, 'overlay-format', '842094158');
      this.mIjkMediaPlayer.setOption(player, 'framedrop', '0');
    } else {
      this.mIjkMediaPlayer.setOption(player, 'framedrop', '5');
    }
    this.mIjkMediaPlayer.setOption(player, 'max_cached_duration', '3000');
    this.mIjkMediaPlayer.setOption(format, 'timeout', '10000000');
    this.mIjkMediaPlayer.setOption(format, 'connect_timeout', '10000000');
    this.mIjkMediaPlayer.setOption(player, 'mediacodec-all-videos', '1');
    this.mIjkMediaPlayer.setOption(player, 'mediacodec-hevc', '1');
  }

  private handleVideoSizeChanged(width: number, height: number, sar_num: number, sar_den: number): void {
    if (this.videoSizeApplyTimer) {
      clearTimeout(this.videoSizeApplyTimer);
    }
    this.videoSizeApplyTimer = setTimeout(() => {
      this.videoSizeApplyTimer = 0;
      if (!this.isPageAlive()) {
        return;
      }
      const prevWidth = this.currentWidth;
      const prevHeight = this.currentHeight;
      if (prevWidth > 0 && prevHeight > 0 && (prevWidth !== width || prevHeight !== height)) {
        const line = `${new Date().toLocaleTimeString()}: ${prevWidth}×${prevHeight} → ${width}×${height}`;
        this.resolutionHistoryText = this.resolutionHistoryText.length > 0 ?
          `${this.resolutionHistoryText}\n${line}` : line;
        this.resolutionChanged = true;
        this.changeHighlightTimer = this.clearTimer(this.changeHighlightTimer);
        this.changeHighlightTimer = setTimeout(() => {
          this.runIfAlive(() => { this.resolutionChanged = false; });
        }, 3000);
      }
      this.currentWidth = width;
      this.currentHeight = height;
      this.applyVideoSizeLayout(width, height);
      this.setOverlay(Visibility.None, Visibility.None);
      LogUtils.getInstance().LOGI(`DynamicResolution onVideoSizeChanged: ${width}x${height}, sar=${sar_num}/${sar_den}`);
    }, this.videoSizeApplyDelayMs);
  }

  private async handlePlaybackCompletion(): Promise<void> {
    if (!this.isPageAlive()) {
      return;
    }
    LogUtils.getInstance().LOGI('DynamicResolution onCompletion');
    this.setOverlay(Visibility.None, Visibility.Visible);
    this.slideEnable = false;
    this.progressValue = this.PROGRESS_MAX_VALUE;
    this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
    await this.stopRecord(false);
    this.stop(false);
  }

  private attachPlayerListeners(): void {
    const sizeListener: OnVideoSizeChangedListener = {
      onVideoSizeChanged: (w, h, sarNum, sarDen) => {
        if (w === 0 || h === 0) {
          return;
        }
        this.handleVideoSizeChanged(w, h, sarNum, sarDen);
      }
    };
    const preparedListener: OnPreparedListener = {
      onPrepared: () => this.runIfAlive(() => {
        LogUtils.getInstance().LOGI('DynamicResolution onPrepared');
        this.setOverlay(Visibility.None, Visibility.None);
      })
    };
    const seekListener: OnSeekCompleteListener = {
      onSeekComplete: () => this.runIfAlive(() => {
        LogUtils.getInstance().LOGI('DynamicResolution onSeekComplete');
        this.setOverlay(Visibility.None, Visibility.None);
        this.setProgress();
      })
    };
    const completionListener: OnCompletionListener = {
      onCompletion: () => { void this.handlePlaybackCompletion(); }
    };
    const errorListener: OnErrorListener = {
      onError: (what, extra) => this.runIfAlive(() => {
        LogUtils.getInstance().error(`DynamicResolution onError: what=${what}, extra=${extra}`);
        this.errorMsg = `播放错误: what=${what}, extra=${extra}`;
        if (IjkplayerMapManager.getInstance().playStatusMap.get(this.xcomponentId)) {
          this.stop(true);
        } else {
          this.playStatus = PlayStatus.INIT;
          this.stopProgressTask();
          this.slideEnable = false;
          this.setOverlay(Visibility.None, Visibility.None);
        }
      })
    };
    const infoListener: OnInfoListener = {
      onInfo: (what, extra) => this.runIfAlive(() => {
        LogUtils.getInstance().LOGI(`DynamicResolution onInfo: what=${what}, extra=${extra}`);
        this.setOverlay(Visibility.None, Visibility.None);
      })
    };
    this.mIjkMediaPlayer.setOnVideoSizeChangedListener(sizeListener);
    this.mIjkMediaPlayer.setOnPreparedListener(preparedListener);
    this.mIjkMediaPlayer.setOnSeekCompleteListener(seekListener);
    this.mIjkMediaPlayer.setOnCompletionListener(completionListener);
    this.mIjkMediaPlayer.setOnErrorListener(errorListener);
    this.mIjkMediaPlayer.setOnInfoListener(infoListener);
  }

  private getXComponentWidth(): string {
    if (this.currentWidth > 0 && this.currentHeight > 0) {
      const wVp = Math.min(this.currentWidth * this.decodePixelToVp, this.scaledWidthMaxVp);
      return `${wVp}vp`;
    }
    return this.videoWidth;
  }

  private startPlayOrResume() {
    if (!this.isVideoFileExists) {
      this.showToast('视频文件不存在,无法播放', 3000);
      return;
    }
    this.mDestroyPage = false;
    if (this.playStatus === PlayStatus.PAUSE) {
      this.mIjkMediaPlayer.start();
      this.playStatus = PlayStatus.PLAY;
      this.setProgress();
      return;
    }
    if (this.playStatus === PlayStatus.INIT) {
      this.startPlay();
    }
  }

  private startPlay() {
    if (!this.videoUrl || this.videoUrl.trim().length === 0) {
      this.errorMsg = '未解析到本地样片路径,请确认 resourceDir 与 resfile 资源';
      return;
    }
    this.errorMsg = '';
    if (this.codecMode === VideoCodecMode.SURFACE && !this.mContext) {
      this.errorMsg = 'Surface 模式需等待上方 XComponent 加载完成后再播放';
      return;
    }
    if (IjkplayerMapManager.getInstance().destroyStatusMap.get(this.xcomponentId)) {
      return;
    }

    this.setOverlay(Visibility.Visible, Visibility.None);
    if (this.mContext) {
      this.mIjkMediaPlayer.setContext(this.mContext, this.xcomponentId);
    }
    if (this.playStatus === PlayStatus.INIT) {
      this.mDestroyPage = false;
      this.stopProgressTask();
      this.startProgressTask();
      this.mIjkMediaPlayer.reset();
    }

    this.playStatus = PlayStatus.PLAY;
    this.resolutionHistoryText = '';
    this.currentWidth = 0;
    this.currentHeight = 0;
    this.mIjkMediaPlayer.setDebug(true);
    this.mIjkMediaPlayer.native_setup(this.codecMode);
    this.mIjkMediaPlayer.setVolume('1', '1');
    this.mIjkMediaPlayer.setDataSource(this.videoUrl);
    this.configurePlayerOptions();
    this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
    this.mIjkMediaPlayer.setLoopCount(false);
    this.attachPlayerListeners();
    this.mIjkMediaPlayer.setMessageListener();
    this.mIjkMediaPlayer.prepareAsync();
    this.mIjkMediaPlayer.start();
    IjkplayerMapManager.getInstance().playStatusMap.set(this.xcomponentId, true);
  }

  private pad2(num: number): string {
    return num < 10 ? '0' + num : num + '';
  }

  private stringForTime(timeMs: number): string {
    const totalSeconds = Math.floor(Math.max(0, timeMs) / 1000);
    const secs = totalSeconds % 60;
    const mins = Math.floor(totalSeconds / 60) % 60;
    const hours = Math.floor(totalSeconds / 3600);
    if (hours > 0) {
      return `${this.pad2(hours)}:${this.pad2(mins)}:${this.pad2(secs)}`;
    }
    return `${this.pad2(mins)}:${this.pad2(secs)}`;
  }

  private setProgress() {
    if (!this.isPageAlive() || !IjkplayerMapManager.getInstance().playStatusMap.get(this.xcomponentId)) {
      return;
    }
    let position = this.mIjkMediaPlayer.getCurrentPosition();
    const duration = this.mIjkMediaPlayer.getDuration();
    if (duration > 0) {
      this.slideEnable = true;
      this.progressValue = Math.min(this.PROGRESS_MAX_VALUE, position / duration * 100);
    }
    this.totalTime = this.stringForTime(duration);
    this.currentTime = this.stringForTime(Math.min(position, duration));
  }

  private startProgressTask() {
    this.stopProgressTask();
    this.updateProgressTimer = setInterval(() => {
      if (!this.isPageAlive()) {
        this.stopProgressTask();
        return;
      }
      if (this.playStatus === PlayStatus.PLAY && !this.isSeekTo) {
        this.setProgress();
      }
    }, 300);
  }

  private stopProgressTask() {
    if (this.updateProgressTimer) {
      clearInterval(this.updateProgressTimer);
      this.updateProgressTimer = 0;
    }
  }

  private pause() {
    if (this.mIjkMediaPlayer.isPlaying()) {
      this.mIjkMediaPlayer.pause();
      this.setProgress();
      this.mDestroyPage = true;
      this.playStatus = PlayStatus.PAUSE;
    }
  }

  private async playNext() {
    if (Date.now() - this.last <= 600) {
      return;
    }
    this.last = Date.now();
    this.curIndex = (this.curIndex + 1) % this.videoUrls.length;
    this.playStatus = PlayStatus.INIT;
    await this.stopRecord(false);
    this.stop(true);
    this.videoUrl = this.getHostResourceDir() + this.videoUrls[this.curIndex];
    this.updateVideoFileExists();
    this.startPlayOrResume();
  }

  private updateVideoFileExists(): void {
    try {
      fs.accessSync(this.videoUrl);
      this.isVideoFileExists = true;
    } catch {
      this.isVideoFileExists = false;
    }
  }

  private startRecord() {
    try {
      if (this.mIjkMediaPlayer.isRecord()) {
        this.showToast($r('app.string.recordIng'));
        return;
      }
      this.recordSaveFilePath = this.getUIContext().getHostContext()?.cacheDir + '/record.mp4';
      this.mIjkMediaPlayer.setRecordDefaultFrameRate('30', false);
      const result = this.mIjkMediaPlayer.startRecord(this.recordSaveFilePath);
      this.recordSessionActive = result;
      this.showToast(result ? $r('app.string.start_record_success') : $r('app.string.start_record_failed'));
    } catch (e) {
      this.logCatchError('Failed to start record', e);
    }
  }

  private async stopRecord(isShowTip: boolean) {
    let isRecord = false;
    try {
      isRecord = this.mIjkMediaPlayer.isRecord();
    } catch (e) {
      this.logCatchError('Failed to check record status', e);
    }
    if (!isRecord && !this.recordSessionActive) {
      if (isShowTip) {
        this.showToast($r('app.string.record_not_enabled'));
      }
      return;
    }
    this.recordSessionActive = false;
    this.recordProgressVisible = Visibility.Visible;
    try {
      const result = await this.mIjkMediaPlayer.stopRecord();
      this.recordProgressVisible = Visibility.None;
      if (!result) {
        this.showToast($r('app.string.stop_record_failed'));
        return;
      }
      await this.saveRecordToAlbum();
    } catch (e) {
      this.recordProgressVisible = Visibility.None;
      this.logCatchError('Failed to stop record', e);
    }
  }

  private async saveRecordToAlbum(): Promise<void> {
    const hostContext = this.getUIContext().getHostContext();
    if (!hostContext) {
      this.showToast($r('app.string.stop_record_failed'));
      return;
    }
    try {
      const atManager = abilityAccessCtrl.createAtManager();
      await atManager.requestPermissionsFromUser(hostContext, ['ohos.permission.WRITE_IMAGEVIDEO']);
      const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(hostContext);
      await new Promise<void>((resolve, reject) => {
        phAccessHelper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4',
          { title: 'record_' + new Date().getTime() }, (err, uri) => {
            if (uri !== undefined) {
              let recordFile: fs.File | undefined;
              let albumFile: fs.File | undefined;
              try {
                recordFile = fs.openSync(this.recordSaveFilePath);
                albumFile = fs.openSync(uri, fs.OpenMode.READ_WRITE);
                fs.copyFileSync(recordFile.fd, albumFile.fd);
                this.showToast($r('app.string.stop_record_success'));
                LogUtils.getInstance().LOGI(`createAsset success uri:${uri}`);
                resolve();
              } catch (copyErr) {
                this.showToast($r('app.string.stop_record_failed'));
                this.logCatchError('Failed to copy record file', copyErr as object);
                reject(copyErr);
              } finally {
                if (recordFile !== undefined) {
                  fs.closeSync(recordFile);
                }
                if (albumFile !== undefined) {
                  fs.closeSync(albumFile);
                }
              }
            } else {
              this.showToast($r('app.string.stop_record_failed'));
              this.logCatchError('createAsset failed', err);
              reject(err);
            }
          });
      });
    } catch (e) {
      this.showToast($r('app.string.stop_record_failed'));
      this.logCatchError('Failed to save record to album', e);
    }
  }

  private stop(resetChrome: boolean = true) {
    if (!IjkplayerMapManager.getInstance().playStatusMap.get(this.xcomponentId)) {
      return;
    }
    this.playStatus = PlayStatus.INIT;
    this.mDestroyPage = true;
    this.clearResolutionTimers();
    this.mIjkMediaPlayer.stop();
    this.mIjkMediaPlayer.release();
    this.stopProgressTask();
    this.progressValue = 0;
    this.currentTime = '00:00';
    this.totalTime = '00:00';
    this.slideEnable = false;
    this.videoWidth = '100%';
    IjkplayerMapManager.getInstance().playStatusMap.set(this.xcomponentId, false);
    if (resetChrome) {
      this.setOverlay(Visibility.None, Visibility.None);
    } else {
      this.loadingVisible = Visibility.None;
    }
  }
}