<template>
    <div class="file-view">
        <!-- 文件预览 -->
        <div v-if="!isImage" class="flex items-center">
            <doc-icon type="file-filled" style="color: #999; font-size: 20px"/>
            <a class="ml-2" @click.prevent="onDown">下载</a>
        </div>
        <van-image :src="file.url" v-else @click="viewImage">
            <template v-slot:loading>
                <van-loading type="spinner" size="20" />
            </template>
        </van-image>
    </div>
</template>

<script>
import { showDialog } from 'vant'
import { copyToClip } from '@/utils/common.js'

export default {
    props: {
        file: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['view-image'],
    computed: {
        isImage() {
            const array = ['JPG', 'PNG', 'JEPG', 'GIF']
            return array.includes(this.file.type) || array.includes(this.file.ext.toLocaleUpperCase())
        }
    },
    methods: {
        onDown() {
            console.log(this.file)
            let wx = window.sessionStorage.getItem('embed')
            if (wx == 'wx') {
                // 复制链接到浏览器下载
                if (copyToClip(this.file.url)) {
                    showDialog({
                        message: '链接复制成功，请在浏览器中打开下载'
                    }).then(() => {})
                } else {
                    console.warn('链接复制失败')
                }
            } else {
                window.open(this.file.url, '_blank')
            }
        },
        viewImage() {
            this.$emit('view-image', this.file)
        }
    }
}
</script>

<style lang="less" scoped>
.file-view {
    width: 100px;
}
</style>
