ImageAndTextPageComponent.ets 12.2 KB
import {
  Logger,
  NumberFormatterUtils,
  DateTimeUtils,
  EmitterUtils,
  EmitterEventId,
  NetworkUtil,
  DisplayUtils
} from 'wdKit';
import {
  Action,
  ContentDetailDTO,
  ContentDTO,
  postRecommendListParams,
  postExecuteLikeParams,
  batchLikeAndCollectResult,
  batchLikeAndCollectParams,
  InteractDataDTO,
  contentListParams,
} from 'wdBean';
import DetailViewModel from '../viewmodel/DetailViewModel';
import { ImageAndTextWebComponent } from './ImageAndTextWebComponent';
import { OperRowListView } from './view/OperRowListView';
import { RecommendList } from '../components/view/RecommendList'
import { CommonConstants } from 'wdConstant';
import { WDRouterPage, WDRouterRule } from 'wdRouter/Index';
import { MultiPictureDetailViewModel } from '../viewmodel/MultiPictureDetailViewModel';
import { PageRepository } from '../repository/PageRepository';
import { detailedSkeleton } from './skeleton/detailSkeleton';
import { publishCommentModel } from '../components/comment/model/PublishCommentModel';
import { EmptyComponent } from '../components/view/EmptyComponent';
import { CommentComponent } from '../components/comment/view/CommentComponent'
import { HttpUtils } from 'wdNetwork/Index';

const PATTERN_DATE_CN_RN: string = 'yyyy年MM月dd日 HH:mm';

const TAG: string = 'ImageAndTextPageComponent'

@Component
export struct ImageAndTextPageComponent {
  scroller: Scroller = new Scroller();
  action: Action = {} as Action
  @State contentDetailData: ContentDetailDTO [] = [] as ContentDetailDTO []
  @State recommendList: ContentDTO[] = []
  @State newsStatusOfUser: batchLikeAndCollectResult | undefined = undefined // 点赞、收藏状态
  @State interactData: InteractDataDTO = {} as InteractDataDTO
  @State isPageEnd: boolean = false
  @State publishTime: string = ''
  @State publishCommentModel: publishCommentModel = new publishCommentModel()
  @State operationButtonList: string[] = ['comment', 'collect', 'share']
  @State isNetConnected: boolean = true
  @State info: Area | null = null
  @State likeNum: number = 0
  build() {
    Column() {
      // 发布时间
      Row() {
        Image(this.contentDetailData[0]?.rmhInfo ? $r('app.media.logo_rmh') : $r('app.media.logo_rmrb'))
          .width(80)
          .height(28)
        Text(this.publishTime)
          .fontColor($r('app.color.color_B0B0B0'))
          .fontSize($r('app.float.font_size_13'))
      }
      .width(CommonConstants.FULL_WIDTH)
      .height(32)
      .padding({ left: 15, right: 15, })
      .justifyContent(FlexAlign.SpaceBetween)
      .alignItems(VerticalAlign.Bottom)

      Row() {
        Image($r('app.media.line'))
          .width('100%')
          .height(6)
          .objectFit(ImageFit.Cover)
          .margin({ top: 10 })
      }
      .padding({ left: 15, right: 15 })
      .backgroundColor(Color.White)

      Stack({ alignContent: Alignment.Bottom }) {
        Scroll(this.scroller) {
          Column() {
            ImageAndTextWebComponent({
              contentDetailData: this.contentDetailData,
              action: this.action,
              isPageEnd: $isPageEnd
            })
              .padding({bottom:10})
            Column() {
              // 点赞
              if (this.contentDetailData[0]?.openLikes && this.contentDetailData[0]?.likesStyle !== 4) {
                Row() {
                  Row() {
                    if (this.newsStatusOfUser?.likeStatus === '1') {
                      Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.ic_like_check') :
                        (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer_active') :
                        $r('app.media.icon_candle_active')))
                        .width(24)
                        .height(24)
                        .margin({ right: 5 })
                    } else {
                      Image(this.contentDetailData[0]?.likesStyle === 1 ? $r('app.media.icon_like') :
                        (this.contentDetailData[0]?.likesStyle === 2 ? $r('app.media.icon_prayer') :
                        $r('app.media.icon_candle')))
                        .width(24)
                        .height(24)
                    }
                    if (this.likeNum > 0) {
                      Text(NumberFormatterUtils.formatNumberWithWan(this.likeNum))
                        .fontSize(16)
                        .fontColor(this.newsStatusOfUser?.likeStatus === '1' ? '#ED2800' : '#999999')
                        .fontWeight(500)
                        .margin({ left: 5 })
                    }
                  }
                  .width(154)
                  .height(40)
                  .justifyContent(FlexAlign.Center)
                  .alignItems(VerticalAlign.Center)
                  .borderRadius(20)
                  .border({
                    width: 1,
                    color: '#EDEDED',
                  })
                  .onClick(() => {
                    this.toggleLikeStatus()
                  })

                }.width(CommonConstants.FULL_WIDTH)
                .padding({top:14,bottom:24})
                .justifyContent(FlexAlign.Center)
              }
              if (this.recommendList.length > 0) {
                Divider().strokeWidth(6).color('#f5f5f5')
                RecommendList({ recommendList: this.recommendList })
              }
              // 评论
              if (this.contentDetailData[0]?.openComment) {
                Divider().strokeWidth(6).color('#f5f5f5')
                CommentComponent({
                  publishCommentModel: this.publishCommentModel
                }).onAreaChange((oldValue: Area, newValue: Area) => {
                  this.info = newValue
                })
                // .onMeasureSize()

              }
            }
          }

        }
        .width(CommonConstants.FULL_WIDTH)
        // .height(CommonConstants.FULL_HEIGHT)
        .padding({ bottom: 76 })
        .scrollBar(BarState.Off)
        .align(Alignment.Top)

        if (!this.isNetConnected) {
          EmptyComponent({
            emptyType: 1,
            emptyButton: true,
            retry: () => {
              this.getDetail()
            }
          }).padding({ bottom: 200 })
        } else {
          if (!this.isPageEnd) {
            detailedSkeleton()
          }
        }
        //底部交互区
        OperRowListView({
          contentDetailData: this.contentDetailData[0],
          publishCommentModel: this.publishCommentModel,
          operationButtonList: this.operationButtonList,
        })
      }

    }
    .width(CommonConstants.FULL_WIDTH)
    .height(CommonConstants.FULL_HEIGHT)
    .backgroundColor(Color.White)
  }

  private async getDetail() {
    this.isNetConnected = NetworkUtil.isNetConnected()
    let contentId: string = ''
    let relId: string = ''
    let relType: string = ''
    if (this.action && this.action.params) {
      if (this.action.params.contentID) {
        contentId = this.action.params.contentID;
      }
      if (this.action && this.action.params && this.action.params.extra) {
        if (this.action.params.extra.relId) {
          relId = this.action.params.extra.relId;
        }
        if (this.action.params.extra.relType) {
          relType = this.action.params.extra.relType
        }

      }
      let detailBeans = await DetailViewModel.getDetailPageData(relId, contentId, relType)
      if (detailBeans && detailBeans.length > 0) {
        this.contentDetailData = detailBeans;
        let dateTime =
          DateTimeUtils.parseDate(this.contentDetailData[0]?.publishTime, DateTimeUtils.PATTERN_DATE_TIME_HYPHEN);
        let _publishTime = DateTimeUtils.formatDate(dateTime, PATTERN_DATE_CN_RN)
        this.publishTime = DateTimeUtils.removeTrailingZeros(_publishTime)
        if (this.contentDetailData[0]?.recommendShow === 1) {
          this.getRecommend()
        }
        if (this.contentDetailData[0]?.openLikes === 1) {
          this.getInteractDataStatus()
          this.queryContentInteractCount()
        }
        if (this.contentDetailData[0]?.openComment) {
          this.publishCommentModel.targetId = String(this.contentDetailData[0]?.newsId || '')
          this.publishCommentModel.targetRelId = String(this.contentDetailData[0]?.reLInfo?.relId)
          this.publishCommentModel.targetTitle = this.contentDetailData[0]?.newsTitle
          this.publishCommentModel.targetRelType = String(this.contentDetailData[0]?.reLInfo?.relType)
          this.publishCommentModel.targetRelObjectId = String(this.contentDetailData[0]?.reLInfo?.relObjectId)
          this.publishCommentModel.keyArticle = String(this.contentDetailData[0]?.keyArticle)
          this.publishCommentModel.targetType = String(this.contentDetailData[0]?.newsType)
        }
        if (this.contentDetailData[0]?.audioList?.length && this.contentDetailData[0]?.audioList[0].audioUrl) {
          this.operationButtonList = ['comment', 'collect', 'listen', 'share']
        }
      }
    }
  }

  private async getRecommend() {
    let params: postRecommendListParams = {
      imei: HttpUtils.getImei(),
      userId: HttpUtils.getUserId(),
      contentId: String(this.contentDetailData[0]?.newsId),
      recType: Number(this.contentDetailData[0]?.reLInfo?.relType),
      contentType: this.contentDetailData[0]?.newsType,
      relId: this.contentDetailData[0]?.reLInfo?.relId,
      channelId: String(this.contentDetailData[0]?.reLInfo?.channelId)
    }
    let recommendList = await DetailViewModel.postRecommendList(params)
    this.recommendList = recommendList;
  }

  // 已登录->查询用户对作品点赞、收藏状态
  private async getInteractDataStatus() {
    try {
      const params: batchLikeAndCollectParams = {
        contentList: [
          {
            contentId: this.contentDetailData[0]?.newsId + '',
            contentType: this.contentDetailData[0]?.newsType + '',
          }
        ]
      }
      console.error(TAG, JSON.stringify(this.contentDetailData))
      let data = await MultiPictureDetailViewModel.getInteractDataStatus(params)
      console.error(TAG, '查询用户对作品点赞、收藏状态', JSON.stringify(data))
      this.newsStatusOfUser = data[0];
      Logger.info(TAG, `newsStatusOfUser:${JSON.stringify(this.newsStatusOfUser)}`)
    } catch (exception) {
      console.error(TAG, JSON.stringify(exception))
    }
  }

  /**
   * 点赞、取消点赞
   */
  toggleLikeStatus() {
    // 未登录,跳转登录
    if (!HttpUtils.getUserId()) {
      WDRouterRule.jumpWithPage(WDRouterPage.loginPage)
      return
    }
    const params: postExecuteLikeParams = {
      status: this.newsStatusOfUser?.likeStatus === '1' ? '0' : '1',
      contentId: this.contentDetailData[0]?.newsId + '',
      contentType: this.contentDetailData[0]?.newsType + '',
    }
    PageRepository.postExecuteLike(params).then(res => {
      console.log(TAG, '点赞、取消点赞', 'toggleLikeStatus==',)
      if (this.newsStatusOfUser) {
        this.newsStatusOfUser.likeStatus = this.newsStatusOfUser?.likeStatus == '1' ? '0' : '1'
        this.queryContentInteractCount()
      }

    })
  }

  /**
   * 查询点赞、收藏数量
   */
  queryContentInteractCount() {
    console.error(TAG, 'contentDetailData2222', JSON.stringify(this.contentDetailData))
    const params: contentListParams = {
      contentList: [{
        contentId: this.contentDetailData[0]?.newsId + '',
        contentType: this.contentDetailData[0]?.newsType,
      }]
    }
    PageRepository.getContentInteract(params).then(res => {
      if (res.data) {
        this.likeNum = Number(res.data[0]?.likeNum) || 0
      }
    })
  }

  aboutToAppear() {
    this.getDetail()
    //注册通知,来自别的组件的评论成功通知
    EmitterUtils.receiveEvent(EmitterEventId.COMMENT_PUBLISH, (targetId?: string) => {
      if (targetId) {
        if (targetId == this.publishCommentModel.targetId) {
          // 滚动到评论列表
          if (this.info) {
            // let height = DisplayUtils.getDeviceHeight() / 2
            let offSetY = this.info?.globalPosition.y as number
            //头部距离48
            this.scroller.scrollTo({
              yOffset: offSetY - 100,
              xOffset: 0,
              animation: { duration: 1000, curve: Curve.Ease }
            })
          }
        }
      }
    })
  }

  aboutToDisappear() {
  }
}