<template>
    <div class="upload" v-if="type == 'image'">
        <template v-if="listType == 'picture'">
            <div class="up-list">
                <div v-for="(item, index) in imglist" :key="item" class="up-after"
                    :style="{ width: width, height: height }" v-loading="index == imglist.length - 1 && loading">
                    <img :src="imglist[index]" />
                    <div class="preview-delete">
                        <el-icon @click="dialogImg(item)">
                            <ZoomIn />
                        </el-icon>
                        <el-icon @click="deleteImgList(index)">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
                <div class="up-front" :style="{ width: width, height: height }">
                    <input ref="uploadFileImgs" type="file" @change="getFile" multiple :accept="accept" />
                    <slot>
                        <div class="up-tips">
                            <div>
                                <el-icon class="plus-icon">
                                    <Plus></Plus>
                                </el-icon>
                                
                                <p>
                                    上传图片
                                </p>
                                <span>或将文件拖到此处</span>
                            </div>
                        </div>
                    </slot>
                    <slot name="image"></slot>

                </div>
            </div>
        </template>
        <template v-else>
            <div class="up-front" v-if="!modelValue" :style="{ width: width, height: height }">
                <input ref="uploadFileImg" type="file" @change="getFile" multiple :accept="accept" />
                <slot>
                    <div class="up-tips">
                        <div>
                            <el-icon class="plus-icon">
                                <Plus></Plus>
                            </el-icon>
                            <div>
                                上传图片
                            </div>

                            <!-- <span>{{$t('common.or_drag_the_file_here')}}</span> -->
                        </div>
                    </div>
                </slot>
                <slot name="image"></slot>

            </div>
            <div v-if="modelValue" class="up-after" :style="{ width: width, height: height }" v-loading="loading">
                <img :src="previewImageUrl" />
                <div class="preview-delete">
                    <el-icon @click="dialogImg(previewImageUrl)">
                        <ZoomIn />
                    </el-icon>
                    <el-icon @click="deleteImg">
                        <Delete />
                    </el-icon>
                </div>
            </div>
        </template>
    </div>
    <div class="upload-button" v-if="type == 'button'">
        <el-button class="upload-el-button" type="primary" icon="Upload">
            <input ref="uploadFileFalod" type="file" @change="getFile" :accept="accept" />
            点击上传
        </el-button>
        <!-- <div class="file-name">{{ fileNmae }}</div> -->
    </div>
    <el-dialog v-model="dialogVisible" append-to-body width="60%" align-center>
        <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
</template>
<script setup>
import { ref, computed, nextTick } from 'vue'
import { uploadFile } from '@/api/upload'
import pinia from "@/store/modules/store"
import { storeToRefs } from 'pinia'
import { ElNotification } from 'element-plus'
const store = storeToRefs(pinia())
const iconSuffix = store.iconSuffix
const props = defineProps({
    type: {
        type: String,
        default: 'image'
    },
    width: {
        type: String,
        default: '120px'
    },
    height: {
        type: String,
        default: '120px'
    },
    action: {
        type: String,
        default: ''
    },

    modelValue: {
        type: String,
        default: ''
    },
    listType: {
        type: String,
        default: ''
    },
    accept: {
        type: String,
        default: ''
    }

})
const dialogImageUrl = ref('')
const imglist = computed(() => {
    if (props.modelValue) {
        return props.modelValue.split(',')
    } else {
        return []
    }
})
const previewImageUrl = computed(() => {
    return props.modelValue
})
const loading = ref(false)
// 'success'长传成功, 'change'选择文件, 'error'上传失败, 'progress'上传中, 'deleteFile' 删除
const emits = defineEmits(["update:modelValue", 'success', 'change', 'error', 'progress', 'deleteFile'])
const fileNmae = ref('')
const uploadFileImg = ref()
const uploadFileFalod = ref()
const uploadFileImgs = ref()
// const imageUrl = ref('')
const dialogVisible = ref(false)
const clearFile = (type) => {
    if (type == 0) {
        return
        // uploadFileOne.value.value = ''
    } else {
        // uploadFile.value.value = ''
    }
}
const getFile = async (e) => {
    if (e.target === null) {
        loading.value = false
        return
    }
    loading.value = true
    const fileMaxSize = 1024 * 1024 * 10
    const file = e.target.files[0]
    const size = file.size
    fileNmae.value = file.name
    if (size > fileMaxSize) {
        ElNotification({
            message: '最大文件不能超过10M',
            type: 'error',
            duration: 2000,
        })
        loading.value = false
        return
    }
    emits('change')
    let formData = new FormData()
    formData.append('file', file)
    const imageUrl = URL.createObjectURL(file)
    if (props.type == 'image') {
        if (props.listType != 'picture') {
            // 单个图片
            emits("update:modelValue", imageUrl)
            try {
                const res = await uploadFile(formData, props.action)
                emits("update:modelValue", res);
                emits('success', res)
                loading.value = false
                clearFile(0)
            } catch {
                emits('error')
                loading.value = false
                emits("update:modelValue", '');
                clearFile(0)
            }
        } else {
            // 多个图片
            imglist.value.push(imageUrl)
            emits("update:modelValue", imglist.value.join(','))
            try {
                const res = await uploadFile(formData, props.action)
                imglist.value[imglist.value.length - 1] = res.data.url
                emits("update:modelValue", imglist.value.join(','))
                emits('success', res)
                loading.value = false
                clearFile(1)
            } catch {
                imglist.value.splice(imglist.value.length - 1, 1)
                emits('error')
                loading.value = false
                clearFile(1)
            }
        }
    } else if (props.type == 'button') {
        // 单个文件
        emits("update:modelValue", imageUrl)
        let file_size = ''
        if(size > 1024*1024){
            file_size = (size / (1024*1024)).toFixed(2) + 'mb'
        }
        if(size > 1024 && size < 1024*1024){
            file_size = (size / 1024).toFixed(2) + 'kb'
        }
        if(size < 1024){
            file_size = size + 'b'
        }
        try {
            const res = await uploadFile(formData, props.action)
            emits("update:modelValue", props.action + '/' + res.file_url);
            emits('success', {...res, file_size: file_size})
            loading.value = false
            clearFile(0)
        } catch {
            emits('error')
            loading.value = false
            emits("update:modelValue", '');
            clearFile(0)
        }
    }
}
const deleteImg = () => {
    emits('deleteFile')
    emits("update:modelValue", '');
}
const deleteImgList = (index) => {
    imglist.value.splice(index, 1)
    emits("update:modelValue", imglist.value.join(','))
    emits('deleteFile')
}
const dialogImg = (item) => {
    dialogImageUrl.value = item
    nextTick(() => {
        dialogVisible.value = true
    })
}
</script>
<style scoped lang="scss">
.upload {
    border-radius: 2px;

    overflow: hidden;
    position: relative;

    .up-front {
        background: var(--mht-upload-bg-color);
        width: 100%;
        height: 100%;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;

        input {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;

        }

        .up-tips {
            text-align: center;
            line-height: 22px;
            color: var(--el-color-primary);
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;

            .plus-icon {
                font-size: 24px;
                // margin-top: 20px;
            }

            // svg {
            //     color: var(--el-color-primary);
            //     width: 40px;
            //     height: 40px;
            // }

            p {
                display: block;
                color: var(--el-color-primary);
                font-size: 14px;

                .icon {
                    font-size: 18px;
                    position: relative;
                    top: 2px;
                }
            }

            span {
                color: var(--el-text-color-placeholder);
                font-size: 12px;
            }
        }
    }

    .up-after {
        width: 100%;
        height: 100%;
        position: relative;

        &:hover {
            .preview-delete {
                display: flex;
            }
        }

        img {
            position: absolute;
            z-index: 0;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            object-fit: cover;
        }

        .preview-delete {
            position: relative;
            z-index: 1;
            width: 100%;
            height: 100%;
            display: none;
            justify-content: center;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.3);
            color: #fff;

            i {
                font-size: 24px;
                cursor: pointer;
            }

            i+i {
                margin-left: 10px;
            }
        }
    }
}

.upload-el-button {
    position: relative;

    input {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        opacity: 0;
        cursor: pointer;
    }
}
.upload-button{
    padding-top: 10px;
}
.file-name {
    margin-top: 10px;
    font-size: 14px;
    color: var(--el-text-color-secondary)
}

.up-list {
    overflow: hidden;

    &>div {
        overflow: hidden;
        border-radius: 2px;
        float: left;
        display: inline-block;
        margin-right: 15px;
        margin-bottom: 15px;
    }
}
</style>