/*
 * 修改设备名称页
 * EZOpenSDK
 *
 * Created by junecheng on 2024/3/7.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */
import emitter from '@ohos.events.emitter'
import EmitterEvents from '../../global/EmitterEvents'
import { EZDeviceInfo, EZOpenSDK } from '@ohos/EZOpenSDK'

import RouterManager from '../../global/RouterManager/RouterManager'

import { NavigationView } from '../../global/view/NavigationView'

@Entry
@Component
export struct EZEditDeviceNamePage {
  // 设备名称
  @State deviceName: string = ''
  private deviceInfo: EZDeviceInfo = new EZDeviceInfo()

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

  aboutToAppear() {
    this.deviceInfo = RouterManager.getParams() as EZDeviceInfo
  }

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

  saveNameAction() {
    EZOpenSDK.setDeviceName(this.deviceName, this.deviceInfo.deviceSerial, (error) => {

      if (!error) {
        emitter.emit({ eventId: EmitterEvents.EZDeviceNameRefresh }, { data: { 'name': this.deviceName } })
        RouterManager.back()
      } else {
        console.error(`saveNameAction error:${error}`)
      }
    })
  }

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

  build() {
    Column() {
      NavigationView({
        title: $r('app.string.device_modify_name_title'),
        rightNavTitle: $r('app.string.cancel'),
      })
      Column() {
        TextInput({ text: this.deviceName, placeholder: $r('app.string.device_input_placeholder') })
          .maxLength(50)
          .backgroundColor(Color.White)
          .borderRadius(0)
          .height(40)
          .margin({ top: 50 })
          .onChange((value) => {
            this.deviceName = value
          })
        Text($r('app.string.device_notice_placeholder'))
          .fontColor(Color.Gray)
          .width('100%')
          .margin({ left: 16, top: 16 })
        Button($r('app.string.device_save'))
          .backgroundColor($r('app.color.ez_text_blue'))
          .width(285)
          .height(40)
          .margin({ top: 32 })
          .onClick(() => {
            this.saveNameAction()
          })
      }
    }.backgroundColor($r('app.color.message_cell_select_color'))
    .height('100%')
  }
}