import { PLVMediaPlayerSingleVideoLayout } from 'scene_single_video';
import { DependScope, Disposable, requireNotNull, runCatching } from '@polyvharmony/media-player-sdk';
import {
  createId,
  PLVMediaPlayerScenes,
  PLVMediaPlayerSingleVideoPageParam,
  PLVMPPageControlViewModel,
  PLVOrientationManager,
  PLVOrientationManagerObserver
} from 'media-player-common';
import common from '@ohos.app.ability.common';
import window from '@ohos.window';
import { createDependScope } from '@polyvharmony/media-player-sdk'
import {
  commonPageModule,getDisplayWindowWidth
} from 'media-player-common'
import { HdNav,BasicConstant } from '@itcast/basic'
import HashMap from '@ohos.util.HashMap';
import { hdHttp, HdResponse ,logger} from '@itcast/basic/Index'
import { emitter,BusinessError } from '@kit.BasicServicesKit';
import { VideoDetailModel,VideoCommentModel,commentModel,VideoDetailsComment } from 'home'
import { router,promptAction } from '@kit.ArkUI';
import inputMethod from '@ohos.inputMethod';

@Entry
@Component
export struct PLVMediaPlayerSingleVideoPage {
  @Provide pageDependScope: DependScope = createDependScope(commonPageModule)
  // @Consume pageDependScope: DependScope
  private params: VideoPageParam = router.getParams() as VideoPageParam

  private param: PLVMediaPlayerSingleVideoPageParam = this.params.param
  private context = getContext(this) as common.UIAbilityContext
  private pageControlViewModel: PLVMPPageControlViewModel = this.pageDependScope.get(PLVMPPageControlViewModel)
  private onBackPressDisposable: Disposable | undefined = undefined
  private readonly plv_media_player_single_video_background: string = createId()

  @State isPortrait: boolean = true;//是否竖屏
  @State commentList:Array<commentModel> = [];//评论列表
  @State commentContent:string = '';//评论内容

  @State note:string=''
  aboutToAppear(): void {
    requireNotNull(this.param, () => "param is null")
    this.onBackPressDisposable = this.pageControlViewModel.onBackPressHandler.register(10, () => this.onBackPress())
    runCatching(async () => {
      const windowInstance = await window.getLastWindow(this.context)
      windowInstance.setWindowKeepScreenOn(true)
    })
    this.getVideoDetail(this.params.video_uuid)
    this.getCommentdata(this.params.video_uuid)

    PLVOrientationManager.getInstance().isPortrait.observe((isPortrait) => {
      if (typeof isPortrait === 'boolean') {
        this.isPortrait = isPortrait
      }
    })

    emitter.on({ eventId: 250529 }, () => {
      this.getCommentdata(this.params.video_uuid)
    })
  }

  @State currentIndex: number = 0;

  @Builder tabBuilder(title: string, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#8D2316' : '#848284')
        .fontSize(14)
        .lineHeight(45)
        .height(45)

    }
    .width('100%')
    .height(50)
    .justifyContent(FlexAlign.Center)
  }
  build() {
    Column(){
      if (this.isPortrait) {
        HdNav({ title: '视频详情', showRightIcon: false, showLeftIcon: true })
      }

      Stack() {
        // 背景图
        // Image($r('app.media.plv_media_player_video_item_background_portrait'))
        //   .id(this.plv_media_player_single_video_background)
        //   .objectFit(ImageFit.Cover)
        //   .expandSafeArea(undefined, [SafeAreaEdge.BOTTOM])

        PLVMediaPlayerSingleVideoLayout({
          mediaResource: this.param.mediaResource,
          enterFromDownloadCenter: this.param.enterFromDownloadCenter
        })

        // 屏幕方向监听器
        PLVOrientationManagerObserver()
      }
      .width('100%')
      .height(this.getPlayerAreaHeight())

      Tabs() {
        TabContent() {
          Text(this.note).fontSize(14).fontColor(Color.Black)
        }
        .align(Alignment.TopStart)
        .padding(15)
        .customTabbar('视频简介')

        TabContent() {
          Column() {
            List(){
              ForEach(this.commentList,(model:commentModel)=>{
                ListItem(){
                  VideoDetailsComment({model:model,videoCommentUuid:this.params.video_uuid});
                }
              })
            }.height('calc(100% - 100vp)').width('100%').backgroundColor('#f4f4f4').scrollBar(BarState.Off)
            Row({space:10}) {
              Row() {
                TextInput({ placeholder: '我也说一句',text:this.commentContent })
                  .fontSize(17)
                  .backgroundColor(Color.White)
                  .width('95%')
                  .onChange((value: string) => {
                    this.commentContent = value; // 实时更新临时内容[3](@ref)
                    console.info('视频详情评论输入框内容：', this.commentContent);
                  })
              }.borderRadius(5).borderWidth(1).borderColor('#333333').backgroundColor(Color.White).height(50).width('calc(100% - 100vp)')
              .margin({ left: 10,top: 10 })

              Button('发送')
                .borderRadius(5)
                .type(ButtonType.ROUNDED_RECTANGLE)
                .backgroundColor($r('app.color.main_color'))
                .fontColor(Color.White)
                .fontSize(17)
                .width(70).height(50)
                .margin({top:10})
                .onClick(()=>{
                  this.addComment();
                })
            }.backgroundColor(Color.White).width('100%').height(100).justifyContent(FlexAlign.Start).alignItems(VerticalAlign.Top)
            // Button('推荐的内容').fontSize(30).alignSelf(ItemAlign.Start)
          }
          .justifyContent(FlexAlign.End)
        }
        .backgroundColor('#f4f4f4')
        .customTabbar('评论')
      }
      .divider( {
        strokeWidth: 1,
        color: $r('app.color.common_gray_border'),
      })
      .layoutWeight(1)
      .onChange((index: number) => {
        this.currentIndex = index;
      })
    }

  }

  getPlayerAreaHeight(): string | number {
    if (this.isPortrait) {
      return getDisplayWindowWidth().vp / 16 * 9
    } else {
      return '100%'
    }
  }

  onBackPress(): boolean {
    if (!PLVOrientationManager.getInstance().isPortrait.value) {
      PLVOrientationManager.getInstance().requestOrientation('port');
      return true;
    }
    return false;
  }

  aboutToDisappear(): void {
    this.onBackPressDisposable?.dispose()
    runCatching(async () => {
      const windowInstance = await window.getLastWindow(this.context)
      windowInstance.setWindowKeepScreenOn(false)
    })

    emitter.off(250529)
  }

  getVideoDetail(video_uuid:string) {
    const hashMap: HashMap<string, string> = new HashMap();
    hashMap.clear();
    hashMap.set('video_uuid', video_uuid)
    hdHttp.httpReq<string>(BasicConstant.videoDetail,hashMap).then(async (res: HdResponse<string>) => {
      logger.info('Response videoDetails'+video_uuid);
      logger.info('Response videoDetail'+res);
      let json:VideoDetailModel = JSON.parse(res+'') as VideoDetailModel;
      this.note=json.video.note
    }).catch((err: BusinessError) => {
    })
  }

  getCommentdata(video_uuid:string) {
    const hashMap: HashMap<string, string> = new HashMap();
    hashMap.clear();
    hashMap.set('uuid', video_uuid)
    hdHttp.httpReq<string>(BasicConstant.videoCommentListV2,hashMap).then(async (res: HdResponse<string>) => {
      logger.info('Response videoDetails commentList:'+video_uuid);
      logger.info('Response videoDetail commentList:'+res);
      let json:VideoCommentModel = JSON.parse(res+'') as VideoCommentModel;
      if(json.data != null && json.data!) {
        this.commentList = json.data;
      }
    }).catch((err: BusinessError) => {
    })
  }

  addComment() {
    inputMethod.getController().hideTextInput();//关闭键盘
    if (this.commentContent.length == 0) {
      promptAction.showToast({ message: '请输入评论内容', duration: 1000 })
      return;
    }

    const hashMap: HashMap<string, string> = new HashMap();
    hashMap.set('article_uuid', this.params.video_uuid)
    hashMap.set('comment', this.commentContent)
    hashMap.set('type', '8')
    hdHttp.httpReq<string>(BasicConstant.addCommentV2,hashMap).then(async (res: HdResponse<string>) => {
      logger.info('Response replyComment:'+res);
      let json:CommentV2Model = JSON.parse(res+'') as CommentV2Model;
      if(json.code == 200) {
        promptAction.showToast({ message: '发表评论成功', duration: 1000 })
        this.getCommentdata(this.params.video_uuid);
        this.commentContent = '';
      } else {
        promptAction.showToast({ message: json.message, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
    })
  }
}

@Extend(TabContent)
function customTabbar(name:string) {
  .tabBar(SubTabBarStyle.of(name)
    .labelStyle({ unselectedColor: '#848284', selectedColor:'#8D2316' ,  font: { size: 17 }})
    .indicator({
      color: '#8D2316', //下划线颜色
      height: 1, //下划线高度
      marginTop:16 //下划线与文字间距
    }))
  .height('100%')
}

interface VideoPageParam {
  video_uuid:string
  param:PLVMediaPlayerSingleVideoPageParam
}

export interface CommentV2Model{
  code:number;
  data:Object[];
  message:string;
  msg:string
}