LiveLikeComponent.ets 8.31 KB
import { DisplayUtils, NumberFormatterUtils } from 'wdKit/Index'
import { SPHelper } from 'wdKit';
import { WDRouterPage, WDRouterRule } from 'wdRouter/Index';
import { SpConstants } from 'wdConstant/Index';
import measure from '@ohos.measure'
import {
  ContentDetailRequest,
  postExecuteLikeParams,
} from 'wdDetailPlayApi/src/main/ets/request/ContentDetailRequest';
import { ParamType, TrackConstants, TrackingContent } from 'wdTracking/Index';
import {
  ContentDetailDTO,
  contentListParams,
} from 'wdBean';
import { PageRepository } from '../../repository/PageRepository';
import { LiveModel } from '../../viewmodel/LiveModel';
import { HttpUtils } from 'wdNetwork/Index';

const TAG = 'LiveLikeComponent';

interface ILikeStyleResp {
  url: Resource;
  name: string;
}

@Component
export struct LiveLikeComponent {
  private LiveModel: LiveModel = new LiveModel()
  @Consume contentDetailData: ContentDetailDTO
  @Prop pageComponentType: number
  @State likesStyle: string = "love" // 点赞样式 love爱心型  thumb点赞手势 mourning 蜡烛(默哀) pray 祈福
  @State likeStatus: boolean = false
  @State openLikes: boolean = false // 是否可以点赞  1:可以 0:不可以
  @Prop @Watch('onDataUpdated') data: Record<string, string>
  enableBtn = true
  styleType: number = 1 //1: 白色背景(图文底部栏)    2: 黑色背景(图集底部栏) 3 透明背景
  @State likeCount: number = 0 //点赞数
  pageParam: ParamType = {}
  PageName: string = ''

  //上层传值  样例
  // this.data['contentId'] = '30035444649' //必须
  // this.data['userName'] = '人民日报网友2kD2xW'
  // this.data['contentType'] = '8'  //必须
  // this.data['title'] = '开创两校交流先河!克罗地亚教育代表团访问同济大学'
  // this.data['userHeaderUrl'] = ""
  // this.data['channelId'] = "2059"  //必须
  // this.data['status'] = "1"
  // 内容用 是否开启点赞 1是 0否;
  // this.contentDetailData.openLikes == 1
  async aboutToAppear() {
    // 2:竖屏直播页  4:横屏直播页
    // 点赞样式 love爱心型  thumb点赞手势 mourning 蜡烛(默哀) pray 祈福
    this.likesStyle = this.contentDetailData?.liveInfo?.likesStyle
    this.openLikes = this.contentDetailData?.liveInfo?.likeEnable == 1 ? true : false
    console.log(TAG, 'this.contentDetailData', JSON.stringify(this.contentDetailData))
    console.log(TAG, 'this.likesStyle', this.likesStyle)
    console.log(TAG, 'this.openLikes', this.openLikes)
    this.onDataUpdated()
    this.contentTrackingDict()
  }

  onDataUpdated() {
    console.log(TAG, '点赞点击')
    if (this.data) {
      if (this.data['contentType'] !== 'undefined') {
        //获取点赞状态
        this.getLikeStatus()
        //获取点赞数
        this.getLikeCount()
      }
    }
  }

  contentTrackingDict(){
    this.pageParam = {
      'contentType': `${this.contentDetailData.newsType}`,
      'contentId': `${this.contentDetailData.newsId}`,
      'contentName': `${this.contentDetailData.newsTitle || ''}`,
    }
    if(this.contentDetailData.newsType == 2) {
      this.PageName = TrackConstants.PageName.Live_Detail // 直播
    }
  }

  build() {
    // 直播,点赞按钮底测有灰色圆角背景+右上点赞数量
    this.likeCompStyle()
  }

  /**
   * 将点赞样式转换为icon
   */
  transLikeStyle(): ILikeStyleResp {
    if (this.likesStyle === 'love' || this.likesStyle === 'thumb') {
      return {
        url: this.likeStatus ? $r(`app.media.ic_like_check`) :
          this.styleType == 1 ? $r('app.media.icon_like_default') : $r(`app.media.ic_like_uncheck`),
        name: '赞'
      }
    } else if (this.likesStyle === 'pray') {
      return {
        url: this.likeStatus ? $r(`app.media.ic_thub_check`) : $r(`app.media.ic_thub_uncheck`),
        name: '祈祷'
      }
    } else if (this.likesStyle === 'mourning') {
      return {
        url: this.likeStatus ? $r(`app.media.ic_candle_check`) :
        $r(`app.media.ic_candle_uncheck`),
        name: '默哀'
      }
    }
    return {
      url: this.likeStatus ? $r(`app.media.ic_like_check`) :
        this.styleType == 1 ? $r('app.media.icon_like_default') : $r(`app.media.ic_like_uncheck`),
      name: '点赞'
    }
  }

  @Builder
  likeCompStyle() {
    Stack({ alignContent: Alignment.Bottom }) {
      Column() {
        Image(this.transLikeStyle().url)
          .width(24)
          .height(24)
          .onClick(() => {
            this.clickButtonEvent()
          })
      }
      .justifyContent(FlexAlign.Center)
      .width(36)
      .height(36)
      .borderRadius(18)
      .backgroundColor((this.pageComponentType === 4 || this.pageComponentType === 2) ? '#4D000000' : this.pageComponentType === 8 ? Color.Transparent : '#FFF5F5F5')
      Row() {
        Text(NumberFormatterUtils.formatNumberWithWan(this.likeCount || ''))
          .fontSize(8)
          .fontColor(Color.White)
          .padding({ left: 8, right: 2 })
      }
      .height(12)
      .alignItems(VerticalAlign.Center)
      .position({ x: '100%', y: 10 })
      .markAnchor({ x: '100%' })
      .backgroundImage($r('app.media.ic_like_back'))
      .backgroundImageSize({height: 13})
      .width(this.getMeasureText(NumberFormatterUtils.formatNumberWithWan(this.likeCount || '')) +
        12)
      .visibility(this.likeCount > 0 ? Visibility.Visible : Visibility.Hidden)
    }
    .width(36)
    .height(42)
    .visibility(this.likesStyle == 'empty' || !this.openLikes ? Visibility.None : Visibility.Visible)

  }

  async clickButtonEvent() {
    console.log(TAG, '点赞点击')
    // 未登录,跳转登录
    const user_id = await SPHelper.default.get(SpConstants.USER_ID, '')
    if (!user_id) {
      console.log(TAG, '点赞点击,未登录')
      WDRouterRule.jumpWithPage(WDRouterPage.loginPage)
      return
    }

    // if (!this.enableBtn) {
    //   return
    // }
    this.executeLike(this.likeStatus ? '0' : '1')

  }

  executeLike(status: string) {
    console.log(TAG, '点赞接口调用', status)

    const params: postExecuteLikeParams = {
      status: Number(status),
      contentId: this.data['contentId'],
      contentType: this.data['contentType']
    }
    if(this.data['relType']) {
      params.relType = this.data['relType']
    }
    if(this.data['contentRelId']) {
      params.contentRelId = this.data['contentRelId']
    }
    if(this.data['channelId']) {
      params.channelId = this.data['channelId']
    }

    console.log(TAG, "点赞 params", JSON.stringify(params))
    ContentDetailRequest.postExecuteLike(params).then((data) => {

      console.log(TAG, '点赞接口调用成功', JSON.stringify(data))

      // 直播点赞一直增加
      if (this.contentDetailData.liveInfo) {
        this.likeStatus = true
        this.likeCount++
        TrackingContent.like(true,this.PageName,this.PageName,this.pageParam)
      }

      if (this.likeCount <= 0) {
        this.likeCount = 0
      }

      this.enableBtn = true
    }).catch(() => {
      this.enableBtn = true
    })
  }

  async getLikeStatus() {
    const user_id = await SPHelper.default.get(SpConstants.USER_ID, '')
    if (!user_id) {
      console.log(TAG, '查询点赞状态,未登录')
      return
    }
    this.LiveModel.getLiveLike(this.data['contentId'], user_id, HttpUtils.getDeviceId()).then(data => {
      console.log(TAG, '查询点赞、收藏状态==', JSON.stringify(data))
      this.likeStatus = data
    }).catch(() => {
      this.likeStatus = false
    })
  }

  /**
   * 获取点赞数
   */
  getLikeCount() {
    // console.error(TAG, 'contentDetailData2222', JSON.stringify(this.contentDetailData))
    const params: contentListParams = {
      contentList: [{
        contentId: this.contentDetailData?.newsId + '',
        contentType: this.contentDetailData?.newsType,
      }]
    }
    console.log(TAG, '查询点赞、收藏数量', JSON.stringify(params))
    PageRepository.getContentInteract(params).then(res => {
      console.log(TAG, '查询点赞、收藏数量 res', JSON.stringify(res))
      if (res.data) {
        this.likeCount = Number(res.data[0]?.likeNum)
      } else {
        this.likeCount = 0
      }
    }).catch(() => {
      this.likeCount = 0
    })
  }
  private getMeasureText(text: string) {
    let width = measure.measureText({
      textContent: text,
      fontSize: 8,
      lineHeight: 12,
      constraintWidth: DisplayUtils.getDeviceWidth(),
    })
    width = px2vp(width)
    return width
  }
}