<template>
	<u-upload ref="uUpload" name="imgs"  @on-uploaded="uploadFinished"
	:limitType="imagetype" :max-count="9" :action="action" width="140rpx" height="140rpx" custom-btn :auto-upload="false" >
		<template slot="addBtn">
			<addicon width="140rpx" height="140rpx"></addicon>
		</template>
	</u-upload>
</template>

<script>
	import addicon from "./addicon.vue"
	export default {
		components:{
			addicon
		},
		data() {
			return {
				imagetype:['png', 'jpg', 'jpeg'],
				action: this.uploadurl,
			}
		},
		methods: {
			formatImages(){
				const images = this.$refs.uUpload.lists;
				let imgs = images.filter(image=>{
					return image.response&&image.response.code==0&&image.response.data.length;
				}).map(image=>{
					return image.response.data[0].name
				})
				return imgs
			},
			bindCallback(fn){
				this.uploadScuccess = fn.bind(this,"success")
				this.uploadError = fn.bind(this,"failed")
			},
			clear(){
				this.$refs.uUpload.clear()
			},
			getImages(){
				return this.formatImages()
			},
			checkAndUpload(fn){
				let isComplete = this.isComplete()
				if(fn){
					this.bindCallback(fn)
				}
				if(isComplete===0){
					this.uploadScuccess(this.getImages())
					return true
				}
				if(isComplete===1){
					this.uploadImages()
					return true
				}
				if(isComplete===2){
					this.reUploadImages()
					return true
				}
				if(isComplete===3){
					this.uploadScuccess(this.getImages())
					return true
				}
				return false
			},
			reUploadImages(fn) {
				if(fn){
					this.bindCallback(fn)
				}
				this.$refs.uUpload.reUpload()
			},
			uploadImages(fn) {
				if(fn){
					this.bindCallback(fn)
				}
				this.$refs.uUpload.upload()
			},
			isComplete(){
				if(!this.$refs.uUpload.lists.length){
					return 0 // 没有图片
				}
				let res = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				if(!res.length){
					// 都没上传
					return 1
				}
				if(res.length&&res.length!==this.$refs.uUpload.lists.length){
					// 存在部分没上传，需要重新上传
					return 2
				}
				return 3
			},
			uploadFinished() {
				let res = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				let len = this.$refs.uUpload.lists.length;
				let picture=[];
				for(let i=0;i<res.length;i++){
					picture.push(res[i].response.data[0].name)
				}
				if(picture.length!=this.$refs.uUpload.lists.length){
					this.uploadError(picture, len)
				}else{
					this.uploadScuccess(picture, len)
				}
			},
			uploadScuccess(){},
			uploadError() {},
		},
	}
</script>

<style>
</style>
