<template>
  <div>
    <div class="old">
      <el-tag
        class="tag"
        v-for="(oit, oindex) in oldLabels"
        :key="oit.id"
        closable
        type="success"
        size="medium"
        @close="removeOldLabel(oindex)"
      >{{oit.name}}</el-tag>
    </div>
    <div class="new">
      <el-button
        type="danger"
        plain
        v-for="(nit, nindex) in newLabels"
        :key="nit.id"
        v-on:click="add(nindex)"
        size="mini"
      >{{nit.name}}</el-button>
    </div>
    <div class="option">
      <el-button type="primary" @click="save" size="mini">保存</el-button>
      <el-button @click="goBack" size="mini">取消</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      gid: 0,
      oldLabels: [],
      newLabels: []
    };
  },
  methods: {
    getOldGoodLabels: function() {
      this.$http.getGoodLabels({ gid: this.gid }, this).then(res => {
        if (res.code === 0) {
          this.oldLabels = res.obj;
        }
      });
    },
    getNewGoodLabels: function() {
      this.$http.okLabels({}, this).then(res => {
        this.newLabels = res.obj;
      });
    },
    removeOldLabel: function(index) {
      this.oldLabels.splice(index, 1);
    },
    goBack: function() {
      this.$router.back();
    },
    add: function(index) {
      var item = this.newLabels[index];
      var have = false;
      this.oldLabels.forEach(it => {
        if (it.id === item.id) {
          have = true;
        }
      });
      if (!have) {
        this.oldLabels.push({ id: item.id, name: item.name });
      }
    },
    save: function() {
      var lids = [];
      this.oldLabels.forEach(it => {
        lids.push(it.id);
      });
      var that = this;
      this.$http
        .setGoodLabels({ gid: this.gid, lids: lids }, this)
        .then(res => {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1000,
            onClose: function() {
              that.goBack();
            }
          });
        });
    }
  },
  mounted() {
    var gid = this.$route.query.gid;
    this.gid = gid;
    this.getOldGoodLabels();
    this.getNewGoodLabels();
  }
};
</script>

<style scoped>
.old {
  min-height: 45px;
}
.new {
  border-top: 1px solid #E6E6E6;
  padding-top: 20px;
  min-height: 45px;
}
.tag {
  margin-right: 10px;
}
.option {
  border-top: 1px solid #E6E6E6;
  padding-top: 20px;
}
</style>

