import { borderRadiuses } from '@kit.ArkUI';
import { MenuEntity, homeMenuList } from '../../../entity/MenuEntity';
import { NoticeEntity } from '../../../entity/NoticeEntity';
import { HomeViewModel } from '../../../viewModel/HomeViewModel';
import { AppUtil, WantUtil } from '@pura/harmony-utils';
import { EventConstants } from '../../../common/EventConstants';
import { BannerEntity } from '../../../entity/BannerEntity';
import { ConfigManager } from '../../../manager/UserConfigManager';
import { LoginManager } from '../../../manager/LoginGlobalManager';
import { RouterUrls } from '../../../common/RouterUrls';
import { TipDialog } from '../../../dialog/TipDialog';
import { EventReportManager } from '../../../manager/EventReportManager';
import { Constants } from '../../../common/Constants';
import { MaterialEntity } from '../../../entity/MaterialEntity';
import { DownSamplingStrategy, ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro';

@ComponentV2
export struct HomePage {
  @Local notices?: Array<string> = [];
  @Local banners: Array<BannerEntity> = [];
  @Local materialList: Array<MaterialEntity> = []
  @Local isRefreshing: boolean = false
  @Local isLoading: boolean = false
  @Local canLoadMore: boolean = false

  viewModel: HomeViewModel = new HomeViewModel(this.getUIContext());

  noticeScroller: Scroller = new Scroller();

  noticeTaskId: number = 0;
  bannerTaskId: number = 0;

  private page: number = 1;

  @Monitor('viewModel.noticeEntity')
  onNoticeChange(monitor: IMonitor) {
    const noticeEntity = monitor.value()?.now as NoticeEntity;
    this.notices = noticeEntity.notice;
    if (this.notices && this.notices.length >= 1) {
      this.startNoticeTask();
    } else {
      this.stopNoticeTask();
    }
  }

  @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.initBanner();
    this.viewModel.noticeList();
    this.viewModel.getMaterialList(this.page.toString())
  }

  aboutToDisappear(): void {
    this.stopNoticeTask();
  }

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.HomeRefreshEvent, () => {
      this.viewModel.noticeList();
    })
  }

  initBanner() {
    if (this.banners.length > 0) {
      this.banners.splice(0, this.banners.length)
    }
    const list = ConfigManager.getHomeBanner();
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.page === 'check_Task') {
        continue
      } else if (item.page === 'recharge' && LoginManager.getUserInfo()?.vip === 3) {
        continue
      }
      this.banners.push(item);
    }
  }

  startNoticeTask() {
    if (this.noticeTaskId === 0 && this.notices && this.notices.length >= 1) {
      this.noticeTaskId = setInterval(() => {
        this.noticeScroller.scrollBy(3, 0)
        if (this.noticeScroller.isAtEnd()) {
          this.notices = this.notices?.concat(this.notices);
        }
      }, 25)
    }
  }

  stopNoticeTask() {
    if (this.noticeTaskId !== 0) {
      clearInterval(this.noticeTaskId);
      this.noticeTaskId = 0;
    }
  }

  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}) {
      Scroll() {
        RelativeContainer() {
          Image($r('app.media.ic_home_top_bg')).width('100%').aspectRatio(1.973)

          Swiper() {
            ForEach(this.banners, (item: BannerEntity) => {
              Image(item.image).width('100%').aspectRatio(2.5).margin({left: 12, right: 12})
                .onClick(() => {
                  switch (item.page) {
                    case 'vip': {
                      if (LoginManager.getUserInfo()?.vip !== 3) {
                        this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIP_PAGE, params: {origin: 'banner'}})
                        EventReportManager.eventReport(EventConstants.JUMP_TO_MEMBER_RECHARGE, 'banner')
                      }
                      break;
                    }
                    case 'check_Task': {
                      break
                    }
                    case 'course': {
                      this.getUIContext().getRouter().pushUrl({url: RouterUrls.COURSE_PAGE})
                      break
                    }
                    case 'web_link': {
                      WantUtil.toWebBrowser(Constants.WEB_URL)
                      break
                    }
                  }
                })
                .borderRadius(10)
            })
          }
          .indicator(
            Indicator.dot()
              .itemWidth(4)
              .itemHeight(4)
              .selectedItemWidth(12)
              .selectedItemHeight(4)
              .color('#D6D6D6')
              .selectedColor(Color.White)
          )
          .loop(this.banners && this.banners.length > 1)
          .autoPlay(true)
          .interval(2000)
          .margin({ top: 70 })
          .visibility(this.banners && this.banners.length > 0 ? Visibility.Visible : Visibility.None)
          .id('swiper_banner')

          RelativeContainer() {
            List({space: 100, scroller: this.noticeScroller}) {
              if (this.notices && this.notices.length >= 1) {
                ForEach(this.notices, (item: string) => {
                  ListItem() {
                    Text(item).height('100%').textAlign(TextAlign.Center).fontColor('#1876E2').fontSize(13)
                  }
                })
              }
            }
            .listDirection(Axis.Horizontal)
            .backgroundColor('#E4EDFD')
            .borderRadius(borderRadiuses(6))
            .alignRules({
              top: { anchor: '__container__', align: VerticalAlign.Top },
              bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
              left: { anchor: '__container__', align: HorizontalAlign.Start },
              right: { anchor: '__container__', align: HorizontalAlign.End }
            })
            .scrollBar(BarState.Off)
            .enableScrollInteraction(false)
            .margin({ left: 12, right: 12 })
            .padding({left: 45})
            .height(36)
            .id('li_notice')

            Image($r('app.media.ic_notice'))
              .alignRules({
                top: { anchor: '__container__', align: VerticalAlign.Top },
                bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
              })
              .margin({ left: 5, bottom: 2 })
              .width(54)
              .height(54)
          }
          .alignRules({
            top: { anchor: 'swiper_banner', align: VerticalAlign.Bottom }
          })
          .margin({top: 11})
          .width('100%')
          .height(54)
          .visibility(this.notices && this.notices?.length > 0 ? Visibility.Visible : Visibility.None)
          .id('layout_notice')

          Row() {
            Column() {
              Row() {
                Text('链接提取').fontColor('#15005D').fontSize(17).fontFamily('almmsht')
                Image($r('app.media.ic_home_top_menu_arrow1')).width(12).height(12).margin({left: 2})
              }
              Text('涵盖大多数平台').fontColor($r('app.color.color_666666')).fontSize(11).margin({top: 4})
              Blank().layoutWeight(1)
              Text('1000+国内外视频平台').fontColor($r('app.color.color_999999')).fontSize(10)
              Row({space: 6}){
                Image($r('app.media.ic_home_link_support_icon1')).width(30).width(30)
                Image($r('app.media.ic_home_link_support_icon2')).width(30).width(30)
                Image($r('app.media.ic_home_link_support_icon3')).width(30).width(30)
                Text('更多').fontColor(Color.White).fontSize(10).width(30).height(30).textAlign(TextAlign.Center).backgroundColor('#825EFF').borderRadius(6)
              }
              .margin({top: 8})
              Row() {
                Image($r('app.media.yq_0')).width(14).height(14).borderRadius(7)
                Image($r('app.media.yq_1')).width(14).height(14).borderRadius(7).margin({left: -4})
                Image($r('app.media.yq_2')).width(14).height(14).borderRadius(7).margin({left: -4})
                Text('1000+用户体验中').fontColor($r('app.color.color_999999')).fontSize(10).margin({left: 6})
              }
              .margin({top: 12})
            }
            .width('52.7%')
            .aspectRatio(1.12)
            .backgroundImage($r('app.media.ic_home_top_menu_bg1'))
            .backgroundImageSize({width: '100%', height: '100%'})
            .padding({left: 10, top: 25, right: 10, bottom: 8})
            .alignItems(HorizontalAlign.Start)
            .id('layout_link')
            .onClick(() => {
              // let info = AppUtil.getSignatureInfoSync()
              this.getUIContext().getRouter().pushUrl({url: RouterUrls.TAKE_MATERIAL_PAGE})
              EventReportManager.eventReport(EventConstants.JUMP_TO_LINK_EXTRACT)
            })

            Column() {
              Column() {
                Row() {
                  Text('视频号').fontColor('#113100').fontSize(16).fontFamily('almmsht')
                  Image($r('app.media.ic_home_top_menu_arrow2')).width(12).height(12).margin({left: 2})
                }
                Text('支持微信视频号').fontColor($r('app.color.color_666666')).fontSize(11).margin({top: 3})
                Blank().layoutWeight(1)
                Row() {
                  Image($r('app.media.yq_3')).width(14).height(14).borderRadius(7)
                  Image($r('app.media.yq_4')).width(14).height(14).borderRadius(7).margin({left: -4})
                  Image($r('app.media.yq_5')).width(14).height(14).borderRadius(7).margin({left: -4})
                  Text('1200+用户体验中').fontColor($r('app.color.color_999999')).fontSize(10).margin({left: 6})
                }
              }
              .width('48.7%')
              .aspectRatio(1.965)
              .backgroundImage($r('app.media.ic_home_top_menu_bg2'))
              .backgroundImageSize({width: '100%', height: '100%'})
              .padding({left: 10, top: 20, right: 10, bottom: 8})
              .margin({top: -5})
              .alignItems(HorizontalAlign.Start)
              .id('layout_wx_video')
              .onClick(() => {
                this.getUIContext().getRouter().pushUrl({url: RouterUrls.WX_VIDEO_PAGE, params: { isPlayback: false }})
                EventReportManager.eventReport(EventConstants.JUMP_TO_WECHAT_VIDEO)
              })

              Column() {
                Row() {
                  Text('直播回放').fontColor('#4A0006').fontSize(16).fontFamily('almmsht')
                  Image($r('app.media.ic_home_top_menu_arrow3')).width(12).height(12).margin({left: 2})
                }
                Text('支持微信直播回放').fontColor($r('app.color.color_666666')).fontSize(11).margin({top: 3})
                Blank().layoutWeight(1)
                Row() {
                  Image($r('app.media.yq_6')).width(14).height(14).borderRadius(7)
                  Image($r('app.media.yq_7')).width(14).height(14).borderRadius(7).margin({left: -4})
                  Image($r('app.media.yq_8')).width(14).height(14).borderRadius(7).margin({left: -4})
                  Text('2000+用户体验中').fontColor($r('app.color.color_999999')).fontSize(10).margin({left: 6})
                }
              }
              .width('48.7%')
              .aspectRatio(2.28)
              .backgroundImage($r('app.media.ic_home_top_menu_bg3'))
              .backgroundImageSize({width: '100%', height: '100%'})
              .padding({left: 10, top: 9, right: 10, bottom: 8})
              .margin({top: 9})
              .alignItems(HorizontalAlign.Start)
              .id('layout_wx_playback')
              .onClick(() => {
                TipDialog.show(this.getUIContext(), {title: '提示', content: '仅限微信直播回放视频提取，是否前往？', callback: {
                  confirm: () => {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.WX_VIDEO_PAGE, params: { isPlayback: true }})
                    EventReportManager.eventReport(EventConstants.JUMP_TO_WECHAT_PLAYBACK)
                  }
                }})
              })
            }
          }
          .alignRules({
            top: { anchor: 'layout_notice', align: VerticalAlign.Bottom }
          })
          .padding({left: 12, right: 12})
          .margin({ top: 10 })
          .height('auto')
          .id('layout_top_menu')

          Grid() {
            ForEach(homeMenuList().convertToArray(), (item: MenuEntity) => {
              GridItem() {
                Column() {
                  Image(item.icon)
                    .width(44)
                    .height(44)
                  Text(item.title)
                    .fontColor($r('app.color.color_212226'))
                    .fontSize(12)
                    .margin({ top: 6 })
                }
                .alignItems(HorizontalAlign.Center)
              }
              .width('20%')
              .onClick(() => {
                switch (item.alias) {
                  case 'videoToAudio': {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIDEO_TO_AUDIO_PAGE})
                    break
                  }
                  case 'addWatermark': {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.ADD_WATERMARK_PAGE})
                    break
                  }
                  case 'videoToText': {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIDEO_TO_TEXT_PAGE})
                    break
                  }
                  case 'longImageMerge': {
                    this.getUIContext().getRouter().pushUrl({url: RouterUrls.IMAGE_MERGE_PAGE})
                    break
                  }
                  case 'moreTools': {
                    AppUtil.getContext().eventHub.emit(EventConstants.JumpToToolsEvent);
                    break
                  }
                }
              })
            })
          }
          .maxCount(5)
          .layoutDirection(GridDirection.Row)
          .alignRules({
            top: { anchor: 'layout_top_menu', align: VerticalAlign.Bottom }
          })
          .margin({
            top: 20,
            left: 12,
            right: 12
          })
          .id('li_menu')

          Column() {
            Stack() {
              Image($r('app.media.ic_tab_indicator')).width(27).height(11).margin({top: 13})
              Text('高清推荐素材').fontColor($r('app.color.color_212226')).fontSize(16).fontWeight(FontWeight.Medium)
            }
            .alignSelf(ItemAlign.Start)
            .margin({left: 12, top: 27})

            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})
            .margin({top: 14})
            .onReachEnd(() => {
              this.page++
              this.isLoading = true
              this.viewModel.getMaterialList(this.page.toString())
            })
            .nestedScroll({
              scrollForward: NestedScrollMode.PARENT_FIRST,
              scrollBackward: NestedScrollMode.SELF_FIRST
            })
          }
          .alignRules({
            top: {anchor: 'li_menu', align: VerticalAlign.Bottom}
          })
          .height('100%')
        }
        .height('auto')
      }
      .scrollBar(BarState.Off)
    }
    .backgroundColor(Color.White)
    .onRefreshing(() => {
      this.page = 1
      this.isRefreshing = true
      this.viewModel.getMaterialList(this.page.toString())
    })
  }

  @Builder
  itemFoot() {
    // 注意：不要直接用IfElse节点作为footer的根节点
    // 必须在外面使用(Column/Row/Stack等)容器包裹，确保布局正确
    Column() {
      if (!this.canLoadMore) {
        Text('到底啦')
          .width('100%')
          .height(50)
          .textAlign(TextAlign.Center)
      } else if (this.isLoading) {
        Row() {
          LoadingProgress().height(32).width(48)
          Text("加载中")
        }.width("100%")
        .height(50)
        .justifyContent(FlexAlign.Center)
      }
    }
  }
}