<template>
  <el-table v-loading="loading" :data="tableData" :stripe="true">
    <el-table-column label="附件名称" align="center" prop="title" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-link type="primary" download :href="scope.row.url" :underline="false" target="_blank">下载</el-link>
        <el-button v-if="showPreview" class="m-l-10px" link type="primary" @click="handlePreview(scope.row.url, row)">预览</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <Dialog title="附件详情" v-model="openPreview" width="1000" @close="openPreview = false">
    <div>
      <IFrame style="max-height: 80vh;" :src="fileUrl" />
    </div>
  </Dialog>
</template>

<script setup>
defineOptions({ name: 'PersonAttachment' })
import { PersonInfoApi } from '@/api/menduner/system/person'
import { Base64 } from 'js-base64'

const props = defineProps({
  showPreview: Boolean,
  userId: [String, Number]
})

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  userId: props.userId
})

const fileUrl = ref('')
const openPreview = ref(false)
const fileName = ref('')
const baseUrl = import.meta.env.VITE_PREVIEW_URL
const handlePreview = (url) => {
  if (!url) return message.warning('预览失败！')

  openPreview.value = true
  fileUrl.value = !url.includes('.pdf') ?  `${baseUrl}/onlinePreview?url=${encodeURIComponent(Base64.encode(url))}` : url
}

const getList = async () => {
  loading.value = true
  try {
    const data = await PersonInfoApi.getPersonAttachmentList(queryParams)
    tableData.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

watch(() => props.userId, (newVal) => {
  if (newVal) {
    queryParams.userId = newVal
    getList()
  }
}, { immediate: true }, { deep: true })
</script>
