import { defineComponent, ref, watch } from 'vue';
import {
  getEditorEmits,
  getInputNumberProps,
  useNamespace,
} from '@ibiz-template/vue-util';

export const IBizInputNumber = defineComponent({
  name: 'IBizInputNumber',
  props: getInputNumberProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('input-number');

    const c = props.controller;

    const currentVal = ref<number | null>(null);

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          currentVal.value = newVal!;
        }
      },
      { immediate: true },
    );

    const handleChange = (e: number | null) => {
      emit('change', e);
    };

    const inputRef = ref();

    if (props.autoFocus) {
      watch(inputRef, newVal => {
        if (newVal) {
          const input = newVal.$el.getElementsByTagName('input')[0];
          input.focus();
        }
      });
    }

    return {
      ns,
      c,
      currentVal,
      handleChange,
      inputRef,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-input-number
          ref='inputRef'
          value={this.currentVal}
          placeholder={this.c.placeHolder}
          readonly={this.c.model.readOnly}
          precision={this.c.model.precision}
          on-on-change={this.handleChange}
        ></i-input-number>
      </div>
    );
  },
});
