import { DownSamplingStrategy, ImageKnifeComponent, ImageKnifeOption } from "@ohos/imageknifepro"
import { AppUtil } from "@pura/harmony-utils"
import { EventConstants } from "../../../common/EventConstants"
import { RouterUrls } from "../../../common/RouterUrls"
import { MaterialEntity } from "../../../entity/MaterialEntity"
import { EmptyView, PageStatus } from "../../../view/EmptyView"
import { MaterialViewModel } from "../../../viewModel/MaterialViewModel"

@ComponentV2
export struct MaterialListPage {
  @Param cateId: string = ''
  @Param initKeywords: string = ''

  @Local materialList: Array<MaterialEntity> = []
  @Local keywords: string = this.initKeywords
  @Local isRefreshing: boolean = false
  @Local isLoading: boolean = false
  @Local canLoadMore: boolean = false

  private viewModel: MaterialViewModel = new MaterialViewModel(this.getUIContext())
  private page: number = 1;

  @Monitor('viewModel.materialList')
  onMaterialListChange(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<MaterialEntity>
    if (this.page === 1) {
      this.materialList = list
      this.isRefreshing = false
    } else {
      this.materialList.push(...list)
      this.isLoading = false
    }
    this.canLoadMore = list.length === 20
  }

  aboutToAppear(): void {
    this.initObserver()
    this.viewModel.getMaterialList(this.page, this.cateId, this.keywords)
  }

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

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.MaterialListRefreshEvent, (keywords: string) => {
      this.keywords = keywords
      this.page = 1
      this.isRefreshing = true
      this.viewModel.getMaterialList(this.page, this.cateId, this.keywords)
    })
  }

  createImageOption(item: MaterialEntity): ImageKnifeOption {
    const option:ImageKnifeOption = {
      loadSrc: item.pic ? item.pic.url : '',
      placeholderSrc: $r('app.media.ic_placeholder'),
      thumbnailSrc: $r('app.media.ic_placeholder'),
      errorSrc: $r('app.media.ic_placeholder'),
      objectFit: ImageFit.Cover,
      border: {radius: 6},
      downSampling: DownSamplingStrategy.FIT_CENTER_QUALITY,
      onLoadListener:{
        onLoadSuccess: (imageInfo) => {
          item.pic_size = `${imageInfo.imageWidth}:${imageInfo.imageHeight}`
        }
      }
    }
    return option
  }

  build() {
    Refresh({refreshing: this.isRefreshing}) {
      Stack() {
        WaterFlow() {
          ForEach(this.materialList, (item: MaterialEntity, index: number) => {
            FlowItem() {
              ImageKnifeComponent({
                imageKnifeOption:this.createImageOption(item)
              })
                .width('100%')
                .height('100%')
                .borderRadius(6)
                .backgroundColor($r('app.color.color_ededed'))
                .onClick(() => {
                  if (item.pic?.url) {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.MATERIAL_DETAIL_PAGE, params: {material: item}})
                  }
                })
            }
            .width('100%')
            .height(500 / (index % 2 === 0 ? 2 : 3))
          })
        }
        .columnsTemplate('1fr 1fr')
        .columnsGap(7)
        .rowsGap(7)
        .width('100%')
        .height('100%')
        .padding({left: 12, right: 12})
        .onReachEnd(() => {
          this.page++
          this.isLoading = true
          this.viewModel.getMaterialList(this.page, this.cateId, this.keywords)
        })

        EmptyView({
          status: this.materialList.length > 0 ? PageStatus.GONE : PageStatus.NO_DATA,
          noDataImage: $r('app.media.ic_empty_data'),
          noDataText: '暂无数据'
        })
      }
    }
    .width('100%')
    .height('100%')
    .onRefreshing(() => {
      this.page = 1
      this.isRefreshing = true
      this.viewModel.getMaterialList(this.page, this.cateId, this.keywords)
    })
  }
}