<template>
    <section class="upload-component">
        <VueDraggable ref="VueDraggableRef" v-model="imgUrl" class="flex" v-if="canSort" @end="onDragEnd">
            <template v-for="(item, idx) in imgUrl" :key="item">
                <div style="margin-bottom: 10px">
                    <div class="uploadWrapBorder">
                        <div class="has_uploaded_img">
                            <video :src="item" v-if="item.includes('mp4')"></video>
                            <img :src="item" v-else />

                            <div class="mask"></div>
                            <div class="operation">
                                <el-icon @click="onPreviewImg(idx)">
                                    <ZoomIn />
                                </el-icon>
                                <el-icon @click="onDeleteImg(idx)" v-if="!canUpload">
                                    <Delete />
                                </el-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </VueDraggable>
        <template v-for="(item, idx) in imgUrl" v-else>
            <div class="uploadWrapBorder">
                <div class="has_uploaded_img">
                    <!-- 判断一下item是不是video -->
                    <video autoplay="true" :src="item" v-if="item.includes('mp4')"></video>
                    <img :src="item" v-else />

                    <div class="mask"></div>
                    <div class="operation">
                        <el-icon @click="onPreviewImg(idx)">
                            <ZoomIn />
                        </el-icon>
                        <el-icon @click="onDeleteImg(idx)" v-if="!canUpload">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
            </div>
        </template>
        <div
            v-if="imgUrl.length < imgCount && !canUpload"
            v-loading="imgUploading"
            class="uploadWrapBorder"
            element-loading-background="rgba(0, 0, 0, 0.5)"
        >
            <div class="no_upload" @click="onUploadClick">
                <el-icon>
                    <Plus />
                </el-icon>
            </div>
        </div>
        <input ref="InputFileRef" :accept="acceptType" :maxFileSize="maxFileSize" type="file" @change="onUploadInputChange($event)" />
        <template v-if="acceptType == 'image/*'">
            <el-image-viewer v-if="showImageViewer" :url-list="imgViewUrl" @close="imgPreviewClose" :initial-index="showIndex" />
        </template>
        <template v-else>
            <el-dialog v-model="dialogVisible" title="" width="50%">
                <div>
                    <video :src="imgViewUrl[0]" autoplay controls="controls" style="height: 800px; width: 100%"></video>
                </div>
                <!-- <el-carousel indicator-position="none" motion-blur height="800px" width="100%">
                    <el-carousel-item v-for="(item, index) in imgViewUrl.length" :key="item" width="100%">
                        <video controls="controls" autoplay :style="{ height: '780px', width: '100%', objectFit: 'contain' }">
                            <source :src="imgViewUrl[index]" type="video/mp4" />
                        </video>
                    </el-carousel-item>
                </el-carousel> -->
            </el-dialog>
        </template>
    </section>
</template>
<script>
import { computed, defineComponent, nextTick, reactive, ref, toRefs, watch } from 'vue';
import { VueDraggable } from 'vue-draggable-plus';
import { upload } from '~/api/common/index.js';

export default defineComponent({
    components: { VueDraggable },
    props: {
        avatar: {
            type: Array,
            default: [],
            required: true,
        },
        limit: {
            type: Number,
            default: 1,
            reqiured: false,
        },
        isDetail: {
            type: Boolean,
            default: false,
            required: false,
        },
        sortAble: {
            type: Boolean,
            default: false,
            required: false,
        },
        accept: {
            type: String,
            default: 'image/*',
            required: false,
        },
        maxFileSize: {
            // 新增最大文件大小属性
            type: Number,
            default: 10 * 1024 * 1024, // 默认值为10MB
            required: false,
        },
    },
    setup(props, ctx) {
        const dialogVisible = ref(false);
        const InputFileRef = ref(null);
        const imgUrl = ref(props.avatar);
        const imgUploading = ref(false);

        const showImageViewer = ref(false);
        const imgViewUrl = ref([]);
        const showIndex = ref(0);
        const canSort = computed(() => props.sortAble);
        const acceptType = computed(() => {
            return props.accept;
        });

        const imgCount = computed(() => {
            return props.limit;
        });

        const canUpload = computed(() => {
            return props.isDetail;
        });

        const maxFileSizeType = computed(() => props.maxFileSize); // 新增计算属性

        const VueDraggableRef = ref(null);
        // const onDragEnd = () => {
        //     VueDraggableRef.value.onDragEnd();
        // };

        const ComponentInteraction = reactive({
            onDragEnd: () => {
                ctx.emit('update:avatar', imgUrl.value);
            },
            onUploadClick: () => {
                if (InputFileRef.value) {
                    InputFileRef.value.click();
                }
            },
            onUploadInputChange: (e) => {
                const { target } = e;
                const val = target.value;
                if (val !== '') {
                    const file = target.files[0];
                    if (file && file.size <= maxFileSizeType.value) {
                        // 检查文件大小
                        imgUploading.value = true;
                        const formData = new FormData();
                        formData.append('file', file);
                        upload(formData)
                            .then((ret) => {
                                imgUrl.value.push(ret.data.src);
                                target.value = '';
                                ctx.emit('update:avatar', imgUrl.value);
                                imgUploading.value = false;
                            })
                            .catch((err) => {
                                // imgUploading.value = false;
                            });
                    } else {
                        alert(`文件过大，请选择不超过${(maxFileSizeType.value / 1024 / 1024).toFixed(2)}MB的文件`);
                        imgUploading.value = false;
                    }
                }
            },
            onDeleteImg: (idx) => {
                imgUrl.value.splice(idx, 1);
                ctx.emit('update:avatar', imgUrl.value);
            },
            onPreviewImg: (idx) => {
                showIndex.value = idx;
                imgViewUrl.value = imgUrl.value;
                showImageViewer.value = true;
                if (acceptType.value == 'video/*') {
                    dialogVisible.value = true;
                }
            },
            imgPreviewClose: () => {
                showImageViewer.value = false;
            },
        });

        // onMounted(() => {
        //     imgUrl.value = props.avatar;
        // });

        watch(
            () => props.avatar,
            (nVal) => {
                imgUrl.value = nVal;
            },
            {
                immediate: true,
            },
        );

        return {
            InputFileRef,
            imgUrl,
            imgUploading,
            imgCount,
            ...toRefs(ComponentInteraction),
            showImageViewer,
            imgViewUrl,
            dialogVisible,
            showIndex,
            canUpload,
            canSort,
            acceptType,
            VueDraggableRef,
        };
    },
});
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
    height: 800px;
}
section.upload-component {
    display: flex;
    width: 94%;
    .flex {
        flex-wrap: wrap;
    }
    div.uploadWrapBorder {
        margin-right: 10px;
        width: 120px;
        height: 120px;
        background: #ffffff;
        border-radius: 5px;
        border: 1px solid #dcdfe6;
        text-align: center;
        line-height: 80px;
        cursor: pointer;
        border-radius: 2px;
        position: relative;
        overflow: hidden;

        div.no_upload {
            @apply flex items-center justify-center;
            position: absolute;
            width: 100%;
            height: 100%;

            i.iconfont {
                font-size: var(--el-strong-font-size);
                font-weight: bold;
            }
        }

        div.no_upload:hover {
            i.iconfont {
                color: var(--el-color-primary);
            }
        }

        div.has_uploaded_img {
            position: relative;
            width: 100%;
            height: 100%;
            overflow: hidden;
            > img {
                position: absolute;
                width: 100%;
                left: 0px;
                top: 50%;
                transform: translateY(-50%);
            }

            div.mask {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background: #000;
                opacity: 0.6;
                z-index: 1;
                display: none;
            }

            div.operation {
                @apply w-full h-full items-center justify-center;
                z-index: 10;
                display: none;
                position: absolute;
                left: 0px;
                top: 0px;

                i {
                    margin-right: 10px;
                    font-size: 20px;
                    color: #fff;
                    font-weight: bold;
                }

                i:last-child {
                    margin-right: 0px;
                }
            }
        }

        div.has_uploaded_img:hover {
            div.mask,
            div.operation {
                display: flex;
            }
        }
    }

    input {
        display: none;
    }
}
</style>
