<template>
  <div class="avatar">
    <div class="avatar-list">
      <template v-if="avatar.status === 'finished'">
        <img :src="avatar.url">
        <div class="avatar-list-cover">
          <Icon type="ios-eye-outline" @click.native="handleView()" />
          <Icon type="ios-trash-outline" @click.native="handleRemove()" />
        </div>
      </template>
      <template v-else>
        <Progress v-if="avatar.showProgress" :percent="avatar.percentage" hide-info />
      </template>
    </div>
    <Upload
      class="avatar-upload"
      ref="avatar"
      v-show="avatar.status !== 'finished'"
      :action="info.form.action || ''"
      :name="info.form.name"
      :format="(typeof info.form.fileType === 'string' ?
        info.form.fileType.split(',') : info.form.fileType)"
      :disabled="info.form.disabled"
      :max-size="1024"
      :show-upload-list="false"
      :on-success="onSuccess"
      :on-error="onError">
      <div
        class="avatar-upload-camera"
        :title="`只能上传不超过 1MB 的 ${info.form.fileType} 文件!`">
        <Icon type="ios-camera" size="20"></Icon>
      </div>
    </Upload>
  </div>
</template>
<script>
import { baseComponentMixins } from '../mixins'

export default {
  name: 'BaseAvatarUpload',
  mixins: [ baseComponentMixins ],
  data() {
    return {
      avatar: {},
    }
  },
  methods: {
    // 上传成功时的钩子
    onSuccess(rsp, file, fileList) {
      this.avatar = file
      console.log(rsp, file, fileList)
    },
    // 上传失败时的钩子
    onError(err, file, fileList) {
      console.log(err, file, fileList)
    },
    // 预览
    handleView() {
      // TODO 预览
    },
    // 移除
    handleRemove() {
      this.$refs['avatar'].fileList = []
      this.avatar = {}
    },
  },
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 60px;
  height: 60px;
}
.avatar-list {
  position: relative;
  img,
  &-cover {
    @extend .avatar;
    border: none;
  }
  &-cover {
    font-size: 18px;
    color: #fff;
    position: absolute;
    top: 0;
    line-height: 60px;
    text-align: center;
    background-color: rgba(0, 0, 0, .5);
    > i {
      cursor: pointer;
      margin: 0 3px;
    }
  }
}
.avatar-upload {
  &-camera {
    @extend .avatar;
    line-height: 58px;
    text-align: center;
    border-radius: 4px;
    border: 1px dotted #ccc;
    cursor: pointer;
  }
}
</style>