<template>
    <view>
        <u-upload
            ref="uploadRef"
            name="Img"
            :multiple="true"
            :previewFullImage="true"
            :maxCount="maxCount"
            :fileList="fileListImg"
            :sizeType="['compressed']"
            :width="width"
            :height="height"
            :capture="capture"
            :uploadText="uploadText"
            @beforeRead="beforeRead"
            @afterRead="afterRead"
            @delete="deletePic"></u-upload>
    </view>
</template>

<script>
/* https://uviewui.com/components/upload.html */
import { isEmpty,isArray,isString } from 'lodash';
import * as imageConversion from 'image-conversion'
import { getToken } from '@/utils/auth'
import { uploadUrl } from '@/api/common/system.js'
import {server_url} from '@/utils/config.js'
import {createWaterMark} from '@/utils/watermark'
/**
* blob转url临时访问地址
* @param String blob 对象
*/

function createObjectURL(blob){
	return URL.createObjectURL(blob);
}



export default {
	props: {
		value: {
			type: String,
			default: ''
		},
		maxCount: {
			type: String | Number,
			default: 6
		},
		sizeType: { //original 原图，compressed 压缩图，H5无效
			type: Array,
			default: () => ['compressed'],
		},
		//开启h5压缩
		h5Compressed: {
			type: Boolean,
			default: true
		},
		//0.01-1压缩质量 1-N 压缩大小
		h5CompressedSize: {
			type: Number,
			default: 0.8
		},
		width: {
			type: String | Number,
			default: 68,
		},
		height: {
			type: String | Number,
			default: 68,
		},
		capture: {
			type: String | Array,
			default: () => ['album', 'camera'],
		},
		uploadText: {
			type: String,
			default: '请上传图片'
		},
		querParams: {
			type: Object,
			default: () => {
				return {}
			}
		},
		
		//开启用户信息水印
		userInfoWaterMark: {
			type: Boolean,
			default: false
		},
		
	},
    data() {
        return {
            fileListImg: [],
        }
    },
	computed: {
		userName: function() {
		      return this.$store.getters.name
		}
	},
	watch: {
		value: {
			immediate: true,
			deep: true,
			handler(newVal) {
					console.log(newVal,'newVal')
				let list = []
				if (isString(newVal) && !isEmpty(newVal)) {
					list = newVal.split(',').map((url) => {
						let thumb = this.$getImages(url)
						
						// console.log(thumb,'thumb--url')
						return {
							status: 'success',
							message: '上传成功',
							url: thumb,
							thumb: thumb,
							value: url,
						}
					 
					})
					
				} 
			
				this.fileListImg = list
			},
		},
		fileListImg: {
			immediate: false,
			deep: true,
			handler(newVal) {
				// console.log(newVal,'newVal-fileListImg')
				let newUrl = newVal.map(e => e.value).join(',')
				this.$emit('input',newUrl)
				this.$emit('confirm',newUrl)
			}
		}
	},
    methods: {
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
		
        // 读取后的处理函数
        async afterRead(event) {
			
			let time = this.dayjs().format('YYYY-MM-DD HH:mm:ss')
			
			let watermarks = [time,this.userName]
			
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })

			
            for (let i = 0; i < lists.length; i++) {
				
				// #ifdef H5
				
				if(this.h5Compressed) {
					//图片压缩
					if(lists[i].type == 'image') {
						
						let blob = await imageConversion.urltoBlob(lists[i].url)	
						console.log(blob,'压缩前blobd对象')
						if(blob) {
							let res
							//压缩大小
							if (this.h5CompressedSize>1) {
								res = await imageConversion.compressAccurately(blob,this.h5CompressedSize)
							} else { //压缩质量
								res = await imageConversion.compress(blob,this.h5CompressedSize)
							}
							if(res) {
								console.log(res,'压缩后blob对象')	
								let newBlobUrl = createObjectURL(res)
								lists[i].thumb = lists[i].url = newBlobUrl
								lists[i].size = res.size
								
							}
						}
					}
					
				}
				
				// #endif
				if(lists[i].type == 'image') {
					if(this.userInfoWaterMark) {
						
						lists[i].thumb = lists[i].url = await createWaterMark(lists[i].url,watermarks)
					}
				}
				
				
               const res = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList${event.name}`][fileListLen]
				
				if (res.code == 0) {			
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					    status: 'success',
					    message: '上传成功',
					    value: res.fileName,
					}))
					fileListLen++

				} else {
					this[`fileList${event.name}`].splice(fileListLen, 1,)
				}             
            }
			
        },
		
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
				// console.log(url,'urlurl')
                let a = uni.uploadFile({
                    url: uploadUrl, // 仅为示例，非真实的接口地址
					header: {
						'Authorization': 'Bearer ' + getToken()
					},
                    filePath: url,
                    name: 'file',
                    formData: {
                        ...this.querParams,
                    },
                    success: (res) => {			
						let data = JSON.parse(res.data)
						resolve(data)
                    },
					fail: (err) => {
						resolve({
							code: -1,
							msg: '上传失败'
						})
					}
                });
            })
        },
    }

}
</script>

<style lang="scss" scoped>
	
</style>
