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) {
          const number = Number(newVal);
          currentVal.value = Number.isNaN(number) ? 0 : number;
        }
      },
      { 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(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.readonly ? (
          this.currentVal
        ) : (
          <i-input-number
            ref='inputRef'
            value={this.currentVal}
            placeholder={this.c.placeHolder}
            precision={this.c.model.precision}
            disabled={this.disabled}
            on-on-change={this.handleChange}
          ></i-input-number>
        )}
      </div>
    );
  },
});
