/*
 * 设备设置页面
 * EZOpenSDK
 *
 * Created by junecheng on 2024/4/5.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */

import emitter from '@ohos.events.emitter'
import EZToastUtil from '../../utils/EZToastUtil'
import GlobalKit from '../../global/GlobalKit'
import RouterManager from '../../global/RouterManager/RouterManager'
import EmitterEvents from '../../global/EmitterEvents'

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

import { EZDeviceInfo, EZDeviceVersion, EZErrorCode, EZOpenSDK } from '@ohos/EZOpenSDK'

@Entry
@Component
struct EZSettingPage {
  // 是否显示加载进程
  @State isLoadingShow: boolean = false
  // 布局数组
  @State settingList: Array<ResourceStr | Array<ResourceStr>> = []
  // 设备版本信息对象
  @State deviceVersion: EZDeviceVersion = new EZDeviceVersion()
  // 活动检测开关是否可用【Toggle组件有bug，需要加个enable状态来处理】
  @State defenceSwitchEnable: boolean = true
  // 活动检测开关状态
  @State defenceSwitchOn: boolean = false
  // 视频图片加密开关是否可用【Toggle组件有bug，需要加个enable状态来处理】
  @State videoEncryptSwitchEnable: boolean = true
  // 视频图片加密开关状态
  @State videoEncryptSwitchOn: boolean = false
  // 硬解码开关状态
  @State hdSwitchOn: boolean = false
  @State deviceName: string = ''
  private deviceInfo: EZDeviceInfo = new EZDeviceInfo()
  // 验证码输入内框容
  @State verifyCodeDialogInputContent: string = ''
  // 视频图片加密关闭，验证码验证校验弹框控制器
  private verifyCodeDialogController: CustomDialogController = new CustomDialogController({
    customStyle: true,
    builder: VerifyCodeDialog({
      title: $r('app.string.setting_device_security_check'),
      message: $r('app.string.setting_input_code_plz'),
      placeholder: $r('app.string.device_input_vierify_code'),
      inputContent: this.verifyCodeDialogInputContent,
      confirmClick: () => {
        this.setDeviceEncryptStatus(this.deviceInfo.deviceSerial, this.verifyCodeDialogInputContent, false)
      },
      cancelClick: () => {
        this.videoEncryptSwitchOn = true
        this.videoEncryptSwitchEnable = true
      }
    }),
    alignment: DialogAlignment.Center,
    autoCancel: false
  })
  // 设备删除 二次确认弹框控制器
  private deleteDialogController: CustomDialogController = new CustomDialogController({
    customStyle: true,
    alignment: DialogAlignment.Bottom,
    builder: SheetDialog({
      titles: [$r('app.string.delete')],
      titleColor: Color.Red,
      confirmClick: () => {
        this.isLoadingShow = true
        EZOpenSDK.deleteDevice(this.deviceInfo.deviceSerial, (error) => {
          this.isLoadingShow = false
          if (error) {
            EZToastUtil.showToast($r('app.string.device_delete_failed', `${error.code}`))
          } else {
            // 发出刷新通知
            emitter.emit({ eventId: EmitterEvents.EZDeviceListPageRefresh })
            RouterManager.back()
          }
        })
      }
    }),
    autoCancel: true,
    offset: { dx: 0, dy: -25 }
  })

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

  aboutToAppear() {
    this.initData()
    emitter.on({ eventId: EmitterEvents.EZDeviceNameRefresh }, (emitterData) => {
      let data: Map<string, Object> = emitterData.data as Map<string, Object>
      if (data['name']) {
        this.deviceName = `${data['name'] ?? ''}  >`
        emitter.emit({ eventId: EmitterEvents.EZDeviceListPageRefresh })
      }
    })
  }

  aboutToDisappear() {
    emitter.off(EmitterEvents.EZDeviceNameRefresh)
  }

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

  /*
   * 设备名修改Action
   */
  updateDeviceNameAction = () => {
    RouterManager.pushUrl(RouterManager.editDeviceNamePage, this.deviceInfo)
  }
  /*
   * 设备固件升级Action
   */
  upgradeDeviceAction = () => {
    if (this.deviceVersion?.isNeedUpgrade > 0) {
      RouterManager.pushUrl(RouterManager.deviceUpgradePage,
        { deviceVersion: this.deviceVersion, deviceSerial: this.deviceInfo.deviceSerial })
    }
  }

  /*
   * 活动监测开关Action
   */
  defenceSwitchAction(isOn: boolean) {
    this.defenceSwitchEnable = false
    this.setDeviceDefenceStatus(isOn)
  }

  /*
   * 视频加密开关Action
   */
  encryptSwitchAction(isOn: boolean) {
    this.videoEncryptSwitchEnable = false
    // 打开直接调用api，关闭需要二次确认
    if (isOn) {
      this.setDeviceEncryptStatus(this.deviceInfo.deviceSerial, '', true)
    } else {
      this.verifyCodeDialogController.open()
    }
  }

  /**
   * 硬解码开关Action
   * @param isOn
   */
  hdSwitchAction(isOn: boolean) {
    this.hdSwitchOn = isOn
    GlobalKit.getInstance().saveData('EZVideoPlayHardDecodingStatus_' + this.deviceInfo.deviceSerial, isOn)
  }

  /*
   * 设备删除Action
   */
  deleteDeviceAction() {
    this.deleteDialogController.open()
  }

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

  /*
   * 加密开关请求
   */
  setDeviceEncryptStatus(deviceSerial: string, verifyCode: string, isEncrypt: boolean) {
    this.isLoadingShow = true
    EZOpenSDK.setDeviceEncryptStatus(deviceSerial, verifyCode, isEncrypt, (error) => {
      this.videoEncryptSwitchEnable = true
      this.isLoadingShow = false
      if (error) {
        EZToastUtil.showToast($r('app.string.setting_opration_fail'))
        this.videoEncryptSwitchOn = !isEncrypt
      } else {
        EZToastUtil.showToast($r('app.string.setting_opration_success'))
        this.videoEncryptSwitchOn = isEncrypt
        // 发出刷新通知
        emitter.emit({ eventId: EmitterEvents.EZDeviceEncrptStatusRefresh }, { data: { 'isEncrypt': isEncrypt } })
      }
    })
  }

  setDeviceDefenceStatus(isOn: boolean) {
    this.isLoadingShow = true
    EZOpenSDK.setDefence(isOn, this.deviceInfo.deviceSerial, (error) => {
      this.defenceSwitchEnable = true
      this.isLoadingShow = false
      if (error) {
        this.defenceSwitchOn = !isOn
        EZToastUtil.showToast($r('app.string.setting_opration_fail'))
      } else {
        EZToastUtil.showToast($r('app.string.setting_opration_success'))
        this.defenceSwitchOn = isOn
        // 发出刷新通知
        emitter.emit({ eventId: EmitterEvents.EZDeviceDefenceStatusRefresh }, { data: { 'isDefence': isOn } })
      }
    })
  }

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

  initData() {
    this.deviceInfo = RouterManager.getParams() as EZDeviceInfo

    this.settingList.push($r('app.string.setting_device_name'))
    this.settingList.push($r('app.string.setting_device_serial'))
    this.settingList.push([$r('app.string.setting_device_version'), $r('app.string.setting_device_new_version')])
    if (this.deviceInfo?.cameraNum == 0) {
      let str = '防护状态：'
      if (this.deviceInfo?.defence == 0) {
        str += '睡眠模式'
      } else if (this.deviceInfo?.defence == 8) {
        str += '在家模式'
      } else {
        str += '外出模式'
      }
      this.settingList.push(str)
      this.settingList.push($r('app.string.setting_ignore_code'))
    } else {
      this.settingList.push($r('app.string.setting_action_detect'))
      this.settingList.push($r('app.string.setting_secure_code'))
    }
    this.settingList.push($r('app.string.setting_hardware_decoding'))
    this.settingList.push($r('app.string.delete'))

    this.isLoadingShow = true
    EZOpenSDK.getDeviceVersion(this.deviceInfo.deviceSerial, (version, error) => {
      this.deviceVersion = version
      this.isLoadingShow = false
    })
    this.defenceSwitchOn = this.deviceInfo.defence > 0
    this.videoEncryptSwitchOn = this.deviceInfo.isEncrypt > 0
    this.hdSwitchOn = GlobalKit.getInstance()
      .getSavedData('EZVideoPlayHardDecodingStatus_' + this.deviceInfo.deviceSerial) as boolean
    this.deviceName = (this.deviceInfo.deviceName ? this.deviceInfo.deviceName : '') + ' >'
  }

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

  build() {
    Column() {
      NavigationView({
        title: $r('app.string.setting_device_set_title')
      })
      Stack() {
        List({ space: 24 }) {
          ForEach(this.settingList, (item: string | Array<string>, index) => {
            ListItem() {
              if (index == 0) {
                Row() { // 设备名
                  Text(item as string).height(40)
                    .fontSize(16).fontColor(Color.Black)
                  Text(this.deviceName)
                    .fontSize(16).fontColor(Color.Gray)
                }
                .width('100%')
                .padding({ left: 16, right: 16 })
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.SpaceBetween)
                .onClick(this.updateDeviceNameAction)
              } else if (index == 1) {
                Row() { // 序列号
                  Text(item as string).height(40)
                    .fontSize(16).fontColor(Color.Black)
                  Text(this.deviceInfo.deviceSerial ? this.deviceInfo.deviceSerial : '')
                    .fontSize(16).fontColor(Color.Gray)
                }.width('100%').padding({ left: 16, right: 16 })
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.SpaceBetween)
              } else if (index == 2) {
                Column() {
                  Row() { // 当前版本
                    Text((item as Array<string>)[0]).height(40)
                      .fontSize(16).fontColor(Color.Black)
                    Text(this.deviceVersion?.currentVersion ? this.deviceVersion?.currentVersion : '')
                      .fontSize(16).fontColor(Color.Gray)
                  }.width('100%').padding({ left: 16, right: 16 })
                  .backgroundColor(Color.White)
                  .justifyContent(FlexAlign.SpaceBetween)

                  Divider()

                  Row() { // 最新版本
                    Row() {
                      Text((item as Array<string>)[1]).height(40).fontSize(16).fontColor(Color.Black)
                      Image($r('app.media.upgrade')).objectFit(ImageFit.Contain).height(20).margin({ left: 15 })
                        .visibility(this.deviceVersion?.isNeedUpgrade > 0 ? Visibility.Visible : Visibility.Hidden)
                    }

                    Text(this.deviceVersion?.isNeedUpgrade > 0 ? this.deviceVersion?.newestVersion :
                      this.deviceVersion?.currentVersion)
                      .fontSize(16).fontColor(Color.Black)
                  }
                  .width('100%')
                  .padding({ left: 16, right: 16 })
                  .backgroundColor(Color.White)
                  .justifyContent(FlexAlign.SpaceBetween)
                  .onClick(this.upgradeDeviceAction)
                }
              } else if (index == 3) {
                Row() { // 活动检测提醒
                  Text(item as string).width('100').height(40)
                    .fontSize(16).fontColor(Color.Black)
                  Toggle({ type: ToggleType.Switch, isOn: this.defenceSwitchOn })
                    .enabled(this.defenceSwitchEnable)
                    .selectedColor($r('app.color.ez_text_blue'))
                    .onClick(() => {
                      this.defenceSwitchAction(!this.defenceSwitchOn)
                    })
                }.width('100%').padding({ left: 16, right: 16 })
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.SpaceBetween)

              } else if (index == 4) {
                Row() { // 视频图片加密
                  Text(item as string).width('100').height(40)
                    .fontSize(16).fontColor(Color.Black)
                  Toggle({ type: ToggleType.Switch, isOn: this.videoEncryptSwitchOn })
                    .enabled(this.videoEncryptSwitchEnable)
                    .selectedColor($r('app.color.ez_text_blue'))
                    .onClick(() => {
                      this.encryptSwitchAction(!this.videoEncryptSwitchOn)
                    })
                }
                .width('100%')
                .padding({ left: 16, right: 16 })
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.SpaceBetween)
                .backgroundColor(Color.White)

              } else if (index == 5) {
                Row() { // 硬解码
                  Text(item as string).width('100').height(40)
                    .fontSize(16).fontColor(Color.Black)
                  Toggle({ type: ToggleType.Switch, isOn: this.hdSwitchOn })
                    .selectedColor($r('app.color.ez_text_blue'))
                    .onClick(() => {
                      this.hdSwitchAction(!this.hdSwitchOn)
                    })
                }.width('100%').padding({ left: 16, right: 16 })
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.SpaceBetween)

              } else if (index == 6) {
                Row() { // 删除
                  Text(item as string).height(40)
                    .fontSize(16).fontColor(Color.Red).align(Alignment.Center)
                }.width('100%')
                .backgroundColor(Color.White)
                .justifyContent(FlexAlign.Center)
                .onClick(() => {
                  this.deleteDeviceAction()
                })
              }
            }.width('100%')
          }, (item: string | Array<string>) => {
            return JSON.stringify(item)
          })
        }.width('100%').padding({ top: 24 })

        // 加载进程
        LoadingProgress().width(40).aspectRatio(1)
          .visibility(this.isLoadingShow ? Visibility.Visible : Visibility.Hidden)
      }
    }.backgroundColor($r('app.color.message_cell_select_color'))
    .height('100%')
  }
}