/*
 * AP配网结果页面
 * EZOpenSDK
 *
 * Created by junecheng on 2024/8/14.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */
import { emitter } from '@kit.BasicServicesKit'
import { EZError, EZErrorCode, EZOpenSDK } from '@ohos/EZOpenSDK'

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

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

const MAX_COUNT: number = 20

@Entry
@Component
@Preview
struct EZAPConfigResultPage {
  @State showLoadingProgress: boolean = false
  // 设备是否添加成功
  @State isAddDeviceSuccess: boolean = false
  // 重试按钮是否显示
  @State showRetryBtn: boolean = false
  // 设备添加定时器ID
  addDeviceTimerIntervalID: number = 0
  addCount: number = 0

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

  aboutToAppear() {
    this.startTimer()
  }

  aboutToDisappear() {
    this.stopTimer()
  }

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

  /**
   * 重试Action
   */
  retryAction = () => {
    this.showLoadingProgress = true
    this.showRetryBtn = false
    this.startTimer()
  }
  /**
   * 完成Action
   */
  doneAction = () => {
    // 发出刷新通知
    emitter.emit({ eventId: EmitterEvents.EZDeviceListPageRefresh })
    RouterManager.back(RouterManager.deviceListPage)
  }

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

  addDevice() {
    EZOpenSDK.probeDeviceInfo(GlobalKit.getInstance().deviceSerialNo, GlobalKit.getInstance().deviceModel,
      (deviceInfo, error) => {
        if (error) {
          this.probeDeviceErrorProcess(error)
        } else {
          EZOpenSDK.addDevice(GlobalKit.getInstance().deviceSerialNo, GlobalKit.getInstance().deviceVerifyCode,
            (error) => {
              if (error) {
                this.addDeviceErrorProcess(error)
              } else {
                this.addDeviceSuccessProcess()
              }
            })
        }
      })
  }

  addDeviceSuccessProcess() {
    this.stopTimer()
    this.showLoadingProgress = false
    this.isAddDeviceSuccess = true
  }

  addDeviceErrorProcess(error: EZError) {
    this.showLoadingProgress = false
    let msgRes: Resource
    if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_VALICATECODE_ERROR) {
      msgRes = $r('app.string.device_verify_code_wrong')
    } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_ADDED) {
      msgRes = $r('app.string.ad_already_added')
    } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_IS_ADDED) {
      msgRes = $r('app.string.ad_added_by_others')
    } else {
      msgRes = $r('app.string.wifi_add_fail')
    }
    EZToastUtil.showToast(msgRes)
  }

  probeDeviceErrorProcess(error: EZError) {
    this.showLoadingProgress = false

    let msgRes: Resource
    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) {
      msgRes = $r('app.string.ad_already_added')
      this.isAddDeviceSuccess = true

    } else if (error.code == EZErrorCode.EZ_HTTPS_DEVICE_ONLINE_IS_ADDED ||
      error.code == EZErrorCode.EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED) {
      msgRes = $r('app.string.ad_added_by_others')
    } else {
      return
    }
    this.stopTimer()
    EZToastUtil.showToast(msgRes)
  }

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

  startTimer() {
    this.stopTimer()
    this.addCount = 0

    this.showLoadingProgress = true
    this.addDevice()
    this.addDeviceTimerIntervalID = setInterval(() => {
      this.addCount++
      if (this.addCount > MAX_COUNT) {
        this.timeoutProcess()
        return
      }
      this.addDevice()
    }, 5000)
  }

  stopTimer() {
    clearInterval(this.addDeviceTimerIntervalID)
  }

  timeoutProcess() {
    this.stopTimer()
    EZToastUtil.showToast($r('app.string.wifi_ap_add_device_timeout'))
    this.showRetryBtn = true
    this.showLoadingProgress = false
  }

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

  build() {
    Column() {
      NavigationView({
        title: $r('app.string.wifi_ap_add_device_title')
      })
      Stack({ alignContent: Alignment.Center }) {
        Image($r('app.media.wifi_bg'))
        Image($r('app.media.device_add_success'))
          .fitOriginalSize(true)
          .visibility(this.isAddDeviceSuccess ? Visibility.Visible : Visibility.Hidden)
        Column() {
          Text($r('app.string.wifi_ap_add_device_loading'))
            .textAlign(TextAlign.Center)
            .visibility(this.showLoadingProgress ? Visibility.Visible : Visibility.Hidden)
          Button($r('app.string.retry'))
            .width(100)
            .height(40)
            .margin({ top: 20 })
            .backgroundColor(Color.Orange)
            .visibility(this.showRetryBtn ? Visibility.Visible : Visibility.Hidden)
            .onClick(this.retryAction)
          Button($r('app.string.complete'))
            .width(100)
            .height(40)
            .margin({ top: 100 })
            .backgroundColor(Color.Orange)
            .visibility(this.isAddDeviceSuccess ? Visibility.Visible : Visibility.Hidden)
            .onClick(this.doneAction)
        }

        LoadingProgress().width(40).height(40)
          .visibility(this.showLoadingProgress ? Visibility.Visible : Visibility.Hidden)
      }
    }
  }
}