<template>
    <div>
        <!--action="/api/abk/web/v1/resource/file" -->
        <el-upload
            :action="actionUrl"
            :auto-upload="autoUpload"
            style="width: 100%"
            :on-success="(response, file) => successUpload(response, file)"
            :on-error="errorUpload"
            :accept="acceptTypeList.join(',')"
            :before-upload="beforeUpload"
            :multiple="multiple"
            :limit="maxLimit"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :disabled="disabledFlag"
            :on-remove="(file, fileList) => removeFile(file, fileList)"
            :on-preview="(file) => preview(file)"
            :on-progress="(event, file, fileList) => onProgressFn(event, file, fileList)"
            list-type="picture-card">
            <!-- 上传的按钮 或者 icon 通过具名插槽的方式 -->
            <slot name="uploadBtn"></slot>
        </el-upload>
        <el-progress v-if="showProcessFlag && processFlag" :percentage="loadProcess"></el-progress>
    </div>
</template>

<script lang="ts" setup>
    import { ref, nextTick } from 'vue'
    import { ElMessage } from 'element-plus'
    import { Base64 } from 'js-base64'
    const props = defineProps({
        actionUrl: {
            //上传的地址
            type: String,
            default: ''
        },
        autoUpload: {
            //是否开启自动上传
            type: Boolean,
            default: false
        },
        acceptTypeList: {
            //接受的文件类型
            type: Array,
            default: () => {
                return ['.jpg', '.jpeg', '.png']
                //  ['doc', 'docx', 'xlsx', 'xls', 'txt', 'pdf','jpg','jpeg','png','zip,'rar']
            }
        },
        multiple: {
            //是否开启多图上传
            type: Boolean,
            default: false
        },
        maxLimit: {
            // 最大上传个数限制
            type: Number || String,
            default: 1
        },
        maxSize: {
            // 文件上传的最大体积 M
            type: Number || String,
            default: 4
        },
        disabledFlag: {
            //是否禁用
            type: Boolean,
            default: false
        },
        fileList: {
            //文件列表
            type: Array,
            default: () => {
                return []
            }
        },
        listType: {
            type: String, //'text' | 'picture' | 'picture-card'
            default: 'picture'
        },
        extraData: {}, //上传时的额外参数 如 name等
        /* 
    {
        name:'12321'
    }
    */
        dragFlag: {
            type: Boolean,
            default: true //是否启用拖拽上传 此处默认启用  element 官方默认是 不启用的
        },
        downLoadTypeList: {
            //需要下载的文件类型
            type: Array,
            default: () => {
                return ['doc', 'docx', 'xlsx', 'xls', 'txt']
            }
        },
        preveiwTypeList: {
            //需要预览的文件类型
            type: Array,
            default: () => {
                return ['pdf', 'jpg', 'jpeg', 'png']
            }
        },
        officePreviewFlag: {
            //是否启用office在线预览
            type: Boolean,
            default: false
        },
        showProcessFlag: {
            //是否显示进度条
            type: Boolean,
            default: false
        }
    })
    // office预览
    // https://view.officeapps.live.com/op/view.aspx?src=
    // https://view.officeapps.live.com/op/view.aspx?src=文档地址
    //

    const officeOnlineAddress = 'https://view.officeapps.live.com/op/view.aspx?src='
    const officeType = ['doc', 'docx', 'xlsx', 'xls']
    let processFlag = ref(false) //是否显示进度条
    let loadProcess = ref(0) //进度条的刻度值

    // 上传图片 成功
    const successUpload = (response: any, file: any) => {
        console.log('successUpload', response, file)
        if (response.rt.status === 200) {
            props.fileList.push({
                url: response.data,
                name: file.name
            })
        } else {
            ElMessage({
                type: 'warning',
                message: response.data
            })
        }
    }
    const errorUpload = (res: any) => {
        ElMessage({
            type: 'warning',
            message: '上传失败请重试！'
        })
    }
    const beforeUpload = (file) => {
        const { name = '', size } = file
        if (size > props.maxSize * 1024 * 1000) {
            ElMessage({
                type: 'warning',
                message: `文件最大仅支持${props.maxSize}M`
            })
            return false
        }

        if (!props.acceptTypeList.includes(name.split('.').pop()) + '.') {
            ElMessage({
                type: 'warning',
                message: `文件格式仅支持${props.acceptTypeList.join(',')}M`
            })
            return false
        }
    }
    const handleExceed = (files, fileList) => {
        ElMessage({
            type: 'warning',
            message: `当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
                files.length + fileList.length
            } 个文件`
        })
    }
    // 移除文件
    const removeFile = (file, data) => {
        console.log(file, data)
        props.fileList = data
    }
    // 预览
    const preview = (data) => {
        const { url, response = {} } = data || {}
        let name = data.name
        const downLoadTypeList = props.downLoadTypeList
        const preveiwTypeList = props.preveiwTypeList
        if (!name) {
            name = ''
        }
        const suffixFileType = name.split('.').pop()
        if (downLoadTypeList.includes(suffixFileType)) {
            //预览 'doc', 'docx', 'xlsx', 'xls', 'txt' 文件
            name = name.replace(/&/g, '') // & 不兼容
            const target = encodeURIComponent(
                Base64.encode(
                    `${location.origin}/api/abk/web/v1/resource/file?fileId=${
                        url || response.data
                    }&fullfilename=${name}&sid=4AC67ADB4E264AB0A8B899A671072875`
                )
            )
            if (props.officePreviewFlag && officeType.includes(suffixFileType)) {
                // office预览的
                const preveiewURL = officeOnlineAddress + target
                window.open(preveiewURL)
            } else {
                // 非office预览
                window.open(`https://test/preview/onlinePreview?url=${target}`, '_blank')
            }
        } else if (preveiwTypeList.includes(suffixFileType)) {
            //新窗口打开 预览图片文件
            window.open('/api/abk/web/v1/resource/file?fileId=' + (url || response.data), '_blank')
        }
    }

    const onProgressFn = (event, file, fileList) => {
        processFlag.value = true
        loadProcess.value = event.percent.toFixed(2)
        if (loadProcess.value >= 100) {
            loadProcess.value = 100
            nextTick(() => {
                processFlag.value = false
            })
        }
    }
</script>

<style lang="scss" scoped></style>
