/*
 * P2P测试页面
 * EZOpenSDK
 *
 * Created by junecheng on 2025/12/8.
 * Copyright (c) 2025年 Ezviz. All rights reserved.
 */
import { EZDeviceInfo, EZOpenSDK } from "@ohos/EZOpenSDK"
import EZToastUtil from "../../utils/EZToastUtil"
import { NavigationView } from "../../global/view/NavigationView"

@Entry
@Component
@Preview
struct EZP2pTestPage {
  private readonly TAG: string = `${EZP2pTestPage.name}:`
  @State p2pInfoValue: string = ''
  // 设备列表
  @State deviceArray: Array<EZDeviceInfo> = []
  @State processedPreconnectSerialArray: Array<string> = []
  toDoPreconnectSerialArray: Array<string> = []
  @State selectDevice: EZDeviceInfo | undefined = undefined
  // 定时器ID
  timerIntervalID: number = 0

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

  aboutToAppear() {
    this.getDeviceList()
    this.timerIntervalID = setInterval(this.refreshAction, 1000)
  }

  aboutToDisappear() {
    clearInterval(this.timerIntervalID)
  }

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

  /** 连接Action */
  connectAction = () => {
    if (!this.selectDevice) {
      EZToastUtil.showToast('请先选择一个设备')
      return
    }
    EZOpenSDK.startP2PPreconnect(this.selectDevice.deviceSerial)
  }
  /** 断开连接Action */
  disconnectAction = () => {
    if (!this.selectDevice) {
      EZToastUtil.showToast('请先选择一个设备')
      return
    }
    EZOpenSDK.clearP2PPreconnect(this.selectDevice.deviceSerial)
  }
  /** 设备p2p预连接是否成功Action */
  isPreConnectionSucceedAction = async () => {
    if (!this.selectDevice) {
      EZToastUtil.showToast('请先选择一个设备')
      return
    }
    let isSuccess = await EZOpenSDK.isPreConnectionSucceed(this.selectDevice.deviceSerial)
    EZToastUtil.showToast(isSuccess ? 'Success' : 'Failed')
  }
  /** 刷新Action */
  refreshAction = () => {
    this.processedPreconnectSerialArray = EZOpenSDK.getAllProcessedPreconnectSerials()
    this.toDoPreconnectSerialArray = EZOpenSDK.getAllToDoPreconnectSerials()
    this.p2pInfoValue =
      `p2p预连接设备数量：${this.processedPreconnectSerialArray.length}\n正在排队的p2p预连接设备数量：${this.toDoPreconnectSerialArray.length}`
  }

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

  /*
   * 获取设备列表接口
   */
  getDeviceList() {
    EZOpenSDK.getDeviceList(0, 20, (deviceList, totalCount, error) => {
      this.deviceArray = deviceList
    })
  }

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

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

  build() {
    Column() {
      NavigationView({
        title: 'P2P测试'
      })
      Column() {
        Row() {
          Button('连接')
            .height(40)
            .width(100)
            .fontSize(14)
            .fontColor(Color.White)
            .backgroundColor(Color.Orange)
            .onClick(this.connectAction)
          Button('断开')
            .height(40)
            .width(100)
            .fontSize(14)
            .fontColor(Color.White)
            .backgroundColor(Color.Orange)
            .margin({ left: 10 })
            .onClick(this.disconnectAction)
          Button('预连接结果')
            .height(40)
            .width(100)
            .fontSize(14)
            .fontColor(Color.White)
            .backgroundColor(Color.Orange)
            .margin({ left: 10 })
            .padding(0)
            .onClick(this.isPreConnectionSucceedAction)
        }.padding(10)

        Text(this.p2pInfoValue).fontColor(Color.Orange).padding(10)
        List() {
          ForEach(this.deviceArray, (item: EZDeviceInfo, index) => {
            ListItem() {
              Column() {
                Text(item.deviceName ? item.deviceName : `${item.category}(${item.deviceSerial})`)
                  .textAlign(TextAlign.Start)
                  .width('100%')
                  .height('100%')
                  .padding({ left: 15 })
                  .fontColor(this.processedPreconnectSerialArray?.indexOf(item.deviceSerial) >= 0 ? Color.Orange :
                  Color.Black)
                  .backgroundColor(this.selectDevice?.deviceSerial == item.deviceSerial ? $r('app.color.C6C6C8') :
                  Color.White)
                Divider()
              }.height(45)
              .onClick((): void => {
                this.selectDevice = item
              })
            }
          })
        }

        Text('橙色:p2p已连接或正在连接中  黑色:p2p未连接').fontColor(Color.Gray).fontSize(14).padding(15)
      }
      .alignItems(HorizontalAlign.Start)
      .width('100%')
    }
    .width('100%').height('100%')
  }
}