<template>
	<div>
		<template v-if="multiple">
			<el-upload
			class="upload-demo"
			:action="uploadFileUrl"
			:before-remove="beforeRemove"
			:before-upload="beforeUpload"
			:on-success="successHandleList"
			:index="index"
			:data="params"
      :on-preview="previewFile"
			multiple
			:accept="accept"
      :headers="headers"
			:file-list="fileList">
				<el-button type="primary" :disabled="disabledVisible">点击上传</el-button>
				<div v-if="tip" class="el-upload__tip" slot="tip">{{tip}}</div>
			</el-upload>
		</template>
		<template v-else>
			<el-upload :class="showPic ? 'avatar-uploader': 'singlebox'"
			:action="uploadFileUrl"
			:show-file-list="false"
			:accept="accept"
			:on-success="handleSuccess"
			:index="index"
			:data="params"
      :headers="headers"
			:before-upload="beforeUpload"
			:on-progress="handleProgress">
				<template v-if="showPic">
					<img v-if="singleFile.url" :src="file.url" class="avatar" :width="imgWidth" :height="imgHeight">
	  				<i v-else class="el-icon-plus avatar-uploader-icon" :style="'width:'+imgWidth+'px; height:'+imgHeight+'px;line-height: '+imgHeight+'px;'"></i>
				</template>
				<el-button v-else type="primary" class="btn" :disabled="disabledVisible">
					<template v-if="singleFile.url">重新上传</template>
					<template v-else>点击上传</template>
				</el-button>
				<div v-if="tip" class="el-upload__tip" slot="tip">{{tip}}</div>
			</el-upload>
			<template v-if="!showPic && singleFile.url">
				<a class="singlefile" :href="singleFile.url" :title="singleFile.name" target="_blank">
					<i class="el-icon-document"></i>{{singleFile.name}}
				</a>
			</template>
		</template>
	</div>
</template>
<script>
  import { getToken } from "@/utils/auth";
	export default {
		props: {
			file: {
				type: Object,
				default: function () {
					return {
						name: '',
						url: ''
					}
				}
			},
			files: {
				type: Array,
				default: function () {
					return []
				}
			},
      disabledVisible: {
        type: Boolean,
        default: false
      },
			multiple: {
				type: Boolean,
				default: false
			},
			showPic: {
				type: Boolean,
				default: false
			},
			sizeLimit: {
				type: Number,
				default: 0
			},
			accept: {
				type: String,
				default: ''
			},
			tip: {
				type: String,
				default: ''
			},
			index:{
				type:Number,
				default: -1
			},
			imgWidth: {
				type: Number,
				default: 178
			}, // showPic 时 图片宽度
			imgHeight: {
				type: Number,
				default: 178
			}, // showPic 时 图片高度
			params: {
				type: Object,
				default: function () {
          return {}
        }
			}
		},
		data () {
			return {
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/attach/upload", // 上传的图片服务器地址
				// uploadFileUrl: 'http://124.232.146.72:7015/api/common/attach/upload', // 上传的图片服务器地址
				headers: {
				  Authorization: "Bearer " + getToken(),
				},
				singleFile: {
					name: this.file.name,
					url: this.file.url
				},
				fileList: [],
			}
		},
		created () {

		},
		mounted () {
			this.$emit('update:file', this.singleFile)
			this.$emit('update:files', this.fileList)
			this.fileList = this.files
		},
		methods: {
      previewFile(file) {
        console.log(file)
        if (file) {
          const addTypeArray = file.name.split(".");
          const addType = addTypeArray[addTypeArray.length - 1];
          console.log(addType);
          if (addType === "pdf") {
            let routeData = this.$router.resolve({
              path: "/pdfPreview",
              query: { url: file.filePath },
            });
            window.open(routeData.href, "_blank");
          }
          //".rar, .zip, .doc, .docx, .xls, .txt, .pdf, .jpg,  .png, .jpeg,"
          else if (addType === "doc" || addType === "docx" || addType === "xls" || addType === "xlsx") {
            // window.open(
            //   "http://view.officeapps.live.com/op/view.aspx?src=" + file.filePath
            // );
            window.open(file.filePath);
          } else if (addType === "txt") {
            window.open(file.filePath);
          } else if (["png", "jpg", "jpeg"].includes(addType)) {
            window.open(file.filePath);
          } else if (addType === "rar" || addType === "zip") {
            this.$message({
              message: "该文件类型暂不支持预览",
              type: "warning",
            });
             return false;
          }
        }
      },
			handleSuccess(res, file) {
				if (res.code == 200) {
					this.singleFile.name = file.name
					this.singleFile.url = res.data.url
					if(this.index == -1){
						this.$emit('input', this.singleFile)
					}else{
						this.$emit('input', this.singleFile, this.index)
					}
				} else {
					this.$message.error(res.msg)
				}
			},
			beforeUpload(file) {
				const isLTM = this.sizeLimit > 0 ? file.size / 1024 / 1024 < this.sizeLimit : true
				let isInAccept = true
				if (this.accept) {
					isInAccept = false
					if (file.type.indexOf('image') != -1) {
						if (this.accept.indexOf('image') != -1) {
							isInAccept = true
						}
					} else {
						isInAccept = this.accept.indexOf(file.type) == -1 ? false : true
					}
					if (!isInAccept) {
						this.$message.error(`文件格式错误`)
					} else {
						if (!isLTM) {
							this.$message.error(`文件大小不能超过 ${this.sizeLimit}MB!`)
						}
					}
				}
				return isInAccept && isLTM
			},
			handleProgress(file) {

			},
			beforeRemove (file, fileList) {
				let hasTip = false;
				if (file.raw) {
					const isLTM = this.sizeLimit > 0 ? file.raw.size / 1024 / 1024 < this.sizeLimit : true
					if (this.accept) {
						let isInAccept = false
						if (file.raw.type.indexOf('image') != -1) {
							if (this.accept.indexOf('image') != -1) {
								isInAccept = true
							}
						} else {
							isInAccept = this.accept.indexOf(file.raw.type) == -1 ? false : true
						}
						if (!isLTM || !isInAccept) {
							this.fileList = fileList
						} else {
							hasTip = true
						}
					}
				} else {
					hasTip = true
				}
				if (hasTip) {
					return this.$confirm(`确定移除 ${file.name}？`).then(() => {
						this.fileList = fileList
						if(this.index == -1){
							this.$emit('input', this.fileList)
						} else {
							this.$emit('input', this.fileList, this.index)
						}
					})
				}
			},
			successHandleList (response, file, fileList) {
				this.fileList = fileList;
        fileList.forEach((item, index) => {
          if (item.url == undefined && item.response != undefined) {
            fileList[index].fileName = item.response.data.fileName;
            fileList[index].filePath = item.response.data.url;
            fileList[index].url = item.response.url;
          }
        });
				if(this.index == -1){
					this.$emit('input', this.fileList)
				}else{
					this.$emit('input', this.fileList, this.index)
				}
			}
		},
		watch: {
			'file' () {
				this.singleFile = this.file
			},
			'files' () {
				this.fileList = this.files
			}
		}
	}
</script>
