<script setup>
import Live from './Live.vue'
import LivePlayback from './LivePlayback.vue'
import { getTest, getRecord, pushSubtitle } from '../api'
import { useCountdown } from '@/composables/useCountdown'

const props = defineProps({
  id: { type: String },
  recordId: { type: String },
  isView: { type: Boolean, default: false },
})

const { timeLeft, formattedTime, stop, reset } = useCountdown({
  // 倒计时结束
  onEnd: () => {
    live.value?.stop()
  },
})
const live = ref(null)

const detail = ref(null)
provide('detail', detail)

const duration = computed(() => {
  return parseInt(detail.value?.duration) * 60 || 0
})
const isLocalUpload = computed(() => {
  return detail.value?.upload_way == 2
})

async function fetchInfo() {
  const res = await getTest({ id: props.id })
  detail.value = res.data.detail
  timeLeft.value = duration.value
}
watchEffect(() => {
  !props.isView && fetchInfo()
})

// 商品卖点
const hotList = computed(() => {
  return detail.value?.live_speech.selling_point.split(/;|；/)
})
// 营销活动
const actList = computed(() => {
  return detail.value?.live_speech.marketing_campaign.split(/;|；/)
})

// 直播记录数据
const record = ref(null)
provide('record', record)

// 直播数据
const stats = computed(() => {
  const result = { totalViewers: 0, peakViewers: 0, totalGifts: 0, totalLikes: 0, totalGiftViewers: 0 }
  return Object.assign(result, record.value?.live_info.stats)
})

const timelines = ref([])
const fetchRecord = async () => {
  const res = await getRecord({ id: props.recordId })
  const resDetail = res.data.detail
  record.value = { ...resDetail, live_info: JSON.parse(resDetail.live_info) }
  detail.value = resDetail.live_practice_info
  timeLeft.value = duration.value
  timelines.value = JSON.parse(resDetail.subtitle)?.Result?.Sentences || []
}
onMounted(() => {
  props.isView && fetchRecord()
})

// 毫秒转分钟 00:00,需要补0
const formatTime = (time) => {
  const minutes = Math.floor(time / 1000 / 60)
  const seconds = Math.floor((time / 1000) % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const orderCount = ref(0)
const onSentenceEnd = async (result, data) => {
  console.log('onSentenceEnd', result, data)
  const res = await pushSubtitle({
    subtitle: result,
    selling_point: detail.value.live_speech.selling_point,
    marketing_campaign: detail.value.live_speech.marketing_campaign,
  })
  orderCount.value = res.data.count
}

const currentStats = ref({})
const onStatsChange = (stats) => {
  currentStats.value = stats
}
</script>

<template>
  <div class="live-row">
    <div class="live-col">
      <template v-if="isView">
        <LivePlayback :record="record" v-if="record"></LivePlayback>
      </template>
      <template v-else>
        <Live
          ref="live"
          :isLocalUpload="isLocalUpload"
          :onStart="() => reset(duration)"
          :onStop="stop"
          :onSentenceEnd="onSentenceEnd"
          :onStatsChange="onStatsChange"
          v-if="detail" />
      </template>
    </div>
    <div class="live-col" style="flex: 1" v-if="isView">
      <el-timeline style="max-width: 600px">
        <el-timeline-item
          placement="top"
          v-for="(item, index) in timelines"
          :key="index"
          :timestamp="formatTime(item.BeginTime)">
          {{ item.Text }}
        </el-timeline-item>
      </el-timeline>
    </div>
    <div class="live-col" style="flex: 1">
      <h2 class="h2-title">直播话术</h2>
      <div class="live-talk-content" v-html="detail?.live_speech.content"></div>
    </div>
    <div class="live-col" style="width: 350px" v-if="!isView">
      <div class="live-col-box" v-if="isView">
        <h2 class="h2-title">直播数据</h2>
        <div class="live-data">
          <dl>
            <dt>观众总人数：</dt>
            <dd>{{ stats.totalViewers }}</dd>
          </dl>
          <dl>
            <dt>最高峰人数：</dt>
            <dd>{{ stats.peakViewers }}</dd>
          </dl>
          <dl>
            <dt>点赞数：</dt>
            <dd>{{ stats.totalLikes }}</dd>
          </dl>
          <dl>
            <dt>刷礼物人数：</dt>
            <dd>{{ stats.totalGiftViewers }}</dd>
          </dl>
          <dl>
            <dt>刷礼物总数：</dt>
            <dd>{{ stats.totalGifts }}</dd>
          </dl>
        </div>
      </div>
      <div class="live-col-box" v-else>
        <h2 class="h2-title">倒计时</h2>
        <h3 class="live-time">{{ formattedTime }}</h3>
        <div class="live-data">
          <dl>
            <dt>观众人数：</dt>
            <dd>{{ currentStats.viewers }}</dd>
          </dl>
          <dl>
            <dt>订单量：</dt>
            <dd>{{ orderCount }}</dd>
          </dl>
        </div>
      </div>
      <div class="live-col-box">
        <h2 class="h2-title">主题卖点</h2>
        <ul class="live-tag live-tag__hot">
          <li v-for="item in hotList" :key="item">{{ item }}</li>
        </ul>
      </div>
      <div class="live-col-box">
        <h2 class="h2-title">营销活动</h2>
        <ul class="live-tag live-tag__act">
          <li v-for="item in actList" :key="item">{{ item }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.live-row {
  height: 100%;
  display: flex;
  gap: 20px;
}
.live-col {
  padding: 20px;
  border-radius: 10px;
  border: 1px solid #eee;
  max-height: 100%;
  overflow-y: auto;
  .h2-title {
    margin-top: 0;
  }
}
.live-tag {
  margin: 20px 0;
  background-color: #eee;
  border-radius: 10px;
  padding: 20px;
  gap: 10px;
  li {
    line-height: 30px;
    background-color: #fff;
    text-align: center;
    border: 1px solid rgba(105, 113, 140, 0.12);
  }
}
.live-data {
  padding: 0 0 20px 10px;
  dl {
    margin: 10px 0;
    display: flex;
  }
  dt {
    font-weight: bold;
  }
}
.live-time {
  height: 140px;
  font-size: 72px;
  text-align: center;
  color: var(--main-color);
}
.live-tag__hot {
  display: flex;
  flex-wrap: wrap;
  li {
    flex: 0 0 calc(50% - 10px);
  }
}
.live-tag__act {
  li {
    margin: 10px 0;
  }
}
.live-talk-content {
  max-height: 660px;
  overflow-y: auto;
  line-height: 24px;
}
</style>
