<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" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text text-center">
          上传概要图片
        </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="less" scoped>

.ant-upload-select-picture-card i {
  font-size: 30px;
  color: #999;
}

/deep/.ant-upload.ant-upload-select-picture-card{
  width: 355px;
  height: 90px;
  >img{
    width: 355px;
  height: 90px;
  object-position: center;
  object-fit: cover;
  }
}

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