<template>
	<div>
		<el-upload action :accept="defFilterTypes" list-type="picture-card" :on-change="handleChange" :file-list="fileList" :http-request="uploadFile"
			:on-success="uploadSuccess" :on-error="uploadError" :limit="limitCount" :class="{hide:hideUpload}">
			<i slot="default" class="el-icon-plus" />
			<div slot="file" slot-scope="{file}">
				<img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
				<span class="el-upload-list__item-actions">
					<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
						<i class="el-icon-delete" />
					</span>
				</span>
			</div>
		</el-upload>
	</div>
</template>
<script>
	// import {
	// 	getFileList,
	// 	uploadhimage
	// } from '@/api/fileInfo'

	import COS from 'cos-js-sdk-v5'

	export default {
		name: 'PlUpload',
		componentName: 'plUpload',
		model: {
			event: 'refreshModel'
		},
		props: {
			linkId: {
				type: Number
			}, // 关联主键ID
			linkUrl: {
				type: String
			}, // 关联主键图片
			fileUrl: {
				type: [Array, String]
			}, // 关联编辑图片
			limitCount: {
				type: Number,
				default: 6
			}, // 最大上传量
			disabled: {
				type: Boolean,
				default: false
			}, // 是否编辑
			type: {
				type: Number,
				default: 1
			}, // 返回类型 1：返回fileListJson 2.最大上传量为1时返回url
			times: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				hideUpload: '',
				fileList: [],
				uploadFileList: [],
				defFilterTypes: '.jpg, .jpeg, .png', // 默认上传类型
				cosVal: {
					SecretId: "AKIDJSP9gz469yZv77tQjotsgHguvjIgtvkL",
					SecretKey: "b3MVRD1g8RYS9g195oMkvukQvDKZfbOz",
					SecurityToken: "1320402385",
					Bucket: "jinganminsu-1320402385",
					Region: "ap-nanjing",
				}
			}
		},
		watch: {
			'linkUrl': { // 深度监听，可监听到对象、数组的变化
				handler(newV, oldV) {
					this.init()
				}
			},
			'linkId': { // 深度监听，可监听到对象、数组的变化
				handler(newV, oldV) {
					this.init()
				}
			},
			'times': { //深度监听，可监听到对象、数组的变化
				handler(newV, oldV) {
					this.init()
				}
			}
		},
		created() {
			this.init()
		},
		methods: {
			init() {
				this.uploadFileList = []
				this.fileList = []
				if (this.linkId || this.linkUrl) { // 编辑进来
					if (this.type === 2 && this.limitCount === 1) {
						this.fileList.push({
							url: this.linkUrl
						})
						this.hideUpload = this.fileList.length >= this.limitCount
						this.refreshUploadFile()
					} else {
						const tempData = this.fileUrl
						if (tempData.length > 0) {
							for (var i = 0; i < tempData.length; i++) {
								let t = {
									url: tempData[i]
								};
								this.fileList.push(t)
								this.uploadFileList.push(t)
							}
						} else {
							this.fileList = []
						}

						// getFileList(this.linkId).then((res) => {
						// 	// console.log('getImageFiles', res);
						// 	const tempData = res.data
						// 	if (typeof tempData !== 'undefined' && tempData !== '') {
						// 		for (var i = 0; i < tempData.length; i++) {
						// 			this.fileList.push(tempData[i])
						// 			this.uploadFileList.push(tempData[i])
						// 		}
						// 	} else {
						// 		this.fileList = []
						// 	}
						// 	this.hideUpload = this.fileList.length >= this.limitCount
						// 	this.refreshUploadFile()
						// }).catch((err) => {
						// 	this.$message.error(err.message)
						// })
					}
				}
				this.hideUpload = this.fileList.length >= this.limitCount
				this.refreshUploadFile()
			},
			handleClick(tab, event) {
				// console.log(tab, event)
			},
			// 上传列表
			handleChange(file, fileList) {
				this.fileList = fileList
				this.hideUpload = this.fileList.length >= this.limitCount
				this.refreshUploadFile()
			},
			// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
			beforeUploadFile(file) {
				let isSubmit = true

				const size = file.size / 1024 / 1024
				if (size > 10) {
					this.$message.warning('文件大小不得超过10M')
					isSubmit = false
				}
				return isSubmit
			},
			// 移除
			handleRemove(file) {
				// 使用filter()方法从数组中删除元素
				const index = this.fileList.findIndex(item => item.url === file.url)
				this.fileList.splice(index, 1)
				this.uploadFileList.splice(index, 1)
				this.refreshUploadFile()
				setTimeout(() => {
					this.hideUpload = this.fileList.length >= this.limitCount
				}, 1000)
			},
			uploadFile(files) {
				const self = this
				const loading = this.$loading({
					lock: true,
					text: '附件上传中',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				})
				// 发起上传
				const file = files.file;
				const key = `/uploads/minsu/${new Date().getTime()}`; // 设置上传到 COS 后的文件名
				const cos = new COS(self.cosVal);
				cos.putObject({
						Bucket: "jinganminsu-1320402385",
						Region: "ap-nanjing",
						Key: key,
						Body: file,
					},
					function(err, data) {
						if (err) {
							// console.error(err);
							self.$message.error(err);
							self.fileList.splice(self.fileList.length - 1, 1)
							console.log(err)
							loading.close()
							self.$message.error('上传失败')
							return;
						} else {
							// console.log(data);
							// 由于后端上传图片接口返回的数据结构发生变化，需要做一下处理
							var objData = {}
							objData.id = ''
							objData.linkId = ''
							objData.name = ''
							objData.url = `https://${data.Location}`

							self.uploadFileList.push(objData)
							self.fileList = self.uploadFileList
							setTimeout(() => {
								// console.log("附件信息", self.uploadFileList)
								self.refreshUploadFile()
								loading.close()
							}, 1000)
						}
					}
				);
				// uploadhimage(file).then((res) => {
				// 	// console.log('uploadImagesFiles', res.data)
				// 	// 由于后端上传图片接口返回的数据结构发生变化，需要做一下处理
				// 	var objData = {}
				// 	objData.id = ''
				// 	objData.linkId = ''
				// 	objData.name = ''
				// 	objData.url = res.data

				// 	self.uploadFileList.push(objData)
				// 	self.fileList = self.uploadFileList
				// 	setTimeout(() => {
				// 		// console.log("附件信息",self.fileList)
				// 		self.refreshUploadFile()
				// 		loading.close()
				// 	}, 1000)
				// }).catch((err) => {
				// 	self.fileList.splice(self.fileList.length - 1, 1)
				// 	console.log(err)
				// 	loading.close()
				// 	this.$message.error('上传失败')
				// })
			},
			uploadSuccess(file) {
				this.$message.success('上传成功')
			},
			uploadError(err, file, fileList) {
				this.$message.error('上传失败' + err)
			},
			refreshUploadFile() {
				if (this.type === 2 && this.limitCount === 1) {
					if (this.fileList.length > 0) {
						this.$emit('refreshModel', this.fileList[0].url)
					} else {
						this.$emit('refreshModel', undefined)
					}
				} else {
					this.$emit('refreshModel', JSON.stringify(this.uploadFileList))
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	::v-deep .hide .el-upload--picture-card {
		display: none;
	}
</style>