<template>
  <el-upload
    :auto-upload=false
    :on-change="handleChange"
    ref="avatar"
    :class="className?className:'avatar-uploader'"
    action=""
    :show-file-list="false"
    :disabled="!!disabled"
  >
    <img v-if="picUrl" :src="Axios+picUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import Axios from 'axios'
import {testWidthHeight} from '@/utils/image-tool'
export default {
  name: 'pic-uploader',
  props: ['picUrl', 'className', 'disabled'],
  data() {
    return {
      imageUrl: '',
      product: {},
      Axios: Axios.defaults.baseURL,
      params: {},
      file: null
    }
  },
  computed: {
  },
  mounted(){
  },
  methods: {
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传logo图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return true
    },

    handleChange (e) {  // 上传照片
      let self = this
      let file = e.raw

      // 封装form信息
      let param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      param.append('chunk', '0') // 添加form表单中其他数据
      // console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去

      // 获取图片宽高
      let getShapeInfo = testWidthHeight(file)
      getShapeInfo.then(function(result) {
        param.append('width', result.width) // 通过append向form对象添加数据
        param.append('height', result.height) // 通过append向form对象添加数据

        self.file = result
        self.params = param

        self.$api.common.uploadFile(param)
          .then(res => {
            if (res.code == 1) {
              console.log(res.data)
              self.$emit('uploadSuccess',{param: result, result: res.data});
            }
          })
      })
    },

  },
  watch:{
  }
}
</script>

<style scoped>
</style>
