<template>
  <div class="field has-addons">
    <p class="control has-icons-left has-icons-right is-expanded">
      <input
        type="text"
        v-model="value"
        @keyup="doCheck"
        :class="['input', disabled && 'has-text-black']"
        :placeholder="placeholder || ''"
        :disabled="disabled"
      />
      <span class="icon is-left">
        <Icon
          name="mdi:calculator"
          :size="22"
        />
      </span>
    </p>
    <p
      v-if="unit"
      class="control"
    >
      <a class="button is-static fs-12 h-full">
        {{ unit }}
      </a>
    </p>
  </div>
</template>
<script>
export default {
  props: ["record", "attr", "placeholder", "disabled", "defaultValue", "unit"],
  data() {
    return {
      value: this.getInitialValue(),
      timer: undefined,
    };
  },
  created() {
    if (this.defaultValue) {
      this.value = this.value !== undefined ? this.$formatNum(this.value) : this.$formatNum(0);
    } else {
      if (this.value !== undefined && this.value !== null) {
        this.value = this.$formatNum(this.value);
      } else {
        this.value = "";
      }
    }
  },
  watch: {
    record() {
      this.value = this.$formatNum(this.record[this.attr]);
    },
  },
  methods: {
    getInitialValue() {
      const recordValue = this.record ? this.record[this.attr] : undefined;

      if (this.defaultValue) {
        if (recordValue === null || recordValue === undefined || recordValue === "") {
          return 0;
        }
        return this.$copy ? this.$copy(recordValue) : recordValue;
      } else {
        if (recordValue === null || recordValue === undefined || recordValue === "") {
          return undefined;
        }
        return this.$copy ? this.$copy(recordValue) : recordValue;
      }
    },

    getDisplayValue(recordValue) {
      if (this.defaultValue) {
        if (recordValue === null || recordValue === undefined || recordValue === "") {
          return this.$formatNum(0);
        }
        return this.$formatNum(recordValue);
      } else {
        if (recordValue === null || recordValue === undefined || recordValue === "") {
          return "";
        }
        return this.$formatNum(recordValue);
      }
    },
    doCheck() {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => this.checkChange(), 500);
    },
    doChange() {
      this.$emit("change", this.value);
    },
    checkChange() {
      if (!this.$empty(this.value)) {
        this.value = this.$formatNum(this.$parseNum(this.value));
        this.$emit("number", this.$parseNum(this.value));
      } else {
        if (this.defaultValue) {
          this.value = this.$formatNum(0);
          this.$emit("number", 0);
        } else {
          this.value = "";
          this.$emit("number", null);
        }
      }
    },
  },
};
</script>
