<script setup lang="ts">
import type { ExperimentBookType } from '../types'
import { Document, CloseBold } from '@element-plus/icons-vue'
import Preview from '@/components/Preview.vue'
import { getExperimentBookList } from '../api'

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

interface Props {
  experiment_id?: string
  course_id?: string
}
const props = defineProps<Props>()
const emits = defineEmits(['empty'])

let list = $ref<ExperimentBookType[]>([])
function fetchInfo() {
  if (!props.experiment_id) return
  getExperimentBookList({ experiment_id: props.experiment_id }).then((res) => {
    list = res.data.items
    if (list.length === 0) {
      emits('empty')
    }
  })
}
watchEffect(() => {
  fetchInfo()
})

let currentRaw = $ref<ExperimentBookType | undefined>()
let show = $ref(false)
// 预览
function handleView(row: ExperimentBookType) {
  currentRaw = row
  show = true
  // 日志上送
  log.upload({
    event: 'file_event',
    action: 'experiment_book_stu_watch_action',
    data: { experiment_id: props.experiment_id, course_id: props.course_id, book_id: row.id },
  })
}
// 关闭
function handleClose() {
  show = false
}
</script>

<template>
  <div v-if="props.experiment_id && list.length">
    <ul class="book-list">
      <li v-for="item in list" :key="item.id" @click="handleView(item)">
        <el-icon><Document /></el-icon>
        <p>{{ item.name }}</p>
      </li>
    </ul>
  </div>
  <el-empty description="暂无数据" v-else />
  <!-- 预览 -->
  <div class="book-preview" v-if="show && currentRaw">
    <div class="book-preview__close" @click="handleClose">
      <el-button type="info" circle :icon="CloseBold" />
    </div>
    <Preview :url="currentRaw.url"></Preview>
  </div>
</template>

<style lang="scss">
.book-list {
  li {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 14px;
    cursor: pointer;
    .el-icon {
      margin-right: 5px;
    }
  }
}
.book-preview {
  position: absolute;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
  background-color: #fff;
}
.book-preview__close {
  position: absolute;
  right: -12px;
  top: -12px;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
}
</style>
