ImageAndTextPageComponent.ets 21.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
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';
import { viewBlogItemInsightIntentShare } from '../utils/InsightIntentShare'
import { common } from '@kit.AbilityKit';
import { componentUtils } from '@kit.ArkUI';
import { TrackConstants, TrackingContent, TrackingPageBrowse } from 'wdTracking/Index';
import { LottieView } from '../components/lottie/LottieView';

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
  @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 operationButtonList: string[] = ['comment', 'collect', 'share']
  @State operationButtonList: string[] = []
  @State isNetConnected: boolean = true
  @State emptyType: number = 1 // 缺省图类型
  @State detailContentEmpty: boolean = false
  @State info: Area | null = null
  @State likeNum: number = 0
  @State reachEndIncreament: number = 0
  @State bottomSafeHeight: number = AppStorage.get<number>('bottomSafeHeight') || 0
  @State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') || 0
  @State isScrollTop: boolean = true
  @State offsetY: number = 0
  @State executedStartTime: number = new Date().getTime()
  private screenHeight: number = 0
  private topHeight: number = 32
  private bottomHeight: number = 150
  @State showMainText: boolean = false
  pageShowTime:number = 0;
  pageHideTime:number = 0;
  lastTimeoutId?: number
  @State needAnimation: boolean = false;

  @Consume @Watch('pageShowForUpdateData') pageShow :number
  @Consume @Watch('pageHideForUpdateData') pageHide :number

  pageShowForUpdateData() {
    this.pageShowTime = DateTimeUtils.getTimeStamp()
  }

  //内容浏览Tracking
  pageHideForUpdateData(): void {
    this.pageHideTime = DateTimeUtils.getTimeStamp()
    let duration = 0
    duration = Math.floor((this.pageHideTime - this.pageShowTime)/1000)
    TrackingPageBrowse.trackCommonPageExposureEnd(TrackConstants.PageName.Customer_Personal,TrackConstants.PageName.Customer_Personal,duration)
  }

  build() {
    Stack({ alignContent: Alignment.Top }) {
      Stack({ alignContent: Alignment.Bottom }) {
        Scroll(this.scroller) {
          Column() {
            ImageAndTextWebComponent({
              contentDetailData: [this.contentDetailData],
              action: this.action,
              isPageEnd: $isPageEnd
            })
              .padding({ bottom: 10 })
            Column() {
              // 点赞
              if (this.contentDetailData?.openLikes && this.contentDetailData?.likesStyle !== 4) {
                Row() {
                  Row() {
                    if (this.newsStatusOfUser?.likeStatus == '1') {
                      if (this.contentDetailData?.likesStyle === 1) {
                        if (this.needAnimation) {
                          Row() {
                            LottieView({
                              name: 'articleLike',
                              path: 'lottie/article_like.json',
                              lottieWidth: 40,
                              lottieHeight: 40,
                              autoplay: true,
                              loop: false,
                            })
                              .position({
                                left: -6,
                                top: -8
                              })
                          }
                          .width(24)
                          .height(24)
                          .margin({ right: 3 })
                        } else {
                          Image($r('app.media.icon_like_select'))
                            .width(24)
                            .height(24)
                            .margin({ right: 5 })
                        }
                      } else if (this.contentDetailData?.likesStyle === 2) {
                        Image($r('app.media.icon_prayer_active'))
                          .width(24)
                          .height(24)
                          .margin({ right: 5 })
                      } else {
                        Image($r('app.media.icon_candle_active'))
                          .width(24)
                          .height(24)
                          .margin({ right: 5 })
                      }
                    } else {
                      Image(this.contentDetailData?.likesStyle === 1 ? $r('app.media.icon_like') :
                        (this.contentDetailData?.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')
                        .fontColor((this.likeNumTextColor()))
                        .fontFamily('PingFang SC-Regular')
                        .fontWeight(400)
                        .margin({ left: 5 })
                        .lineHeight(20)
                    }
                  }
                  .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?.openComment) {
                Divider().strokeWidth(6).color('#f5f5f5')
                CommentComponent({
                  publishCommentModel: this.publishCommentModel,
                  fixedHeightMode: false,
                  reachEndIncreament: this.reachEndIncreament,
                  reachEndLoadMoreFinish: () => {
                  }

                }).id('comment')

                  .onAreaChange((oldValue: Area, newValue: Area) => {
                    this.info = newValue
                    console.log(TAG, "总页面滑动偏移量", this.scroller.currentOffset().yOffset)
                    console.log(TAG, "总页面滑动偏移量111", newValue.globalPosition.y as number)
                    this.checkToScrollCommentArea()
                  })
                // .onMeasureSize()

              }
            }
          }
          .id('imgTextContainer')
        }
        .padding({bottom: 44})
        .width(CommonConstants.FULL_WIDTH)
        .scrollBar(BarState.Off)
        .align(Alignment.Top)
        .onReachEnd(() => {
          this.reachEndIncreament += 1
        })

        if (!this.isNetConnected || this.detailContentEmpty) {
          EmptyComponent({
            emptyType: this.emptyType,
            emptyButton: this.emptyType === 1 ? true : false,
            retry: () => {
              this.getDetail()
            }
          }).padding({ bottom: 44 })
        } else {
          if (!this.isPageEnd) {
            detailedSkeleton().padding({ bottom: 44 })
          }
        }

      }
      .margin({top: `${this.topSafeHeight}px`, bottom: `${this.bottomSafeHeight}px`})
      .width(CommonConstants.FULL_WIDTH)
      // .height(CommonConstants.FULL_HEIGHT)

      Stack(){
        // 底部交互区 固定底部
        OperRowListView({
          contentDetailData: this.contentDetailData,
          publishCommentModel: this.publishCommentModel,
          operationButtonList: this.operationButtonList,
          showMainText:this.showMainText,
          styleType: 1,
          onCommentIconClick: () => {
            const info = componentUtils.getRectangleById('comment');
            console.log(TAG, "点击滑动页面", JSON.stringify(info))

            //评论区当前位置
            let currentCommonentOffSetY = this.info?.globalPosition.y as number
            let offSetY = 0
            if (currentCommonentOffSetY >= (this.screenHeight-this.bottomHeight) ) {
              offSetY = currentCommonentOffSetY-200
            }

            // if (!this.offsetY) {
            //   this.offsetY = componentUtils.getRectangleById('comment').windowOffset.y
            // }
            //   定位到评论区域
            if (this.isScrollTop) {
              this.scroller.scrollTo({
                xOffset: 0,
                yOffset: offSetY,
                animation: { duration: 1000, curve: Curve.Ease }
              })
            } else {
              this.scroller.scrollEdge(Edge.Top)
            }
            this.isScrollTop = !this.isScrollTop
          }
        })
      }
      .alignContent(Alignment.Top)
      .position({y:'85%'})
      .width(CommonConstants.FULL_WIDTH)
      .backgroundColor(Color.White)
      .height(this.bottomHeight)

      // 发布时间
      Column() {
        Row() {
          if (this.isNetConnected && !this.detailContentEmpty) {
            Image(this.contentDetailData?.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(13)
          }
        }
        .width(CommonConstants.FULL_WIDTH)
        .height(this.topHeight)
        .padding({ left: 15, right: 15, })
        .justifyContent(FlexAlign.SpaceBetween)
        .alignItems(VerticalAlign.Bottom)

        if (this.isNetConnected && !this.detailContentEmpty) {
          Row() {
            Image($r('app.media.ic_news_detail_division'))
              .width('100%')
              .height(6)
              .margin({ top: 10 })
              .objectFit(ImageFit.Fill)
          }
          .padding({ left: 15, right: 15 })
          .backgroundColor(Color.White)
          }
      }.backgroundColor(Color.White)
    }
    .margin({top: `${this.topSafeHeight}px`, bottom: `${this.bottomSafeHeight}px`})
    .width(CommonConstants.FULL_WIDTH)
    .height(CommonConstants.FULL_HEIGHT)
    .backgroundColor(Color.White)
  }

  private likeNumTextColor() {
    if(this.newsStatusOfUser?.likeStatus == '1'){
      //已点赞状态  祈福和默哀为黑色  其余为红色
      return (this.contentDetailData?.likesStyle == 2 || this.contentDetailData?.likesStyle == 3) ? '#222222' : '#ED2800'
    }
    return '#999999'
  }

  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) {
        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
      }
      if (detailBeans && detailBeans.length > 0) {
        this.contentDetailData = detailBeans[0];
        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 || '')
        }
        if (this.contentDetailData?.openAudio && this.contentDetailData?.audioList?.length &&
        this.contentDetailData?.audioList[0].audioUrl) {
          this.operationButtonList = ['comment', 'collect', 'listen', 'share']
        } else {
          this.operationButtonList = ['comment', 'collect', 'share']
        }
      }
    }
  }

  //意图上报
  private viewBlogInsightIntentShare() {
    let context = getContext(this) as common.UIAbilityContext;
    viewBlogItemInsightIntentShare(this.executedStartTime, context, this.contentDetailData, this.interactData)
  }

  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() {
    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) {
        //内容点赞、取消点赞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()
      }

    })
  }

  /**
   * 查询点赞、收藏数量
   */
  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
      }
    })
  }

  initAnimationConfig() {
    if (this.contentDetailData?.openLikes && this.contentDetailData?.likesStyle !== 4) {
      if (this.newsStatusOfUser?.likeStatus == '1') {
        if (this.contentDetailData?.likesStyle === 1) {
          this.needAnimation = false;
        } else {
          this.needAnimation = true;
        }
      }
    } else {
      this.needAnimation = true;
    }
  }

  aboutToAppear() {
    this.getDetail()
    this.screenHeight = DisplayUtils.getDeviceHeight()
    this.initAnimationConfig();
    //注册通知,来自别的组件的评论成功通知
    EmitterUtils.receiveEvent(EmitterEventId.COMMENT_PUBLISH, (targetId?: string) => {
      if (targetId) {
        if (targetId == this.publishCommentModel.targetId) {
          // 滚动到评论列表
          if (this.info) {
            // let height = DisplayUtils.getDeviceHeight() / 2
            //评论区当前位置
            let currentCommonentOffSetY = this.info?.globalPosition.y as number
            //当前页面滚动的位置
            let currentScrollOffSetY = this.scroller.currentOffset().yOffset
            if (currentCommonentOffSetY > 0 && currentCommonentOffSetY < (this.screenHeight-this.bottomHeight)){
              return
            }
            let offSetY = currentScrollOffSetY
            if (currentCommonentOffSetY >= (this.screenHeight-this.bottomHeight) ) {
              offSetY = currentCommonentOffSetY-200
            }else {
              offSetY = currentScrollOffSetY + currentCommonentOffSetY-100
            }
            //头部距离48
            this.scroller.scrollTo({
              yOffset: offSetY,
              xOffset: 0,
              animation: { duration: 1000, curve: Curve.Ease }
            })
          }
        }
      }
    })
    // 登录成功
    EmitterUtils.receiveEvent(EmitterEventId.LOGIN_SUCCESS, () => {
      this.getInteractDataStatus()
    })
  }

  aboutToDisappear() {
    //意图上报
    this.viewBlogInsightIntentShare()
  }
  
  checkToScrollCommentArea() {
    if (!this.info) {
      // 需要评论区位置,调用前 请确保它有值
      return
    }
    let offSetY = this.info?.globalPosition.y as number -60
    Logger.debug(TAG, "即将滚动至yOffset: " + offSetY)
    if (offSetY >= (this.screenHeight-this.bottomHeight) ) {
      this.showMainText = false
    }else {
      this.showMainText = true
    }

    if (this.action.params?.targetLayout && this.action.params.targetLayout == "comment") {
      if (this.lastTimeoutId) {
        clearTimeout(this.lastTimeoutId)
      }
      this.lastTimeoutId = setTimeout(() => {
        //头部距离48
        this.scroller.scrollTo({
          yOffset: offSetY,
          xOffset: 0,
          animation: { duration: 1000, curve: Curve.Ease }
        })
        this.action.params!.targetLayout = undefined
      }, 600)
    }
  }
}