<style scoped>
  .wrapper {
    display: inline-block;
    position: relative;
  }

  .avatar-image-wrap {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .avatar-image-wrap.circle {
    border-radius: 50%;
  }

  .avatar-image {
    display: block;
    width: 100%;
  }

  .avatar-operate {
    width: 24px;
    height: 24px;
    text-align: center;
    background-color: #409EFF;
    position: absolute;
    right: 0px;
    bottom: 0px;
    cursor: pointer;
    opacity: .8;
  }

  .avatar-operate.circle {
    border-radius: 50%;
    margin-bottom: 8%;
    margin-right: 8%;
    /*transform: translate(-25%, -25%);*/
  }

  .avatar-operate:hover {
    opacity: 1;
  }

  .avatar-operate .el-icon-edit-outline {
    color: #fff;
    font-size: 16px;
    line-height: 24px;
  }

</style>

<template>
  <div class="wrapper" :style="{
    width: size + 'px',
    height: size + 'px'
  }">
    <div class="avatar-image-wrap" :class="{ circle: type === 'circle' }">
      <img class="avatar-image" :src="imagePath" alt="">
    </div>
    <div class="avatar-operate"
         :class="{ circle: type === 'circle' }" @click="handleOperateClick">
      <i class="el-icon-edit-outline"></i>
    </div>

    <avatar-dialog v-model="showDialog"
                   :width="size"
                   :height="size"
                   :no-circle="type !== 'circle'"
                   :no-square="type !== 'square'"
                   :url="uploadPath"
                   :with-credentials="true"
                   @crop-upload-success="handleUploadSuccess"
                   @crop-upload-fail="handleUploadFail"></avatar-dialog>
  </div>
</template>

<script>
import AvatarDialog from 'vue-image-crop-upload'
const defaultUploadPath = `/ui/commonimagecutting/upload`

export default {
  name: 'Avatar',
  props: {
    src: {
      type: String,
      required: true
    },
    size: {
      type: Number,
      default: 100
    },
    type: { // 类型： 圆形 circle 或方形 square
      type: String,
      default: 'square'
    },
    uploadPath: {
      type: String,
      default: defaultUploadPath
    },
    defaultAvatar: {
      type: String,
      default: '/assets/images/user-circle-o.png'
    }
  },
  data () {
    return {
      showDialog: false
    }
  },
  components: {
    'avatar-dialog': AvatarDialog
  },
  computed: {
    imagePath () {
      if (this.src) {
        return this.src
      }
      return this.defaultAvatar
    }
  },
  methods: {
    handleOperateClick () {
      this.showDialog = true
    },
    handleUploadSuccess (jsonData, field) {
      this.$emit('update:src', jsonData.previewPath)
    },
    handleUploadFail (status, field) {
      //  console.log(status field)
    }
  },
  created () {}
}
</script>
