<script setup lang="ts">
import type { CourseResourceType } from '../types'

import ResourceIcon from '@/components/ResourceIcon.vue'
import { Download } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import { collectionResource } from '../api'

const { query } = useRoute()
const courseId = $ref(query.course_id as string)
const chapterId = $ref(query.chapter_id as string)
const semesterId = $ref(query.semester_id as string)
const sectionId = $ref(query.section_id as string)

interface Props {
  data: CourseResourceType
}
const props = defineProps<Props>()

// 跳转链接
const targetHref = computed(() => {
  const info = props.data.info
  if (['pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(info.type)) {
    return `https://view.officeapps.live.com/op/view.aspx?src=${info.url}`
  } else {
    return info.url
  }
})

// 收藏/取消收藏
function toggleCollection(data: CourseResourceType) {
  // 资源类型: 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: chapterId,
    section_id: sectionId,
    source_id: data.resource_id,
    type: typeMap[data.resource_type],
    status: data.collection_count ? 0 : 1
  }).then(() => {
    data.collection_count = data.collection_count ? 0 : 1
  })
}

// 是否可以下载
function canDownload(type: number) {
  return [4, 10, 11].includes(type)
}
// 下载资源
function downloadFile(data: CourseResourceType) {
  data.info.url && saveAs(data.info.url, data.info.name)
}
</script>

<template>
  <div class="course-resource-item">
    <p>
      <a :href="targetHref" target="_blank">
        <ResourceIcon :resourceType="data.resource_type" />
        {{ data.name }}
      </a>
    </p>
    <div class="actions">
      <i class="icon-star" :class="!!data.collection_count ? 'is-active' : ''" @click="toggleCollection(data)"></i>
      <i class="icon-download" @click="downloadFile(data)" v-if="canDownload(data.resource_type)"><Download /></i>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.course-resource-item {
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 20px;
  border-bottom: 1px solid #e6e6e6;
  p {
    flex: 1;
    line-height: 48px;
  }
  &:hover {
    color: var(--main-color);
  }

  .actions {
    width: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.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>
