H5NewsWebPageComponent.ets 11.3 KB
import {
  Logger,
  NumberFormatterUtils,
  DateTimeUtils,
  EmitterUtils,
  EmitterEventId,
  NetworkUtil,
  ToastUtils,
} from 'wdKit';
import {
  Action,
  ContentDetailDTO,
  ContentDTO,
  postRecommendListParams,
  postExecuteLikeParams,
  batchLikeAndCollectResult,
  batchLikeAndCollectParams,
  InteractDataDTO,
  contentListParams,
} from 'wdBean';
import { WdWebComponent } from 'wdWebComponent';
import DetailViewModel from '../viewmodel/DetailViewModel';
import router from '@ohos.router';
import { CommonConstants } from 'wdConstant'
import { BridgeWebViewControl } from 'wdJsBridge';
import { publishCommentModel } from '../components/comment/model/PublishCommentModel';
import { HttpUtils } from 'wdNetwork/Index';
import { MultiPictureDetailViewModel } from '../viewmodel/MultiPictureDetailViewModel';
import { WDRouterPage, WDRouterRule } from 'wdRouter/Index';
import { PageRepository } from '../repository/PageRepository';
import { OperRowListView } from './view/OperRowListView';
import { CommentDialogView } from './CommentDialogView';
import { CustomTitleUI } from './reusable/CustomTitleUI';

const TAG = 'H5NewsWebPageComponent'

@Component
export struct H5NewsWebPageComponent {
  @State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') as number;
  @State bottomSafeHeight: number = AppStorage.get<number>('bottomSafeHeight') || 0
  webviewControl: BridgeWebViewControl = new BridgeWebViewControl()
  scroller: Scroller = new Scroller();
  action: Action = {} as Action
  @State webUrl: string = '';
  @Provide 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 isNetConnected: boolean = true
  @State emptyType: number = 1 // 缺省图类型
  @State detailContentEmpty: boolean = false
  @State info: Area | null = null
  @State likeNum: number = 0
  @State operationButtonList: string[] = []
  @State showComment: boolean = false
  @State showCommentList: boolean = false
  @State index: number = 0
  @State currentIndex: number = 0
  @State navTitle: string = ""

  build() {
    Stack({ alignContent: Alignment.Top }){
      Stack(){
        Column(){
          CustomTitleUI({ titleName: this.navTitle ,imgBack:false})
          WdWebComponent({
            webviewControl: this.webviewControl,
            webUrl: this.webUrl,
            isPageEnd: $isPageEnd
          })
        }.width(CommonConstants.FULL_WIDTH)
        .height(`calc(85% - ${ this.topSafeHeight + 'px'})`)
      }

      Stack(){
        //底部交互区
        OperRowListView({
          contentDetailData: this.contentDetailData,
          publishCommentModel: this.publishCommentModel,
          operationButtonList: this.operationButtonList,
          styleType: 1,
          onCommentIconClick: () => {
            this.showCommentList = true
          }
        })
      }
      .alignContent(Alignment.Top)
          .position({y:'85%'})
          .width(CommonConstants.FULL_WIDTH)
          .backgroundColor(Color.White)
          .height(150)

      //全部评论
      CommentDialogView({
        index: $index,
        currentIndex: $currentIndex,
        showCommentList: $showCommentList,
        publishCommentModel: $publishCommentModel,
        interactData: $interactData,
      }).visibility(this.showComment ? Visibility.Visible : Visibility.Hidden)
    }
    .margin({top: `${this.topSafeHeight}px`, bottom: `${this.bottomSafeHeight}px`})
    .width(CommonConstants.FULL_WIDTH)
    .height(CommonConstants.FULL_HEIGHT)
  }

  private async getDetail() {
    this.isNetConnected = NetworkUtil.isNetConnected()
    if (!this.isNetConnected) {
      this.emptyType = 1
    }
    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) {
        this.navTitle = this.action.params.extra.title
        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)
      // 判断内容是否已下线,空数组表示下线
      this.detailContentEmpty = detailBeans.length === 0 ? true : false
      if (this.detailContentEmpty) {
        this.emptyType = 18
      }
      console.log(TAG, "dl1111111111", JSON.stringify(detailBeans[0]))
      if (detailBeans && detailBeans.length > 0) {
        this.contentDetailData = detailBeans[0];
        this.navTitle = this.contentDetailData.newsTitle
        let dateTime =
          DateTimeUtils.parseDate(this.contentDetailData?.publishTime, DateTimeUtils.PATTERN_DATE_TIME_HYPHEN);
        // let _publishTime = DateTimeUtils.formatDate(dateTime, PATTERN_DATE_CN_RN)
        // this.publishTime = DateTimeUtils.removeTrailingZeros(_publishTime)
        // if (this.contentDetailData?.recommendShow === 1) {
        //   this.getRecommend()
        // }
        if (this.contentDetailData?.openLikes === 1) {
          console.log(TAG, '点赞this.getInteractDataStatus()')
          this.getInteractDataStatus()
          this.queryContentInteractCount()
        }
        if (this.contentDetailData?.openComment) {
          this.publishCommentModel.targetId = String(this.contentDetailData?.newsId || '')
          this.publishCommentModel.targetRelId = String(this.contentDetailData?.reLInfo?.relId || '')
          this.publishCommentModel.targetTitle = this.contentDetailData?.newsTitle
          this.publishCommentModel.targetRelType = String(this.contentDetailData?.reLInfo?.relType || '')
          this.publishCommentModel.targetRelObjectId = String(this.contentDetailData?.reLInfo?.relObjectId || '')
          this.publishCommentModel.keyArticle = String(this.contentDetailData?.keyArticle || '')
          this.publishCommentModel.targetType = String(this.contentDetailData?.newsType || '')
          this.publishCommentModel.visitorComment = String(this.contentDetailData?.visitorComment || '')
        }

        this.operationButtonList = []
        if ( this.contentDetailData.openComment === 1) {
          this.operationButtonList.push('comment')
        }
        if (this.contentDetailData.openLikes === 1) {
          this.operationButtonList.push('like')
        }
        // if (this.contentDetailData?.openAudio && this.contentDetailData?.audioList?.length &&
        // this.contentDetailData?.audioList[0].audioUrl) {
        //   this.operationButtonList.push('listen')
        // }
        this.operationButtonList.push('collect')
        if (this.contentDetailData.shareInfo?.shareOpen === 1) {
          this.operationButtonList.push('share')
        }
      }
    }
  }

  // private async getRecommend() {
  //   let params: postRecommendListParams = {
  //     imei: HttpUtils.getImei(),
  //     userId: HttpUtils.getUserId(),
  //     contentId: String(this.contentDetailData?.newsId),
  //     recType: 1,
  //     contentType: this.contentDetailData?.newsType,
  //     relId: this.contentDetailData?.reLInfo?.relId,
  //     // channelId: String(this.contentDetailData?.reLInfo?.channelId)
  //   }
  //   let recommendList = await DetailViewModel.postRecommendList(params)
  //   if (recommendList.length > 0) {
  //     //推荐列表过滤音频和活动入口
  //     this.recommendList = recommendList.filter(item => item.objectType !== '3' && item.objectType !== '13');
  //   }
  //
  // }

  // 已登录->查询用户对作品点赞、收藏状态
  private async getInteractDataStatus() {
    if (!HttpUtils.isLogin()) {
      return
    }
    try {
      const params: batchLikeAndCollectParams = {
        contentList: [
          {
            contentId: this.contentDetailData?.newsId + '',
            contentType: this.contentDetailData?.newsType + '',
            contentRelId: this.contentDetailData?.reLInfo?.relId || '' + '',
          }
        ]
      }
      // console.log(TAG,'contentDetailData', JSON.stringify(params.contentList))
      let data = await MultiPictureDetailViewModel.getInteractDataStatus(params)
      console.log(TAG, '查询用户对作品点赞、收藏状态', JSON.stringify(data))
      this.newsStatusOfUser = data[0];
      // console.log(TAG, `newsStatusOfUser:${JSON.stringify(this.newsStatusOfUser)}`)
    } catch (exception) {
      console.error(TAG,'exception', 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?.newsId + '',
      contentType: this.contentDetailData?.newsType + '',
      contentRelId: this.contentDetailData?.reLInfo?.relId || '' + '',
    }
    console.log(TAG, '点赞、取消点赞params', JSON.stringify(params))
    PageRepository.postExecuteLike(params).then(res => {
      // console.log(TAG, '点赞、res', JSON.stringify(res))
      console.log(TAG, '点赞、取消点赞 this.newsStatusOfUser', JSON.stringify(this.newsStatusOfUser))
      if (this.newsStatusOfUser && res.code == 0) {
        //内容点赞、取消点赞Tracking 1点赞  0取消点赞
        this.newsStatusOfUser.likeStatus = this.newsStatusOfUser?.likeStatus == '1' ? '0' : '1'
        if (this.newsStatusOfUser.likeStatus === '1') {
          this.likeNum = Number(this.likeNum) + 1
        } else {
          this.likeNum = Number(this.likeNum) - 1
        }
        console.log(TAG, '点赞newsStatusOfUser.likeStatus ', this.newsStatusOfUser.likeStatus)
        // this.queryContentInteractCount()
        // TrackingContent.like(this.newsStatusOfUser?.likeStatus == '1', TrackConstants.PageName.My, TrackConstants.PageName.My)
      } else {
        // 初次进入详情页偶现获取失败,重新获取newsStatusOfUser对象
        this.getInteractDataStatus()
      }
    }).catch((error:Error) =>{
      ToastUtils.showToast(error.message, 1000);
    })

  }

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

  aboutToAppear() {
    let action: Action = router.getParams() as Action
    if (action) {
      this.webUrl = action.params?.url || ''
    }
    this.getDetail()

    // 登录成功
    EmitterUtils.receiveEvent(EmitterEventId.LOGIN_SUCCESS, () => {
      this.getInteractDataStatus()
    })
  }
}