<template>
    <div class="upload-container">
        <el-upload class="upload-demo" drag action="#" multiple :show-file-list="true" :before-upload="beforeUpload"
            :on-change="handleFileChange" :on-remove="handleRemove" :on-exceed="handleExceed" :file-list="files"
            :accept="accept" :limit="limitUploadNum" :auto-upload="autoUpload">
            <div class="upload-content">
                <!-- 当只有一张图片时显示缩略图 -->
                <div v-if="showImagePreview" class="image-preview">
                    <img :src="previewImageUrl" :alt="previewImageName" class="preview-thumbnail" />
                    <div class="preview-overlay">
                        <div class="preview-text">
                            <div class="main-text">点击更换图片</div>
                            <div class="tip-text">或拖拽新图片到此处</div>
                        </div>
                    </div>
                </div>

                <!-- 当只有一个文档文件时显示文件图标 -->
                <div v-else-if="showFilePreview" class="file-preview">
                    <div class="file-icon-container">
                        <i :class="getFileIconClass()" class="file-icon"></i>
                        <div class="file-name">{{ previewFileName }}</div>
                    </div>
                    <div class="preview-overlay">
                        <div class="preview-text">
                            <div class="main-text">点击更换文件</div>
                            <div class="tip-text">或拖拽新文件到此处</div>
                        </div>
                    </div>
                </div>

                <!-- 默认上传区域 -->
                <div v-else class="upload-text">
                    <div class="main-text"> + 点击或将文件拖拽到这里上传</div>
                    <div class="tip-text">
                        <div>文件大小上限 {{ maxFileTips }}，</div>
                        <div>支持文件类型：{{ uploadType }}</div>
                    </div>
                </div>
            </div>
        </el-upload>
    </div>
</template>

<script>
import {uploadSmallFileByOcr} from '@/api/common/uploadFile.js'
export default {
    name: 'UploadFile',
    props: {
        fileList: {
            type: Array,
            default: () => []
        },
        maxFileTips: {
            type: String,
            default: '20MB'
        },
        uploadType: {
            type: String,
            default: 'png、jpg、jpeg'
        },
        limitUploadNum: {
            type: Number,
            default: 1
        },
        fileUploadRule: {
            type: Object,
            default: () => ({})
        },
        autoUpload: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            files: this.fileList,
            previewImageUrl: '',
            previewImageName: '',
            previewFileName: '',
            previewFileType: ''
        }
    },
    methods: {
        beforeUpload(file) {
            // 验证文件类型
            const fileExtension = file.name.split('.').pop().toLowerCase();
            const isAllowedType = this.allowedTypes.includes(fileExtension);

            // 验证MIME类型（额外验证）
            const isAllowedMimeType = this.mimeTypes.includes(file.type);

            // 验证文件大小
            const isLtMaxSize = file.size / 1024 / 1024 < this.maxSizeMB;

            if (!isAllowedType || !isAllowedMimeType) {
                this.$message.error(`只能上传 ${this.uploadType} 格式的文件!`);
                return false;
            }

            if (!isLtMaxSize) {
                this.$message.error(`文件大小不能超过 ${this.maxFileTips}!`);
                return false;
            }

            return false;
        },
        // 文件状态改变
        handleFileChange(file, fileList) {
            this.files = fileList;

            // 生成预览
            if (file.raw && fileList.length === 1) {
                if (this.isImageFile(file.raw)) {
                    // 图片预览
                    this.generateImagePreview(file.raw);
                } else if (this.isDocumentFile(file.raw)) {
                    // 文档预览
                    this.generateDocumentPreview(file.raw);
                }
            } else {
                // 如果不是单个文件，清除预览
                this.clearPreview();
            }
            console.log('文件列表更新:', this.files.length, '个文件');
            // this.$emit('file-change', this.files);

            // 如果启用自动上传且文件验证通过，触发上传
            if (this.autoUpload && file.status === 'ready') {
                
                if(Object.keys(this.fileUploadRule).length !== 0){
                    // 文件需要ocr识别
                    this.uploadFile(file,'识别中');
                }else{
                    // 文件不需要ocr识别
                    this.uploadFile(file,'上传中');
                }
                
            }
        },

        // 上传文件
        uploadFile(file,text){
            console.log(file);
            this.$bus.$emit('startUpload', text);
            const formData = new FormData();
            formData.append('file', file.raw);
            formData.append('params', JSON.stringify(this.fileUploadRule));
            uploadSmallFileByOcr(formData).then(res => {
                console.log(res);
                this.$message.success(res.msg);
                this.$bus.$emit('endUpload');
            }).catch(err => {
                this.$message.error(err.msg);
                this.$bus.$emit('endUpload');
            })
        },
        // 处理文件超出限制
        handleExceed(files, fileList) {
            // 当文件数量超出限制时，用新文件替换旧文件
            if (files.length > 0) {
                // 清空原有文件列表
                this.files = [];

                // 手动触发新文件的上传流程
                const newFile = files[0];
                this.beforeUpload(newFile); // 先进行验证

                // 创建新的文件对象
                const newFileObj = {
                    name: newFile.name,
                    size: newFile.size,
                    type: newFile.type,
                    raw: newFile,
                    uid: Date.now() // 生成新的uid
                };

                // 更新文件列表
                this.files = [newFileObj];

                // 生成预览
                if (this.isImageFile(newFile)) {
                    this.generateImagePreview(newFile);
                } else if (this.isDocumentFile(newFile)) {
                    this.generateDocumentPreview(newFile);
                }

                this.$emit('file-change', this.files);
                // this.$message.success('文件已替换');
            }
        },
        // 移除文件
        handleRemove(file, fileList) {
            this.files = fileList;

            // 根据剩余文件重新生成预览
            if (fileList.length === 0) {
                this.clearPreview();
            } else if (fileList.length === 1 && fileList[0] && fileList[0].raw) {
                if (this.isImageFile(fileList[0].raw)) {
                    this.generateImagePreview(fileList[0].raw);
                } else if (this.isDocumentFile(fileList[0].raw)) {
                    this.generateDocumentPreview(fileList[0].raw);
                }
            } else {
                this.clearPreview();
            }

            this.$emit('file-change', fileList);
        },
        // 判断是否为图片文件
        isImageFile(file) {
            return file && file.type && file.type.startsWith('image/');
        },
        // 判断是否为文档文件
        isDocumentFile(file) {
            if (!file || !file.name) return false;
            const fileExtension = file.name.split('.').pop().toLowerCase();
            return ['pdf', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExtension);
        },
        // 生成图片预览
        generateImagePreview(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.previewImageUrl = e.target.result;
                this.previewImageName = file.name;
                // 清除文档预览
                this.previewFileName = '';
                this.previewFileType = '';
            };
            reader.readAsDataURL(file);
        },
        // 生成文档预览
        generateDocumentPreview(file) {
            const fileExtension = file.name.split('.').pop().toLowerCase();
            this.previewFileName = file.name;
            this.previewFileType = fileExtension;
            // 清除图片预览
            this.previewImageUrl = '';
            this.previewImageName = '';
        },
        // 清除预览
        clearPreview() {
            this.previewImageUrl = '';
            this.previewImageName = '';
            this.previewFileName = '';
            this.previewFileType = '';
        },
        // 获取文件图标类型
        getFileIconClass() {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'xls': 'el-icon-document',
                'xlsx': 'el-icon-document'
            };
            return iconMap[this.previewFileType] || 'el-icon-document';
        },
        // 清空所有文件
        clearFiles() {
            this.files = [];
            this.clearPreview();
            this.$emit('file-change', []);
        }
    },
    computed: {
        // 是否显示图片预览
        showImagePreview() {
            return this.previewImageUrl &&
                this.files.length === 1 &&
                this.files[0] &&
                this.files[0].raw &&
                this.isImageFile(this.files[0].raw);
        },
        // 是否显示文件预览
        showFilePreview() {
            return this.previewFileName &&
                this.previewFileType &&
                this.files.length === 1 &&
                this.files[0] &&
                this.files[0].raw &&
                this.isDocumentFile(this.files[0].raw);
        },
        accept() {
            return this.uploadType.split('、').map(type => `.${type}`).join(',');
        },
        // 获取支持的文件类型数组
        allowedTypes() {
            return this.uploadType.split('、');
        },
        // 获取文件大小限制（转换为MB数字）
        maxSizeMB() {
            const sizeStr = this.maxFileTips.toLowerCase();
            if (sizeStr.includes('mb')) {
                return parseFloat(sizeStr);
            } else if (sizeStr.includes('kb')) {
                return parseFloat(sizeStr) / 1024;
            } else if (sizeStr.includes('gb')) {
                return parseFloat(sizeStr) * 1024;
            }
            return 20;
        },
        // 获取MIME类型映射
        mimeTypes() {
            const typeMap = {
                'png': 'image/png',
                'jpg': 'image/jpeg',
                'jpeg': 'image/jpeg',
                'gif': 'image/gif',
                'bmp': 'image/bmp',
                'webp': 'image/webp',
                'svg': 'image/svg+xml',
                'pdf': 'application/pdf',
                'doc': 'application/msword',
                'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'xls': 'application/vnd.ms-excel',
                'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            };
            return this.allowedTypes.map(type => typeMap[type] || '');
        }
    },
    watch: {
        fileList: {
            handler(newVal) {
                this.files = newVal;
                // 如果外部传入文件列表，也尝试生成预览
                if (newVal.length === 1 && newVal[0] && newVal[0].raw) {
                    if (this.isImageFile(newVal[0].raw)) {
                        this.generateImagePreview(newVal[0].raw);
                    } else if (this.isDocumentFile(newVal[0].raw)) {
                        this.generateDocumentPreview(newVal[0].raw);
                    }
                } else {
                    this.clearPreview();
                }
            },
            deep: true
        },
    },
}
</script>

<style scoped lang="scss">
.upload-container {
    width: 100%;

    .upload-demo {
        width: 100%;

        ::v-deep .el-upload {
            width: 100%;

            .el-upload-dragger {
                width: 100%;
                height: 240px;
                border: 2px dashed #DCDFE6;
                border-radius: 8px;
                background-color: #FAFAFA;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;

                &:hover {
                    border-color: #409EFF;
                    background-color: #F5F7FA;
                }
            }
        }
    }

    .upload-content {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 5px;

        // 图片预览样式
        .image-preview {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 6px;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;

            .preview-thumbnail {
                max-width: 100%;
                max-height: 100%;
                width: auto;
                height: auto;
                object-fit: contain;
                display: block;
            }

            .preview-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.6);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s ease;
                pointer-events: none;

                .preview-text {
                    text-align: center;
                    color: white;
                    pointer-events: none;

                    .main-text {
                        font-size: 16px;
                        margin-bottom: 8px;
                        font-weight: 500;
                    }

                    .tip-text {
                        font-size: 12px;
                        opacity: 0.9;
                    }
                }
            }

            &:hover .preview-overlay {
                opacity: 1;
            }
        }

        // 文件预览样式
        .file-preview {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 6px;
            overflow: hidden;

            .file-icon-container {
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                background: #f9fafc;

                .file-icon {
                    font-size: 64px;
                    color: #1F72EA;
                    margin-bottom: 16px;
                }

                .file-name {
                    font-size: 14px;
                    color: #606266;
                    text-align: center;
                    padding: 0 20px;
                    word-break: break-all;
                    max-width: 100%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    line-clamp: 2;
                    -webkit-box-orient: vertical;
                }
            }

            .preview-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.6);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s ease;
                pointer-events: none;

                .preview-text {
                    text-align: center;
                    color: white;
                    pointer-events: none;

                    .main-text {
                        font-size: 16px;
                        margin-bottom: 8px;
                        font-weight: 500;
                    }

                    .tip-text {
                        font-size: 12px;
                        opacity: 0.9;
                    }
                }
            }

            &:hover .preview-overlay {
                opacity: 1;
            }
        }

        // 默认上传区域样式
        .upload-text {
            text-align: center;

            .main-text {
                font-size: 18px;
                color: #1F72EA;
                margin-bottom: 12px;
                font-weight: 500;
            }

            .tip-text {
                font-size: 14px;
                color: #909399;
                line-height: 1.5;

                div {
                    margin-bottom: 2px;
                }
            }
        }
    }
}
</style>