<template>
    <el-dialog v-model="dialogVisible" title="附件" width="600">
        <vxe-table v-bind="defaultAttribute" ref="vxeRef" height="500px" :data="tableData">
            <vxe-column field="name" title="名称"></vxe-column>
            <vxe-column title="操作" width="150">
                <template #default="{ row }">
                    <el-button type="primary" link @click="view(row)">查看</el-button>
                    <el-button type="primary" link @click="download(row)">下载</el-button>
                </template>
            </vxe-column>
        </vxe-table>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { getFileNameAndFilePath, downloadFile } from '@/api/system-boot/file'

const dialogVisible = ref(false)
const tableData: any = ref([])
const open = (row: any) => {
    tableData.value = []
    row.split(',').map((v: any) => {
        tableData.value.push({ name: v.split('/supervision/')[1], url: v })
    })
    console.log('🚀 ~ row.split ~  tableData.value:', tableData.value)

    dialogVisible.value = true
    // console.log('🚀 ~ open ~ row:', row)
    // url.value = row
}
const view = (row: any) => {
    window.open(window.location.origin + '/#/previewFile?' + row.url)
}
const download = (row: any) => {
    let url = row.url

    let urls = url
    let name = url.match(/\/([^/]+)\.(\w+)$/)[1]
    downloadFile({ filePath: url }).then((res: any) => {
        let blob = new Blob([res], {
            type: urls.includes('.pdf')
                ? 'application/pdf'
                : urls.includes('.docx')
                ? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                : urls.includes('.xls')
                ? 'application/vnd.ms-excel'
                : urls.includes('.xlsx')
                ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                : urls.includes('.png')
                ? 'image/png'
                : urls.includes('.jpeg')
                ? 'image/jpeg'
                : urls.includes('.jpg')
                ? 'image/jpg'
                : ''
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = name
        document.body.appendChild(link)
        link.click()
        link.remove()
    })
}
defineExpose({ open })
</script>
<style lang="scss" scoped></style>
