<template>
    <view style="width: 100%;height: 100%;">
        <view class="upload-wrap">
            <view class="btn-click mgb-16 upload-btn" @click="handleUploadClick()" v-show="isUpload === false">
                <!-- <image :src="icons.upload" mode="aspectFill" class="upload-icon" /> -->
                <i class="el-icon-upload2"></i>
                <text class="upload-text">上传附件</text>
                <text class="upload-text1">{{ `只能上传不超过${this.limit}个文件` }}</text>
            </view>
            <view class="mgb-16 file-wrap" v-for="(item, index) in fileList" :key="index">
                <view class="btn-click file-line" @click="handlePreview(item)">
                    <!-- <view class="btn-click file-line" @click="handleUploadFile(item)"> -->
                    <view class="file-info">
                        <i :class="`el-icon-${icons[getFileType(item.name) || 'file']}`"></i>
                        <text class="file-name">{{ item.name || title[type] }}</text>
                    </view>

                    <i :class='`el-icon-${icons.close}`' v-if="isDelete === false"
                        @click.stop="handleDeleteFile(index)"></i>
                </view>
            </view>
            <view class="mgb-16 file-wrap" v-if="fileList.length === 0">
                <view class="file-line">
                    <text class="file-empty">暂无数据</text>
                </view>
            </view>
        </view>
        <xe-upload ref="XeUpload" :options="{ url: uploadUrl }" @callback="handleUploadCallback"></xe-upload>

        <u-action-sheet @close="uploadShow = false" cancelText="取消" :actions="uploadList"
            @select="handleChangeUploadType" :title="uploadTitle" :show="uploadShow"></u-action-sheet>
        <mumu-previewOffce :fileType="prviewFileType" :fileUrl='prviewFileUrl'
            v-model='showPreview'></mumu-previewOffce>
        <u-popup v-if="videoShow" @close="handleCloseVideo" mode="top" :overlay="true" :show="videoShow"
            :closeOnClickOverlay="true">
            <view v-if="videoShow" style="width: 100%;height: 100%;">
                <video v-if="videoShow" style="width: 100%;" :src="videoUrl" controls preload="auto" autoPlay={true} />
            </view>
        </u-popup>

    </view>
</template>

<script>
import MumuPreviewOffce from '@/uni_modules/mumu-previewOffce/components/mumu-previewOffce/mumu-previewOffce.vue'
import { mapState, mapMutations, mapActions } from 'vuex'
import OSSService from "@/api/sys/OSSService"

export default {
    components: {
        MumuPreviewOffce
    },
    computed: mapState({
        userInfo: (state) => state.user.userInfo,
    }),
    created() {
        this.ossService = new OSSService()
    },
    props: {
        //上传地址
        uploadUrl: {
            type: String,
            default: ''
        },
        // 文件列表
        fileList: {
            type: Array,
            default: () => []
        },
        // 最大上传个数
        limit: {
            type: Number,
            default: 9
        },
        // 是否可以删除
        isDelete: {
            type: Boolean,
            default: false
        },
        // 是否可以上传
        isUpload: {
            type: Boolean,
            default: false
        },
    },
    ossService: null,
    data() {
        return {
            uploadType: '',
            videoShow: false,
            videoUrl: '',
            prviewFileType: '',
            prviewFileUrl: '',
            showPreview: false,
            icons: {
                close: 'circle-close',
                image: 'picture-outline',
                video: 'video-camera',
                file: 'document',
                audio: 'bell',
                unknown: 'document'
            },
            uploadFile: '',
            uploadShow: false,
            uploadTitle: '附件上传',
            uploadList: [
                {
                    name: '视频上传',
                },
                {
                    name: '图片上传',
                },
                {
                    name: '文件上传',
                }
            ],
        }

    },
    methods: {
        handleCloseVideo() {
            this.videoUrl = ""
            this.videoShow = false
        },

        handleDeleteFile(index) {
            console.log();

            const deletedFile = this.fileList[index]; // 获取被删除的文件
            // this.fileList.splice(index, 1); // 删除文件
            this.$emit("onRemove", deletedFile, this.fileList, index); // 传递剩余文件列表和被删除的文件
        },
        // 预览
        handlePreview(row) {
            const fileType = this.getFileType(row.name);
            const flieArr = row.name.split('.');
            let suffix = flieArr[flieArr.length - 1];
            this.ossService.getTemporaryUrl("/" + row.url).then((data) => {
                if (fileType == "image") {
                    return uni.previewImage({
                        current: data,
                        urls: [data],
                    });
                }
                if (fileType == "video") {
                    this.videoUrl = data
                    this.videoShow = true
                    return
                }
                if (fileType == "file") {
                    this.prviewFileUrl = data
                    this.prviewFileType = suffix
                    this.showPreview = true
                    return
                }
                uni.showModal({
                    title: '提示',
                    content: data,
                    showCancel: false,
                });
            })


        },

        handleUploadClick() {
            if (this.fileList.length >= this.limit) {
                uni.showModal({
                    title: '提示',
                    content: `只能上传不超过${this.limit}个文件`,
                    showCancel: false,
                });
                return
            }
            this.uploadShow = true
            this.uploadType = 'type'
        },
        getFileType(fileName = '') {
            const flieArr = fileName.split('.');
            let suffix = flieArr[flieArr.length - 1];
            if (!suffix) return '';
            suffix = suffix.toLocaleLowerCase();
            const image = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'];
            if (image.includes(suffix)) return 'image';
            const video = ['mp4', 'm4v'];
            if (video.includes(suffix)) return 'video';
            const audio = ['mp3', 'm4a', 'wav', 'aac'];
            if (audio.includes(suffix)) return 'audio';
            const office = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'plain'];
            if (office.includes(suffix)) return 'file';
            return 'unknown';
        },
        handleChangeUploadType(index) {
            if (index.name == "视频上传") {
                this.$refs.XeUpload.upload('video', {});
            }
            if (index.name == "图片上传") {
                this.$refs.XeUpload.upload('image', {});
            }
            if (index.name == "文件上传") {
                this.$refs.XeUpload.upload('file', {});
            }
        },
        handleUploadCallback(e) {
            this.uploadShow = false
            const file = e.data[0]
            this.fileList.push({
                name: file.name,
                size: file.size,
                url: file.response.url,
                lsUrl: file.response.lsUrl,
                createBy: this.userInfo,
                by: this.userInfo.id,
                createTime: this.formatDateNew(new Date())
            })
            console.log(this.fileList);

            this.$emit("onSuccess", file, this.fileList)
        },
        formatDateNew(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

    }
}
</script>

<style scoped lang="scss">
.btn-click {
    transition: all 0.3s;
    opacity: 1;
}

.btn-click:active {
    opacity: 0.5;
}

.mgb-16 {
    margin-bottom: 16rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.upload-wrap {
    width: 100%;
    border-radius: 16rpx;
    background: white;

    .upload-btn {
        width: 100%;
        height: 176rpx;
        border: 2rpx dashed;
        color: #409EFF;
        border-color: #b3d8ff;
        background: #ecf5ff;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;

        .upload-icon {
            width: 48rpx;
            height: 48rpx;
            margin-bottom: 8rpx;
        }

        .upload-text {
            font-size: 26rpx;
            line-height: 40rpx;
        }

        .upload-text1 {
            font-size: 20rpx;
            line-height: 40rpx;
        }
    }

    .file-wrap {
        .file-line {
            width: 100%;
            border-color: #b3d8ff;
            background: #ecf5ff;
            border-radius: 8rpx;
            padding: 16rpx;
            font-size: 26rpx;
            color: #409EFF;

            line-height: 40rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .file-info {
                width: 90%;
                display: flex;
                align-items: center;

                .file-name {
                    max-width: 80%;
                    padding-left: 16rpx;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            .file-icon {
                width: 40rpx;
                height: 40rpx;
                flex-shrink: 0;
            }

            .file-empty {
                color: #999999;
            }
        }
    }
}
</style>
