/*
 * P2P测试页面
 * EZOpenSDK
 *
 * Created by junecheng on 2026/1/4.
 * Copyright (c) 2026年 Ezviz. All rights reserved.
 */
import {
  EZDeviceRecordFile,
  EZVideoRecordTypeEx,
  EZOpenSDK,
  EZTimeUtil,
  EZVideoRecordLocation,
  EZDeviceRecordInfo
} from "@ohos/EZOpenSDK"
import TimeUtil from '../../utils/EZTimeUtil'
import EZToastUtil from "../../utils/EZToastUtil"
import { NavigationView } from "../../global/view/NavigationView"
import { PullToRefresh, PullToRefreshConfigurator } from "@ohos/pulltorefresh"
import GlobalKit from "../../global/GlobalKit"
import Constants from "../../global/DemoConfig"

@Entry
@Component
@Preview
struct EZDeviceRecordDirectQueryPage {
  private readonly TAG: string = `${EZDeviceRecordDirectQueryPage.name}:`
  private pageSize: number = 20
  // 录像查询开始时间
  private endTime: Date = new Date()
  // 录像查询结束时间
  private beginTime: Date = new Date()
  // 登录时指定的设备序列号
  private specificDevice: string = ''
  private scroller: Scroller = new Scroller()
  private refreshConfigurator: PullToRefreshConfigurator = new PullToRefreshConfigurator()
  // 录像列表
  @State deviceRecordArray: Array<EZDeviceRecordFile> = []
  // 上一次录像查询对象
  lastestDeviceRecordInfo: EZDeviceRecordInfo = new EZDeviceRecordInfo()
  // 列表刷新事件
  onRefresh: () => Promise<string> = () => {
    return new Promise<string>((resolve, reject) => {
      this.getDeviceRecordList(this.beginTime, resolve)
    })
  }
  // 列表加载事件
  onLoadMore: () => Promise<string> = () => {
    return new Promise<string>((resolve, reject) => {
      this.getDeviceRecordList(this.lastestDeviceRecordInfo.nextFileTime, resolve)
    })
  }

  // ------------------------ 生命周期 ------------------------

  aboutToAppear() {
    // 获取开始结束时间
    let startAndEndOfDay = EZTimeUtil.getStartAndEndOfDay(new Date())
    this.beginTime = startAndEndOfDay.startOfDay
    this.endTime = startAndEndOfDay.endOfDay

    this.specificDevice = GlobalKit.getInstance().getSavedData(Constants.UserDevSerial) as string
    this.onRefresh()
  }

  aboutToDisappear() {
  }

  // ------------------------ Actions ------------------------


  // ------------------------ 网络请求 ------------------------

  /*
   * 获取设备录像接口
   */
  getDeviceRecordList(beginTime: Date, resolve?: (value: string | PromiseLike<string>) => void) {
    EZOpenSDK.searchRecordFileFromDeviceEx(this.specificDevice, 1, beginTime, this.endTime,
      EZVideoRecordTypeEx.EZVideoRecordTypeExNone, false, EZVideoRecordLocation.EZVideoRecordLocationLocal,
      this.pageSize, (deviceRecordInfo, error) => {
        if (resolve) {
          resolve(EZTimeUtil.getCurrentTimeString())
        }
        if (error) {
          this.deviceRecordArray = []
          EZToastUtil.showToast(`error code: ${error.code}`)
          return
        }
        if (beginTime == this.beginTime) {
          this.deviceRecordArray = []
        }
        this.lastestDeviceRecordInfo = deviceRecordInfo
        this.deviceRecordArray = this.deviceRecordArray.concat(deviceRecordInfo.deviceRecordFileList)

        // 到顶了 不能加载更多
        this.refreshConfigurator.setHasLoadMore(deviceRecordInfo.deviceRecordFileList &&
          deviceRecordInfo.deviceRecordFileList.length == this.pageSize)
      }
    )
  }

  // ------------------------ 自定义方法 ------------------------

  // ------------------------ UI ------------------------

  build() {
    Column() {
      NavigationView({
        title: 'NVR下的IPC设备录像直查'
      })
      Column() {
        PullToRefresh({
          data: this.deviceRecordArray,
          scroller: this.scroller,
          customList: () => {
            this.DeviceRecordListView()
          },
          onAnimLoading: () => {
          },
          onRefresh: this.onRefresh,
          onLoadMore: this.onLoadMore,
          customLoad: null,
          customRefresh: null,
          refreshConfigurator: this.refreshConfigurator
            .setMaxTranslate(60)
            .setRefreshTextSize(12)
            .setLoadTextSize(12)
            .setLoadTextLoading('正在加载更多的数据...')
        })
          .height('100%')
      }
      .alignItems(HorizontalAlign.Start)
      .width('100%')
    }
    .width('100%').height('100%')
  }

  @Builder
  DeviceRecordListView() {
    List({ scroller: this.scroller }) {
      ForEach(this.deviceRecordArray, (item: EZDeviceRecordFile, index) => {
        ListItem() {
          Column() {
            Text(`${EZTimeUtil.dateFormat(item.startTime, 'HH:mm:ss')} - ${EZTimeUtil.dateFormat(item.stopTime,
              'HH:mm:ss')} (${TimeUtil.formatTimeDifference(item.stopTime, item.startTime).toString()})`)
              .height(44)
              .margin({ left: 15 })
            Divider()
          }.alignItems(HorizontalAlign.Start)
        }
      })
    }
    .edgeEffect(EdgeEffect.None)
  }
}