/*
 * 登录页面
 * EZOpenSDK
 *
 * Created by junecheng on 2024/3/5.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */

import bundleManager from '@ohos.bundle.bundleManager'
import EZOpenSDK from '@ohos/EZOpenSDK/src/main/ets/PublicHeader/EZOpenSDK'

import EZToastUtil from '../../utils/EZToastUtil'
import RouterManager from '../../global/RouterManager/RouterManager'
import GlobalKit from '../../global/GlobalKit'
import DemoConfig from '../../global/DemoConfig'
import ServerAreasEnum from './ServerAreasEnum'

import LoginTextInput from './view/LoginTextInput'

@Entry
@Component
struct MainPage {
  // Select选项
  @State selectServerArray: Array<SelectOption> = ServerAreasEnum.getSelectServerArray()
  // Select选中项索引
  @State selectedIndex: number = 0
  // Select选中项
  @State selectedServer: ServerAreasEnum = ServerAreasEnum.ALL_SERVERS[0]
  @State sdkVersion: string = ''
  @State appKeyInput: string = ''
  @State accessTokenInput: string = ''
  @State specifiedDeviceInput: string = ''
  @State apiUrlInput: string = this.selectedServer.apiUrl
  @State authUrlInput: string = this.selectedServer.authUrl
  @State showLoadingProgress: boolean = false

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

  aboutToAppear() {
    this.initData()
    this.autoLogin()

    this.appKeyInput = DemoConfig.APPKEY_DEV
    this.accessTokenInput = DemoConfig.TOKEN_DEV
    this.specifiedDeviceInput = DemoConfig.DEVICE_DEV
  }

  async test() {

  }

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

  /**
   * 通过AccessToken进行体验
   */
  async startExperienceAction() {
    this.test()
    if (this.checkLoginInfo()) {
      // 日志开启必须在initLibWithAppKey方法之前，正式发布时必须设置为false或者删除
      EZOpenSDK.setDebugLogEnable(true)
      // 码流缓存开关，在initLib方法之前调用；正式发布时必须设置为false或者删除；否则本地会缓存大量的调试文件
      EZOpenSDK.setDebugStreamEnable(true)
      // 开启p2p取流功能
      EZOpenSDK.enableP2P(true)
      GlobalKit.getInstance().enableP2P = true
      /**
       * 注意：Demo兼容accessToken模式和tkToken小权限模式，所以需要通过.tk进行判断
       * 开发者App只能使用一种模式，EZOpenSDK.enableSDKWithTKToken直接设置true或false
       */
      let isEnableSDKWithTKToken: boolean = this.accessTokenInput.startsWith('tk.')
      EZOpenSDK.enableSDKWithTKToken(isEnableSDKWithTKToken)
      // 1.SDK初始化 & 设置accessToken
      if (this.apiUrlInput) {
        await EZOpenSDK.initLibWithAppKey(this.appKeyInput, this.apiUrlInput, this.authUrlInput)
      } else {
        await EZOpenSDK.initLibWithAppKey(this.appKeyInput)
      }
      if (isEnableSDKWithTKToken) {
        await EZOpenSDK.setHttpToken(this.accessTokenInput)
      } else {
        await EZOpenSDK.setAccessToken(this.accessTokenInput)
      }
      // 2.appKey & accessToken验证
      this.showLoadingProgress = true
      this.checkAppKeyAndAccessToken(() => {
        this.showLoadingProgress = false
        GlobalKit.getInstance()
          .saveLastSdkInitParams(this.appKeyInput, this.accessTokenInput, this.apiUrlInput, this.authUrlInput,
            this.specifiedDeviceInput)
        RouterManager.replaceUrl(RouterManager.deviceListPage)
      })
    }
  }

  /**
   * 萤石账号登录
   */
  ezvizAccountLoginAction() {

  }

  /**
   * 自动登录
   */
  async autoLogin() {
    let appKey: string = GlobalKit.getInstance().getSavedData(DemoConfig.UserAppKey) as string
    let accessToken: string = GlobalKit.getInstance().getSavedData(DemoConfig.UserAccessToken) as string
    let apiUrl: string = GlobalKit.getInstance().getSavedData(DemoConfig.UserApiUrl) as string
    let authUrl: string = GlobalKit.getInstance().getSavedData(DemoConfig.UserAuthUrl) as string
    if (!appKey || !accessToken) {
      return
    }
    this.showLoadingProgress = true
    // 日志开启必须在initLibWithAppKey方法之前，正式发布时必须设置为false或者删除
    EZOpenSDK.setDebugLogEnable(true)
    // 码流缓存开关，在initLib方法之前调用；正式发布时必须设置为false或者删除；否则本地会缓存大量的调试文件
    EZOpenSDK.setDebugStreamEnable(true)
    // 开启p2p取流功能
    EZOpenSDK.enableP2P(true)
    GlobalKit.getInstance().enableP2P = true
    // 小权限token登录，仅支持国内
    let isEnableSDKWithTKToken: boolean = accessToken.startsWith('tk.')
    EZOpenSDK.enableSDKWithTKToken(isEnableSDKWithTKToken)
    await EZOpenSDK.initLibWithAppKey(appKey, apiUrl, authUrl)
    isEnableSDKWithTKToken ? await EZOpenSDK.setHttpToken(accessToken) : await EZOpenSDK.setAccessToken(accessToken)

    this.checkAppKeyAndAccessToken(() => {
      this.showLoadingProgress = false
      RouterManager.replaceUrl(RouterManager.deviceListPage)
    })
  }

  jcTestAction() {
    let serverArea: ServerAreasEnum = ServerAreasEnum.ALL_SERVERS[0]
    this.appKeyInput = DemoConfig.APPKEY_JC
    this.accessTokenInput = DemoConfig.TOKEN_JC
    this.specifiedDeviceInput = DemoConfig.DEVICE_JC
    this.apiUrlInput = serverArea.apiUrl
    this.authUrlInput = serverArea.authUrl
    this.startExperienceAction()
  }

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

  /**
   * 验证是否输入 AppKey 和 AccessToken
   */
  checkLoginInfo(): boolean {
    if (this.appKeyInput.trim() == '') {
      EZToastUtil.showToast('AppKey不能为空')
      return false
    }
    if (this.accessTokenInput.trim() == '') {
      EZToastUtil.showToast('AccessToken不能为空')
      return false
    }
    return true
  }

  /**
   * 通过调用服务接口判断AppKey和AccessToken是否有效
   * @return 是否依旧有效
   */
  checkAppKeyAndAccessToken(callback: () => void) {
    EZOpenSDK.getDeviceList(0, 1, (deviceList, totalCount, error) => {
      if (error) {
        let errMsg: Resource
        switch (error.code) {
          case 400031:
            errMsg = $r('app.string.tip_of_bad_net')
            break
          default:
            errMsg = $r('app.string.login_expire')
            break
        }
        this.showLoadingProgress = false
        EZToastUtil.showToast(errMsg)
      } else {
        if (callback) {
          callback()
        }
      }
    })
  }

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

  build() {
    Row() {
      Stack() {
        LoadingProgress().width(40).height(40)
          .visibility(this.showLoadingProgress ? Visibility.Visible : Visibility.Hidden)
        Column() {
          Image($r('app.media.login_logo'))
            .width('70%')
            .objectFit(ImageFit.Auto)
            .onClick(() => {
              if (GlobalKit.isJCTest) {
                this.jcTestAction()
              }
            })
          Text(this.sdkVersion).fontSize(14).fontColor(Color.Gray).margin({ top: 25, bottom: 25 })
          Column() { // 服务器区域
            Text($r('app.string.server_area')).fontSize(18).width('100%')
            Select(this.selectServerArray)
              .selected(this.selectedIndex)
              .value(this.selectedServer.areaName)
              .font({ style: FontStyle.Normal })
              .fontColor(Color.Red)
              .backgroundColor(Color.Transparent)
              .onSelect((index: number) => {
                this.selectedIndex = index
                this.selectedServer = ServerAreasEnum.ALL_SERVERS[index]
                this.apiUrlInput = this.selectedServer.apiUrl
                this.authUrlInput = this.selectedServer.authUrl
                // 萤石测试将appKey代入，方便测试
                if (DemoConfig.EzvizTest == this.selectedServer.areaName) {
                  this.appKeyInput = this.selectedServer.defaultOpenAuthAppKey
                  this.accessTokenInput = ''
                  this.specifiedDeviceInput = ''
                }
              })
              .borderRadius(0)
              .width(300)
            Text($r('app.string.explain_of_server_area')).fontSize(10).fontColor(Color.Gray).width('100%')
          }

          LoginTextInput({ textInputTitle: 'ApiUrl:', textInputValue: $apiUrlInput })
          LoginTextInput({ textInputTitle: 'AuthUrl:', textInputValue: $authUrlInput })
          LoginTextInput({
            textInputTitle: 'AppKey:',
            textInputValue: $appKeyInput,
            textInputPlaceholder: $r('app.string.explain_of_app_key')
          })
          LoginTextInput({
            textInputTitle: 'AccessToken/TKToken:',
            textInputValue: $accessTokenInput,
            textInputPlaceholder: $r('app.string.explain_of_app_key')
          })
          LoginTextInput({
            textInputTitle: $r('app.string.specified_device'),
            textInputValue: $specifiedDeviceInput,
            textInputPlaceholder: $r('app.string.tip_specified_device')
          })
          Button($r('app.string.start_to_experience'), { type: ButtonType.Normal })
            .onClick(() => {
              this.startExperienceAction()
            })
            .fontColor(Color.Black)
            .fontSize(14)
            .fontWeight(400)
            .backgroundColor('#D1D1D6')
            .margin({ top: 20 })
            .borderRadius(3)
            .width('100%')
          // Text($r('app.string.login_by_ezviz_account'))
          //   .visibility(this.selectedServer.defaultOpenAuthAppKey.length > 0 ? Visibility.Visible : Visibility.Hidden)
          //   .fontSize(16)
          //   .fontColor(0x39a4cb)
          //   .margin({ top: 10 })
          //   .onClick(() => {
          //     this.ezvizAccountLoginAction()
          //   })
        }.width('100%').padding({ left: 30, right: 30 })
      }
    }.height('100%')
  }

  initData() {
    // 获取SDK版本号
    let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT
    bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
      this.sdkVersion = 'SDK Version：v' + data.versionName
    })
    // 设置选中的服务器区域
    for (let i = 0; i < ServerAreasEnum.ALL_SERVERS.length; i++) {
      if (ServerAreasEnum.ALL_SERVERS[i].apiUrl === this.authUrlInput) {
        this.selectedIndex = i
        break
      }
    }
  }
}