<!-- 单图片上传组件 -->
<template>
	<el-upload v-loading="loading" :disabled="disabled" action="" :http-request="uploadFile" :show-file-list="false" :auto-upload="false" :on-change="changeFinish" :accept="typeArray">
		<img v-if="imageUrl" :src="imageUrl" class="avatar" />
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>
<script>
import fileMixin from '@/mixins/upload';
import { uuid } from "@/utils/index"
import { getUploadFilePath } from "@/config/index"
import {debounce} from '@/utils/index';

export default {
	mixins: [fileMixin],
	model: {
		prop: 'value',
		event: 'change',
	},
	props: {
		disabled: {
			//是否禁用
			type: Boolean,
			default: false,
		},
		url: {
			//图片地址
			type: String,
			default: '',
		},
		value:{
			//图片地址
			type: String,
			default: ''
		},
		filePath: {
			type: String,
			default: 'imageUpload',
		},
		maxSize: {
			type: Number,
			default: 10
		},
		type: {
			type: Array,
			default: () => {
				return ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
			},
		},
	},
	data() {
		return {
			imageUrl: '',
			loading: false,
		};
	},
	computed: {
		typeArray() {
			return this.type.map((item) => `.${item}`).join(','); //转换结果为.jpg,.png
		},
		countUrl: function () {
			if (this.value) {
				this.imageUrl = getUploadFilePath(this.value);
			} else {
				this.imageUrl = '';
			}
			return this.value;
		},
	},
	watch: {
		countUrl: function (newValue, oldValue) {},
	},
	methods: {
		//表单图片显示
		previewImg(files) {
			var reader = new FileReader(); //调用FileReader
			reader.readAsDataURL(files[0]); //将文件读取为 DataURL(base64)
			reader.onload = (evt) => {
				this.imageUrl = evt.target.result;
			};
		},
		//文件变更函数事件，建议此处处理文件过滤
		// onChange(file, fileList) {
		// 	// console.log("onChange")
		// 	this.filterFile([file.raw], this.type);
		// 	this.$emit('change', [file.raw]);
		// 	this.previewImg([file.raw]);
		// 	// this.uploadFile(this.fileList)//上传函数由用户提交数据时触发，文件上传至浏览器期间不触发
		// },
    beforeUpload(file){
      const alows = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/bmp'];
      if (alows.indexOf(file.type) === -1){
        this.$message.warning("存在不支持的图片格式")
      }else if(this.maxSize > 0 && file.size / 1024 / 1024 > this.maxSize){
        this.$message.warning(`单张图片最大不超过 ${this.maxSize}MB`)
      }else {
        return true
      }
      return false
    },
    changeFinish: debounce(function (file, fileList){
	  this.filterFile([file.raw], this.type);
      this.loading = true;
      let targetFileList = fileList;
      let originFileList = [];
      let upFileList = [];
      let namesArr = [];
      targetFileList.forEach(item => {
        if(item.status !== 'success') {
          upFileList.push(item.raw);
          // namesArr.push(`${item.name}`);
          let nameArr = item.name.split('.')
          let fileType = nameArr[nameArr.length - 1];
          let newName = `${uuid() + new Date().getTime() + '.' + fileType}`;
          namesArr.push(newName);
        }else {
          originFileList.push(item.value)
        }
      })
      if(!this.beforeUpload(file.raw)) {
        this.loading = false;
        return false
      }
      if(upFileList.length) {
        this.uploadFileRemoteRename(upFileList, [`${this.filePath}/${Date.now()}`], namesArr)
             .then((res) => {
                let newList = [...originFileList,...res];
                this.$emit("change", newList.join(","));
				if(newList && newList.length) {
					this.imageUrl = getUploadFilePath(newList[0]);
				}else {
					this.imageUrl = '';
				}
                this.loading = false;
            }).catch((err) => {
             	this.$emit("change", originFileList.join(","));
				if(originFileList && originFileList.length) {
					this.imageUrl = getUploadFilePath(originFileList[0]);
				}else {
					this.imageUrl = '';
				}
              this.loading = false;
            })
      }else  {
        this.$emit("change", originFileList.join(","));
		if(originFileList && originFileList.length) {
			this.imageUrl = getUploadFilePath(originFileList[0]);
		}else {
			this.imageUrl = '';
		}
        this.loading = false;
      }
    },
			1000,
			false
		),
	},
	mounted() {},
};
</script>

<style scoped lang="scss">
::v-deep .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

::v-deep .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
