<template>
    <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="商品名称">
            <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="商品简介">
            <el-input v-model="form.describe"></el-input>
        </el-form-item>
        <el-form-item label="商品图标">
            <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false" :on-success="onUploadSuccess" :before-upload="onBeforeUpload">
                <img v-if="form.icon" :src="form.icon" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <p class="zy">
                注意：图标比例一定要1:1
            </p>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button>取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script>
export default {
  data() {
    return {
      uploadAction: process.env.SERVER_PATH + 'upload',
      form: {
        name: '',
        describe: '',
        icon: '',
        status: false
      }
    }
  },
  methods: {
    onBeforeUpload: function(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'

      if (!isJPG && !isPNG) {
        this.$message.error('上传商品图标只能是 JPG/PNG 格式!')
        return false
      } else {
        return true
      }
    },
    onUploadSuccess: function(res, file) {
      if (res.code != 0) {
        this.$message.error(
          '上传图片失败 原因:' + res.msg + '(' + res.code + ')'
        )
        return
      } else {
        this.form.icon = res.obj
      }
    },
    save: function() {
      let goods = {
        name: this.form.name,
        describe: this.form.describe,
        icon: this.form.icon
      }

      this.$http.editGoods(goods, this).then(data => {
        console.log(data)
      })
    }
  }
}
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.zy {
  color: red;
}
</style>