<template>
  <view>
    <CuNavbar></CuNavbar>
    <!-- 文章 -->
    <template v-if="info.type == 1">
      <view class="h-400rpx">
        <uv-image width="100%" height="100%" :src="info.cover_image" />
      </view>
    </template>
    <!-- 视频 -->
    <template v-if="info.type == 2">
      <video class="w-full" :src="info.video" />
    </template>
    <view class="p-base space-y-10rpx">
      <view class="font-500 text-30rpx">{{ info.title }}</view>
      <view class="text-hex-999999">{{ info.description }}</view>
      <view class="text-hex-999 text-right">{{
        timeFormat(info.created_at)
      }}</view>
    </view>

    <template v-if="info.type == 3">
      <view class="p-base space-y-8rpx">
        <view
          v-for="item in info.files"
          class="flex card-shadow bg-white rounded-19rpx p-base"
          :key="item.id"
        >
          <view class="line-clamp-1 flex-1">
            {{ item.name }}
          </view>
          <view @click="downloadFile(item.value)">
            <uv-icon size="40rpx" name="download"></uv-icon>
          </view>
        </view>
      </view>
    </template>

    <!-- 富文本 -->
    <template v-if="info.content">
      <uv-divider />
      <view>
        <uv-parse :content="info.content"></uv-parse>
      </view>
    </template>

    <uv-modal
      ref="modalRef"
      title="标题"
      content="下载成功！是否打开"
      showCancelButton
      @confirm="confirm"
    >
    </uv-modal>
  </view>
</template>
<script setup>
import CuNavbar from '@/components/cu-navbar/index'
import { http } from '@/utils/request'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { timeFormat } from '@climblee/uv-ui/libs/function'

const modalRef = ref(null)
const id = ref('')
const info = ref({})
const tempFile = ref(null)
onLoad((options) => {
  id.value = options.id
  http.get(`/train/books/${id.value}`).then((res) => {
    info.value = res
  })
})

const downloadFile = (url) => {
  const filetype = url.substring(url.lastIndexOf('.') + 1)
  const whiteFile = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx']
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        tempFile.value = res

        if (whiteFile.includes(filetype)) {
          modalRef.value.open()
        } else {
          uni.showToast({
            title: '下载成功',
            icon: 'none',
          })
        }
      }
    },
  })
}

const confirm = () => {
  var filePath = encodeURI(tempFile.value.tempFilePath)
  uni.openDocument({
    filePath: encodeURI(filePath),
    // fileType: filetype,
    showMenu: true,
  })
}
</script>
<style>
page {
  background-color: #fff;
}
</style>
