<script setup lang="ts">
import type { CollectionType, AllCourseType } 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 { getCollectionList, getCourseList, collectionResource } from '../api'

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

const tabs = $ref([
  { label: '全部', value: '' },
  { label: '视频', value: '2' },
  { label: '课件', value: '3' },
  { label: '教案', value: '4' },
  { label: '作业', value: '5' },
  { label: '帖子', value: '6' },
  { label: '其它资料', value: '1' }
])

// 收藏列表
const params = reactive<{ type?: string; course_id: string; semester_id: string; types?: string[] }>({
  type: '',
  course_id: '',
  semester_id: ''
})
let list = $ref<CollectionType[]>([])
function fetchList() {
  const requestParams = Object.assign({}, params)
  if (requestParams.type === '1') {
    delete requestParams.type
    requestParams.types = ['1', '7']
  }
  getCollectionList(requestParams).then(res => {
    list = res.data.items?.map((item: CollectionType) => {
      item.status = 1
      return item
    })
  })
}

// 所有课程列表
let courseList = $ref<AllCourseType[]>([])
const courseActive = $ref()
function fetchCourseList() {
  getCourseList().then(res => {
    courseList = res.data.items || []
  })
}
function handleCourseChange(data: AllCourseType) {
  params.course_id = data.course_id || ''
  params.semester_id = data.semester?.id || ''
  fetchList()
}
onMounted(() => {
  fetchList()
  fetchCourseList()
})

// 时长转换
function formatDuration(duration: number | undefined) {
  if (!duration) return ''
  return format(duration * 1000, { leading: true })
}

// 收藏/取消收藏
function toggleCollection(data: CollectionType) {
  collectionResource({
    course_id: data.course_id,
    semester_id: data.semester_id,
    chapter_id: data.chapter_id,
    section_id: data.section_id,
    source_id: data.source_id,
    type: data.type,
    status: data.status ? 0 : 1
  }).then(() => {
    data.status = data.status ? 0 : 1
  })
}
// 是否可以下载
// function canDownload(type: number) {
//   // return [1, 3, 4].includes(type)
//   return [1].includes(type)
// }
// 下载资源
function downloadFile(data: CollectionType) {
  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: data.course_id,
      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 genCourseViewUrl(item: CollectionType) {
  return `/course/view?course_id=${item.course_id}&semester_id=${item.semester_id}&chapter_id=${item.chapter_id}&section_id=${item.section_id}`
}
// 课程播放页
function genCoursePlayerUrl(item: CollectionType) {
  return `/course/player?course_id=${item.course_id}&chapter_id=${item.chapter_id}&section_id=${item.section_id}&resource_id=${item.source_id}&semester_id=${item.semester_id}`
}
// 文件预览
function genPreviewUrl(item: CollectionType) {
  return `/preview?course_id=${item.course_id}&semester_id=${item.semester_id}&resource_id=${item.info?.id}&resource_type=${item.resource_type}&url=${item.info?.url}`
}
function targetUrl(item: CollectionType) {
  if (item.type === 5) {
    return `/course/exam?course_id=${item.course_id}&semester_id=${item.semester_id}&paper_id=${item.info.id}&type=2&paper_title=${item.info.paper_title}`
  } else if (item.type === 6) {
    return `/bbs/${item.info.id}`
  } else if (item.type === 2) {
    return genCoursePlayerUrl(item)
  } else {
    return genPreviewUrl(item)
  }
}
function targetUrl2(item: CollectionType) {
  if (item.type === 7) {
    return genCourseViewUrl(item)
  } else {
    return genCoursePlayerUrl(item)
  }
}
</script>

<template>
  <AppCard>
    <el-tabs v-model="params.type" @tab-change="fetchList">
      <el-tab-pane v-for="item in tabs" :label="item.label" :name="item.value" :key="item.value"></el-tab-pane>
    </el-tabs>
    <el-select v-model="courseActive" placeholder="所属课程" @change="handleCourseChange" clearable value-key="id">
      <el-option v-for="item in courseList" :key="item.id" :label="item.course_alias_name || item.name" :value="item" />
    </el-select>
    <ul v-if="list.length">
      <li class="collection-item" v-for="item in list" :key="item.id">
        <p>
          <router-link :to="targetUrl(item)" target="_blank">
            <ResourceIcon :resourceType="item.resource_type" :info="item.info" />
            {{ item.info.name || item.info.title || item.info.paper_title }}
          </router-link>
        </p>
        <p>
          <router-link :to="targetUrl2(item)" target="_blank">
            {{ item.course.course_alias_name || item.course.name
            }}<template v-if="item.type !== 7">/{{ item.chapter.name }}</template>
          </router-link>
        </p>
        <div class="collection-item-aside">
          <div class="video-duration" v-if="item.type === 2">
            {{ formatDuration(item.info.length) }}
          </div>
          <div class="actions">
            <i class="icon-star" :class="!!item.status ? 'is-active' : ''" @click="toggleCollection(item)"></i>
            <i class="icon-download" @click="downloadFile(item)" v-if="!!item.can_download"><Download /></i>
          </div>
        </div>
      </li>
    </ul>
    <el-empty description="暂无数据" v-else />
  </AppCard>
</template>

<style lang="scss" scoped>
.collection-item {
  display: flex;
  align-items: center;
  height: 48px;
  border-bottom: 1px solid #e6e6e6;
  p {
    flex: 1;
    line-height: 48px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  p + p {
    margin-left: 20px;
  }
  &:hover {
    color: var(--main-color);
  }

  .video-duration {
    padding: 0 20px;
  }

  .actions {
    width: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 1;
  }
}
.collection-item-aside {
  min-width: 200px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.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;
}
</style>
