<template>
  <div>
    <div class="flex">
      <i class="icon-remove" @click="reduce"></i>
      <div style="width: 40px" class="number-box">
        <el-input
          :min="min"
          :max="max"
          type="number"
          v-model="number"
          placeholder="0"
          @blur="valChange(number, true)"
          @input="valChange"
        ></el-input>
      </div>
      <!-- <i class="el-icon-remove"></i> -->
      <i class="el-icon-circle-plus icon-add" @click="add"></i>
    </div>
  </div>
</template>
<script>
import { formatPrice } from "@/utils/format";

export default {
  props: {
    value: {
      type: Number,
      default: 1,
    },
    min: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: Infinity,
    },
  },
  watch: {
    value(val){
      this.number = val;
    },
    min(val) {
      this.number = val;
    },
  },
  data() {
    return { number: 1 };
  },
  methods: {
    valChange(val, isNow = false) {
      console.log(val);
      const max = this.max;
      const min = this.min;
      const returnNewval = formatPrice(val, min, max, true);
      let newval = 0;
      if (typeof returnNewval !== "number") {
        newval = returnNewval.value;
      } else {
        newval = returnNewval;
      }
      newval=parseInt(newval);
      console.log(newval);
      if (isNow) {
        this.number = newval;
        this.$emit("input", this.number);
        return;
      }
      setTimeout(() => {
        this.number = newval;
        this.$emit("input", this.number);
      }, 100);
    },
    emitInput() {
      this.$emit("input", this.number);
    },
    reduce() {
      if (this.number > this.min) {
        this.number--;
        this.emitInput();
      }
    },
    add() {
      if (this.number < this.max) {
        this.number++;
        this.$emit("input", this.number);
      }
    },
  },
  mounted(){
    this.number = this.value;
  }
};
</script>

<style lang="scss" scoped>
::v-deep .number-box .el-input__inner {
  border: none;
  padding: 0 2px;
  text-align: center;
}
.icon-add {
  color: #1890ff;
  font-size: 22px;
  cursor: pointer;
}
.icon-remove {
  border: 1px solid #d8d8d8;
  width: 22px;
  height: 22px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  box-sizing: border-box;
  cursor: pointer;

  &::after {
    content: "";
    display: block;
    width: 10px;
    height: 1px;
    background: #999;
  }
}
</style>