import { defineComponent, ref, watch } from 'vue';
import type { PropType } from 'vue';
import { TextBoxEditorController } from '@ibiz-template/controller';
import { useNamespace } from '@ibiz-template/vue-util';

export default defineComponent({
  props: {
    value: Number,
    controller: {
      type: TextBoxEditorController,
      required: true,
    },
    data: {
      type: Object as PropType<IData>,
      required: true,
    },
  },
  emits: {
    change: (_value: number | null) => true,
  },
  setup(props, { emit }) {
    const ns = useNamespace('app-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);
    };

    return {
      ns,
      c,
      currentVal,
      handleChange,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-input-number
          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>
    );
  },
});
