<template>
    <div class="uploadpic">
        <el-upload
            ref="upload"
            :action="imgAction"
            :headers="headers"
            :file-list="fileList"
            :before-upload="imgBeforeUpload"
            :list-type="listtype"
            :on-preview="handlePreview"
            :limit="limit"
            :class="objClass"
            :auto-upload="true"
            :on-remove="handelDelete"
            :on-error="handleError"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"

            multiple
        >
            <template v-if="fileName == '步骤照片' || fileName == '文档' || fileName == '附件上传'">
                <el-button
                    
                    size="small"
                    type="primary"
                    >点击上传</el-button
                >
                <span slot="tip" class="el-upload__tip" style="margin-left:10px">最多上传3个文件</span>
            </template>

            <!-- <el-button  v-if="fileName=='步骤照片' || fileName=='文档'" size="small" type="primary">导入模板</el-button> -->
            <div v-else>
                <i slot="default" class="el-icon-plus"></i>
                <!-- class="picetucard" <div slot="tip" class="el-upload__tip">点击上传
            最多可上传{{ limit }}个文件，文件请选用jpg,png格式
            请选用png,jpg,jpeg格式
          </div> -->
            </div>
        </el-upload>

        <div v-if="imageVisible && fileName != '文档'">
            <div v-if="fileName != '附件上传'">
                <el-image-viewer
                    :on-close="closeViewer"
                    :url-list="[dialogImageUrl]"
                    z-index="5000"
                />
            </div>
        </div>
    </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
    // name: "MultiUpload",
    components: { ElImageViewer },
    model: {
        prop: 'value',
    },
    props: {
        //配合v-model 加载初始值
        value: {
            type: Array,
            default: () => [],
        },
        limit: Number,
        fileName: String,
        serverAddr: String,
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: {
            type: Array,
            default: () => ['png', 'jpg', 'jpeg'],
        },
    },
    data() {
        return {
            objClass: {
                upLoadShow: true,
                upLoadHide: false,
                wendangHide: false,
            },
            fileList: [],
            filePath: '',
            imageVisible: false,
            dialogImageUrl: '',
            imgAction: process.env.VUE_APP_BASE_API + '/upload',
            progressPercent: 0,
            imageType: '',
            minSize: 1 * 1024,
            maxSize: 50 * 1024 * 1024,
            minSizeTip: '1KB',
            maxSizeTip: '50MB',
            listtype: '',
        }
    },
    computed: {
        ...mapGetters(['token']),
        headers() {
            return { Authorization: 'Bearer ' + this.token }
        },
    },
    created() {},

    mounted() {},

    methods: {
        // 回填文件
        setFile(arr) {
            this.fileList = arr.map((it, index) => {
                return {
                    url: it,
                    name: `附件${index + 1}`,
                }
            })
        },
        // 删除前
        // beforeRemove(file, fileList) {
        //     return this.$confirm(`确定移除 ${file.name}？`)
        // },
        // 效验方法
        imgBeforeUpload(file) {
            // 校检文件类型
            // console.log('this.fileType',this.fileType)
            // if (this.fileType) {
            //     let fileExtension = ''
            //     if (file.name.lastIndexOf('.') > -1) {
            //         fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
            //     }
            //     // console.log('照片文件的后缀---',fileExtension)
            //     // 判断后缀是否在this.fileType里面
            //     const isTypeOk = this.fileType.some((type) => {
            //         if (file.type.indexOf(type) > -1) return true
            //         if (fileExtension && fileExtension.indexOf(type) > -1) return true
            //         return false
            //     })
            //     // 不在this.fileType里面提示
            //     if (!isTypeOk) {
            //         this.$message.warning(`请上传${this.fileType.join('/')}格式文件!`)
            //         return false
            //     }
            // }
            const lastIndex = file.name.lastIndexOf('.');
            // 如果没有点，或者点在文件名开头，则说明没有扩展名
            if (lastIndex === -1 || lastIndex === 0) {
                return false;
            }
            // 获取文件扩展名并转换为小写
            const fileExtension = file.name.slice(lastIndex + 1).toLowerCase();
            // 检查文件扩展名是否在允许的类型列表中
            const flag =  this.fileType.includes(fileExtension);
            if (!flag) {
                this.$message.warning(`请上传${this.fileType.join('/')}格式文件!`)
                return false
            }

            let isRightSize = file.size <= this.maxSize
            if (!isRightSize) {
                this.$message.error('文件大小不能超过' + this.maxSizeTip)
                return false
            }
            isRightSize = file.size >= this.minSize
            if (!isRightSize) {
                this.$message.error('文件大小不能小于' + this.minSizeTip)
                return false
            }
            // return isRightSize && flag
        },
        // 文件上传时
        handlePreview(file) {
            this.imageVisible = true
            this.dialogImageUrl = file.url
        },
        // 上传成功
        handleSuccess(response, file) {
            file.percentage = 100
            file.filePath = response.filePath
            this.value.push(file.filePath)
            this.filePath = file.filePath
        },
        // 关闭放大查看
        closeViewer() {
            this.imageVisible = false
        },
        // 删除时方法
        handelDelete(file, fileList) {
            console.log('删除文件', file)
            // 新加的
            if (file.filePath) {
                const index = this.value.findIndex((it) => it == file.filePath)
                this.value.splice(index, 1)
            }
            // 老的
            if (file.url) {
                const index1 = this.value.findIndex((it) => it == file.url)
                this.value.splice(index1, 1)
            }
        },

        //上传失败
        handleError() {
            this.$message.error('文件上传失败，请重新上传或联系管理员')
        },
        // 文件超出个数限制
        handleExceed() {
            this.$message.error('最多只能上传' + this.limit + '个文件')
        },
        setFileList(stringList) {
            if (this.fileName != '文档') {
                let detailFile = []
                if (stringList && stringList.length > 0) {
                    for (let index in stringList) {
                        detailFile.push({
                            url: stringList[index],
                        })
                    }
                }
                this.fileList = detailFile
                if (this.fileList.length > 0) {
                    this.filePath = this.fileList[0].filePath
                }
            } else {
                this.fileList = []
                let detailFile = []
                if (stringList && stringList.length > 0) {
                    stringList.forEach((item) => {
                        this.fileList.push({ name: item.name, url: item.url })
                    })
                }
            }
        },
        reset() {
            this.fileList = []
            this.filePath = ''
        },
    },
}
</script>

<style scoped>
.uploadpic >>> .el-upload--picture-card {
    background-color: transparent;
    border: 1px dashed #34b2ed;
}
.uploadpic >>> .el-upload--picture-card i {
    color: #34b2ed;
}
.el-upload__tip {
    /* color: #34b2ed; */
}
.uploadpic >>> .el-upload-list__item-name {
    color: #34b2ed;
    /* width:135px; */
    /* width: 80px; */
}
.uploadpic >>> .el-upload-list {
    /* width: 200px; */
    width: 300px;
    /* margin-left:20px; */
}
.uploadpic >>> .el-button {
    background: #0066eb;
    color: #ffffff;
    /* width:40px; */
    height: 33px;
    /* line-height:30px; */
    text-align: center;
    font-size: 15px;
    border-radius: 3px;
    border: 1px solid transparent;
}
.picetucard {
    border: 1px dashed #34b2ed;
    width: 148px;
    height: 148px;
    line-height: 146px;
    text-align: center;
    border-radius: 6px;
}
.picetucard i {
    color: #34b2ed;
    width: 28px;
    height: 28px;
}
.uploadpic >>> .el-upload-list__item-name [class^='el-icon'] {
    color: #34b2ed;
}
/*当upLoadShow为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
.uploadpic >>> .upLoadShow .el-upload {
    /* width: 148px;
      height: 148px;
      line-height: 146px; */
}

/*当upLoadHide为true时，启用如下样式，即缩略图的样式，若为false则不启用该样式*/
.uploadpic >>> .upLoadHide .el-upload-list--picture-card .el-upload-list__item {
    width: 148px;
    height: 148px;
    line-height: 146px;
}
/*当upLoadHide为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
.uploadpic >>> .upLoadHide .el-upload {
    display: none;
}

.uploadpic >>> .wendangHide .el-upload {
    width: 148px;
    height: 33px;
    line-height: 33px;
}
.uploadpic >>> .el-progress__text {
    color: #67c23a;
}
/* .uploadpic>>>.el-upload .el-upload--text{
      height: 50px;
      line-height: 1px;
    } */
</style>
