/*
 * 设备查询结果页面
 * EZOpenSDK
 *
 * Created by junecheng on 2024/3/22.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */

import { emitter } from '@kit.BasicServicesKit'
import { EZErrorCode, EZOpenSDK, EZProbeDeviceInfo } from '@ohos/EZOpenSDK'

import EZBusinessTool from '../../businesstool/EZBusinessTool'
import EZToastUtil from '../../utils/EZToastUtil'
import EmitterEvents from '../../global/EmitterEvents'
import GlobalKit from '../../global/GlobalKit'
import RouterManager from '../../global/RouterManager/RouterManager'

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

@Entry
@Component
struct EZDeviceResultPage {
  @State showLoadingProgress: boolean = true
  @State showResultImage: boolean = false
  @State showNoWifiImage: boolean = false
  // 设备序列号显示
  @State resultText: ResourceStr = $r('app.string.ad_get_device_info_msg')
  // 状态文本、颜色
  @State showStatusText: boolean = false
  @State statusText: ResourceStr = $r('app.string.ad_get_device_info_status_no_wifi')
  @State statusTextColor: Color = 0xD55A2D
  // 按钮状态、文本
  @State showActionBtn: boolean = false
  @State actionBtnText: Resource = $r('app.string.ad_connect_net')
  // 配网能力
  supportApMode: boolean = false
  supportWiFi5G: boolean = false

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

  aboutToAppear() {
    this.searchDeviceInfo()
  }

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

  nextAction = () => {
    let actionText = getContext().resourceManager.getStringSync(this.actionBtnText)
    if (actionText == getContext().resourceManager.getStringSync($r('app.string.ad_connect_net'))) { // 连接网络
      RouterManager.pushUrl(RouterManager.wifiTipsPage, { supportApMode: this.supportApMode, supportWiFi5G: this.supportWiFi5G })
    } else if (actionText == getContext().resourceManager.getStringSync($r('app.string.ad_add'))) { // 添加
      if (GlobalKit.getInstance().deviceVerifyCode) {
        this.addDevice()
      } else {
        this.showSetPassword()
      }
    } else { // 重试
      this.searchDeviceInfo()
    }
  }

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

  searchDeviceInfo() {
    EZOpenSDK.probeDeviceInfo(GlobalKit.getInstance().deviceSerialNo, GlobalKit.getInstance()
      .deviceModel, (deviceInfo, error) => {
      this.showLoadingProgress = false
      this.showResultImage = true
      this.resultText = GlobalKit.getInstance().deviceSerialNo
      if (error) {
        if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ADDED_MYSELF ||
          error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_ADDED ||
          error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED_MYSELF) {
          this.statusTextColor = Color.Black
          this.statusText = $r('app.string.ad_already_added')
          this.showStatusText = true
        } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_IS_ADDED ||
          error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED) {
          this.statusTextColor = Color.Black
          this.statusText = $r('app.string.ad_added_by_others')
          this.showStatusText = true
        } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_NOT_EXISTS) {
          this.statusTextColor = Color.Black
          this.statusText = $r('app.string.ad_not_exist')
          this.showStatusText = true
        } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_NOT_ADDED) {
          this.showStatusText = true
          this.showActionBtn = true
          if (deviceInfo) {
            let supportAP: number = EZProbeDeviceInfo.supportAP(deviceInfo.supportExtJSON)
            this.supportApMode = supportAP == 2
            this.supportWiFi5G = EZProbeDeviceInfo.support5GWiFi(deviceInfo.supportExtJSON)
            // 记录该设备热点前缀
            GlobalKit.getInstance().WiFiConfigPrefix =
              EZBusinessTool.getWiFiConfigPrefix(EZProbeDeviceInfo.getDeviceHotSpot(deviceInfo.supportExtJSON))
          } else {
            // 查不到能力级则根据设备灯来判断配网模式
          }
          this.actionBtnText = $r('app.string.ad_connect_net')
        } else {
          this.showResultImage = false
          this.showNoWifiImage = true
          this.showActionBtn = true
          this.resultText = $r('app.string.get_info_fail')
          this.actionBtnText = $r('app.string.retry')
        }
        return
      }
      this.showActionBtn = true
      this.actionBtnText = $r('app.string.ad_add')
    })
  }

  addDevice() {
    this.showLoadingProgress = true
    EZOpenSDK.addDevice(GlobalKit.getInstance().deviceSerialNo, GlobalKit.getInstance().deviceVerifyCode, (error) => {
      this.showLoadingProgress = false
      if (!error) {
        EZToastUtil.showToast('设备添加成功')
        // 发出刷新通知
        emitter.emit({ eventId: EmitterEvents.EZDeviceListPageRefresh })
        RouterManager.back(RouterManager.deviceListPage)
        return
      }
      if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_VALICATECODE_ERROR) {
        this.showSetPassword()
      } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ADDED_MYSELF ||
        error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_ADDED ||
        error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED_MYSELF) {
        EZToastUtil.showToast($r('app.string.ad_already_added'))
      } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_IS_ADDED ||
        error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED) {
        EZToastUtil.showToast($r('app.string.ad_added_by_others'))
      } else {
        EZToastUtil.showToast($r('app.string.wifi_add_fail'))
      }
    })
  }

  // ------------------------ 验证码输入 ------------------------

  showSetPassword() {
    this.verifyCodeDialogController.open()
  }

  @State
  verifyCodeDialogInputContent: string = ''
  verifyCodeDialogController: CustomDialogController = new CustomDialogController({
    customStyle: true,
    builder: VerifyCodeDialog({
      deviceSerial: '',
      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: () => {
        GlobalKit.getInstance().deviceVerifyCode = this.verifyCodeDialogInputContent
        this.addDevice()
      },
      cancelClick: () => {

      }
    }),
    alignment: DialogAlignment.Center,
    autoCancel: false
  })

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

  build() {
    Column({ space: 8 }) {
      NavigationView({
        title: $r('app.string.ad_result_title'),
      })
      Stack() {
        Image($r('app.media.device_default')).width(150).height(165).align(Alignment.Center)
          .visibility(this.showResultImage ? Visibility.Visible : Visibility.Hidden)
        Image($r('app.media.no_wifi')).width(95).height(95).align(Alignment.Center)
          .visibility(this.showNoWifiImage ? Visibility.Visible : Visibility.Hidden)
        LoadingProgress().width(40).height(40)
          .visibility(this.showLoadingProgress ? Visibility.Visible : Visibility.Hidden)
      }.width('100%').height(200)

      Text(this.resultText).fontColor(Color.Gray).height(24)
      Text(this.statusText).fontColor(this.statusTextColor).height(24)
        .visibility(this.showStatusText ? Visibility.Visible : Visibility.Hidden)
      Button(this.actionBtnText)
        .width('80%')
        .height(40)
        .backgroundColor($r('app.color.ez_text_blue'))
        .margin({ top: 10 })
        .onClick(this.nextAction)
        .visibility(this.showActionBtn ? Visibility.Visible : Visibility.Hidden)
    }.backgroundColor($r('app.color.message_cell_select_color')).width('100%').height('100%')
  }
}
