<template>
  <el-form ref="form" :model="form" label-width="120px">
    <el-form-item label="标题">
      <el-input v-model="form.title" size="mini"></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>
    </el-form-item>
    <el-form-item label="跳转地址">
      <el-input v-model="form.url" size="mini"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save" size="mini">保存</el-button>
      <el-button @click="goBack" size="mini">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  data() {
    return {
      uploadAction: process.env.SERVER_PATH + "upload",
      form: {
        id: 0,
        title: "",
        icon: "",
        url: ""
      }
    };
  },
  methods: {
    save: function() {
      var that = this;
      this.$http
        .bannerSave(
          {
            id: this.form.id,
            title: this.form.title,
            icon: this.form.icon,
            url: this.form.url
          },
          this
        )
        .then(res => {
          if (res.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1000,
              onClose: function() {
                that.goBack();
              }
            });
          }
        });
    },
    goBack: function() {
      this.$router.back();
    },
    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;
      }
    }
  },
  mounted: function() {
    var id = this.$route.query.id;
    if (id === 0) {
      return;
    }
    this.form.id = id;
    this.$http.bannerGet({ id: id }, this).then(res => {
      if (res.code === 0) {
        this.form.title = res.obj.title;
        this.form.icon = res.obj.icon;
        this.form.url = res.obj.url;
      }
    });
  }
};
</script>

<style scoped>
.avatar-uploader img {
  height: 100%;
  width: 100%;
}
.el-form-item {
  margin-bottom: 0px;
}
</style>
