import { AppUtil, DateUtil } from "@pura/harmony-utils";
import { EventConstants } from "../../../../common/EventConstants";
import { DownloadHistoryEntity } from "../../../../entity/DownloadHistoryEntity";
import { DownloadHistoryItemView } from "../../../../view/DownloadHistoryItemView";
import { EmptyView, PageStatus } from "../../../../view/EmptyView";
import { DownloadHistoryViewModel } from "../../../../viewModel/DownloadHistoryViewModel";

@ComponentV2
export struct DownloadHistoryItemPage {
  @Local isRefreshing: boolean = false;
  @Local isLoading: boolean = false;
  @Local refreshOffset: number = 0;
  @Local refreshState: RefreshStatus = RefreshStatus.Inactive;
  @Local historyList: Array<DownloadHistoryEntity> = []

  @Param type: number = 0

  viewModel: DownloadHistoryViewModel = new DownloadHistoryViewModel(this.getUIContext())
  page: number = 1
  canLoadMore: boolean = false

  @Monitor('viewModel.getHistory')
  onGetDownloadHistory(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<DownloadHistoryEntity>
    if (this.page === 1) {
      this.historyList = list
      this.isRefreshing = false
    } else {
      this.historyList = this.historyList.concat(list)
      this.isLoading = false
    }
    this.canLoadMore = list.length === 20
  }

  aboutToAppear(): void {
    this.isRefreshing = true
    this.initObserver()
  }

  aboutToDisappear(): void {
    AppUtil.getContext().eventHub.off(EventConstants.DownloadHistoryRefreshEvent)
  }

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.DownloadHistoryRefreshEvent, (type: number) => {
      if (type === this.type) {
        this.isRefreshing = true
      }
    })
  }

  getStartTime(): number {
    let nowDate = new Date(DateUtil.getNowYear(), DateUtil.getNowMonth() - 1, 1)
    let lastDate = new Date(DateUtil.getNowYear(), DateUtil.getNowMonth() - 2, 1)
    if (this.type === 0) {
      return Math.trunc(nowDate.getTime() / 1000)
    } else {
      return Math.trunc(lastDate.getTime() / 1000)
    }
  }

  getEndTime(): number {
    let nowDate = new Date(DateUtil.getNowYear(), DateUtil.getNowMonth(), 1)
    let lastDate = new Date(DateUtil.getNowYear(), DateUtil.getNowMonth() - 1, 1)
    if (this.type === 0) {
      return Math.trunc(nowDate.getTime() / 1000)
    } else {
      return Math.trunc(lastDate.getTime() / 1000)
    }
  }

  build() {
    Stack() {
      Refresh({refreshing: this.isRefreshing, builder: this.refreshBuilder()}) {
        List({space: 12}) {
          ForEach(this.historyList, (item: DownloadHistoryEntity) => {
            ListItem() {
              DownloadHistoryItemView({ historyEntity: item })
            }
          })
          ListItem() {
            this.footer();
          }
        }
        .width('100%')
        .height('100%')
        .scrollBar(BarState.Off)
        .onScrollIndex((start: number, end: number) => {
          // 当达到列表末尾时，触发新数据加载。
          if (this.canLoadMore && end >= this.historyList.length - 1) {
            this.page++
            this.isLoading = true;
            this.viewModel.getHistoryList(`${this.page}`, `${this.getStartTime()}`, `${this.getEndTime()}`)
          }
        })
      }
      .onRefreshing(() => {
        this.page = 1
        this.isRefreshing = true
        this.viewModel.getHistoryList(`${this.page}`, `${this.getStartTime()}`, `${this.getEndTime()}`)
      })
      .refreshOffset(50)
      .pullToRefresh(true)
      .visibility(this.historyList.length > 0 ? Visibility.Visible : Visibility.None)

      EmptyView({
        status: this.historyList.length > 0 ? PageStatus.GONE : PageStatus.NO_DATA,
        noDataImage: $r('app.media.ic_empty_data'),
        noDataText: '暂无数据'
      })
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  refreshBuilder() {
    Stack({ alignContent: Alignment.Bottom }) {
      // 可以通过刷新状态控制是否存在Progress组件。
      // 当刷新状态处于下拉中或刷新中状态时Progress组件才存在。
      if (this.refreshState != RefreshStatus.Inactive && this.refreshState != RefreshStatus.Done) {
        Progress({ value: this.refreshOffset, total: 50, type: ProgressType.Ring })
          .width(32).height(32)
          .style({ status: this.isRefreshing ? ProgressStatus.LOADING : ProgressStatus.PROGRESSING })
          .margin(10)
      }
    }
    .clip(true)
    .height("100%")
    .width("100%")
  }

  @Builder
  footer() {
    Row() {
      LoadingProgress().height(32).width(48)
      Text("加载中")
    }.width("100%")
    .height(50)
    .justifyContent(FlexAlign.Center)
    // 当不处于加载中状态时隐藏组件。
    .visibility(this.isLoading ? Visibility.Visible : Visibility.Hidden)
  }
}