<template>
  <view>
    <view class="attachment_body" v-if="props?.list?.length">
      <view class="title"> 查看附件 </view>
      <view
        v-for="(i, index) in props?.list"
        :key="`item_${index}`"
        class="attachment_item"
        @click="handleShowFile(i)"
      >
        <view class="name">
          {{ i?.name || '-' }}
        </view>
        <view class="btn">查看</view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'

const props = defineProps(['list'])

const handleShowFile = (e: { url?: string; name?: string }) => {
  console.log(e, 'e')
  if (!e?.url) {
    return uni.showToast({ title: '文件不存在', icon: 'none' })
  }
  let showimg = false
  let parts = e?.url.split('/')
  let fileName = parts[parts.length - 1]
  if (fileName.endsWith('.jpg') || fileName.endsWith('.png') || fileName.endsWith('.jpeg')) {
    showimg = true
  }
  console.log(fileName, 'fileName')
  getApiLoading(Apis.Auth.TemporaryUrl, {
    filename: fileName,
    alc: 'private'
  }).then(res => {
    uni.showLoading({
      title: '正在打开中..'
    })
    console.log(res, 'res图片')
    if (showimg) {
      uni.downloadFile({
        url: res?.data?.url,
        success: function (e) {
          uni.hideLoading()
          console.log('文件是jpg、png或jpeg格式')
          uni.previewImage({
            current: 0,
            urls: [e?.tempFilePath || '']
          })
          console.log(e, 'e')
        }
      })
      return
    }

    uni.downloadFile({
      url: res?.data?.url,
      filePath: `${uni.env.USER_DATA_PATH}/${e?.name}`,
      success: function (e: { filePath?: string }) {
        const filePath = e.filePath
        console.log(e, 'filePath')
        uni.hideLoading()
        uni.openDocument({
          filePath: filePath as string,
          showMenu: true
        })
      },
      fail() {
        uni.hideLoading()
        uni.showToast({
          title: '打开文件失败！',
          duration: 2000,
          icon: 'none'
        })
      }
    })
    console.log(res, 'res')
  })
}
</script>

<style lang="scss" scoped>
.attachment_body {
  background-color: #f5f8ff;
  border-radius: 15rpx;
  margin: 30rpx;
  .title {
    font-size: 32rpx;
    font-weight: 600;
    padding: 30rpx;
  }
  .attachment_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx 30rpx 30rpx;
    color: #666;
    font-size: 28rpx;
    .name {
      flex: 1;
    }
    .btn {
      color: #3b65a9;
    }
  }
}
</style>
