<template>
  <!-- 上传概要图片 -->
  <div class="border-dotted border-2 p-4 mb-5" :path="path">
    <a-upload
      name="uploadFile"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      action="/proxyApi/api/v1/image/upload"
      :accept="ACCEPT_IMAGE_TYPE"
      :before-upload="beforeUpload"
      @change="handleChange"
    >
      <img v-if="imageUrl" :src="imageUrl" alt="图片不存在" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">
          上传概要图片
        </div>
      </div>
    </a-upload>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { message } from 'ant-design-vue'
import {
  ACCEPT_IMAGE_TYPE,
  isAcceptImageType,
  TOAST_TEXT,
  TOAST_TEXT2,
  MAX_IMAGE_SIZE,
} from '@/const/config/upload'


function getBase64(img: Blob, callback: (any: any) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default Vue.extend({
  props:{
    path:{
      type:String,
      required:true
    }
  },
  watch:{
    path(newV,oldV){
      this.imageUrl = newV
    }
  },
  created() {
    this.imageUrl = this.path
  },
  data(){
    return{
      imageUrl: "", 
      loading: false,
      ACCEPT_IMAGE_TYPE,
      file_name:'',
    }
  },
  methods:{
    handleChange(info:any) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      // get file_hash
      this.file_name = info.file.response.data
      this.$emit('getFileHash',this.file_name)
      getBase64(info.file.originFileObj, imageUrl => {
        this.imageUrl = imageUrl;
        this.loading = false;
      });
    }
  },
  beforeUpload(file: File) {
      const isAccpet = isAcceptImageType(file)
      if (!isAccpet) {
        message.error(TOAST_TEXT)
      }
      const isLt4M = file.size < MAX_IMAGE_SIZE
      if (!isLt4M) {
        message.error(TOAST_TEXT2)
      }
      return isAccpet && isLt4M
    },
  }
})
</script>

<style lang="scss" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
