<script setup lang="ts">
import subjectApi, { book_type_school } from '@/api/subject/subject'
import { useRoute, useRouter } from 'vue-router'
// import { globalStore } from '@/stores';
import ChapterTree from './ChapterTree/index.vue'
import VideoList from './VideoList/index.vue'
import TrainList from './TrainList/index.vue'
import RoundSplit from './RoundSplit.vue'
import MapRegion from '@/page/subject/components/MapRegion.vue'
import { XMessage } from '@/hooks'
import { $XXL } from '@/utils'
import { useLeadTaskStore } from '@/stores/lead-task'
import obj from '@/utils/obj'

defineOptions({
  name: 'TextbookDetail',
})

const taskStore = useLeadTaskStore()
const { updateTaskList } = taskStore

const { userInfo } = storeToRefs(userStore())

const route = useRoute()
const router = useRouter()

const textBookId = ref(route.params.textBookId)
let subjectId = route.params.subjectId
// 这个id是user_book的id
let id = route.query.id as string

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

// 学校的练习模块
const practiceModules = ref([] as any[])
let practiceModuleMap = {} as any
const selectedPracticeModule = ref(0)
// 是否显示练习模块
const practiceModulesVisible = computed(
  () => practiceModules.value?.length && tab.value === tab_chapter_practice,
)
// 默认的章节练习标题
const defaultChapterPracticeTitle = '章节练习'

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

async function getTextBookDetail() {
  if (!id) return
  const data = await subjectApi.getTextBookById(id)
  activeChapter.value = data.currentChapterId || ''
  activeNames.value = data.currentChapterIds?.split(',') || []

  // 获取学习栏目
  if (data.bookType === book_type_school) {
    const modules = (
      await subjectApi.getPracticeModuleList({
        schoolId: userInfo.value.schoolId,
      })
    )?.rows
    let res = modules?.map(item => ({
      value: item.id,
      label: item.name,
    }))
    if (res?.length) {
      // 在最前面插入一个【章节练习】
      res = [{ value: 0, label: defaultChapterPracticeTitle }, ...res]
      practiceModules.value = res
      practiceModuleMap = obj.list2map(modules, 'id')
      selectedPracticeModule.value = practiceModules.value[0]?.value
    }
  }
}

const tap_chapter_video = 0
const tab_chapter_practice = 1
const tab_chapter_know = 2
const tab = ref(tab_chapter_practice)
const tabOptions = ref<anyObj[]>([
  { value: tab_chapter_practice, label: defaultChapterPracticeTitle },
])

// 选取章节
const loading = ref(false)
async function handleSelect(item: anyObj) {
  loading.value = true
  subjectApi.updateCurrentChapter({
    currentChapterId: activeChapter.value,
    currentChapterIds: item.pids,
    id,
  })
  // knowledgeList.value = [];
  // videos.value = [];
  try {
    await Promise.all([getVideos(), getKnowledgeTree()])
    tabOptions.value = [{ value: tab_chapter_practice, label: defaultChapterPracticeTitle }]
    if (videos.value.length) {
      tabOptions.value.push({ value: tap_chapter_video, label: '章节视频' })
    }
    if (knowledgeList.value.length) {
      tabOptions.value.push({ value: tab_chapter_know, label: '章节知识点' })
    }
    tab.value = tabOptions.value[0].value
    // getVideos();
    // getKnowledgeTree();
  } catch {}
  loading.value = false
}

// 获取知识点
const knowledgeList = ref<anyObj[]>([])
async function getKnowledgeTree() {
  const { data: res } = await subjectApi.getSubjectKnowledgeTree({
    chapterId: activeChapter.value,
    masterFlag: true,
    // size: -1,
  })

  knowledgeList.value = res.data || []
}

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

  videos.value = res.data?.rows || []
}

// 初始化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
    subjectApi.updateCurrentChapter({
      currentChapterId: activeChapter.value,
      currentChapterIds: list[0].pids,
      id,
    })
  }
}

const pageLoading = ref(false)
async function init() {
  textBookId.value = route.params.textBookId
  subjectId = route.params.subjectId
  await getChapter()
  await getTextBookDetail()
  if (!activeChapter.value) {
    initChapterId()
  }
  await Promise.all([getKnowledgeTree(), getVideos()])
}

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

function toKnowledgePoints(i: anyObj) {
  if (businessFlag.includes('1') || businessFlag.includes('5')) {
    router.push(
      `/subject/freeStudy/knowledgePoints/${subjectId}/${i.id}?businessFlag=${businessFlag.join(',')}&textBookId=${textBookId.value}`,
    )
  } else {
    XMessage.error('该知识点暂无视频和练习')
  }
}

// 修改tab的标题
watch(
  () => selectedPracticeModule.value,
  val => {
    if (tab.value !== tab_chapter_practice) return
    tabOptions.value[0].label = practiceModuleMap[val]?.name || defaultChapterPracticeTitle
  },
  {
    immediate: true,
  },
)

onMounted(async () => {
  $XXL.setScreenOn(1)
  textBookId.value = route.params.textBookId
  subjectId = route.params.subjectId
  textbookName.value = route.query.textbookName as string
  id = route.query.id as string
  businessFlag = (route.query.businessFlag as string)?.split(',').filter(i => i) || []
  await initTextBook()

  if (activeChapter.value) {
    await getKnowledgeTree()
  }
  updateTaskList()
})

async function initTextBook() {
  tab.value = 0
  activeChapter.value = ''
  activeNames.value = []
  chapterList.value = []
  knowledgeList.value = []
  videos.value = []
  pageLoading.value = true
  try {
    await init()
    tabOptions.value = [{ value: 1, label: '章节练习' }]
    await Promise.all([getVideos(), getKnowledgeTree()])
    if (videos.value.length) {
      tabOptions.value.push({ value: 0, label: '章节视频' })
    }
    if (knowledgeList.value.length) {
      tabOptions.value.push({ value: 2, label: '章节知识点' })
    }
    tab.value = tabOptions.value[0].value
  } catch {}
  pageLoading.value = false
}

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">
      <div class="left">
        <BackBar :leftText="textbookName" />
      </div>
      <div class="right">
        <SelectTab
          v-if="practiceModulesVisible"
          v-model="selectedPracticeModule"
          :dataList="practiceModules"
          class="nav-tab"
          type="small"
        ></SelectTab>
      </div>
    </div>
    <div class="main">
      <div v-if="!pageLoading" class="textbookDetail">
        <div class="text-book-left">
          <el-scrollbar>
            <ChapterTree
              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="tabOptions.length && activeChapter" class="knowledge-list-box">
            <div class="title">
              <SelectTab v-model="tab" :data-list="tabOptions"></SelectTab>
            </div>
            <RoundSplit></RoundSplit>
            <div v-if="tab === tab_chapter_know" class="knowledge-list-box-main">
              <div v-if="knowledgeList.length" class="map-region-box">
                <MapRegion
                  :data="knowledgeList"
                  indicator
                  @clickSymbol="toKnowledgePoints"
                ></MapRegion>
              </div>
              <Empty
                v-else
                center
                :type="loading ? 'loading' : 'learn'"
                content="该章节暂无知识点～"
                style="background: #f9f6ff; border-radius: 16px"
              ></Empty>
            </div>
            <div v-else-if="tab === tap_chapter_video" class="video-list-box">
              <VideoList
                v-if="videos.length"
                :activeChapter="activeChapter"
                :list="videos"
                @onPause="onPause"
              ></VideoList>
              <Empty
                v-else
                center
                :type="loading ? 'loading' : 'learn'"
                content="该章节暂无视频～"
                style="background: #f9f6ff; border-radius: 16px"
              ></Empty>
            </div>
            <div v-else class="train-list-box">
              <!-- 练习 -->
              <TrainList :module-id="selectedPracticeModule" :chapterId="activeChapter"></TrainList>
            </div>
          </div>
          <Empty
            v-else
            type="learn"
            :content="activeChapter ? '该章节暂无视频和知识点～' : '请选择章节进行学习～'"
            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;
  // }

  .top {
    left: 64px;
    right: 64px;
    top: 2.67vh;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 2vh;
    }
  }

  .main {
    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% - 102px);
      }
      .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: #a5b2f7;
          background: linear-gradient(
            180deg,
            rgba(241, 234, 250, 0.35) 65.59%,
            rgba(241, 241, 250, 0.35) 100%
          );
          // filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25));
          // padding: 14px 8px;
          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%);
          }
        }
      }

      .map-region-box {
        height: 100%;
      }
    }
  }
}
</style>
