<template>
  <div class="counter mui-flex">
    <span class="counter__sub"
          :class="{'dis':subDisFlag}"
          @click="change('sub')"></span>
    <input class="counter__inp mui-flex__cell"
           :class="`${size}`"
           :style="{'background-color':bgColor}"
           type="number"
           :value="count"
           v-number-input="count"
           @change="change" />
    <span class="counter__add"
          :class="{'dis':addDisFlag}"
          @click="change('add')"></span>
  </div>
</template>

<script>
import numberInput from '../utils/directives/numberInput';
export default {
  name: 'Counter',
  directives: { numberInput },
  model: {
    prop: 'num',
    event: 'change'
  },
  props: {
    bgColor: {
      type: String,
      default: '#fff'
    },
    num: {
      type: [Number, String],
      default: 0
    },
    max: {
      type: Number,
      default: 99999
    },
    size: {
      type: String,
      default: 'sm'
    }
  },
  data() {
    return {
      count: 0
      // addDisFlag: false,
      // subDisFlag: false
    };
  },
  watch: {
    // 因为父组件手动改子组件值子组件不更新所以需要实时监听
    num: {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        this.count = newVal;
      },
      immediate: true
    }
  },
  computed: {
    // this.addDisFlag = !!this.count;
    // this.subDisFlag = !!this.count;
    addDisFlag() {
      // console.log('this.count', this.count);
      return this.max === this.count;
    },
    subDisFlag() {
      return this.count === 0;
    }

  },
  methods: {
    change(type = '') {
      console.log(this.count, this.max, this.num);
      let flag = false;// 判断是否超了
      if (type === 'add') {
        if (this.count < this.max) {
          this.count = this.count + 1;
        } else {
          // this.addFn && this.addFn();
          console.log(type);
          this.$emit('addFn');
        }
      }
      if (type === 'sub') {
        if (this.count > 0) {
          this.count = this.count - 1;
        } else {
          this.$emit('subFn');
        }
      }
      if (this.count > this.max) {
        flag = true;
        this.count = this.max;
      }

      this.$emit('change', this.count, flag);
    }
  }
};
</script>
