/*
 * 设备列表页面
 * EZOpenSDK
 *
 * Created by junecheng on 2024/3/5.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */
import { PullToRefresh, PullToRefreshConfigurator } from '@ohos/pulltorefresh'
import emitter from '@ohos.events.emitter'

import { EZDeviceInfo, EZError, EZOpenSDK, EZTimeUtil, EzvizSupportKit } from '@ohos/EZOpenSDK'

import EmitterEvents from '../../global/EmitterEvents'
import EZToastUtil from '../../utils/EZToastUtil'
import RouterManager from '../../global/RouterManager/RouterManager'
import GlobalKit from '../../global/GlobalKit'
import DemoConfig from '../../global/DemoConfig'
import { EZPlayType } from '../../global/EZEnumerateHeader'

import EZDeviceListNav from './view/EZDeviceListNav'
import DeviceListCell from './view/DeviceListCell'

import EZMessageListRouterParam from '../Message/EZMessageListPage'

@Entry
@Component
struct EZDeviceListPage {
  private EZDeviceListPageSize: number = 10
  // segmented选中索引
  @State currentSegIndex: number = 0
  // 是否是分享设备的segmented档选中
  @State isSharedDevice: boolean = false
  // 登录时指定的设备序列号
  private specificDevice: string = ''
  private scroller: Scroller = new Scroller()
  private refreshConfigurator: PullToRefreshConfigurator = new PullToRefreshConfigurator()
  // 设备列表
  @State deviceArray: Array<EZDeviceInfo> = []
  // 分页索引
  private currentPageIndex: number = 0
  // 列表刷新事件
  onRefresh: () => Promise<string> = () => {
    this.currentPageIndex = 0
    if (this.isSharedDevice) {
      return new Promise<string>((resolve, reject) => {
        this.getSharedDeviceList(resolve)
      })
    } else {
      return new Promise<string>((resolve, reject) => {
        return this.specificDevice ? this.getDeviceInfo(resolve) : this.getDeviceList(resolve)
      })
    }
  }
  // 列表加载事件
  onLoadMore: () => Promise<string> = () => {
    this.currentPageIndex++
    return new Promise<string>((resolve, reject) => {
      return this.isSharedDevice ? this.getSharedDeviceList(resolve) : this.getDeviceList(resolve)
    })
  }

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

  aboutToAppear() {
    emitter.on({ eventId: EmitterEvents.EZDeviceListPageRefresh }, () => {
      this.onRefresh()
    })
    this.specificDevice = GlobalKit.getInstance().getSavedData(DemoConfig.UserDevSerial) as string
    this.onRefresh()
  }

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

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

  /** 点击列表图片进入预览页面 */
  go2PlayAction = (item: EZDeviceInfo) => {
    if (item.cameraNum == 1) { // 单通道设备，直接跳转预览页面
      RouterManager.pushUrl(RouterManager.realPlayPage, { deviceInfo: item })
    } else if (item.cameraNum > 1) { // 多通道设备，跳转通道列表进行选择
      if (EzvizSupportKit.isSupportMultiChannel(item.abilities)) {// 双目设备
        RouterManager.pushUrl(RouterManager.realPlayPage, { deviceInfo: item })
      } else {
        RouterManager.pushUrl(RouterManager.cameraListPage, { deviceInfo: item, playType: EZPlayType.EZPlayTypeLive })
      }
    } else if (item.subDeviceInfo && item.subDeviceInfo.length > 0) { // 子设备
      RouterManager.pushUrl(RouterManager.cameraListPage, { deviceInfo: item, playType: EZPlayType.EZPlayTypeLive })
    }
  }
  /** 回放 */
  go2RecordAction = (item: EZDeviceInfo) => {
    if (item.cameraNum == 1) { // 单通道设备，直接跳转预览页面
      RouterManager.pushUrl(RouterManager.playbackPage, { deviceInfo: item })
    } else if (item.cameraNum > 1) { // 多通道设备，跳转通道列表进行选择
      if (EzvizSupportKit.isSupportMultiChannel(item.abilities)) { // 双目设备
        RouterManager.pushUrl(RouterManager.playbackPage, { deviceInfo: item })
      } else {
        RouterManager.pushUrl(RouterManager.cameraListPage, { deviceInfo: item, playType: EZPlayType.EZPlayTypePlayback })
      }
    } else if (item.subDeviceInfo && item.subDeviceInfo.length > 0) { // 子设备
      RouterManager.pushUrl(RouterManager.cameraListPage, { deviceInfo: item, playType: EZPlayType.EZPlayTypePlayback })
    }
  }
  /** 消息 */
  go2MessageAction = (item: EZDeviceInfo) => {
    RouterManager.pushUrl(RouterManager.messageListPage, new EZMessageListRouterParam(item.deviceSerial))
  }
  /** 设置 */
  go2SettingAction = (item: EZDeviceInfo) => {
    // 加密开关重新设置后，需要更新设备的加密状态
    emitter.once({ eventId: EmitterEvents.EZDeviceEncrptStatusRefresh }, (eventData) => {
      item.isEncrypt = eventData.data!['isEncrypt']
    })
    emitter.once({ eventId: EmitterEvents.EZDeviceDefenceStatusRefresh }, (eventData) => {
      item.defence = eventData.data!['isDefence']
    })
    RouterManager.pushUrl(RouterManager.settingPage, item)
  }

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

  /*
   * 获取设备列表接口
   */
  getDeviceList(resolve?: (value: string | PromiseLike<string>) => void) {
    EZOpenSDK.getDeviceList(this.currentPageIndex, this.EZDeviceListPageSize, (deviceList, totalCount, error) => {
      this.refreshDeviceList(deviceList, error, resolve)
    })
  }

  /*
   * 获取分享设备列表接口
   */
  getSharedDeviceList(resolve?: (value: string | PromiseLike<string>) => void) {
    EZOpenSDK.getSharedDeviceList(this.currentPageIndex, this.EZDeviceListPageSize, (deviceList, totalCount, error) => {
      this.refreshDeviceList(deviceList, error, resolve)
    })
  }

  /**
   * 根据序列号获取设备信息接口
   */
  getDeviceInfo(resolve?: (value: string | PromiseLike<string>) => void) {
    EZOpenSDK.getDeviceInfo(this.specificDevice, (deviceInfo, error) => {
      this.refreshDeviceList([deviceInfo], error, resolve)
    })
  }

  /*
   * 获取到设备列表数据后再刷新
   */
  refreshDeviceList(deviceList: Array<EZDeviceInfo>, error: EZError,
    resolve?: (value: string | PromiseLike<string>) => void) {
    if (resolve) {
      resolve(EZTimeUtil.getCurrentTimeString())
    }
    if (error) {
      this.deviceArray = []
      EZToastUtil.showToast(`error code: ${error.code}`)
      return
    }
    if (this.currentPageIndex == 0) {
      this.deviceArray = []
    }
    deviceList.forEach((device) => {
      this.deviceArray.push(device)
    })
    // 到顶了 不能加载更多
    this.refreshConfigurator.setHasLoadMore(deviceList && deviceList.length == this.EZDeviceListPageSize)
  }

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

  build() {
    Flex({ direction: FlexDirection.Column }) {
      EZDeviceListNav({
        selectedIndex: this.currentSegIndex,
        segmentClickAction: (index) => {
          this.isSharedDevice = this.currentSegIndex == 1
          this.deviceArray = []
          this.onRefresh()
        },
        exitAction: () => {
          AlertDialog.show({
            title: $r('app.string.login_exit'),
            alignment: DialogAlignment.Center,
            message: '',
            primaryButton: {
              value: $r('app.string.dialog_cancel'),
              action: () => {
              }
            },
            secondaryButton: {
              value: $r('app.string.dialog_ok'),
              action: () => {
                EZOpenSDK.logout((error) => {
                })
                GlobalKit.getInstance().removeLastSDKInitParams()
                RouterManager.replaceUrl(RouterManager.loginPage)

              }
            }
          })
        },
        testAction: () => {
          RouterManager.pushUrl(RouterManager.testPage)
        },
        multiChannelAction: () => {
          EZToastUtil.showToast('多画面')
        },
        addDeviceAction: () => {
          RouterManager.pushUrl(RouterManager.addByQRCodePage)
        }
      })
      PullToRefresh({
        data: this.deviceArray,
        scroller: this.scroller,
        customList: () => {
          this.DeviceListView()
        },
        onAnimLoading: () => {
        },
        onRefresh: this.onRefresh,
        onLoadMore: this.onLoadMore,
        customLoad: null,
        customRefresh: null,
        refreshConfigurator: this.refreshConfigurator
          .setMaxTranslate(60)
          .setRefreshTextSize(12)
          .setLoadTextSize(12)
          .setLoadTextLoading('正在加载更多的数据...')
      })
        .height('100%')
    }
  }

  @Builder
  DeviceListView() {
    List({ scroller: this.scroller }) {
      ForEach(this.deviceArray, (item: EZDeviceInfo, index) => {
        ListItem() {
          DeviceListCell({
            deviceInfo: item,
            onPreviewClick: this.go2PlayAction, // 预览
            onPlaybackClick: this.go2RecordAction, // 回放
            onMessageClick: this.go2MessageAction, // 消息
            onSettingClick: this.go2SettingAction// 设置
          })
        }
      })
    }
    .edgeEffect(EdgeEffect.None)
  }
}