<!-- 学习 -->
<script setup lang="ts">
import type { CourseChapterType, CourseSectionType, CourseResourceType } from '../types'
import ResourceIcon from '@/components/ResourceIcon.vue'
import { Download } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import format from 'format-duration'
import { formatLiveDate, formatLiveStatus } from '@/utils/index'

import { getChapterTreeList, collectionResource } from '../api'

import { useLog } from '@/composables/useLog'
const log = useLog()

let chapterList = $ref<CourseChapterType[]>([])
const { query } = useRoute()
const courseId = $ref(query.course_id as string)
const semesterId = $ref(query.semester_id as string)
const chapterId = $ref(query.chapter_id as string)
const sectionId = $ref(query.section_id as string)

// 章
const chapterIds = $ref<string[]>([])
if (chapterId) {
  chapterIds.push(chapterId)
}
// 节
const sectionIds = $ref<string[]>([])
if (sectionId) {
  sectionIds.push(sectionId)
}

// 获取章节列表
function fetchList() {
  if (!courseId || !semesterId) {
    return
  }
  getChapterTreeList({ course_id: courseId, semester_id: semesterId }).then(res => {
    chapterList = res.data.items
    // 设置展开第一项
    const [first] = chapterList
    if (!chapterId && first) {
      chapterIds.push(first.id)
      const [section] = first.sections
      section && sectionIds.push(section.id)
    }
  })
}
onMounted(() => {
  fetchList()
})

// 时长转换
function formatDuration(duration: number | undefined) {
  if (!duration) return ''
  return format(duration * 1000, { leading: true })
}
// 是否可以收藏
function canCollection(data: CourseResourceType) {
  return [4, 2, 10, 11, 3, 9].includes(data.resource_type)
}
// 收藏/取消收藏
function toggleCollection(resource: CourseResourceType, section: CourseSectionType, chapter: CourseChapterType) {
  // 资源类型: 1章节，2视频，3作业，4其他，6腾讯会议，9考试，10课件，11教案
  // 收藏类型: 1其他， 2视频，3课件，4教案，5作业，6帖子
  const typeMap: Record<number, number> = { 4: 1, 2: 2, 10: 3, 11: 4, 3: 5, 9: 5 }
  collectionResource({
    course_id: courseId,
    semester_id: semesterId,
    chapter_id: chapter.id,
    section_id: section.id,
    source_id: resource.resource_id,
    type: typeMap[resource.resource_type],
    status: resource.collection_count > 0 ? 0 : 1
  }).then(() => {
    resource.collection_count = resource.collection_count > 0 ? 0 : 1
  })
}
// 是否可以下载
// function canDownload(type: number) {
//   // return [4, 10, 11].includes(type)
//   return [4].includes(type)
// }
// 下载资源
function downloadFile(data: CourseResourceType) {
  const { url, name } = data.info
  const urlExtensionName = url?.split('.').pop()
  const nameExtensionName = name?.split('.').pop()
  const filename = nameExtensionName === urlExtensionName ? name : `${name}.${urlExtensionName}`
  url && saveAs(url, filename)

  // 日志上送
  log.upload({
    event: 'file_event',
    action: 'stu_download_file_action',
    data: {
      course_id: courseId,
      resource_id: data.info.id,
      resource_type: data.resource_type,
      download_time: Math.floor(Date.now() / 1000),
      download_name: name,
      download_size: data.info.size
    }
  })
}
// 跳转链接
function targetUrl(resource: CourseResourceType, section: CourseSectionType, chapter: CourseChapterType) {
  if (resource.resource_type === 3 || resource.resource_type === 9) {
    return `/course/exam?course_id=${courseId}&semester_id=${semesterId}&paper_id=${resource.resource_id}&type=2&paper_title=${resource.name}`
  } else if (resource.resource_type === 2) {
    return `/course/player?course_id=${courseId}&chapter_id=${chapter.id}&section_id=${section.id}&resource_id=${resource.resource_id}&semester_id=${semesterId}&paper_title=${resource.name}`
  } else if (resource.resource_type === 6) {
    return resource.info.join_url
  } else {
    return `/preview?course_id=${courseId}&semester_id=${semesterId}&resource_id=${resource.resource_id}&resource_type=${resource.resource_type}&url=${resource.info?.url}`
  }
}
</script>
<template>
  <el-collapse class="course-chapters" v-model="chapterIds" v-if="chapterList.length">
    <el-collapse-item :name="item.id" v-for="item in chapterList" :key="item.id">
      <template #title
        ><i class="icon-chapter"></i>
        <p class="chapter-title">{{ item.name }}</p></template
      >
      <el-collapse class="course-sections" v-model="sectionIds">
        <el-collapse-item :name="section.id" v-for="section in item.sections" :key="section.id">
          <template #title
            ><i class="icon-chapter"></i>
            <p class="section-title">{{ section.name }}</p></template
          >
          <ul>
            <li class="course-resource-item" v-for="resource in section.resources" :key="resource.id">
              <p>
                <a :href="targetUrl(resource, section, item)" target="_blank">
                  <ResourceIcon :resourceType="resource.resource_type" :info="resource.info" />
                  {{ resource.name }}
                </a>
              </p>
              <router-link
                :to="`/course/exam/result?course_id=${courseId}&semester_id=${semesterId}&paper_id=${resource.resource_id}&type=2&paper_title=${resource.name}`"
                target="_blank"
                style="margin: 0 20px"
                v-if="resource.paper_status === 2 || resource.paper_status === 3"
              >
                <el-button round size="small">查看报告</el-button>
              </router-link>

              <div class="video-duration" v-if="resource.resource_type === 2">
                {{ formatDuration(resource.info.length) }}
              </div>
              <template v-if="resource.resource_type === 6 && resource.info">
                <span>{{ formatLiveDate(resource.info.start_time) }}</span>
                <span style="margin-left: 10px">{{ formatLiveStatus(resource.info.status) }}</span>
              </template>

              <div class="actions">
                <i
                  class="icon-star"
                  :class="!!resource.collection_count ? 'is-active' : ''"
                  @click="toggleCollection(resource, section, item)"
                  v-if="canCollection(resource)"
                ></i>
                <i class="icon-download" @click="downloadFile(resource)" v-if="!!resource.can_download">
                  <Download />
                </i>
              </div>
            </li>
          </ul>
        </el-collapse-item>
      </el-collapse>
    </el-collapse-item>
  </el-collapse>
  <el-empty description="暂无数据" v-else />
</template>

<style lang="scss" scoped>
.course-resource-item {
  display: flex;
  align-items: center;
  padding: 0 48px 0 60px;
  height: 48px;
  line-height: 48px;
  border-bottom: 1px solid #e6e6e6;
  p {
    flex: 1;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    color: #666;
  }
  a {
    &:hover {
      color: var(--main-color);
    }
  }
  .video-duration {
    padding: 0 20px;
  }

  .actions {
    min-width: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 1;
    &:empty {
      min-width: auto;
    }
  }
}
.icon-star {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url(@/assets/images/icon_star.png) no-repeat;
  background-size: contain;
  cursor: pointer;
  &.is-active {
    background: url(@/assets/images/icon_star_hover.png) no-repeat;
    background-size: contain;
  }
}
.icon-download {
  display: inline-block;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.icon-chapter {
  margin-right: 10px;
  display: inline-block;
  width: 16px;
  height: 20px;
  background: url(@/assets/images/icon_chapter.png) no-repeat;
  background-size: contain;
}
.course-chapters {
  :deep(.el-collapse-item__header) {
    padding: 0 20px;
    background-color: #e8e9eb;
    border-bottom: none;
  }
}
.course-sections {
  margin-top: 10px;
  :deep(.el-collapse-item__header) {
    padding: 0 40px;
    background-color: #f7f8fa;
    border-bottom: none;
  }
}
.chapter-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}
.section-title {
  font-size: 14px;
  font-weight: 400;
  color: #333333;
}
.el-collapse {
  border-top: none;
  border-bottom: none;
}
:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}
:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
:deep(.el-collapse-item) {
  margin-bottom: 10px;
}
</style>
