import {
  AppUtil, FileUtil, ObjectUtil, PasteboardUtil, RandomUtil, StrUtil
} from '@pura/harmony-utils';
import { EventConstants } from '../../../../common/EventConstants';
import { RouterUrls } from '../../../../common/RouterUrls';
import { DownloadDialog, DownloadStatus } from '../../../../dialog/DownloadDialog';
import { ImageMaterial, MaterialInfoEntity, MediaEntity, VideoMaterial } from '../../../../entity/MaterialInfoEntity';
import { VipAuthEntity } from '../../../../entity/VipAuthEntity';
import { LoginManager } from '../../../../manager/LoginGlobalManager';
import { ShareManager } from '../../../../manager/ShareManager';
import { ConfigManager } from '../../../../manager/UserConfigManager';
import { MediaDownloader } from '../../../../net/MediaDownloader';
import { SaveUtils } from '../../../../utils/SaveUtils';
import { ToastUtils } from '../../../../utils/ToastUtils';
import { TitleBar } from '../../../../view/TitleBar';
import { WxVideoViewModel } from '../../../../viewModel/WxVideoViewModel';
import { WxVideoMaterialPage } from './material/WxVideoMaterialPage';
import { CommonModifier, LevelMode, router } from '@kit.ArkUI';
import { WxImageMaterialPage } from './material/WxImageMaterialPage';
import { OnWXResp, WXApi, WXEventHandler } from '../../../../utils/wechat/WXApiEventHandlerImpl';
import * as WxOpenSdk from '@tencent/wechat_open_sdk';
import { ErrCode, SendAuthResp } from '@tencent/wechat_open_sdk';
import { LoadingDialog } from '../../../../dialog/LoadingDialog';
import BuildProfile from 'BuildProfile';
import { Constants } from '../../../../common/Constants';
import { EventReportManager } from '../../../../manager/EventReportManager';
import { TipDialog } from '../../../../dialog/TipDialog';
import { SimpleTipDialog } from '../../../../dialog/SimpleTipDialog';
import { JoinWxGroupCourseDialog } from '../../../../dialog/JoinWxGroupCourseDialog';
import { PrefUtils } from '../../../../utils/PrefUtils';
import { WxVideoServiceEntity } from '../../../../entity/WxVideoServiceEntity';

@Entry
@ComponentV2
struct WxVideoPage {
  @Local tabBarModifier: CommonModifier = new CommonModifier()
  @Local isPlayback: boolean = false
  @Local currentIndex: number = 0;
  @Local isRefreshing: boolean = false;
  @Local videoList: Array<VideoMaterial> = [];
  @Local imageList: Array<ImageMaterial> = [];
  @Local videoRowCount: number = 1;
  @Local imageRowCount: number = 1;
  viewModel: WxVideoViewModel = new WxVideoViewModel(this.getUIContext());
  tabController: TabsController = new TabsController();
  titles: Array<string> = ['视频', '图片'];
  type: number = 0
  mediaDownloader?: MediaDownloader | null
  selectedList: Array<MediaEntity> = []
  cacheFileUris: Array<string> = []
  downloadIndex: number = 0
  totalSize = 0
  downloadStatus = DownloadStatus.DOWNLOADING
  joinGroupDialogController?: CustomDialogController | null;
  //从微信返回的回调
  onWXResp: OnWXResp = (resp) => {
    //微信返回的数据
    if (resp instanceof SendAuthResp && resp.state?.endsWith('video')) {
      const authResult = JSON.stringify(resp ?? {}, null, 2);
      const errCode = JSON.parse(authResult).errCode as number;
      if (errCode === ErrCode.ERR_OK) {
        const authCode = JSON.parse(authResult).code as string;
        if (ConfigManager.getPlaybackJoinType() === "img") {
          this.showJoinGroupCourseDialog()
        } else {
          this.viewModel.bindWxUserinfo(authCode)
        }
      } else {
        ToastUtils.show(JSON.parse(authResult).errStr);
      }
    }
  }

  @Monitor('viewModel.wxVideoList')
  onMaterialInfoChange(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<MaterialInfoEntity>
    this.createVideoList(list);
    this.createImageList(list);
    if (this.videoList.length > 0) {
      this.tabController.changeIndex(0);
      this.currentIndex = 0
    } else if (this.imageList.length > 0) {
      this.tabController.changeIndex(1);
      this.currentIndex = 1
    }
    this.isRefreshing = false
  }

  @Monitor('viewModel.authInfo')
  onPermissionInfoChange(monitor: IMonitor) {
    const info = monitor.value()?.now as VipAuthEntity;
    if (info.auth) {
      if (!LoginManager.isLogin()) {
        this.getUIContext()
          .getRouter()
          .pushUrl({ url: RouterUrls.LOGIN_PAGE, params: { from: 1 } }, router.RouterMode.Single)
        return;
      }
      this.shareOrDownload()
    } else {
      if (!info.auth_ad) {
        this.getUIContext()
          .getRouter()
          .pushUrl({ url: RouterUrls.VIP_PAGE, params: { origin: 'download_wechat_video' } })
        EventReportManager.eventReport(EventConstants.JUMP_TO_MEMBER_RECHARGE, 'download_wechat_video')
        return;
      }
    }
  }

  @Monitor('viewModel.errorCode')
  onErrorCodeChange(monitor: IMonitor) {
    const errorCode = monitor.value()?.now as number;
    if (errorCode === 12002 || errorCode === 12003 || errorCode === 12004) {
      this.getUIContext().getRouter().pushUrl({ url: RouterUrls.RECHARGE_DIAMOND_PAGE });
      EventReportManager.eventReport(EventConstants.JUMP_TO_RECHARGE_DIAMOND, 'download_wechat_video')
      ToastUtils.show('M币已用完')
    }
  }

  @Monitor('viewModel.deleteVideo')
  onDeleteVideo(monitor: IMonitor) {
    this.isRefreshing = true
    ToastUtils.show('删除成功')
  }

  @Monitor('viewModel.wxService')
  onWxServiceChange(monitor: IMonitor) {
    const info = monitor.value()?.now as WxVideoServiceEntity;
    if (StrUtil.isEmpty(info.corp_id) || StrUtil.isEmpty(info.link)) {
      ToastUtils.show('获取客服信息错误')
    } else {
      ConfigManager.saveBindWxVideoHelper(true)
      this.contactWxService(info)
    }
  }

  @Monitor('viewModel.wxUserinfo')
  onWxUserinfoChange(monitor: IMonitor) {
    if (this.isPlayback) {
      ConfigManager.saveBindWxPlaybackHelper(true)
    } else {
      ConfigManager.saveBindWxVideoHelper(true)
    }
    this.jumpToMiniProgram()
  }

  aboutToAppear(): void {
    WXEventHandler.registerOnWXRespCallback(this.onWXResp)
    this.tabBarModifier.align(Alignment.Start)
    this.initParams()
    this.checkBindStatus()
  }

  aboutToDisappear() {
    WXEventHandler.unregisterOnWXRespCallback(this.onWXResp)
  }

  onPageShow(): void {
    this.isRefreshing = true
  }

  initParams() {
    const params = this.getUIContext().getRouter().getParams() as Record<string, Object>;
    if (params) {
      this.isPlayback = params.isPlayback as boolean
    }
  }

  showSaveTip() {
    if (PrefUtils.getBoolean('show_save_tip', true)) {
      SimpleTipDialog.show(this.getUIContext(), {
        title: '重要提示', content: '下载完成后需要您点击弹窗允许保存之后才能保存文件到相册', callback: {
          confirm: () => {
            this.viewModel.checkVip();
            PrefUtils.put('show_save_tip', false)
          }
        }
      })
    } else {
      this.viewModel.checkVip()
    }
  }

  shareOrDownload() {
    this.cacheFileUris.length = 0
    if (this.type == 0) {
      if (this.selectedList.length > 0) {
        this.shareMedia(this.selectedList[0])
      }
    } else {
      if (this.selectedList.length > 0) {
        this.downloadIndex = 0
        this.downloadMedia(this.selectedList[this.downloadIndex])
      }
    }
  }

  shareMedia(media: MediaEntity) {
    let filePath = FileUtil.getCacheDirPath() + FileUtil.separator + media.initFileName()
    if (FileUtil.accessSync(filePath) && FileUtil.isFile(filePath) &&
      !(media.totalSize === 0 || media.currentLen !== media.totalSize)) {
      this.shareFile(media)
    } else {
      this.showDownloadDialog(media instanceof VideoMaterial && media.isMerge ? DownloadStatus.VIDEO_DOWNLOADING :
      DownloadStatus.DOWNLOADING)
      this.download(media, true)
    }
  }

  async downloadMedia(media: MediaEntity) {
    let filePath = FileUtil.getCacheDirPath() + FileUtil.separator + media.initFileName()
    if (FileUtil.accessSync(filePath) && FileUtil.isFile(filePath) &&
      !(media.totalSize === 0 || media.currentLen !== media.totalSize)) {
      this.cacheFileUris.push(FileUtil.getUriFromPath(filePath))
      if (this.downloadIndex < this.selectedList.length - 1) {
        this.downloadIndex++
        this.downloadMedia(this.selectedList[this.downloadIndex])
      } else {
        let saved = await this.saveFile()
        if (saved) {
          if (this.downloadIndex < this.selectedList.length - 1) {
            this.downloadIndex++
            this.downloadMedia(this.selectedList[this.downloadIndex])
          } else {
            this.updateDownloadDialog(DownloadStatus.COMPLETED, this.totalSize, this.totalSize)
          }
        } else {
          ToastUtils.show('保存失败')
          this.dismissDownloadDialog()
        }
        this.isRefreshing = true
      }
    } else {
      this.showDownloadDialog(media instanceof VideoMaterial && media.isMerge ? DownloadStatus.VIDEO_DOWNLOADING :
      DownloadStatus.DOWNLOADING)
      this.download(media)
    }
  }

  async download(media: MediaEntity, isShare: boolean = false) {
    this.viewModel.reportStatus(media.logid, '1')
    media.initFileName()
    this.mediaDownloader = MediaDownloader.getInstance()
    this.mediaDownloader
      .callback({
        onSuccess: async (path) => {
          if (isShare) {
            this.shareFile(media)
          } else {
            this.cacheFileUris.push(FileUtil.getUriFromPath(path))
            if (this.downloadIndex < this.selectedList.length - 1) {
              this.downloadIndex++
              this.downloadMedia(this.selectedList[this.downloadIndex])
            } else {
              let saved = await this.saveFile()
              if (saved) {
                if (this.downloadIndex < this.selectedList.length - 1) {
                  this.downloadIndex++
                  this.downloadMedia(this.selectedList[this.downloadIndex])
                } else {
                  this.updateDownloadDialog(DownloadStatus.COMPLETED, this.totalSize, this.totalSize)
                }
              } else {
                ToastUtils.show('保存失败')
                this.dismissDownloadDialog()
              }
              this.isRefreshing = true
            }
          }
        },
        onGetTotal: (total) => {
          this.totalSize = total
          this.updateDownloadDialog(this.downloadStatus, total)
        },
        onProgress: (progress) => {
          this.updateDownloadDialog(this.downloadStatus, this.totalSize, progress)
        },
        onMerge: (step) => {
          if (step === 4) {
            this.updateDownloadDialog(DownloadStatus.AUDIO_DOWNLOADING)
          } else {
            this.updateDownloadDialog(DownloadStatus.PROCESSING)
          }
        },
        onPause: () => {
          this.dismissDownloadDialog()
        },
        onCancel: () => {
          this.dismissDownloadDialog()
        },
        onFailed: (msg) => {
          ToastUtils.show('下载失败：' + msg)
          this.dismissDownloadDialog()
          this.viewModel.reportStatus(media.logid, '-1', `${media.totalSize}`, msg)
          this.reportErrorEvent(media, msg)
        }
      })
      .down(media);
  }

  shareFile(media: MediaEntity) {
    ShareManager.shareFile(FileUtil.getCacheDirPath() + FileUtil.separator + media.initFileName())
    this.viewModel.reportStatus(media.logid, '2', `${media.totalSize}`)
    this.dismissDownloadDialog()
  }

  async saveFile(): Promise<boolean> {
    let saved = await SaveUtils.saveImageVideoToAlbumDialog(this.cacheFileUris)
    if (saved) {
      this.cacheFileUris.forEach((uri, index) => {
        let stat = FileUtil.statSync(FileUtil.getFilePath(uri))
        this.viewModel.reportStatus(this.selectedList[index].logid, '2', `${stat.size}`)
      })
    }
    return Promise.resolve(saved)
  }

  showDownloadDialog(status: DownloadStatus = DownloadStatus.DOWNLOADING) {
    this.downloadStatus = status
    DownloadDialog.show(this.getUIContext(), {
      status: status,
      totalSize: 0,
      progress: 0,
      totalCount: this.selectedList.length,
      index: this.downloadIndex,
      callback: {
        confirm: () => {
          if (this.downloadStatus === DownloadStatus.COMPLETED) {
            EventReportManager.eventReport(EventConstants.DIALOG_GO_TO_VIEW, this.titles[this.currentIndex])
            AppUtil.getContext().eventHub.emit(EventConstants.JumpToRecordEvent, this.currentIndex)
            this.getUIContext().getRouter().back()
          } else {
            //todo 后台下载
          }
        },
        cancel: () => {
          if (this.downloadStatus !== DownloadStatus.COMPLETED) {
            if (this.mediaDownloader) {
              this.mediaDownloader.cancel()
              EventReportManager.eventReport(EventConstants.CANCEL_DOWNLOAD_VIDEO,
                this.selectedList[this.downloadIndex].url)
            }
          } else {
            EventReportManager.eventReport(EventConstants.DIALOG_CONFIRM_SAVE_FILE,
              this.titles[this.currentIndex])
          }
        }
      }
    })
  }

  updateDownloadDialog(status: DownloadStatus = DownloadStatus.DOWNLOADING, totalSize: number = 0, progress: number = 0,
    isAudio: boolean = false) {
    this.downloadStatus = status
    DownloadDialog.update({
      status: status,
      totalSize: totalSize,
      progress: progress,
      totalCount: this.selectedList.length,
      index: this.downloadIndex,
      isAudio: isAudio
    })
  }

  dismissDownloadDialog() {
    this.downloadStatus = DownloadStatus.DOWNLOADING
    this.totalSize = 0
    this.downloadIndex = 0
    this.mediaDownloader = null
    DownloadDialog.dismiss()
  }

  createVideoList(materials?: Array<MaterialInfoEntity>) {
    const list = new Array<VideoMaterial>();
    materials?.forEach((info) => {
      info.material?.video?.forEach((video, index) => {
        video.logid = info.logid
        video.isThreading = info.material!!.threading
        if (info.material?.image && info.material.image.length > index) {
          video.thumb = info.material.image[index].url
        }
        video.flag = RandomUtil.getRandomNumber(0, 1000)
        list.push(video)
      })
    })
    this.videoList = list.map(item => ObjectUtil.assign(new VideoMaterial(), item) as VideoMaterial);
    if (this.videoList.length > 0) {
      this.videoList[0].isChecked = true
    }
    this.videoRowCount = this.computeRowCount(this.videoList);
  }

  createImageList(materials?: Array<MaterialInfoEntity>) {
    const list = new Array<ImageMaterial>();
    materials?.forEach((info) => {
      info.material?.image?.forEach((image) => {
        image.logid = info.logid
        image.flag = RandomUtil.getRandomNumber(0, 1000)
        list.push(image)
      })
    })
    this.imageList = list.map(item => ObjectUtil.assign(new ImageMaterial(), item) as ImageMaterial);
    if (this.imageList.length > 0) {
      this.imageList[0].isChecked = true
    }
    this.imageRowCount = this.computeRowCount(this.imageList);
  }

  computeRowCount(list: Array<MediaEntity>): number {
    if (list.length > 8) {
      return 3;
    } else if (list.length >= 3 && list.length <= 8) {
      return 2;
    } else {
      return 1;
    }
  }

  checkBindStatus() {
    if (this.isPlayback && !ConfigManager.isBindWxPlaybackHelper() ||
      !this.isPlayback && !ConfigManager.isBindWxVideoHelper()) {
      if (LoginManager.getLastUserInfo()?.user_id !== LoginManager.getUserInfo()?.user_id) {
        TipDialog.show(this.getUIContext(), {
          title: '提示', content: '系统检测到您更换了账号，请重新添加助手', callback: {
            confirm: () => {
              if (this.isPlayback || !ConfigManager.isWxVideoServiceEnable()) {
                if (ConfigManager.getPlaybackJoinType() === "img") {
                  this.showJoinGroupCourseDialog()
                } else {
                  this.wxAuth()
                }
              } else {
                this.getWxServiceInfo()
              }
            }
          }
        })
      }
    }
  }

  showJoinGroupCourseDialog() {
    this.joinGroupDialogController = new CustomDialogController({
      builder: JoinWxGroupCourseDialog({ isPlayback: this.isPlayback }),
      width: '100%',
      cornerRadius: 20,
      autoCancel: true,
      maskColor: '#CC000000',
      levelMode: LevelMode.EMBEDDED,
      backgroundBlurStyle: BlurStyle.NONE,
      alignment: DialogAlignment.Bottom
    })
    this.joinGroupDialogController.open();
  }

  async wxAuth() {
    if (!WXApi.isWXAppInstalled()) {
      ToastUtils.show('未安装微信客户端，请先下载安装微信客户端');
      return;
    }
    LoadingDialog.show(this.getUIContext());
    let req = new WxOpenSdk.SendAuthReq;
    req.isOption1 = false;
    req.nonAutomatic = true;
    req.scope = 'snsapi_userinfo';
    req.state = BuildProfile.BUNDLE_NAME + RandomUtil.getRandomInt(0, 1000) + '_video';
    req.transaction = '';

    await WXApi.sendReq(AppUtil.getContext(), req)
    EventReportManager.eventReport(EventConstants.JUMP_TO_SHARE_WX_PLAYBACK, '前往微信分享直播回放')
    LoadingDialog.dismiss();
  }

  async jumpToMiniProgram() {
    //保存成功跳转直播回放加群小程序
    try {
      let wxVideoConfig = ConfigManager.getWxVideoConfig()
      if (wxVideoConfig != null && LoginManager.getUserInfo()) {
        PasteboardUtil.setDataText(`${LoginManager.getUserInfo()!!.user_id}|${Constants.APP_ID}`)

        wxVideoConfig.id = `${LoginManager.getUserInfo()!!.user_id}|${Constants.APP_ID}`
        let params = encodeURI(JSON.stringify(wxVideoConfig)).replace('+', '%20')
        let launchMiniProgramReq = new WxOpenSdk.LaunchMiniProgramReq()
        launchMiniProgramReq.userName = Constants.MINI_PROGRAM_APP_ID //拉起的小程序的原始id
        launchMiniProgramReq.path = `pages/index/index?path=share&param=${params}`
        launchMiniProgramReq.miniprogramType = 0 //拉起小程序的类型 0-正式版 1-开发版 2-体验版
        await WXApi.sendReq(AppUtil.getContext(), launchMiniProgramReq)
      } else {
        ToastUtils.show('获取配置失败，请联系客服')
      }
    } catch (e) {
      ToastUtils.show('跳转失败，请联系客服')
    }
  }

  getWxServiceInfo() {
    if (!WXApi.isWXAppInstalled()) {
      ToastUtils.show('未安装微信客户端，请先下载安装微信客户端');
      return;
    }
    this.viewModel.wxServiceInfo()
    EventReportManager.eventReport(EventConstants.JUMP_TO_SHARE_WX_VIDEO, "前往微信分享视频号", '')
  }

  /**
   * 跳转客服
   * @param service
   */
  contactWxService(service: WxVideoServiceEntity) {
    let req = new WxOpenSdk.OpenCustomerServiceChatReq()
    req.corpId = service.corp_id; // 企业ID
    req.url = service.link; // 客服URL
    WXApi.sendReq(AppUtil.getContext(), req)
  }

  reportErrorEvent(media: MediaEntity, message: string) {
    if (media instanceof VideoMaterial) {
      EventReportManager.eventReport(EventConstants.ERROR_CLIENT_DOWNLOAD_VIDEO, media.url, message)
    } else if (media instanceof ImageMaterial) {
      EventReportManager.eventReport(EventConstants.ERROR_CLIENT_DOWNLOAD_IMG, media.url, message)
    }
  }

  build() {
    RelativeContainer() {
      Column() {
        TitleBar({ title: this.isPlayback ? '直播回放' : '视频号' })

        Refresh({ refreshing: this.isRefreshing }) {
          Stack({ alignContent: Alignment.TopEnd }) {
            Tabs({ barPosition: BarPosition.Start, controller: this.tabController, barModifier: this.tabBarModifier }) {
              TabContent() {
                WxVideoMaterialPage({
                  mediaList: this.videoList,
                  rowCount: this.videoRowCount,
                  isPlayback: this.isPlayback,
                  onShare: (video) => {
                    this.type = 0
                    this.selectedList.length = 0
                    this.selectedList.push(video)
                    this.viewModel.checkVip();
                  },
                  onSave: (list) => {
                    this.type = 1
                    this.selectedList = list
                    this.showSaveTip();
                  },
                  onItemDelete: (video) => {
                    TipDialog.show(this.getUIContext(), {
                      title: '提示', content: this.isPlayback ? '确定删除该直播回放？' : '确定删除该视频号？', callback: {
                        confirm: () => {
                          this.viewModel.deleteWxVideo(video.logid)
                        }
                      }
                    })
                  }
                })
              }
              .tabBar(this.tabBuilder(this.titles[0], 0))

              TabContent() {
                WxImageMaterialPage({
                  mediaList: this.imageList,
                  rowCount: this.imageRowCount,
                  isPlayback: this.isPlayback,
                  onShare: (image) => {
                    this.type = 0
                    this.selectedList.length = 0
                    this.selectedList.push(image)
                    this.viewModel.checkVip();
                  },
                  onSave: (list) => {
                    this.type = 1
                    this.selectedList = list
                    this.showSaveTip();
                  },
                  onItemDelete: (image) => {
                    TipDialog.show(this.getUIContext(), {
                      title: '提示', content: this.isPlayback ? '确定删除该直播回放？' : '确定删除该视频号？', callback: {
                        confirm: () => {
                          this.viewModel.deleteWxVideo(image.logid)
                        }
                      }
                    })
                  }
                })
              }
              .tabBar(this.tabBuilder(this.titles[1], 1))
            }
            .scrollable(false)
            .barMode(BarMode.Scrollable)
            .onSelected((index: number) => {
              this.currentIndex = index;
            })

            Row() {
              Image($r('app.media.ic_video_course')).width(16).height(16)
              Text('视频教程').fontColor($r('app.color.color_212226')).fontSize(12).margin({ left: 4 })
            }
            .onClick(() => {
              if (this.isPlayback) {
                this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIDEO_PLAYER_PAGE, params: {uri: ConfigManager.getPlaybackCourse(), title: '视频教程'}})
              } else {
                this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIDEO_PLAYER_PAGE, params: {uri: ConfigManager.getWxVideoCourse(), title: '视频教程'}})
              }
            })
            .height(50)
            .margin({ top: 3, right: 16 })
          }
        }
        .layoutWeight(1)
        .onRefreshing(() => {
          this.isRefreshing = true
          this.viewModel.videoList()
        })
        .refreshOffset(50)
        .pullToRefresh(true)
      }

      Row() {
        Image(this.isPlayback ? $r('app.media.ic_playback_helper') : $r('app.media.ic_video_helper'))
          .width(26)
          .height(26)
        Text(this.isPlayback ? '添加直播\n回放助手' : '添加助手')
          .margin({ left: 6 })
          .fontColor(this.isPlayback ? '#FF9614' : '#008EFF')
          .fontSize(12)
        Image(this.isPlayback ? $r('app.media.ic_playback_helper_arrow') : $r('app.media.ic_video_helper_arrow')).width(16).height(16).margin({ left: 2 })
      }
      .padding(8)
      .backgroundColor(Color.White)
      .borderRadius({ topLeft: 10, bottomLeft: 10 })
      .alignRules({
        right: { anchor: '__container__', align: HorizontalAlign.End },
        bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
      })
      .margin({ bottom: 100 })
      .onClick(() => {
        if (this.isPlayback || !ConfigManager.isWxVideoServiceEnable()) {
          if (ConfigManager.getPlaybackJoinType() === "img") {
            this.showJoinGroupCourseDialog()
          } else {
            this.wxAuth()
          }
        } else {
          this.getWxServiceInfo()
        }
      })
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Stack() {
      if (this.currentIndex === targetIndex) {
        Image($r('app.media.ic_tab_indicator')).width(27).height(11).margin({ top: 13 })
      }
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? $r("app.color.color_212226") : $r('app.color.color_5c5f6c'))
        .fontSize(this.currentIndex === targetIndex ? 16 : 14)
        .fontWeight(this.currentIndex === targetIndex ? FontWeight.Medium : FontWeight.Regular)
    }
    .width('auto')
    .height(50)
    .margin({ left: targetIndex === 0 ? 16 : 40 })
  }
}