<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>
  </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 id = ref('')
const info = ref({})
onLoad((options) => {
  id.value = options.id
  http.get(`/train/books/${id.value}`).then((res) => {
    info.value = res
  })
})

const downloadFile = (url) => {
  // #ifdef H5
  uni.downloadFile({
    url: url, // 文件的URL
    success: function (res) {
      console.log('下载成功', res)
      // 在这里可以处理文件下载后的操作，比如保存到本地、读取文件内容等
    },
    fail: function (err) {
      console.log('下载失败', err)
      // 在这里可以处理文件下载失败的情况，比如重新下载、提示用户等
    },
  })
  // #endif
  // #ifdef APP-PLUS
  let dtask = plus.downloader.createDownload(
    url,
    {
      filename: 'file://storage/emulated/0/Download/',
    },
    (d, status) => {
      if (status == 200) {
        let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename)
        // saveFile(fileSaveUrl)
        uni.showToast({
          title: '下载成功',
          icon: 'none',
        })
      } else {
        //下载失败
        uni.showToast({
          title: '下载失败',
        })
        plus.downloader.clear() //清除下载任务
      }
      console.log(d)
    }
  )
  dtask.start()
  // #endif
}

const saveFile = (filePath) => {
  uni.saveFile({
    tempFilePath: filePath,
    success: (res) => {
      uni.showToast({
        title: '文件保存成功',
      })
      console.log('文件保存成功，路径为：' + res.savedFilePath)
    },
    fail: (err) => {
      console.log('文件保存失败：' + err)
    },
  })
}
</script>
<style>
page {
  background-color: #fff;
}
</style>
