<script setup lang="ts">
import subjectApi from '@/api/subject/subject'
import { useRoute } from 'vue-router'
import ChapterTree from '@/page/subject/freeStudy/views/textbookDetail/ChapterTree/index.vue'
import VideoList from '@/page/subject/freeStudy/views/textbookDetail/VideoList/index.vue'
import RoundSplit from '@/page/subject/freeStudy/views/textbookDetail/RoundSplit.vue'
import { $XXL } from '@/utils'

const route = useRoute()

const textBookId = ref(route.params.textBookId)

const activeChapter = ref('')
const chapterList = ref<anyObj[]>([])
const activeNames = ref<string[]>([])

// 获取章节
async function getChapter() {
  const { data: res } = await subjectApi.getSubjectChapterTree({
    textBookId: textBookId.value,
    resource: 1,
  })
  chapterList.value = res.data
}

// async function getTextBookDetail() {
//     const data = await getTextBookById(id);
//         activeChapter.value = data.currentChapterId || '';
//         activeNames.value = data.currentChapterIds?.split(',') || [];
// }

const select = ref(0)
const selectConfig = ref<anyObj[]>([])

// 选取章节
const loading = ref(false)
async function handleSelect(_item: anyObj) {
  loading.value = true
  selectConfig.value = []
  try {
    await Promise.all([getVideos(), getKnowledgeTree()])
    if (videos.value.length) {
      selectConfig.value.push({ value: 0, label: '章节视频' })
    }
    if (knowledgeVideos.value.length) {
      selectConfig.value.push({ value: 1, label: '知识点视频' })
    }
    select.value = selectConfig.value[0].value
  } catch {}
  loading.value = false
}
// 获取知识点
const knowledgeVideos = ref<anyObj[]>([])
async function getKnowledgeTree() {
  knowledgeVideos.value = []
  const { data: res } = await subjectApi.getSubjectKnowledgeTree({
    chapterId: activeChapter.value,
    masterFlag: true,
    resource: 1,
  })

  res.data?.forEach((item: anyObj) => {
    item.videoList?.forEach((c: anyObj) => {
      if (knowledgeVideos.value.every(i => i.videoBaseId !== c.videoBaseId)) {
        knowledgeVideos.value.push(c)
      }
    })
  })
}

// 获取视频列表
const videos = ref<anyObj[]>([])
async function getVideos() {
  const { data: res } = await subjectApi.getSubjectChapterVideos({
    chapterId: activeChapter.value,
    size: 20,
    resource: 1,
  })
  videos.value = res.data?.rows || []
}

const videoList = computed(() => (select.value ? knowledgeVideos.value : videos.value))

// 初始化ChapterId
function initChapterId(list: anyObj[] = chapterList.value) {
  activeNames.value.push(list[0].id)

  if (list?.[0].children?.length > 0 && !list?.[0].hasVideoFlag) {
    initChapterId(list[0].children)
    activeNames.value.push(list[0].children[0].id)
  } else {
    activeChapter.value = list[0].id
  }
}

const pageLoading = ref(false)
async function init() {
  textBookId.value = route.params.textBookId
  await getChapter()

  // if (!activeChapter.value)
  initChapterId()
  await Promise.all([getVideos(), getKnowledgeTree()])
}

const textbookName = ref(route.query.textbookName as string)
// let businessFlag: string[] = (route.query.businessFlag as string)?.split(',').filter(i => i) || [];

onActivated(() => {
  $XXL.setScreenOn(1)
  textBookId.value = route.params.textBookId
  textbookName.value = route.query.textbookName as string
})

watch(
  textBookId,
  async () => {
    select.value = 0
    activeChapter.value = ''
    activeNames.value = []
    chapterList.value = []
    // knowledgeList.value = [];
    videos.value = []
    selectConfig.value = []
    pageLoading.value = true
    try {
      await init()
      await Promise.all([getVideos(), getKnowledgeTree()])
      if (videos.value.length) {
        selectConfig.value.push({ value: 0, label: '章节视频' })
      }
      if (knowledgeVideos.value.length) {
        selectConfig.value.push({ value: 1, label: '知识点视频' })
      }
      select.value = selectConfig.value[0].value
    } catch {}
    pageLoading.value = false
  },
  { immediate: true },
)

function onPause(id: any, duration: number) {
  const idx = videos.value.findIndex(i => i.id === id)
  if (idx !== -1) {
    videos.value[idx].playDuration = duration
  }
}
</script>
<template>
  <div class="free-study">
    <div class="top">
      <BackBar :leftText="textbookName" />
    </div>
    <div class="main">
      <div v-if="!pageLoading" class="textbookDetail">
        <div class="text-book-left">
          <el-scrollbar>
            <chapter-tree
              ref="XTreeRef"
              v-model="activeChapter"
              v-model:activeNames="activeNames"
              :options="chapterList as any"
              :prop="{
                label: 'name',
                select: 'learnFlag',
              }"
              @select="handleSelect"
            />
          </el-scrollbar>
        </div>
        <div class="text-book-right">
          <div v-if="selectConfig.length" class="knowledge-list-box">
            <div class="title">
              <select-tab v-model="select" :data-list="selectConfig" />
            </div>
            <RoundSplit></RoundSplit>
            <div class="video-list-box">
              <VideoList
                v-if="videoList.length"
                :activeChapter="activeChapter"
                :list="videoList"
                :resource="1"
                @onPause="onPause"
              ></VideoList>
            </div>
          </div>
          <Empty
            v-else
            :type="loading ? 'loading' : 'learn'"
            content="该章节暂无视频"
            style="background: #f9f6ff; border-radius: 16px"
          ></Empty>
        </div>
      </div>
      <Empty v-else :type="pageLoading ? 'loading' : 'network'"></Empty>
    </div>
  </div>
</template>
<style scoped lang="scss">
.free-study {
  position: relative;
  width: 100vw;
  height: 100%;
  // overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;
  @include main_bg;
  @include hidden_scroll;
  .top {
    // padding: 32px 64px 0;
    position: absolute;
    top: 2.67vh;
    left: 64px;
    z-index: 1;
    // margin-bottom: 24px;
  }
  .main {
    // position: absolute;
    // top: 0;
    // left: 0;
    width: 100%;
    height: 100%;
  }
}
.textbookDetail {
  padding: 10.67vh 68px 2vh;
  display: flex;
  height: 100%;
  line-height: 1.5;
  .text-book {
    &-left {
      width: 720px;
      height: 100%;
      margin-right: 40px;
      position: relative;
      flex-shrink: 0;

      .el-scrollbar {
        height: 100%;
        border-radius: 1.67vh;
        overflow: hidden;
        background: linear-gradient(180deg, #f0faff 0%, #fafdff 100%);
      }
    }
    &-right {
      width: 1032px;
      height: 100%;
      .title {
        color: $font-color;
        font-family: $font-special;
        font-size: 3vh;
        height: 8.5vh;
        padding: 0 32px;
        // overflow-x: auto;
        border-radius: 1.67vh;
        background: linear-gradient(269deg, #e3e3ff 2.25%, #ded3fb 51.93%, #c0c7f7 99.65%);
        padding: 1.83vh 24px;
        @include single_ellipsis;
        :deep(.select-list) {
          .data-item {
            width: 50%;
            flex: 1;
            &.active {
              background: linear-gradient(269deg, #86e6ff 2.25%, #9effda 51.93%, #5fdcfd 99.65%);
            }
          }
        }
      }
      .video-list-box {
        height: calc(100% - 8.5vh);
      }
      .train-list-box {
        background: linear-gradient(
          180deg,
          rgba(241, 234, 250, 0.35) 65.59%,
          rgba(241, 241, 250, 0.35) 100%
        );
        padding: 0.67vh;
        padding-top: 1vh;
        border-radius: 1.67vh;
        height: calc(100% - 8.5vh);
      }
      .knowledge-list-box {
        height: 100%;
        position: relative;
        &-main {
          background: linear-gradient(
            180deg,
            rgba(241, 234, 250, 0.35) 65.59%,
            rgba(241, 241, 250, 0.35) 100%
          );

          padding: 0.67vh;
          padding-top: 1vh;
          border-radius: 1.67vh;
          height: calc(100% - 102px);
          .map-region {
            background-color: #ffffff;
            border-radius: 1.67vh;
            height: 100%;
            overflow-x: auto !important;
            @include hidden_scroll;
          }
        }
        .round-split {
          position: absolute;
          width: calc(100% - 50px);
          left: 50%;
          transform: translate(-50%);
          z-index: 12;
          top: 8vh;
          :deep(.dot) {
            background: linear-gradient(180deg, #566db8 0%, #7e98f5 100%);
          }
        }
      }
    }
  }
}
</style>
