<template>
    <div>
        <el-upload :action="uploadAction" list-type="picture-card" :file-list="items" :on-success="onUploadSuccess" :before-upload="onBeforeUpload">
            <i class="el-icon-plus"></i>
        </el-upload>
        <div>
            <el-button type="primary" @click="save">保存</el-button>
             <el-button @click="goBack">取消</el-button>
        </div>
    </div>
</template>
<script>
export default {
  data() {
    return {
      uploadAction: process.env.SERVER_PATH + 'upload',
      items: [],
      gid: 0
    }
  },
  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 + ')'
        )
      } else {
        this.items.push({ name: '', url: res.obj })
      }
    },
    save: function() {
      var items = []
      this.items.forEach(it => {
        items.push({ title: it.name, content: it.url })
      })
      var that = this
      this.$http
        .saveGoodDescribe({ gid: this.gid, items: items }, this)
        .then(res => {
          if (res.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1000,
              onClose: function() {
               that.goBack()
              }
            })
          }
        })
    },
    goBack: function(){
        this.$router.back();
    }
  },
  mounted: function() {
    let gid = this.$route.query.gid
    this.gid = gid
    this.$http.getGoodDescribe({ gid: gid }, this).then(res => {
      if (res.code === 0) {
        var items = []
        res.obj.forEach(item => {
          items.push({ id: item.id, name: item.title, url: item.content })
        })
        this.items = items
      }
    })
  }
}
</script>
