<template>
  <div
    :class="[
      'ps-input-number',
      $slots.prepend && 'ps-input-number-prepend',
      $slots.append && 'ps-input-number-append',
    ]"
  >
    <div class="prefix__prepend-inner" v-if="$slots.prepend">
      <slot name="prepend"></slot>
    </div>
    <el-input-number
      class="ps-input-number-block"
      v-model="inputValue"
      :controls="controls"
      :placeholder="placeholder"
      :disabled="disabled"
      :max="max"
      :min="min"
      :id="id"
      @change="operaChange"
      @blur="operaBlur"
      @focus="operaFocus"
    ></el-input-number>
    <div class="prefix__append-inner" v-if="$slots.append">
      <slot name="append"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "PsInputNumber",
  props: {
    value: undefined,
    placeholder: {
      type: String,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    precision: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: undefined,
    },
    min: {
      type: Number,
      default: undefined,
    },
    controls: {
      type: Boolean,
      default: false,
    },
    id: { type: String, default: "" },
  },
  //处理v-model语法糖的emit事件
  model: {
    prop: "value",
    event: "handler",
  },
  watch: {
    value: {
      handler(val) {
        this.inputValue = val;
      },
      immediate: true,
    },
  },
  data() {
    return {
      inputValue: undefined,
    };
  },
  created() {},
  mounted() {},
  methods: {
    operaChange(e) {
      const DECIMAL = this.operaGetVals(e);
      console.log(DECIMAL + "---------------------");
      this.$emit("change", DECIMAL);
      this.$emit("handler", DECIMAL);
    },
    operaBlur(e) {
      console.log(this.inputValue);
      const DECIMAL = this.operaGetVals(this.inputValue);
      console.log(DECIMAL);
        this.inputValue = DECIMAL;
      this.$emit("blur", e);
      this.$emit("handler", DECIMAL);
    },
    operaFocus(e) {
      this.$emit("focus", e);
    },
    operaGetVals(e) {
      let DECIMAL = null;
      let vals = e;
      let DECIMAL_F = null;
      if (vals && this.precision) {
        vals = e.toString().split(".");
        if (vals[1] && vals[1].length > this.precision) {
          let valLen = vals[1].length;
          DECIMAL_F =
            valLen > this.precision
              ? vals[1].slice(0, -(valLen - this.precision))
              : null;
        } else {
          DECIMAL_F = vals[1];
        }
        DECIMAL = vals[0] + "." + DECIMAL_F;
      } else {
        DECIMAL = parseInt(vals);
      }
      return DECIMAL;
    },
    operaSupplement(val) {
      let suppVals = "";
      for (let i = 0; i < val; i++) {
        suppVals += "0";
      }
      return suppVals;
    },
  },
};
</script>

<style></style>
