<template>
  <section class="AiAvatar">
    <el-row type="flex" v-if="type=='rect'">
      <div class="image-box">
        <el-image v-if="value" :src="value" :preview-src-list="preview?[value]:null"/>
        <div style="margin: 36px auto;" v-else>
          <i class="iconfont iconProfile_Picture"></i>
          <div style="color: #666;font-size: 12px;">暂无照片</div>
        </div>
      </div>
      <div v-if="editable" class="upload-box">
        <el-upload ref="avatarUploader" action :http-request="uploadAvatar" :limit="1" :show-file-list="false"
                   :before-upload="f=>file=f" :on-change="()=>$refs.avatarUploader.clearFiles()"
                   :accept="accept">
          <el-button size="mini">上传图片</el-button>
          <div class="upload-tip" slot="tip">图片必须小于10MB，仅限jpg/png/jpeg格式</div>
        </el-upload>
      </div>
    </el-row>
    <el-avatar v-else-if="type=='circle'" :src="value">
      <slot v-if="!value"/>
    </el-avatar>
  </section>
</template>

<script>
export default {
  name: "AiAvatar",
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {type: String, default: ""},
    instance: Function,
    editable: {type: Boolean, default: true},
    bid: String,
    preview: {type: Boolean, default: true},
    type: {default: "rect"}
  },
  data() {
    return {
      file: null,
      accept: ".jpg,.png,.jpeg"
    }
  },
  methods: {
    uploadAvatar() {
      const fileType = this.file.name.split(".")[1]
      if (fileType && this.accept.indexOf(fileType.toLocaleLowerCase()) > -1) {
        let formData = new FormData()
        formData.append('bizId', this.bid)
        formData.append('bizType', '2')
        formData.append('file', this.file)
        this.instance.post("/admin/file/add", formData).then(res => {
          if (res.data) {
            const fileInfo = res.data[0]
            this.$emit("change", fileInfo.split(";")[0], fileInfo);
            this.$message.success("上传成功")
          }
        })
      } else {
        this.$message.error("上传文件格式错误!")
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.AiAvatar {
  font-size: 12px;
  line-height: initial;

  .iconProfile_Picture {
    color: #89b;
  }

  :deep(.el-avatar) {
    background: #26f;
  }

  .image-box {
    width: 104px !important;
    height: 120px;
    text-align: center;
    background-color: #f5f5f5;
    border: 1px solid rgba(208, 212, 220, 1);
    border-radius: 2px;
    padding: 0;

    .iconfont {
      font-size: 32px
    }

    .el-image {
      width: 100%;
      height: 100%;
    }
  }

  .upload-box {
    width: 104px;
    margin-left: 8px;

    .el-button {
      width: 104px;
      height: 32px;
    }

    .upload-tip {
      padding: 8px 0 0 10px;
      color: #999999;
    }
  }
}
</style>
