<template>
  <div>
    <a-upload
      :action="`${$upload}`"
      accept='.jpg,.JPG,.png,.PNG,.jpeg,.JPEG'
      list-type="picture-card"
      :headers="uploadHeaders"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < 1">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <imgModal :previewVisible='previewVisible' :previewImage='previewImage' @handleCancel='handleCancel'/>
  </div>
</template>

<script>
import imgModal from "./imgModal.vue"
function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}
import store from "@/store";
export default {
	components:{
		imgModal
	},
	data() {
		return{
			previewVisible: false,
			previewImage: '',
			fileList: [],
			uploadHeaders: {
				"admin-login-token": store.getters.getToken
			}
		}
	},
	methods:{
		async handlePreview(file) {
			if (!file.url && !file.preview) {
				file.preview = await getBase64(file.originFileObj);
			}
			this.previewImage = file.url || file.preview;
			this.previewVisible = true;
		},
		handleCancel(){
			this.previewVisible = false;
		},
		handleChange({ fileList }) {
			this.fileList = fileList
			if(fileList[0].status==='done'){
				this.$emit('handleChange',fileList)
			}
		},
	}
};
</script>

<style lang="less">
</style>