<script setup lang="ts">
  import { onLoad, onBackPress } from '@dcloudio/uni-app'
  import { ref, computed, watch, Teleport } from 'vue'
  import TUIRoomEngine, {
    TUIRoomEvents
  } from '@tencentcloud/tuiroom-engine-js'
  import {
    UIKitProvider,
    TUIButton,
    IconClose,
    TUIDialog,
    useUIKit,
    TUIMessageBox
  } from '@tencentcloud/uikit-base-component-vue3'
  import {
    LiveAudienceList,
    LiveCoreView,
    BarrageInput,
    BarrageList,
    LiveGift,
    useLiveAudienceState,
    useLiveListState,
    Avatar,
    useLiveSeatState,
    useRoomEngine,
    LiveListEvent,
    useLoginState,
    useBarrageState
  } from 'tuikit-atomicx-vue3'
  import Drawer from './components/drawer.vue'
  import { navigateBack } from '../../../utils/router'
  import { useAuthUser } from '../../../composables/useAuthUser'
  import {
    getLiveActivityDetail,
    getLiveActivityRecord
  } from '../../../api/tui-kit'
  import { LIVE_BUSINESS } from '@/constants/live-keys'

  const { t } = useUIKit()

  const { messageList } = useBarrageState()
  const { userInfo } = useAuthUser()
  const { setSelfInfo } = useLoginState()
  const { audienceList, fetchAudienceList } = useLiveAudienceState()
  const {
    currentLive,
    joinLive,
    leaveLive,
    subscribeEvent,
    unsubscribeEvent
  } = useLiveListState()
  const isInLive = computed(() => !!currentLive.value?.liveId)
  const { canvas } = useLiveSeatState()
  const roomEngine = useRoomEngine()
  TUIRoomEngine.once('ready', () => {
    roomEngine.instance?.on(
      TUIRoomEvents.onAutoPlayFailed,
      handleAutoPlayFailed
    )
  })
  const audienceListPanelVisible = ref(false)
  const leaveLiveDialogVisible = ref(false)
  /** 直播结束状态 */
  const liveEndVisible = ref(false)
  const leaveLiveText = ref('')
  const liveOwnerName = ref('')
  const liveOwnerAvatar = ref('')
  const autoPlayFailedHandled = ref(false)
  /** 活动信息 */
  const activityData = ref({})
  /** 是否显示活动按钮 */
  const isShowActivity = ref(false)
  const shareDialog = ref(false)

  const audienceListTitle = computed(
    () => `在线人数 (${audienceList.value.length})`
  )

  const emit = defineEmits(['leaveLive'])

  const handleKickedOutOfLive = () => {
    showLeaveLiveDialog('您已被踢出房间')
  }

  watch(
    () => messageList.value,
    newMessages => {
      if (newMessages.length > 0) {
        console.log('弹幕消息列表更新:', newMessages)
        if (newMessages.some(v => v.businessID === LIVE_BUSINESS.ADMIN)) {
        }
      }
    },
    { deep: true }
  )

  watch(
    () => currentLive.value?.liveId,
    liveId => {
      if (!liveId) {
        liveEndVisible.value = true
      }
    }
  )

  onBackPress(async () => {
    if (currentLive.value?.liveId) {
      await leaveLive()
    }
    unsubscribeEvent(
      LiveListEvent.onKickedOutOfLive,
      handleKickedOutOfLive
    )
    roomEngine.instance?.off(
      TUIRoomEvents.onAutoPlayFailed,
      handleAutoPlayFailed
    )
  })

  /**
   * 离开直播
   */
  const handleLeaveLive = () => {
    leaveLiveDialogVisible.value = false
    navigateBack()
  }

  /**
   * 初始化直播间
   */
  const handleJoinLive = async (liveId: string) => {
    try {
      await joinLive({ liveId })
      if (currentLive.value) {
        liveOwnerName.value =
          currentLive.value?.liveOwner.userName ||
          currentLive.value?.liveOwner.userId
        liveOwnerAvatar.value = currentLive.value?.liveOwner.avatarUrl
      }
      const res = await getLiveActivityDetail(liveId)
      // status: 0-未开始 1-进行中 2-已结束 3-已取消
      console.log('活动数据============= ', res.data)
      if (res?.data && res.data.status === 1) {
        const show = await getLiveActivityRecord(res.data.activityId)
        activityData.value = {
          ...res.data,
          isParticipated: show.data
        }
        isShowActivity.value = !show.data
      } else {
        isShowActivity.value = false
      }
    } catch (error) {
      console.error('Failed to join live room, error:', error)
      showLeaveLiveDialog('没有直播间')
    }
  }

  /** 监听是否发送活动 */
  const handleActivity = async (message: any) => {
    console.log('收到弹幕========:')
  }

  function showLeaveLiveDialog(text: string) {
    if (leaveLiveDialogVisible.value || text.trim().length === 0) {
      return
    }

    leaveLiveText.value = text
    leaveLiveDialogVisible.value = true
  }

  /**
   * 显示观众列表
   */
  const showAudienceList = async () => {
    await fetchAudienceList()
    audienceListPanelVisible.value = true
  }

  function handleAutoPlayFailed() {
    if (!currentLive.value?.liveId || autoPlayFailedHandled.value) {
      return
    }
    autoPlayFailedHandled.value = true
    TUIMessageBox.alert({
      content: t('Content is ready. Click the button to start playback'),
      confirmText: t('Play')
    })
  }

  function preventScroll(event: any) {
    event.preventDefault()
  }

  function handleBarrageInputFocus() {
    window.addEventListener('touchmove', preventScroll, {
      passive: false
    })
  }

  function handleBarrageInputBlur() {
    window.removeEventListener('touchmove', preventScroll)
    window.scrollTo({ top: 0, behavior: 'instant' })
  }

  onLoad(async (e: any) => {
    try {
      await setSelfInfo({
        userName: userInfo.value?.userName || userInfo.value?.mobile,
        avatarUrl: userInfo.value?.avatar || ''
      })
      subscribeEvent(
        LiveListEvent.onKickedOutOfLive,
        handleKickedOutOfLive
      )
      await handleJoinLive(e.liveId)
    } catch (err) {
      console.error('Failed to join live room, error:', err)
      showLeaveLiveDialog('没有直播间')
    }
  })
</script>

<template>
  <UIKitProvider language="zh-CN" theme="dark">
    <div id="liveContainer" class="live-player-h5">
      <div class="top">
        <div class="top-left">
          <Avatar
            :src="currentLive?.liveOwner.avatarUrl"
            :size="24"
            :style="{ border: '1px solid rgba(0, 0, 0, 0.1)' }"
          />
          <span>
            {{
              currentLive?.liveOwner.userName ||
              currentLive?.liveOwner.userId
            }}
          </span>
        </div>
        <div class="top-right">
          <div class="audience-list-header" @click="showAudienceList">
            <Avatar
              v-for="item in audienceList.slice(0, 3)"
              :key="item.userId"
              :src="item.avatarUrl"
              :size="24"
            />
            <div class="audience-count">
              <span>{{ audienceList.length }}</span>
            </div>
          </div>
          <IconClose :size="14" @click="handleLeaveLive" />
        </div>
      </div>
      <div v-show="canvas" class="stream-view">
        <LiveCoreView />
      </div>

      <Drawer
        v-model:visible="audienceListPanelVisible"
        :title="audienceListTitle"
        height="90%"
        :z-index="1000"
      >
        <LiveAudienceList />
      </Drawer>

      <!-- 消息列表 -->
      <div class="message-list">
        <BarrageList />
      </div>

      <!-- 底部互动区域 -->
      <div class="bottom">
        <div class="message-input">
          <BarrageInput
            width="158px"
            :autoFocus="false"
            :disabled="!isInLive"
            :placeholder="isInLive ? '' : '说点什么'"
            @focus="handleBarrageInputFocus"
            @blur="handleBarrageInputBlur"
          />
        </div>
        <div class="bottom-operate-button">
          <image
            v-if="isShowActivity"
            class="action-button-icon"
            src="/static/images/activity.png"
            mode="aspectFit"
          />
          <image
            class="action-button-icon"
            src="/static/images/fengxiang.png"
            mode="aspectFit"
            style="margin-left: 14rpx"
            @click="shareDialog = true"
          />
          <!-- <LiveGift class="bottom-operate-button-icon" /> -->
        </div>
      </div>
      <!-- 直播结束显示 -->
      <Teleport to="#app">
        <div v-if="liveEndVisible" class="live-end">
          <div class="close-icon">
            <IconClose :size="20" @click="handleLeaveLive" />
          </div>
          <div class="title">
            <span>直播已结束</span>
          </div>
          <Avatar
            :src="liveOwnerAvatar"
            :size="85"
            :style="{ border: '1px solid rgba(0, 0, 0, 0.1)' }"
          />
          <span>{{ liveOwnerName }}</span>
        </div>
      </Teleport>
    </div>
    <!--  离开直播弹窗 -->
    <TUIDialog
      :visible="leaveLiveDialogVisible"
      :center="true"
      :content="leaveLiveText"
      @close="handleLeaveLive"
    >
      <template #footer>
        <div class="leave-live-dialog">
          <TUIButton size="small" @click="handleLeaveLive">
            确认
          </TUIButton>
        </div>
      </template>
    </TUIDialog>

    <!-- 分享弹框 -->
    <!-- 分享弹窗   :id="productId"
      :cover="viewData.mainImage" -->
    <share-popup v-model:show="shareDialog" type="1"></share-popup>
  </UIKitProvider>
</template>

<style lang="scss" scoped>
  .live-player-h5 {
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #000000;
  }

  .action-button-icon {
    width: 56rpx;
    height: 56rpx;
  }

  .top {
    position: absolute;
    width: 100%;
    height: 50px;
    top: 10px;
    justify-content: space-between;
    align-items: center;
    display: flex;
    z-index: 100;
    color: #fff;
    font-size: 14px;
    font-weight: 400;

    .top-left {
      display: flex;
      gap: 5px;
      max-width: 55%;
      margin-left: 10px;
      padding: 5px;
      overflow: hidden;
      align-items: center;
      border-radius: 25px;
      background-color: rgb(27, 27, 27);

      span {
        max-width: 60%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .top-right {
      display: flex;
      align-items: center;
      overflow: hidden;
      gap: 5px;
      margin-right: 10px;

      .audience-list-header {
        display: flex;
        gap: 1px;

        .audience-count {
          display: flex;
          width: 24px;
          height: 24px;
          overflow: hidden;
          border-radius: 50%;
          text-align: center;
          align-items: center;
          color: #ffffff;
          background-color: rgb(27, 27, 27);

          span {
            flex: 1;
          }
        }
      }
    }
  }

  .live-end {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    gap: 10px;
    color: #fff;
    z-index: 1000;
    background-color: rgb(63, 62, 62);

    .close-icon {
      position: absolute;
      right: 16px;
      top: 16px;
      height: 40px;
    }

    .title {
      padding-top: 100px;
      padding-bottom: 50px;

      span {
        font-size: 24px;
        font-weight: 500;
      }
    }

    span {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .bottom-operate-button {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex: 1 0 auto;
    padding: 0 8px;

    .bottom-operate-button-icon {
      width: 32px;
      height: 32px;
    }
  }

  @media screen and (orientation: landscape) {
    .stream-view {
      width: 100%;
      height: 100%;
    }

    .message-list {
      position: absolute;
      width: 400px;
      height: 100px;
      overflow: hidden;
      left: 0px;
      bottom: 60px;
      z-index: 99;
      .message-group-tip-action {
        color: #fff !important;
      }
    }

    .bottom {
      position: absolute;
      display: flex;
      width: 100%;
      height: 48px;
      bottom: 10px;
      align-items: center;
      justify-content: space-between;
      .message-input {
        margin-left: 10px;
      }
    }
  }

  @media screen and (orientation: portrait) {
    .stream-view {
      width: 100%;
      height: 100%;
    }

    .message-list {
      position: absolute;
      width: 260px;
      height: 180px;
      left: 0px;
      bottom: 60px;
      z-index: 99;
      .message-group-tip-action {
        color: #fff !important;
      }
    }

    .bottom {
      position: absolute;
      display: flex;
      width: 100%;
      height: 48px;
      bottom: 10px;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 0 20px;
      .bottom-operate-button {
        padding: 0;
      }
    }
  }

  .leave-live-dialog {
    padding: 10px;
  }
</style>

<style lang="scss">
  .message-list {
    :deep(.message-group-tip-action) {
      color: #ffffff !important;
    }
  }
</style>
