<template>
  <div class="shop-count-box">
    <div class="title">商品数量</div>
    <div class="count">
      <div class="minus" @click="count('-')"><i></i></div>
      <span class="num">{{ num }}</span>
      <div class="add" @click="count('+')"><i></i></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'shop-count',
  props: {
    value: {},
    stock: {}
  },
  computed: {
    num: {
      get() {
        if (this.stock <= 0) {
          this.$emit('input', 0);
        }
        return this.value;
      },
      set(nVal) {
        this.$emit('input', nVal);
      }
    }
  },
  methods: {
    count(type) {
      if (this.stock) {
        let num = this.value;
        if (type === '-') {
          if (num - 1 < 1) {
            return false;
          }
          num = num - 1 < 1 ? 1 : num - 1;
        } else if (type === '+') {
          if (num + 1 > this.stock) {
            this.$layer.msg('超出限制！');
            return false;
          }
          num = num + 1 > this.stock ? this.stock : num + 1;
        }
        this.num = num;
      } else {
        this.$layer.msg('超出限制！');
        this.num = 0;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.shop-count-box {
  display: flex;
  line-height: 0.3rem;
  .title {
    flex: 1;
    margin-right: 0.1rem;
    width: 0.3rem;
    color: #666666;
    font-size: 0.12rem;
  }
  .count {
    flex: 0 0 auto;
    .minus {
      vertical-align: middle;
      display: inline-block;
      width: 0.32rem;
      height: 0.3rem;
      background: #f8f8f8;
      i {
        display: block;
        width: 100%;
        height: 100%;
        background: url('./img/icon-minus.png') no-repeat center center;
        background-size: 0.1rem auto;
      }
    }
    .add {
      vertical-align: middle;
      display: inline-block;
      width: 0.32rem;
      height: 0.3rem;
      background: #f8f8f8;
      i {
        display: block;
        width: 100%;
        height: 100%;
        background: url('./img/icon-add.png') no-repeat center center;
        background-size: 0.1rem auto;
      }
    }
    .num {
      margin: 0 0.01rem;
      display: inline-block;
      width: 0.38rem;
      height: 0.3rem;
      text-align: center;
      font-size: 0.12rem;
      background: #f1f1f1;
      color: #333333;
    }
  }
}
</style>
